Thursday, 3 October 2013

which of the following is the fastest data type in java?

which of the following is the fastest data type in java?

In java data types(byte,short,int,float,double,boolean) which is the
fastest data type for compilation and why?please list the reason clearly
to understand

Wednesday, 2 October 2013

Trying to use CDI on Glassfish 4 results in javax.el.PropertyNotFoundException: Target Unreachable, identifier 'indexMB' resolved to null

Trying to use CDI on Glassfish 4 results in
javax.el.PropertyNotFoundException: Target Unreachable, identifier
'indexMB' resolved to null

I am getting an error on a single page, and the only error occurs after I
click the SUBMIT button.
I followed the recommendations of the topic JSF2 form submit " Target
Unreachable, identifier 'myModel' resolved to null ONLY on submit but did
not help me.
Any help will be very useful.
Follow my setup and my files:
Glassfish 4
Primefaces 3.5
commons-fileupload 1.3
commons-io 2.4
** index.xhtml
<html ...>
<f:loadBundle basename="i18n" var="bundle" />
<h:head>
<title>#{bundle['index_title']}</title>
</h:head>
<h:body>
#{bundle['index_appname']}
<br />
<h:form id="frmIndex">
<p:panelGrid columns="2">
<p:outputLabel for="user" value="#{bundle['lblUser']}" />
<p:inputText id="user" value="#{indexMB.user}" />
<p:outputLabel for="password" value="#{bundle['lblPassword']}" />
<p:password id="password" value="#{indexMB.password}" />
</p:panelGrid>
<p:commandButton action="#{indexMB.loginTest}"
value="#{bundle['btn_login']}" />
</h:form>
</h:body>
** IndexMB.java
@ManagedBean ("indexMB")
@RequestScoped
public class IndexMB {
private String password;
private String user;
public IndexMB() {
}
public String loginTest(){
...
}
// getters and setters
}
** log (Glassfish)
javax.el.PropertyNotFoundException: /index.xhtml @18,66
value="#{indexMB.user}": Target Unreachable, identifier 'indexMB' resolved
to null
at
com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:100)
at
org.primefaces.renderkit.InputRenderer.findImplicitConverter(InputRenderer.java:170)
at
org.primefaces.renderkit.InputRenderer.findConverter(InputRenderer.java:190)
at
org.primefaces.renderkit.InputRenderer.getConvertedValue(InputRenderer.java:196)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1046)
at javax.faces.component.UIInput.validate(UIInput.java:976)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1249)
at javax.faces.component.UIInput.processValidators(UIInput.java:712)
at
javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIForm.processValidators(UIForm.java:253)
at
javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at
javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1195)
at
com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
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.StandardWrapper.service(StandardWrapper.java:1682)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at
org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at
org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at
org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at
com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at
org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at
org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at
org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at
org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at
org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at
org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at
org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at
org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at
org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at
org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at
org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at
org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at
org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at
org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at
org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:724)
Caused by: javax.el.PropertyNotFoundException: Target Unreachable,
identifier 'indexMB' resolved to null
at com.sun.el.parser.AstValue.getTarget(AstValue.java:174)
at com.sun.el.parser.AstValue.getType(AstValue.java:86)
at com.sun.el.ValueExpressionImpl.getType(ValueExpressionImpl.java:201)
at org.jboss.weld.el.WeldValueExpression.getType(WeldValueExpression.java:93)
at
com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:98)
... 43 more
** web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
** faces-config.xml
<?xml version='1.0' encoding='UTF-8'?>
<faces-config version="2.2"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
<application>
<locale-config>
<default-locale>pt_BR</default-locale>
<supported-locale>en</supported-locale>
<supported-locale>fr</supported-locale>
</locale-config>
</application>
** beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>

hadoop running application- ERROR security.UserGroupInformation: PriviledgedActionException

hadoop running application- ERROR security.UserGroupInformation:
PriviledgedActionException

I have written WordCount code of hadoop as an java application in eclipse
to test hadoop for running applications, but when I try to run it as hdfs
user, this error will appear:
./hadoop jar
/home/masi/eclipse_workspace/WordCount_apacheSample/bin/test2.jar
WordCountApacheSample /user/hdfs/wordCountInput /user/hdfs/wordCountOutput
13/10/02 17:14:50 INFO service.AbstractService:
Service:org.apache.hadoop.yarn.client.YarnClientImpl is inited.
13/10/02 17:14:50 INFO service.AbstractService:
Service:org.apache.hadoop.yarn.client.YarnClientImpl is started.
13/10/02 17:14:50 ERROR security.UserGroupInformation:
PriviledgedActionException as:hdfs (auth:SIMPLE)
cause:java.net.ConnectException: Call From virtual-machine/127.0.1.1 to
localhost:9000 failed on connection exception: java.net.ConnectException:
Connection refused; For more details see:
http://wiki.apache.org/hadoop/ConnectionRefused
Exception in thread "main" java.net.ConnectException: Call From
virtual-machine/127.0.1.1 to localhost:9000 failed on connection
exception: java.net.ConnectException: Connection refused; For more details
see: http://wiki.apache.org/hadoop/ConnectionRefused
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:532)
at org.apache.hadoop.net.NetUtils.wrapWithMessage(NetUtils.java:780)
at org.apache.hadoop.net.NetUtils.wrapException(NetUtils.java:727)
at org.apache.hadoop.ipc.Client.call(Client.java:1239)
at
org.apache.hadoop.ipc.ProtobufRpcEngine$Invoker.invoke(ProtobufRpcEngine.java:202)
at sun.proxy.$Proxy9.getFileInfo(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at
org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:164)
at
org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:83)
at sun.proxy.$Proxy9.getFileInfo(Unknown Source)
at
org.apache.hadoop.hdfs.protocolPB.ClientNamenodeProtocolTranslatorPB.getFileInfo(ClientNamenodeProtocolTranslatorPB.java:630)
at org.apache.hadoop.hdfs.DFSClient.getFileInfo(DFSClient.java:1559)
at
org.apache.hadoop.hdfs.DistributedFileSystem.getFileStatus(DistributedFileSystem.java:811)
at org.apache.hadoop.fs.FileSystem.exists(FileSystem.java:1345)
at
org.apache.hadoop.mapreduce.lib.output.FileOutputFormat.checkOutputSpecs(FileOutputFormat.java:140)
at
org.apache.hadoop.mapreduce.JobSubmitter.checkSpecs(JobSubmitter.java:418)
at
org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:333)
at org.apache.hadoop.mapreduce.Job$11.run(Job.java:1218)
at org.apache.hadoop.mapreduce.Job$11.run(Job.java:1215)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:416)
at
org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1478)
at org.apache.hadoop.mapreduce.Job.submit(Job.java:1215)
at org.apache.hadoop.mapreduce.Job.waitForCompletion(Job.java:1236)
at WordCountApacheSample.main(WordCountApacheSample.java:71)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at org.apache.hadoop.util.RunJar.main(RunJar.java:212)
Caused by: java.net.ConnectException: Connection refused
at sun.nio.ch.SocketChannelImpl.checkConnect(Native Method)
at sun.nio.ch.SocketChannelImpl.finishConnect(SocketChannelImpl.java:597)
at
org.apache.hadoop.net.SocketIOWithTimeout.connect(SocketIOWithTimeout.java:206)
at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:526)
at org.apache.hadoop.net.NetUtils.connect(NetUtils.java:490)
at
org.apache.hadoop.ipc.Client$Connection.setupConnection(Client.java:508)
at
org.apache.hadoop.ipc.Client$Connection.setupIOstreams(Client.java:603)
at org.apache.hadoop.ipc.Client$Connection.access$2100(Client.java:253)
at org.apache.hadoop.ipc.Client.getConnection(Client.java:1288)
at org.apache.hadoop.ipc.Client.call(Client.java:1206)
... 29 more
although I have tested input and output paths with hdfs://localhost:9000/
, there is no difference! BTW, I have studied many posts related to my
problem but they were not useful
any help is appreciated. thanks.

VBScript - copy local file to a FTPS TLS (implicit) server

VBScript - copy local file to a FTPS TLS (implicit) server

I have a script that connects to a DataBase, executes a StoredProcedure,
saves the results into a normal TXT file, compresses the file into a *.rar
file (with a password) and sends the file by e-mail. Our client now wants
we to copy the file to his FTP server, instead of by e-mail.
The problem is that the connection type is implicit FTP over TLS.
I have the following script to test the file copy to an FTP:
'FTP Upload
Dim oShell, objFSO, ftpUser, ftpPass, ftpHost, ftpDir, path
Set oShell = CreateObject("Shell.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
'FTP Server details:
ftpUser = "user"
ftpPass = "password"
ftpHost = "IP address:port"
ftpDir = "/FolderName/"
'File I want to upload:
path = "D:\test.txt"
Call FTPUpload(ftpUser, ftpPass, ftpHost, ftpDir, path)
Public Function FTPUpload(ftpUser, ftpPass, ftpHost, ftpDir, path)
'Upload a file to an FTP server
'Copy Options: 16 = Yes to All
Const copyType = 16
'FTP Wait Time in ms
waitTime = 80000
strFTP = "ftp://" & ftpUser & ":" & ftpPass & "@" & ftpHost & ftpDir
Set objFTP = oShell.NameSpace(strFTP)
'Upload single file
If objFSO.FileExists(path) Then
Set objFile = objFSO.getFile(path)
strParent = objFile.ParentFolder
Set objFolder = oShell.NameSpace(strParent)
Set objItem = objFolder.ParseName(objFile.Name)
objFTP.CopyHere objItem, copyType
End If
'Wait for upload
WScript.Sleep waitTime
End Function
This code works fine with a normal FTP (simple FTP connection), it copies
the file correctly, but with an implicit FTP over TLS connection I think
it doesn't even establish the connection.
With FileZilla I'm able to connect to that server and copy files, but I
want it to be automatic because it's a file we have to send every day.
When I open a Web browser and type ftp://[user]:[password]@host, it shows
me the folders in that FTP server, but with the implicit FTP it doesn't
work even on the web browser. Does it have a different syntax? I'v already
tried with ftps://, but it doesn't work either way.
Is there a way to copy a file to an implicit FTP over TLS using VBScript?
Thanks.

Codefirst "invalid column name xxx" ?

Codefirst "invalid column name xxx" ?

BaseEntity
public abstract class BaseEntity
{
public int Id { get; set; }
}
User
public class User : BaseEntity
{
public User()
{
Roles = new HashSet<Role>();
}
public string UserName { get; set; }
public string DisplayName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public string ProfileImageUrl { get; set; }
public DateTime? LastLoginDate { get; set; }
public string LastLoginIp { get; set; }
public int? LanguageId { get; set; }
public virtual ICollection<Role> Roles { get; set; }
}
user mapping
public class UserMap : EntityTypeConfiguration<User>
{
public UserMap()
{
ToTable("User");
HasKey(x => x.Id);
Property(x => x.DisplayName).HasMaxLength(100);
Property(x => x.Email).HasMaxLength(250);
Property(x => x.LastLoginIp).HasMaxLength(20);
Property(x => x.Password).HasMaxLength(50);
Property(x => x.ProfileImageUrl).HasMaxLength(500);
Property(x => x.UserName).HasMaxLength(50);
HasMany(h => h.Roles).
WithMany(e => e.Users).
Map(
m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
m.ToTable("User_Role");
}
);
}
}
test metod
private MvcProjectContext _context;
private IUnitOfWork _uow;
private IUserService _userService;
[TestInitialize]
public void TestInitialize()
{
_context = new MvcProjectContext();
_uow = new UnitOfWork(_context);
_userService = new UserService(_uow);
}
[TestMethod]
public void TestMethodAddUser()
{
_userService.Insert(new User
{
DisplayName = "test display name",
Email = "test_email@mail.com",
LanguageId = 1,
LastLoginDate = DateTime.Now,
LastLoginIp = "192.168.1.1",
Password = "12345",
ProfileImageUrl = "profile image",
UserName = "test_user"
});
Assert.AreEqual(1,_uow.SaveChanges());
}
I debugged it and checked it, user is adding dbcontext, but when
savechanges method firing, I get error
"invalid column name 'LanguageId'"
I cant find any solution. In DB there is column that named 'LanguageId'.
it does not seem to be something missing. Any advice?

Tuesday, 1 October 2013

cubic lighting integral.

cubic lighting integral.

I am trying to integrate:
(xa-ia+yb-jb+zc-kc)/((x-I)^2+(y-j)^2+(z-k)^2)^(3/2)dxdydz from generic x y
and z initiqls to finals. I have completed part of it, but I am stick on
the part dx/(x^2-2xi+i^2+f)^(3/2) The initial formula is not complete,
right now I am primarily honeing my integration, so please show me your
work as best you can.
A b and c are componentes of a surface normal and i j and k are the
position of the pixel. X y and z are points inside the rectangular prism
light.

Is there a way to make ' ' mean \s* in Perl regular expressions?

Is there a way to make ' ' mean \s* in Perl regular expressions?

This would greatly improve the readability of many regular expressions I
write, and when I write a single literal space in my regexes I almost
always mean \s*, so is there a "mode" that enables this, like /s to make .
match newlines, etc.? A cursory read through perlre didn't give anything,
but maybe I missed something or maybe there's a different way to achieve
this?

Find the result of a weird looking sum

Find the result of a weird looking sum

How do I find the value of such ridiculous-looking sum?
$$\sum^{100}_{i=1}\lfloor \sqrt{i}\rfloor$$

Is it possible to make transparent / translucent pastry=?iso-8859-1?Q?=3F_=96_cooking.stackexchange.com?=

Is it possible to make transparent / translucent pastry? –
cooking.stackexchange.com

I'm looking for something that works like pastry (malleable before baking,
rigid after baking, mild unobtrusive flavour) that is transparent or
translucent. The idea is to use for topping savoury …

Monday, 30 September 2013

Square roots in modular arithmetic [on hold]

Square roots in modular arithmetic [on hold]

Suppose $n = pq$ with $p$ and $q$ both primes.
Suppose that $\gcd(a, pq) = 1$. Prove that if the equation $x^2 ß a \bmod
n$ has any solutions, then it has four solutions.
Suppose you had a machine that could find all four solutions for some
given $a$. How could you use this machine to factor $n$?

SPFile.CopyTo() vs RootFolder.Files.Add() – sharepoint.stackexchange.com

SPFile.CopyTo() vs RootFolder.Files.Add() – sharepoint.stackexchange.com

I've been looking for method of copying a file or folder from one document
library to a number of other libraries with the same name in each subsite
for a particular site collection. What needs to ...

Powershell format operator inside function

Powershell format operator inside function

I've found out the format operator is working differently inside a
function compared to a plain script. Here's a simple example of what is
working as expected:
[string]$name = 'Scripting Guy'
[string]$statement = 'PowerShell rocks'
$s = "The {0} thinks that {1}!" -f $name, $statement
write-host $s
producing:
The Scripting Guy thinks that PowerShell rocks!
While inside a function it does something different:
function myFunc( [string] $iname, [string] $istatement) {
$s = "The {0} thinks that {1}!" -f $iname, $istatement
write-host $s
}
[string]$name = 'Scripting Guy'
[string]$statement = 'PowerShell rocks'
myFunc($name, $statement)
produces:
The Scripting Guy PowerShell rocks thinks that !
I tried to play with it to find out what it's doing:
function myFunc( [string] $iname, [string] $istatement) {
$s = "The {0} thinks that {1}! {2} {3}" -f $iname, $istatement,
"=====", $iname
write-host $s
}
[string]$name = 'Scripting Guy'
[string]$statement = 'PowerShell rocks'
myFunc($name, $statement)
This produces:
The Scripting Guy PowerShell rocks thinks that ! ===== Scripting Guy
PowerShell rocks
So now I don't know what to think about this.

in C/C++ is it legal to define and initialize several id in one row?

in C/C++ is it legal to define and initialize several id in one row?

case 1: int x, y = 0;// what is in x and y? case 2: int x = 0, y = 1, z =
2; //syntax error before ',' taken
for case 2, I am not willing to code as follow:
int x = 0;
int y = 1;
int z = 2;
Is there a simple statement to do the same job? thanks a lot 1

Sunday, 29 September 2013

Jquery Draggable to rearrange divs

Jquery Draggable to rearrange divs

Looking to use .draggable to rearrange some divs on the page. I would like
it to snap into place and then have the other elements rearrange
themselves around it. Not really sure how to approach this. I was able to
get things .draggable() pretty easily as its one line of Jquery. Not
really sure where to go after that.
sample.
<form id="demo-upload" class="dropzone dz-clickable dz-started"
action="http://www.torrentplease.com/dropzone.php">
<div class="dz-default dz-message">
<div class="dz-preview dz-processing dz-image-preview dz-error"
onclick="myFunction()">
<div class="dz-preview dz-processing dz-image-preview dz-error"
onclick="myFunction()">
</div>
</form>
function moveDiv(div){
console.log('clicked');
$(div).draggable({ grid: [ 20,20 ] });
}

Where can I download Spring Framework jars

Where can I download Spring Framework jars

SpringSource.org changed their site to http://spring.io but I just don't
understand why can't they give a simpler way to download latest
project/snapshot? Why do they believe in making things so difficult?
Does someone know how to get the latest build without maven/github? from
http://spring.io/projects
Please fix your website structure to help navigate downloading recent
project easily.

onCreate method not getting called

onCreate method not getting called

I have following method inside a ActionBar.TabListener method and when I
am calling the setContentView I am expecting it to call onCreate method
for that view: But that method is not called here.
so, how can I create an activity outside of the onCreate method?
public void onTabSelected(Tab tab, FragmentTransaction arg1) {
int tabPosition = tab.getPosition();
switch (tabPosition) {
case 0:
setContentView(R.layout.class_view);
break;
case 1:
setContentView(R.layout.detail_view);
break;
case 2:
setContentView(R.layout.class_view);
break;
}
}

asp.net gridview if cell row value is equal then

asp.net gridview if cell row value is equal then

i am populating a datatable then binding it to a gridview , now im readin
the rows in the grid and coloring the row if value = [x] the thing when i
try to display on the page the row that is colored im getting it
duplicated lets say i have colored 1 row but the response.write will be
like 100 times the same result , below is my code , hope some one can help
:
protected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string alert = Request.QueryString["check"];
// loop over all the Rows in the Datagridview
foreach (GridViewRow row in gv1.Rows)
{
// if condition is met color the row text and send email
if (gv1.Rows[0].Cells[0].Text.ToString() == alert)
{
Session ["fn"] = gv1.Rows[0].Cells[2].Text;
gv1.Rows[0].ForeColor = Color.Red;
}
Response.Write(Session["fn"]);
}

Saturday, 28 September 2013

moving files from one foder to another automatically

moving files from one foder to another automatically

I have 100 main folders each folder contains 2 sub folder and name of one
of those folder is "NEW FOLDER" which contain pdf files I want to
overwrite/move those files in another sub folder. kindly provide me a
script/batch file for windows so that all the data moves from "NEW FOLDER"
to adjsent folder at once for n number of main folders

Update WebBrowser in Delphi

Update WebBrowser in Delphi

Hi I am making a web browser in delphi, so for now I'm doing is letting
the user can modify the headers at will, the current problem is that I use
a checkbox to check when the user wants to use the headers that are in a
memo the problem is that when I use it for the first time it works fine
but when I disable the checkbox and try to use the browser without the
headers is that the headers are still active and that should not be
happening.
The code page used to test local
<? php
$ nav = $ _SERVER ['HTTP_USER_AGENT'];
echo "<h1> Test:". $ nav. "</ h1>";
?>
The code delpi
TForm2.sButton1Click procedure (Sender: TObject);
var
Flags, Headers, targetFrameName, PostData: OleVariant;
Url, Ref: string;
begin
Flags: = '1 ';
TargetFrameName: ='';
PostData: ='';
URL: = sEdit1.Text;
if (sCheckBox1.Checked) then
begin
Headers: = sMemo1.Text;
WebBrowser1.Navigate (URL, Flags, targetFrameName, PostData, Headers);
end
else
begin
Headers: ='';
WebBrowser1.Navigate (URL, Flags, targetFrameName, PostData, Headers);
end;
end;

sql subtract subquery sum multiple tables

sql subtract subquery sum multiple tables

How can I subtract the sum of a subquery table from another table?
SELECT i.column1 * i.column2 AS Expr1
, i.column1 * i.column2 - (SELECT SUM(table2.column1) AS Expr1
FROM table2
WHERE (table2.column3 = table1.column3)) AS
derivedExpression
FROM table1
Only the derivedExpression in the first row is correct. The rest rows
returns null for derivedExpression. For Expr1, everything is fine. Any
help?

Friday, 27 September 2013

node.js require of a json file

node.js require of a json file

I am trying to require() this JSON file.
{
"info" : function (request) {
var i = "<pre>";
i+= "current working directory: " + process.cwd() + "\n";
i+="request url: " + request.url + "\n";
i+= "</pre>";
return i;
}
}
Using this line
var render = require('./render.json');
But I get an exception from the JSON file of : Unexpected token u
What am I doing wrong please ?

Align images using CSS

Align images using CSS

I'm using this tooltip called open tips. how can I get these images to
align horizontally instead of vertically?
fiddle
the only css I have is:
.images {
top: -20px;
width: 1400px;
float: left;
}

jQuery - Smooth scroll only working to top - need it to work to bottom aswell

jQuery - Smooth scroll only working to top - need it to work to bottom aswell

im trying to use a smooth scroll for my href elements. The only problem is
that i can only get it to do it upwards.
The live site is here
If you click on the box "Webdesign" it should do a smooth scrool down to
the .content. The same thing if you hit the button of the bottom of that
content it should scroll up to the top again smoooth(That works fine) -
Its downwards to the start of the "webdesign" content it doesnt work.
script used in the bottom of the site:
<script type="text/javascript">
$("a[href^='#']").click(function(){
var contentPosTop = $('.content').position().top;
$('html, body').stop().animate({
scrollTop: contentPosTop
}, 1500);
});
</script>
Any ideas?

How to iterate through an enumeration of flags and create checkboxes that are checked appropriately for each value?

How to iterate through an enumeration of flags and create checkboxes that
are checked appropriately for each value?

I have an Enum of flags to represent the days of the week, with a few
extra values that indicate weekdays, weekends, every day, or no days.
Here's the Enum:
[Flags]
public enum DayOfWeek : short
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
Weekday = 62,
Weekend = 65,
Everyday = 127,
None = 0
}
I also have a View Model with a property, DayOfWeek with a type of DayOfWeek.
In my View, I need to create a checkbox for each day of the week and
somehow appropriately check the boxes based on which days have been saved.
How can I do this? I'm guessing this needs to be done in a foreach loop,
but that's all I have to go on so far.

Php pagination link not showing on last page

Php pagination link not showing on last page

I have a pagination script which works. The first page has a 'next' link,
the last page should have a 'previous' link and the ones in between have
both. The problem is that the last page doesnt show it 'previous' link.
Heres the code
include '../inc/connect.php';
//paganation settings
$per_page = 2;
$pages_query = mysqli_query($link, "SELECT COUNT(`id`) FROM `gallery`") or
die(mysqli_error($link));
$result = mysqli_fetch_array($pages_query, MYSQLI_NUM);
$pages = $result[0] / $per_page;
$page = (isset($_GET['page']) AND (int)$_GET['page'] > 0) ?
(int)$_GET['page'] : 1;
$start = ($page - 1) * $per_page;
$last = ($pages - 1) / $per_page;
$prev = $page - 1;
$next = $page + 1;
//query the db
$q =mysqli_query($link, "SELECT * FROM gallery
ORDER BY id DESC
LIMIT $start, $per_page");
//find out the page we are on and display next and previous links accordingly
if ($page >= 1 && $page < $pages){
echo "<span class='next'>";
echo "<a href=\"?page={$next}\">Next page</a> ";
echo "</span>";
if ($page >=2){
echo "<span class='prev'>";
echo "<a href=\"?page={$prev}\">Previous page</a> ";
echo "</span>";
}
}
else if ($page > $pages + 1){
echo 'No more images in the database';
}
//display images
while($row=mysqli_fetch_array($q)){
echo "<a href='{$row['filename']}' rel='thumbnail'>
<img class='nailthumb-container' src='{$row['filename']}'
alt='{$row['description']}.Image' title='{$row['description']}' />
</a>";
}

The type arguments for method cannot be inferred from the usage error for creating a relationship

The type arguments for method cannot be inferred from the usage error for
creating a relationship

So I have a class that describes the Relationship like so:
public class GraphRelationship<TObject> :
Relationship<RelationshipObject>,
IRelationshipAllowingSourceNode<TObject>,
IRelationshipAllowingTargetNode<TObject>
{
string RelationshipName;
public GraphRelationship(string RelationshipName, NodeReference
targetNode, RelationshipObject relationshipTypeObject)
: base(targetNode, relationshipTypeObject)
{
this.RelationshipName = RelationshipName;
}
public override string RelationshipTypeKey
{
get { return RelationshipName; }
}
}
Now I have a method that I want to use to create an instance of the above
mentioned class, but I get this The type arguments for method cannot be
inferred from the usage error.
Here is the method:
public RelationshipReference CreateObjectRelationship(string
relationshipType, string parentObjectId, string childObjectId,
RelationshipObject relationshipProperties)
{
RelationshipReference relationshipReference = 0;
NodeReference parentNodeReference = GetObjectReference(parentObjectId);
NodeReference childNodeReference = GetObjectReference(childObjectId);
relationshipReference =
GraphConnection.CreateRelationship(parentNodeReference, new
GraphRelationship<RelationshipObject>(relationshipType,
childNodeReference, relationshipProperties));
return relationshipReference;
}
Im sure this is a trivial problem, but how would i fix this?

Redirect in subfolder .htaccess

Redirect in subfolder .htaccess

I have file /abc/index.html
I want to access it via /index.html with some rules in /abc/.htaccess file.
Is this possible? How?!

Thursday, 26 September 2013

Call custom function inside shortcode

Call custom function inside shortcode

I have a function to display a list of files from a given directory as
links. I then have a shortcode to display the function, but I can't figure
out how to make the shortcode work without using inline php to call the
function. The shortcode only works right now because I have another
third-party plugin that allows inline php in the WordPress text editor.
Here's the function:
function showFiles($path){
if ($handle = opendir($path))
{
$up = substr($path, 0, (strrpos(dirname($path."/."),"/")));
while (false !== ($file = readdir($handle)))
{
if ($file != "." && $file != "..")
{
$fName = $file;
$file = $path.'/'.$file;
if(is_file($file)) {
echo "<li><a href='/".$file."'
target=_blank>".$fName."</a></li>";
}
}
}
closedir($handle);
}
}
And here's a pared down version of the shortcode function I'm using:
function sc_showfiles( $atts, $content = null ) {
extract( shortcode_atts( array(
'type' => '',
), $atts ) );
$showfiles = '<ul><?php
showFiles(\'files/'.$type.'files/'.do_shortcode($content).'\');
?></ul>';
return $showfiles;
}
add_shortcode('showfiles', 'sc_showfiles');
The content area allows the user to enter a shortcode with a user
generated meta so the directory it's pulling from will match the logged in
user.
I've tried about six different things, and haven't been able to achieve
this without calling the showFiles function using inline php. I came close
once using:
$files = showFiles('files/'.$type.'files/'.do_shortcode($content).);
and
$showfiles = '<ul>'.$files.'</ul>';
return $showfiles;
but that threw the list of files at the top of the page, I assume because
the original showFiles function is echoing the html output. But if I
change echo to return in the top function I get nothing.

Wednesday, 25 September 2013

Accepting XML on server side using RESTEasy

Accepting XML on server side using RESTEasy

I want to create a REFTful web service that accepts XML. I can see a lot
of examples where server is sending response as an XML. But I want to
process request as an XML. Anyone has idea on how to do that?

Thursday, 19 September 2013

Eclipse The deployment descriptor of the module 'xxx.war' cannot be loaded or found

Eclipse The deployment descriptor of the module 'xxx.war' cannot be loaded
or found

There's been a number of similar questions raised on this error on Eclipse:
The deployment descriptor of the module 'xxx.war' cannot be loaded or found.
This is a very generic error, and after scouring the web I have multiple
different causes and solutions. I'm going to attempt to list them all
here, so others won't have to go through the same thing I did.
If anyone experienced other causes and solutions, please list them here
too. =)
(Moderators, please wait for me to put the answer up before judging this
question)

jQuery Remove part of the HTML and append new HTML

jQuery Remove part of the HTML and append new HTML

We have approval with our client, just a heads up to cover me in any way.
We are needing to modify some of the code in a clients site if a cookie is
seen on their computer, the client's site is in ASPX format. I have the
first part of the code created, but where I am getting stuck is this:
I need to remove the last 2000 characters (or so) of the body of the page,
then append the new HTML to it.
I tried:
$('body').html().substring(0, 10050)
but that doesn't work, I also tried copying that HTML (which did work) and
put it back with the new code, but it created a loop of the script
running.
Any suggestions on what I should do? It has to be javascript/jQuery sadly.
//////// EDIT ////////////
My script is brought in by Google Tag Manager, and added to the page at
the bottom, then my script runs, this is what was causing the loop in the
script. Basically, here is the setup:
My Script on my server is loaded into the client site using Google Tag
Manager, added to the bottom of the page. From there it is able to
execute, but when doing this, it creates a loop of adding the Google Tag
Manager script, causing my code to re-add, causing it to re-execute again.
The client is not willing to do anything, he has pretty much told us to
just figure it out, and to not involve his web guy.

How do I pull a package / deb file from an apt server on a mac?

How do I pull a package / deb file from an apt server on a mac?

How can I programmatically pull down the latest deb file for an apt
package and extract the contents in order to be able to access a script
therein? I want this to work on a mac with the standard suite of tools
(i.e. no apt-get or apt-cache).
Background: My simulation project uses client code to execute. The host
simulation tool runs on a linux environment and is managed through an
internal apt server. One colleague is using apt-get on his linux box to
install the package and then is sending a single file to us. I want our
client to do this programmatically in a way that will work on mac clients.
I have dry run the process (see example answer), but I am surprised nobody
has talked about this already.
Any recommendations on how best to do this?

Grunt watch: compile only one file not all

Grunt watch: compile only one file not all

I have grunt setup to compile all of my coffee files into javascript and
maintain all folder structures using dynamic_mappings which works great.
coffee: {
dynamic_mappings: {
files: [{
expand: true,
cwd: 'assets/scripts/src/',
src: '**/*.coffee',
dest: 'assets/scripts/dest/',
ext: '.js'
}]
}
}
What I would like to do is then use watch to compile any changed coffee
file and still maintain folder structure. This works using the above task
with this watch task:
watch: {
coffeescript: {
files: 'assets/scripts/src/**/*.coffee',
tasks: ['coffee:dynamic_mappings']
}
}
The problem is that when one file changes it compiles the entire directory
of coffee into Javascript again, it would be great if it would only
compile the single coffee file that was changed into Javascript. Is this
naturally possible in Grunt or is this a custom feature.
We have custom watch scripts at work and I'm trying to sell them on Grunt
but will need this feature to do it.

get ID at time of insert / replicate value into other

get ID at time of insert / replicate value into other

Is it possible to get the ID of what the entry in the MySQL DB is going to
be ? Or even better replicate the value of ID into another field ? For
example I have:
ID and User_ID and I want them always to be the same value
--------------------
| ID User_ID |
| 1 1 |
| 2 2 |
| 3 3 |
| 4 4 |
| 5 5 |
--------------------
And so on

PHP Application Server Blocked Due To CGI/PHP Overload

PHP Application Server Blocked Due To CGI/PHP Overload

I an working on a e-governance Web App made in php which has been blocked
by Server Provider. His mail reads -
DISABLED CONTENT :: CGI/PHP Overload on domainname.org
During a recent audit of the server we found the account [domainname] to
be exceeding our allowed resource usage:
Below they mentioned some of the php pages of my app which they are saying
are using excess resourcethan allowed.
#####################################
AVERAGE SERVER RESOURCE LIMITS
Memory usage may not exceed 10% per domain/file/application<br/>
CPU usage may not exceed 20% per domain/file/application<br/>
Apache connections may not exceed 30 connections<br/>
15 MySQL maximum user connections allowed<br/>
350 emails per hour, per domain
#####################################
I want to ask is there something that i can do with my programming. During
office timing, some 50-60 users might be working on it. Is this due to
concurrent MySQL connections or Apache connections.
Another important thing - this is the 2nd time this is happening this
month. A week ago the same problem occurred. My server provider suggested
me to buy a remote MySQL. So i did bought a remote MySQL and also changed
domain. Again this has happened. Only for 6-8 months this site has more
traffic. Can someone suggest what should i do.

How to generate data frame following a pattern

How to generate data frame following a pattern

I'm trying to find a quick (i.e. not manual) way of generating a data
frame that follows the following pattern. The columns are accident yearand
development_year:
accident_year development_year
2 10
3 9
3 10
4 8
4 9
4 10
5 7
5 8
... ...
5 10
... ...
10 2
... ...
10 10
So for the accident_year column I need a vector that goes has one 2, two
3s, three 4s and so on. For the other column (development year) I
basically need a vector of sequences 10,9, 10,9,8, 10,9,7, ... ,
10,9,8,7,6,5,4,3,2.
Does anyone know how to easily generate those?
Thanks!

Wednesday, 18 September 2013

Make Xpath choose parts of an attribute

Make Xpath choose parts of an attribute

I have xml-documents with tables. Every table has an attribute hdsl-percent.
First of all, I'd like to know, what exactly that is . Never came across
it. Google didn't yield any useful results.
Now, this attribute contains the widths of the table-columns in
percentages, e.g. hsdl-percent="23.5 36.7 39.7".
Is there any way that I could get XPath to use these values for the widths
of the table-columns? So 23.5% width for the first column and so on...
The problem is that each table is different, many of them with rowspans
and colspans and since I'm using Apache FOP and it doesn't support
table-layout auto, my tables just have width="100%", no column-width
specified and therefore some columns are wider than they should be.
Thanks for your help and suggestions!

Can Chrome debugger show me the full path to HTML element?

Can Chrome debugger show me the full path to HTML element?

Using Chrome debugger, the "Copy as XPath" returns results that (I think)
are relative to the entity's parent element or maybe parent iframe
(document? form??). I need the entire path from window.top.document. The
entity is deeply nested in a page with many forms and iframes. Extra
points if I can the the path as a jQuery selector.

Want answer of this 8086 assembly code and values of AL,BL and status flags after every instruction?

Want answer of this 8086 assembly code and values of AL,BL and status
flags after every instruction?

Unable to find the values of status register. I have download the emulator
of 8086 assembly language.I it shows error in line SBB and asking for more
operands.
STC
MOV AL,4CH
SBB
XOR BL,BL
MOV [SI],BL
HLT

Pyhton pandas: How to combine the data from many data frames into a single data frame with an array as the data values

Pyhton pandas: How to combine the data from many data frames into a single
data frame with an array as the data values

If I have many panda data frames, with the same index structure, I want to
create a data frame with the same index structure but the data values are
np.arrays (actually I want np.matrix.)
Merging seems to do just fine with simple operations df1 + df2 adds
element wise but np.array((df1,df2)) doesn't do at all what I want.
Does pandas have a method of doing this without rebuilding the entire
object element by element?
E.g. if I have
df1 = col1 col2
1 1 2
2 3 4
df2 = col1 col2
1 5 6
2 7 8
and want
df2 = col1 col2
1 [1,5] [2,6]
2 [3,7] [4,8]

Google Map Markermanager using a xml file

Google Map Markermanager using a xml file

I am trying to adapt this code (comming from Google Developpers)
//<![CDATA[
var map;
var mgr;
var icons = {};
var allmarkers = [];
function load() {
var myOptions = {
zoom: 3,
center: new google.maps.LatLng(50.62504, -100.10742),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map'),
myOptions);
mgr = new MarkerManager(map);
google.maps.event.addListener(mgr, 'loaded', function(){
setupOfficeMarkers();
google.maps.event.addListener(map, 'zoom_changed', function() {
updateStatus(mgr.getMarkerCount(map.getZoom()));
});
});
}
function getIcon(images) {
var icon = false;
if (images) {
if (icons[images[0]]) {
icon = icons[images[0]];
} else {
var iconImage = new google.maps.MarkerImage('images/' +
images[0] + '.png',
new google.maps.Size(iconData[images[0]].width,
iconData[images[0]].height),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
var iconShadow = new google.maps.MarkerImage('images/' +
images[1] + '.png',
new google.maps.Size(iconData[images[1]].width,
iconData[images[1]].height),
new google.maps.Point(0,0),
new google.maps.Point(0, 32));
var iconShape = {
coord: [1, 1, 1, 32, 32, 32, 32, 1],
type: 'poly'
};
icons[images[0]] = {
icon : iconImage,
shadow: iconShadow,
shape : iconShape
};
}
}
return icon;
}
function setupOfficeMarkers() {
allmarkers.length = 0;
for (var i in officeLayer) {
if (officeLayer.hasOwnProperty(i)) {
var layer = officeLayer[i];
var markers = [];
for (var j in layer["places"]) {
if (layer["places"].hasOwnProperty(j)) {
var place = layer["places"][j];
var icon = getIcon(place["icon"]);
var title = place["name"];
var posn = new google.maps.LatLng(place["posn"][0],
place["posn"][1]);
var marker = createMarker(posn, title,
getIcon(place["icon"]));
markers.push(marker);
allmarkers.push(marker);
}
}
mgr.addMarkers(markers, layer["zoom"][0], layer["zoom"][2]);
}
}
mgr.refresh();
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
function createMarker(posn, title, icon) {
var markerOptions = {
position: posn,
title: title
};
if(icon !== false){
markerOptions.shadow = icon.shadow;
markerOptions.icon = icon.icon;
markerOptions.shape = icon.shape;
}
var marker = new google.maps.Marker(markerOptions);
google.maps.event.addListener(marker, 'dblclick', function() {
mgr.removeMarker(marker)
updateStatus(mgr.getMarkerCount(map.getZoom()));
});
return marker;
}
function showMarkers() {
mgr.show();
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
function hideMarkers() {
mgr.hide();
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
function deleteMarker() {
var markerNum =
parseInt(document.getElementById("markerNum").value);
mgr.removeMarker(allmarkers[markerNum]);
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
function clearMarkers() {
mgr.clearMarkers();
updateStatus(mgr.getMarkerCount(map.getZoom()));
}
function reloadMarkers() {
setupOfficeMarkers();
}
function updateStatus(html) {
document.getElementById("status").innerHTML = html;
}
//]]>
google-maps-utility-library-v3 Markermanager
It is an example about how to use markermanager but it is using a js file
as raw material and I would like to use a xml file. I tried several
possibilities but no success.
Here you can find the js file
http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markermanager/examples/google_northamerica_offices.js
The target is to adapt the code in order to use a XML file with these
markers:
Name
icon
Icon_shadow
Long
Lat
Zoom_max
Zoom_min
Some help please !

Tumblr with webview

Tumblr with webview

In my app i want to post image to tumblr.So i follow the tumblr api and i
used the the sample from the github.This is the github address
"https://github.com/RobertSzkutak/AndroidExamples". And every thing is
fine to upload the image successfully in tumblr. But in this sample they
are using browser to open tumblr login page and authentication.But my
question is how to use webview instead of browser.I google alot,but i did
not find any solution.So please guide me how to do this?.

Using VB.net to get Excel Cell Value which is not the correct value?

Using VB.net to get Excel Cell Value which is not the correct value?

I've been stuck on this for the past few hours so I really could do with
some help. I am trying to get numeric (integer and decimal) values from an
Excel spreadsheet and use it create a graph on my form using the chart
control or even display that value in a textbox.
The Value of cell A11 is "2003" and K11 is "12.00" but the returned values
are 0 and 12. I use formulas to calculate the rest of the y values. The
strange thing is that text works fine. Cell A3 has "initial" which comes
back as "initial", it's just the numbers which don't work.
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Open("C:\File.xls")
xlWorkBook = xlApp.Workbooks.Add("C:\File.xls")
xlSheet = xlWorkBook.Worksheets(1)
Dim x1 As String
Dim y1 As String
x1 = xlSheet.Range("A11").Value.ToString
y1 = xlSheet.Range("K11").Value.ToString
MsgBox(x1)
Thanks in advance

Generating unique download link to download once only

This summary is not available. Please click here to view the post.

Tuesday, 17 September 2013

formatting xml string to xml format for jaxb in java

formatting xml string to xml format for jaxb in java

I have a requirement that i have the string xml and i want to use this xml
string in another level to display in xml format.
My xmlgenerator is :
import javax.xml.bind.Marshaller;
import javax.xml.stream.XMLStreamWriter;
import com.db.accounting.application.server.common.DDAMessage;
@SuppressWarnings("restriction")
public class XmlGenerator {
private JAXBContext jaxbContext;
private XMLOutputFactory xmlOutputFactory;
public XmlGenerator() {
try {
jaxbContext = JAXBContext
.newInstance("com.db.accounting.application.server.jaxbautogenerated");
xmlOutputFactory = XMLOutputFactory.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
public final String getMessage(DDAMessage ddaMessage) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
Marshaller jaxbMarshaller =
jaxbContext.createMarshaller();
jaxbMarshaller.setProperty("jaxb.encoding", "UTF-8");
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT,
true);
XMLStreamWriter xmlStreamWriter = xmlOutputFactory
.createXMLStreamWriter(baos, (String)
jaxbMarshaller
.getProperty(Marshaller.JAXB_ENCODING));
xmlStreamWriter.writeStartDocument((String)
jaxbMarshaller
.getProperty(Marshaller.JAXB_ENCODING),
"1.0");
ObjectFactory factory = new ObjectFactory();
TXNREQUEST txnrequest = factory.createTXNREQUEST();
TXNREQHDR txnreqhdr =
factory.createTXNREQUESTTXNREQHDR();
PFTACTGORDERMST pftactgordermst = factory
.createTXNREQUESTTXNREQHDRPFTACTGORDERMST();
PFTACTGORDERTXN pftactgordertxn = factory
.createTXNREQUESTTXNREQHDRPFTACTGORDERTXN();
pftactgordermst.setOUID("ift sift header");
pftactgordermst.setONSHREOFSHREINDCTR("ACU");
pftactgordermst.setORGN("1004");
pftactgordermst.setPREEXCTDFLG("1");
pftactgordermst.setNOOFBKNGS("2");
txnreqhdr.setPFTACTGORDERMST(pftactgordermst);
pftactgordertxn.setACNTREFTYP("7");
pftactgordertxn.setDRCRFLG("1");
pftactgordertxn.setTXNCRNCY("USD");
pftactgordertxn.setTXNAMT("XYZ");
pftactgordertxn.setVALDT("DDMMYY");
pftactgordertxn.setCUSREF("FFMMLL");
pftactgordertxn.setCNTRCTIDNTFRSOURCE("22630-1");
pftactgordertxn.setOWNERSHIPCODE("gle expense code");
pftactgordertxn.setPRDCTCODE("4210");
pftactgordertxn.setMRKTNGCODE("0072");
txnreqhdr.setPFTACTGORDERTXN(pftactgordertxn);
txnrequest.setTXNREQHDR(txnreqhdr);
jaxbMarshaller.marshal(txnrequest, xmlStreamWriter);
xmlStreamWriter.writeEndDocument();
xmlStreamWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
return new String(baos.toByteArray());
}
}
From this file i am able to generate the xml file in string and when i am
accessing this xml in next level, I want display in xml format in log
file.
Thanks In Advance Ravindar Nidigonda

uploading of files WCF c#

uploading of files WCF c#

I am working on uploading files with a WCF web service, here's my code for
uploading:
public string UploadTransactionsFile(string uploadPath)
{
string uploadTransactionsFile;
if (String.IsNullOrEmpty(uploadPath))
return string.Empty;
if (!ValidateTransactionsFile(uploadPath))
return string.Empty;
try
{
var dir = @"C:\Upload\";
string myUploadPath = dir;
var myFileName = Path.GetFileName(uploadPath);
CheckDirectory(myUploadPath);
var client = new WebClient { Credentials =
CredentialCache.DefaultCredentials };
client.UploadFile(myUploadPath + myFileName, "PUT", uploadPath);
client.Dispose();
uploadTransactionsFile = "ok";
}
catch (Exception ex)
{
uploadTransactionsFile = ex.Message;
}
return uploadTransactionsFile;
}
I created a Windows Forms test client and added the service reference, but
my code in calling the method and hardcoded the file i want to upload:
private testServiceClient testService;
private void Button_Click(object sender, RoutedEventArgs e)
{
var File = "C:\\file.csv";
testService = new testServiceClient();
mgiService.UploadTransactionFile(File);
}
I can upload files using one computer, but when I put my test client to
another computer, then I can't, because the file is just passing the
stringpath, which cannot be found on server computer.
Am I missing something?
Do I have to send my file as byte[]? If so, then how do I do this?

Import XML into Azure

Import XML into Azure

Somebody knows how to simply import xml into sql azure please? I will
thank you for that. any tutorial or else... I tried OPENXML but not
supported in azure I tried different software too, but nothing works?

Jersey Restful API Validation

Jersey Restful API Validation

how can i validate user name and password using jersey restful API.
Here is the code Below:
I tried using the HttpRequest and HttpResponse
@POST
@Path("/login")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_JSON)
public String postLoginJson(@FormParam("userName") String userName,
@FormParam("password") String password) {
String user = null;
try {
user = userObjectJson();
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("User Name = " + userName);
System.out.println("Password = " + password);
return user;
}

Wrong default form values from model

Wrong default form values from model

I have a backup variable for an account's username that I save through
posts in a hidden field, @Html.HiddenFor(u => u.backupUsername). This is
the function the form posts to:
[HttpPost]
public ActionResult Update(AccountModel newInfo)
{
validateUserInfo(newInfo);
if (ModelState.IsValid)
{
newInfo.updateToDatabase();
}
return View(newInfo);
}
In updateToDatabase(), the backup username is updated to match the current
one. I've set breakpoints and looked at the values during debug to confirm
that this does happen and work.
However, as soon as Update() is called again, newInfo.backupUsername is
back to what it was before anything had been changed. What am I missing
here? Shouldn't the form's--and therefore the hidden field's--values get
repopulated from the model passed in?

Sunday, 15 September 2013

Intellij 12 always do "make"(several seconds) even no code change

Intellij 12 always do "make"(several seconds) even no code change

I just start learning the Intellij. I create a small project and create
several java files in a module. There is one thing bothers me, that
Intellij always do a "make", which takes about 6-8 seconds, every time
before run or debug the java code, no matter if I changed the code or not.
I have turned on the "make project automatically" setting in compiler
setting. Anyone have a idea?

smoothAnchors.js not working in IE

smoothAnchors.js not working in IE

I'm having trouble getting smoothAnchors.js to work in IE. Can anybody see
where I'm going wrong please?
I am using bigvideo.js on this page
http://thewebsitedeveloper.co.nz/thinkRedTest/sureFire/index.html and also
have a button activating a scrolling animation to a div using
smoothAnchors.js
The scrolling animation works perfectly in all browsers on my local host,
and on the test site it works fine on all browsers except IE where the
scrolling animation is not working. it does work when I turn off
bigvideo.js. Can anybody suggest a way to make this work with the video?
Any help greatly appreciated. Thanks in advance.
HTML
<div class="arrowButton" id="scrollIt">
<a href="#lower-content">
<img src="images/arrowDown2.png" alt="down pointing arrow icon">
</a>
</div>
jQuery
<script>
$(function() {
var BV = new $.BigVideo();
BV.init();
BV.show('video/surefireRedBg.mp4',{ambient:true});
//scrolling to anchor links
$.smoothAnchors("slow");
});
</script>

MappingException: The class 'Acme\UserBundle\Entity\User' was not found in the chain configured namespaces

MappingException: The class 'Acme\UserBundle\Entity\User' was not found in
the chain configured namespaces

I need to use etity_managers instead of auto_mappings
it shows this error.
MappingException: The class 'Acme\UserBundle\Entity\User' was not found in
the chain configured namespaces
my config.yml is like this.
doctrine: dbal:
orm:
auto_generate_proxy_classes: %kernel.debug%
entity_managers:
FOSUserBundle: ~
FOSMessageBundle: ~
AcmeUserBundle: ~
Is there anything I have to do ?

perl splitting function exception conditions

perl splitting function exception conditions

I have a requirement for splitting in perl . Please have a look in below Ex
"john","David2,mick",25,"12-12-2009","male"
I have to split this record on comma (,) but should not consider the comma
in quotes...
O/P I required is
john
david2mick
25
12-12-2009
male
Could you please help me in this.

Why does Bash enclose strings in a backtick and single-quote?

Why does Bash enclose strings in a backtick and single-quote?

Note lines 2 and 4. I always notice this, and get curious as to why they
quote a string with different characters.
root@vm:/# stat 1
stat: cannot stat `1': No such file or directory
root@vm:/# stat /
File: `/'
...

Nullpointer exception in hashmap when running nutch on a hadoop cluster

Nullpointer exception in hashmap when running nutch on a hadoop cluster

I run nutch crawler on a hadoop cluster with only 2 node, but when i ran
nutch job on hadoop i get a nullpointer exception after "update-table"
phase,
the specific error comes below
Exception in thread "main" java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:394)
at java.util.Properties.setProperty(Properties.java:143)
at org.apache.hadoop.conf.Configuration.set(Configuration.java:419)
at org.apache.nutch.indexer.IndexerJob.createIndexJob(IndexerJob.java:128)
at org.apache.nutch.indexer.solr.SolrIndexerJob.run(SolrIndexerJob.java:44)
at org.apache.nutch.crawl.Crawler.runTool(Crawler.java:68)
at org.apache.nutch.crawl.Crawler.run(Crawler.java:192)
at org.apache.nutch.crawl.Crawler.run(Crawler.java:250)
at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65)
at org.apache.nutch.crawl.Crawler.main(Crawler.java:257)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.hadoop.util.RunJar.main(RunJar.java:160)
i'm newbie in hadoop and nutch and don't know where to look.
i use hadoop-1.2.0 and nutch 2.2.1.
i ran nutch crawler by this command
~/hadoop-1.2.0/bin/hadoop jar apache-nutch-2.2.1.job
org.apache.nutch.crawl.Crawler -solr http://10.1.1.69:8090/solr/core1/
urls -depth 1 -topN 1 -batch 111

sqlplus doesn't start on linux 64

sqlplus doesn't start on linux 64

I installed, on Mint15 64bit, the Oracle Instant client package 11
Each time I try running sqlplus I get message
Error 6 initializing SQL*Plus
SP2-0667: Message file sp1<lang>.msb not found
SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory
Of course I set correctly the $ORACLE_HOME. I tried to set LANG=us Same
result.
I tried with instant oracle 12.1, same results !?
Except waving to MariaDb ;) What part is wrong in my install ?

Saturday, 14 September 2013

compare and print starting($1) and ending($2) number in given input $1 using unix

compare and print starting($1) and ending($2) number in given input $1
using unix

i having input in a.txt file,
10000030 10000029 10000028 10000027 10000026 10000024 10000023 10000021
10000018 10000018 10000017 10000016 10000015 10000014 10000013 10000011
10000010 10000009 10000008 10000006 10000005 10000004 10000003 10000002
10000001
need output in b.txt
10000001,10000006,6 10000008,10000011,4 10000013,10000019,7
10000021,10000021,1 10000023,10000024,2 10000026,10000030,5
Help me solve this script.....

Physics-based drawing app

Physics-based drawing app

I'm working on a project that's rather complex for me, considering that I
only recently picked up javascript.
Basically I want to use the box2d phsyics engine and I want to allow users
to draw on on a canvas and then I want box2d physics to act on the objects
the users have drawn.
I worked through these two tutorials and then played around with the
results a little bit:
http://net.tutsplus.com/tutorials/html-css-techniques/build-your-first-game-with-html5/
http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app/
So now I have a little drawing app as well as a physics based game. I have
no idea whatsoever how to combine this in any way.
I'd be very grateful if anyone had any sort of general pointers or advice
for me on how I would approach this.

Get Albumart in .mp3 file for Windows Store App

Get Albumart in .mp3 file for Windows Store App

How can i get the AlbumArt image in the mp3 file? I am developing Windows
Store app with c#.
MusicProperties class gives me Album name artist name vs. But it cant give
me albumart.

Python Script To Upload 300,000 files- Sqlite3 or massive list?

Python Script To Upload 300,000 files- Sqlite3 or massive list?

I am writing a script that will upload files to a cloud account. There
will be various directories containing the files, but only one
depth...there will be no nested/directories inside of directories. Each
directory will be a container in which the files will go in. Sometimes the
files may be as large as 300,000 files. I will be using multiprocessing.
I would like to keep track of the filenames, outoutput information,
returns codes using sqlite, so I had a few questions:
1) If I only had sqlite3 run in memory rather than as flat files(since I
only need the info untill I'm done with the script) would it bloat the
memory? 2) Would there be a major performance impact using sqlite3 as
opposed to keeping track with a massive list of lists or a dictionary of
lists?

Can I get an instance of a class that implements an interface?

Can I get an instance of a class that implements an interface?

I have this function:
/***
* Changes the windows panel and allows a state change
* you can also change the minimum window size
* */
public void changePanel(CBPanel panel){
mainFrame.setContentPane();
mainFrame.setMinimumSize(panel.getMinSize());
mainFrame.setResizable(panel.canResize());
}
It takes CBPanel as the only argument and CBPanel is interface that
generally will be implemented onto a JCOmponent. Is there any way I can
get an instance of the JComponent from interface class?
I call it like so
changePanel(new LoginPanel());
So logically, I should be able to get an instance of the LoginPanel,
right? I was wondering if it does using some kind of type declaration of
type cast?

Concatenate 2 letters with preg_replace and regex

Concatenate 2 letters with preg_replace and regex

I have a list of company names to process, and send to various places
after formatting. My current issue is the following :
Example lines
J C PENNEY CO INC
DOLLAR TREE INC
C H ROBINSON WORLDWIDE INC
GOOGLE INC
I would like to concatenate the single letters J C , and C H into JC and
CH, so the final result reads :
JC PENNEY CO INC
DOLLAR TREE INC
CH ROBINSON WORLDWIDE INC
GOOGLE INC
This should happen only at the beginning of the word. I have no problem
finding the pattern, with /^\w\s\w\s/, but how can I remove the space in
the middle? Thanks for your help!

Memory waste by postincrement/decrement

Memory waste by postincrement/decrement

Why is it so that memory is wasted when we use a post-increment/ decrement
operator as when the operator returns a temp it is de-allocated and memory
is freed up?

code restricting creation of more than one object in private constructor in C#

code restricting creation of more than one object in private constructor
in C#

I want to create a code in C# for Private constructor.I want that it
should allow only one object to be created but when I try to create more
than one a message showing " no more object can be created" should be
shown.I don't want to use static constructor in this code.

Friday, 13 September 2013

Can not run mongo command in terminal

Can not run mongo command in terminal

I installed mongoDB with a .tar in a certian directory and I can only run
mongo in that directory if i use
./mongo
Otherwise if i try to just use
mongo
The terminal will tell me that it is not installed. What should I do?

How to use String.startWith(..) to ignore leading whitespace?

How to use String.startWith(..) to ignore leading whitespace?

Let's say I have the following that start with "needle", ignoring leading
whitespace:
String haystack = "needle#####^&%#$^%...";
String haystackWithSpace = " needle******!@@#!@@%@%!$...";
I want to capture anything that starts with "needle" or "/s*needle"(if
there was a regex allowed). Is there an elegant way to do this without
calling .trim()? Or is there a way to make a regex work here? I want the
following to be true:
haystackWithSpace.startsWith("needle"); // doesn't ignore leading whitespace
haystackWithSpace.startsWith("/s*needle"); // doesn't work
Basically, is there a String s that will satisfy the following?:
haystack.startsWith(s) == haystackWithSpace.startsWith(s);

Our prof says for a double loop, T(n) is a*(n^2) + b*n + c. I think it's just a*(n^2). What's the exact answer?

Our prof says for a double loop, T(n) is a*(n^2) + b*n + c. I think it's
just a*(n^2). What's the exact answer?

This is the slide by our prof.
Example 4: Consider this simple program: 1: s = 0 2: for i = 1 to n do 3:
for j = 1 to n do 4: s= s+i+j 5:end for 6:end for` T(n) =? It's hard to
get the exact expression of T(n) even for this very simple program. We can
see: the loop iterates n2 times, and loop body takes constant number of
instructions. So T(n) = a*(n^2) + bn + c for some constants a, b, c.
Now here's what I think. Let's assume that the body loop takes constant
time 'a'. Then that itself will be looped over for a*(n^2) times. So, I
don't understand from where b*n + c comes! What's the actual answer?

Sqlite randomly slowing down on simple (but big) table on iOS

Sqlite randomly slowing down on simple (but big) table on iOS

I'm working on an enterprise sales app, for iPad, that uses Sqlite as its
internal database, and a strange behaviour recently showed up.
I have a huge table that is filled with information from several other
tables (sort of like a "materialized view"), which can contain over 2
million rows, depending on how the user is set up. When the user wants to
search for an item, the app performs a query on this huge table that has
an indexed column and on other columns that are used as filters and/or
metadata. I'll post the query and the basic idea below. Anyway, this query
usually returns in 2~3 seconds on an iPad 4th gen, no more than that, and
this is just fine. This table is dropped, re-created and filled every time
the user taps a button to synchronize his data with our server.
However, recently the same query in the same table (with no relevant
changes at all), randomly started to take 40~50 seconds. If you do the
same thing later, on the same device, with the same filters (or even
changing the filters!), the same query on the same table takes the 2~3
seconds again. I haven't found any specific situation that causes this
slowdown, the app is the only one running at that time. The device is not
the problem, we've seen this happen on at least 5 different iPads, one is
an iPad 3 and the others are iPads 4th gen.
I don't think it is some sort of caching, since the app does not cache
anything, and these times are rather random. Sometimes they take 40
seconds for 10 times in a row, then suddenly it starts to take only 2
seconds again, and the same thing the other way. The only thing that is
clear to me is that this slowdown only occurs after intensive use (1 - 2
days of work using the app), so I'm also having troubles to cause this
behaviour while debugging on the iPad I have with me.
What I've tried:
Attach Instruments to the process and check what resources are being used
during the slowdown. The app does INTENSIVE use of the iPad's 'disk'
(flash memory) during the whole time. I don't have the example to analyse
it again now, but I think the CPU usage was around 30%. The RAM usage is
stable at 90~100MB, which is normal for our app.
Run VACCUM on the db; - reduced ~50MB on a database I had as example.
Run ANALYZE on the db; - didn't see any improvements
Run REINDEX on the db; - seems to be helping a little, but it's not
solving the problem.
Kill the process and start over - nothing changes
The huge table is constructed as the following, and does NOT have any
foreign keys or other any other constraint:
CREATE TABLE FMV_CATALOG(
UNIQUE_ID TEXT,
PRODUCT_ID INTEGER,
<bunch of metadata/filtered columns - total of 20 columns>
);
And the query that is made to find the products is:
SELECT
PRODUCT_ID
,UNIQUE_ID
<all other required columns, ~20 columns>
FROM
FMV_CATALOG
WHERE
UNIQUE_ID = '<some id>_<other id>'
AND PRODUCT_NAME LIKE '%iPhone%'
<and other optional, rarely used, filters.>
I'm totally out of ideas, so any help will be appreciated.
Thanks!

How can i make my CSS class to fit my image size?

How can i make my CSS class to fit my image size?

Hi I have image of this size :
<span class="Col2">
<img src="../Content/Images/20_thumb.jpg" width="281" height="200"
border="0" alt="image" />
</span>
And I have this CSS style which I am applying over this image:
.listRowA {
border: 1px solid #fff;
}
.listRowAHover {
background-color: #F4E4E4;
border: 1px solid #fff;
}
My hover style :
.listPageCol {
padding:5px;
margin-right:75px;
cursor:pointer;
}
Here problem I am facing is when I hover my image I can see pointer and
background-color outside my image also.So how can I fix this to fit to my
image?

Thursday, 12 September 2013

AngularJS - How to write unit test case for ng-init directive?

AngularJS - How to write unit test case for ng-init directive?

I have ng-init set to call a function init in my controller scope.
<div ng-init="init('start')" ng-controller="ProgressController"></div>
My test suite is as below.
describe("Progress controller", function () {
var $scope = null;
var controller = null;
beforeEach(module('MyApp'));
beforeEach(inject(function ($rootScope, $controller) {
$scope = $rootScope.$new();
controller = $controller('ProgressController', {
$scope: $scope
});
}));
}
How do I include ng-init in my test case so that whenever the controller
is initialized, init function should be triggered?

Django: querying multiple types of objects

Django: querying multiple types of objects

I have a fairly basic model that allows users to create posts of different
'types'. There's currently a Text type and a Photo type that inherits from
a base 'Post' type.
I'm currently pulling TextPosts and PhotoPosts and chaining the two
QuerySets, but this seems like a bad idea.
Is there a way to simply query for both types of posts at once? The reason
I'm not using .filter() on Post itself is because I (presumably) don't
have any way of getting the TextPost or PhotoPost object from it (or do
I?)
PS: Does it make more sense to call it BasePost or Post if I'll never be
using Post by itself?
class Post(AutoDateTimeModel):
POST_TYPES = (
# Linkable Social Networks
('TEXT', 'Text'),
('PHOTO', 'Photo'),
('LINK', 'Link'),
)
post_type = models.ForeignKey(ContentType)
user = models.ForeignKey(User, blank=True, null=True)
interests = models.ManyToManyField(Interest, related_name='interests')
class Meta:
app_label = 'posts'
ordering = ('-created_at',)
def save(self, *args, **kwargs):
if not self.pk:
self.post_type = ContentType.objects.get_for_model(type(self))
# import pdb; pdb.set_trace()
super(Post, self).save(*args, **kwargs)
class TextPost(Post):
""" Text post model """
body = models.TextField()
class Meta:
app_label = 'posts'
class PhotoPost(Post):
""" Photo post model. This can contain multiple photos. """
description = models.TextField()
class Meta:
app_label = 'posts'
class Photo(models.Model):
""" Individual image model, used in photo posts. """
caption = models.TextField()
# source_url = models.URLField(blank=True, null=True)
image = ImageField(upload_to=upload_to)
post = models.ForeignKey(PhotoPost, blank=True, null=True,
related_name='photos')
user = models.ForeignKey(User, blank=True, null=True,
related_name='photos')
class Meta:
app_label = 'posts'
def __unicode__(self):
return 'Photo Object by: ' + str(self.user.get_full_name())

NullPointerException when running JUnit tests, saying interface is null

NullPointerException when running JUnit tests, saying interface is null

I'm trying to write a java program that allows the user to input a series
of data values then for the program to sort through finding the mean and
the median of that series, using an interface to "treat" different objects
as if they were the same. However when I run my JUnit test, it keeps
saying my interface is null.
NoiseFilter.java
package noisefilter.model;
import java.util.ArrayList;
public interface NoiseFilter {
public double getBestMesurement(ArrayList<Double> samples);
}
AveragingFilter.java
package noisefilter.model;
import java.util.ArrayList;
public class AveragingFilter implements NoiseFilter {
@Override
/**
* The method getBestMeasurement takes an array list of type double and
returns a
*/
public double getBestMesurement(ArrayList<Double> samples) {
// TODO Auto-generated method stub
if (samples.equals(null)) {
throw new IllegalArgumentException("The Samples cannot be null");
}
if (samples.size() < 3) {
throw new IllegalArgumentException("The Sample size must have 3");
}
double sum = 0.0;
for (Double number : samples) {
sum += number;
}
return (sum / samples.size());
}
}
SensorData.java
package noisefilter.model;
import java.util.ArrayList;
public class SensorData implements NoiseFilter {
ArrayList<Double> data;
NoiseFilter filter;
public SensorData() {
this.data = new ArrayList<Double>();
this.filter = null;
}
public void addSample(double sample) {
data.add(sample);
}
public void setFilter(NoiseFilter filterVar) {
this.filter = filterVar;
}
public double getFilteredResult() {
if (filter.equals(null)) {
throw new IllegalStateException("The filter cannot be left null");
}
return filter.getBestMesurement(data);
}
@Override
public double getBestMesurement(ArrayList<Double> samples) {
samples = this.data;
return 0;
}
WhenAveragingFilter.java (JUnit Test)
package noisefilter.tests;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import noisefilter.model.NoiseFilter;
import noisefilter.model.SensorData;
public class WhenAverageFiltering {
NoiseFilter filter;
SensorData dataSet;
@Before
public void setUp() throws Exception {
this.dataSet = new SensorData();
dataSet.setFilter(filter);
}
@Test
public void averageOfThree100sShouldBe100() {
dataSet.addSample(100);
dataSet.addSample(100);
dataSet.addSample(100);
assertTrue(dataSet.getFilteredResult() == 100);
}
@Test
public void averageOfThreeDifferent() {
dataSet.addSample(120);
dataSet.addSample(140);
dataSet.addSample(130);
assertTrue(dataSet.getFilteredResult() == 130);
}
@Test
public void averageOfFiveDifferent() {
dataSet.addSample(10);
dataSet.addSample(50);
dataSet.addSample(60);
assertTrue(dataSet.getFilteredResult() == 40);
}
}
Here's the errors that I get when I run the JUnit Test.
java.lang.NullPointerException
at noisefilter.model.SensorData.getFilteredResult(SensorData.java:24)
at
noisefilter.tests.WhenAverageFiltering.averageOfFiveDifferent(WhenAverageFiltering.java:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at
org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at
org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

plot in the x-axis a rotate labels in R

plot in the x-axis a rotate labels in R

I've to plot these data:
day temperature
02/01/2012 13:30:00 10
10/01/2012 20:30:00 8
15/01/2012 13:30:00 12
25/01/2012 20:30:00 6
02/02/2012 13:30:00 5
10/02/2012 20:30:00 3
15/02/2012 13:30:00 6
25/02/2012 20:30:00 -1
02/03/2012 13:30:00 4
10/03/2012 20:30:00 -2
15/03/2012 13:30:00 7
25/03/2012 20:30:00 1
in the x-axis I want to label only the month and the day (e.g. Jan 02 )
rotating of 45 degree. How can I do this using the command plot()?

Simple SOAP progam

Simple SOAP progam

I have to do a simple scritp (unix/linux target) to close log_file of a
print spooler program
the spooler program give the chances to call the function over soap, but I
know nothing of it
this is the function:
- <!-- VPSX System Close Account file Command request
-->
- <message name="VPSX_SystemCloseAcct">
<part name="SessID" type="xsd:string" />
<part name="VPSID" type="xsd:string" />
</message>
- <!-- VPSX System close account file Command request/response
-->
- <operation name="VPSX_SystemCloseAcct">
<input message="lrs:VPSX_SystemCloseAcct" />
<output message="lrs:VPSX_SystemCmdResponse" />
</operation>
<!-- VPSX System close account file Command request/response
-->
- <operation name="VPSX_SystemCloseAcct">
<soap:operation soapAction="" />
- <input>
<soap:body use="encoded" namespace="http://www.lrs.com"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</input>
- <output>
<soap:body use="encoded" namespace="http://www.lrs.com"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
</operation>
is there a simple way (python?php?java?) to do this?

What is the role of a default constructor exactly?

What is the role of a default constructor exactly?

From Thinking in C++
The first hidden argument to the constructor is the this pointer. this
pointer holds the address of the caller object. In the case of constructor
this pointer points towards an uninitialized block of memory. It is the
job of the constructor to initialize this block of memory properly.
So, basically, the constructor is used to get a pointer to the object's
space in RAM? Is that correct?
How does the default constructor initialize that memory? Does it get
initialized to zero?

Wednesday, 11 September 2013

Detecting if rectangles (buttons) overlap on x or y axis

Detecting if rectangles (buttons) overlap on x or y axis

I am currently trying to develop a prototype in android where the user is
able to drag 4 separate buttons around the screen.
The trouble I am having is with collision detection. If one of the buttons
is alongside another, for example, only movement along the Y axis should
be permitted. Similarly, if one of the buttons is touching the top or
bottom of another button, only movement along the X axis should be
allowed.
Something like
for (TouchButton t:myButtons)
{
if(!(t.equals(b)))
{
if((b.getY() >= t.getY() && (b.getY() <= (t.getY() +
t.getMeasuredHeight()))))
{
if((b.getX() >= t.getX() && (b.getX() <= (t.getX() +
t.getMeasuredWidth()))))
{
//dont move
}
}
}
should be able to detect if the buttons are touching across both axis? But
how do I determine if it should then be possible to slide up or across the
object?

iOS ARC: When and which memory stays alive

iOS ARC: When and which memory stays alive

Say I have a custom NSObject class called customClass with a property
NSMutableArray *thisArray;
I instantiate customClass *instance = [[customClass alloc] init] in my
root view controller. Somewhere in the the customClass implementation
thisArray is set.
Now I have a property in my root view controller NSMutableArray
(strong,nonatomic) *anotherArray and I set it via anotherArray =
customClass.thisArray. If I then set customClass to nil, will anotherArray
still point to an object in memory or is / should it be destroyed? What
about the rest of the object and its properties memory?

Values retrieved using JS localStorage differs in PHP

Values retrieved using JS localStorage differs in PHP

Below is the php code which would take the session variables using JS.The
values retrieved are correct but mysql query returns zero.But if i
hardcode the same values the mysql query is passing.Appreciate your
help.Thanks in advance.Below is the code. test.php
$msessionEmail =
"<script>document.write(localStorage.getItem(\"sessionEmailID\"));</script>";//Retrieves
"hello@test.com"
$msessionPassword =
"<script>document.write(localStorage.getItem(\"sessionPassword\"));</script>";//Retrieves
"test"
$sessionEmail="hello@test.com";
$sessionPassword="test";
echo gettype($msessionEmail);//it is string
echo gettype($sessionEmail);//it is string
echo $msessionEmail;//hello@test.com
echo $sessionEmail;//hello@test.com
if($msessionEmail==$sessionEmail)
{
echo "equal";
}
else
{
echo "not equal";//This gets printed but their values are same.
}

Not saved image when creating content on Drupal 6

Not saved image when creating content on Drupal 6

this problem: In the form of adding material has fields with images.
Choose a file, click download, the file is loaded, the image is displayed.
Others fill in the form and add material. The material is added, it's
fine, but that's only the images are not stored. But after editing, all
the images are stored properly. That is, the problem only by adding
material. I watched the logs of Drupal (admin/reports/dblog), while adding
no error pops up. In what could be the problem? How can I solve it?
Thank you. Sorry for my bad English.

Android black box testing tool

Android black box testing tool

I am searching for a tool/software for black box testing of android apps.
I researched for some of them-Robotium, Calabash. But these tools require
access to the source codes. Also the tool should be free and opensource
for use.

Trying to merge a COUNT query in to an existing SELECT query

Trying to merge a COUNT query in to an existing SELECT query

I'm stuck trying to merge a COUNT query in to an existing SELECT query
that I have.
Currently, I use this SELECT statement to fetch some contact info:
SELECT contact.id_contact, contact.cname, contact.cemail,
contact.trading_id, trading_name.trading_name
FROM contact
INNER JOIN trading_name ON contact.trading_id = trading_name.id_trading_name
WHERE (CHAR_LENGTH(contact.cname) > 0)
ORDER BY contact.cname
I also have this COUNT query which I need to somehow include in to the
same SELECT statement:
SELECT COUNT(AlertID) AS CustomerAlertCountTotal FROM
customer_support_dev.customer_alerts WHERE (AlertTradingID = @tradingid)
Basically I need to know how many 'AlertIDs' there are for each
'trading_name', and for that value to be returned in
'CustomerAlertCountTotal' - but by using just one query.
(If it makes a difference, I'm using a MySQL database)
Hope that makes sense :)