Trigger is not working and value not auto selected
Trigger is not working and state value not auto selected from state drop
down. I have form and onchange event fill listing information into
country,state..etc in that form. state is by default hidden field and
populate upon change in country field. customField are form field
jr_country, jr_state..etc
for (customField in ui.item) {
if (customField == 'value' || customField == 'label') continue;
if (ui.item[customField] == null || ui.item[customField] == ''
|| ui.item[customField] == 'undefined') continue;
try{
var fieldObject =
jQuery('#jr-form-listing').find('.'+customField);
if(fieldObject.is('input')){
var fieldType = fieldObject.attr('type');
switch (fieldType) {
// radio buttons
case 'radio':
jQuery(fieldObject.selector + '[value=' +
ui.item[customField].replace(/\*/g,'') +
']').click();
break;
// text and other types
default:
fieldObject.val(ui.item[customField]);
break;
}
} else if(fieldObject.is('select')) {
jQuery(fieldObject.selector + ' option[value=' +
ui.item[customField].replace(/\*/g,'') +
']').attr('selected', 'selected');
}
fieldObject.trigger('change');
} catch(err){
//alert(customField); // show error field name
}
}
}
Thursday, 3 October 2013
Wednesday, 2 October 2013
Ant: NoClassDefFound exception
Ant: NoClassDefFound exception
I am developing a java project. My instructor wants us to strictly use
apache ant for compilation. I knew nothing about it, and don't know about
apache ant either. I have generated an ant buildfile and edited that for
target "run", so that program will run after ant run command.
I am getting following error,
Exception in thread "main" java.lang.NoClassDefFoundError: src/Client
[java] Caused by: java.lang.ClassNotFoundException: src.Client
[java] at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
[java] at java.security.AccessController.doPrivileged(Native Method)
[java] at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
[java] at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
[java] at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
[java] at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
[java] Could not find the main class: src.Client. Program will exit.
I think I have resolved all the target dependencies. But still this error
persists.
Can somebody help me? This is my ant build.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- WARNING: Eclipse auto-generated file.
Any modifications will be overwritten.
To include a user specific buildfile here, simply create one
in the same
directory with the processing instruction
<?eclipse.ant.import?>
as the first entry and export the buildfile again. -->
<project basedir="." default="build" name="client">
<property environment="env"/>
<property name="ECLIPSE_HOME" value="../../../../usr/lib/eclipse"/>
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.6"/>
<property name="source" value="1.6"/>
<path id="client.classpath">
<pathelement location="bin"/>
<pathelement location="libthrift-1.0.0-javadoc.jar"/>
<pathelement location="libthrift-1.0.0.jar"/>
<pathelement location="log4j-1.2.14.jar"/>
<pathelement location="slf4j-api-1.5.8.jar"/>
<pathelement location="slf4j-log4j12-1.5.8.jar"/>
</path>
<target name="init">
<mkdir dir="bin"/>
<mkdir dir="build"/>
<copy includeemptydirs="false" todir="bin">
<fileset dir="src">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
<target name="clean">
<delete dir="bin"/>
</target>
<target depends="clean" name="cleanall"/>
<target depends="build-subprojects,build-project" name="build"/>
<target name="build-subprojects"/>
<target depends="init" name="build-project">
<echo message="${ant.project.name}: ${ant.file}"/>
<javac debug="true" debuglevel="${debuglevel}" destdir="bin"
source="${source}" target="${target}">
<src path="src"/>
<classpath refid="client.classpath"/>
</javac>
</target>
<target name="jar" depends="init">
<mkdir dir="build/jar" />
<jar destfile="client.jar" basedir="bin">
<manifest>
<attribute name="Main-Class" value="src.Client" />
</manifest>
</jar>
</target>
<target description="Build all projects which reference this project.
Useful to propagate changes." name="build-refprojects"/>
<target description="copy Eclipse compiler jars to ant lib directory"
name="init-eclipse-compiler">
<copy todir="${ant.library.dir}">
<fileset dir="${ECLIPSE_HOME}/plugins"
includes="org.eclipse.jdt.core_*.jar"/>
</copy>
<unzip dest="${ant.library.dir}">
<patternset includes="jdtCompilerAdapter.jar"/>
<fileset dir="${ECLIPSE_HOME}/plugins"
includes="org.eclipse.jdt.core_*.jar"/>
</unzip>
</target>
<target description="compile project with Eclipse compiler"
name="build-eclipse-compiler">
<property name="build.compiler"
value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
<antcall target="build"/>
</target>
<target name="Client">
<java classname="Client" failonerror="true" fork="yes">
<classpath refid="client.classpath"/>
</java>
</target>
<target name="run" depends="jar">
<java jar="client.jar" fork="true">
</java>
</target>
</project>
Can anybody spot the mistake for me?
I am developing a java project. My instructor wants us to strictly use
apache ant for compilation. I knew nothing about it, and don't know about
apache ant either. I have generated an ant buildfile and edited that for
target "run", so that program will run after ant run command.
I am getting following error,
Exception in thread "main" java.lang.NoClassDefFoundError: src/Client
[java] Caused by: java.lang.ClassNotFoundException: src.Client
[java] at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
[java] at java.security.AccessController.doPrivileged(Native Method)
[java] at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
[java] at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
[java] at
sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
[java] at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
[java] Could not find the main class: src.Client. Program will exit.
I think I have resolved all the target dependencies. But still this error
persists.
Can somebody help me? This is my ant build.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- WARNING: Eclipse auto-generated file.
Any modifications will be overwritten.
To include a user specific buildfile here, simply create one
in the same
directory with the processing instruction
<?eclipse.ant.import?>
as the first entry and export the buildfile again. -->
<project basedir="." default="build" name="client">
<property environment="env"/>
<property name="ECLIPSE_HOME" value="../../../../usr/lib/eclipse"/>
<property name="debuglevel" value="source,lines,vars"/>
<property name="target" value="1.6"/>
<property name="source" value="1.6"/>
<path id="client.classpath">
<pathelement location="bin"/>
<pathelement location="libthrift-1.0.0-javadoc.jar"/>
<pathelement location="libthrift-1.0.0.jar"/>
<pathelement location="log4j-1.2.14.jar"/>
<pathelement location="slf4j-api-1.5.8.jar"/>
<pathelement location="slf4j-log4j12-1.5.8.jar"/>
</path>
<target name="init">
<mkdir dir="bin"/>
<mkdir dir="build"/>
<copy includeemptydirs="false" todir="bin">
<fileset dir="src">
<exclude name="**/*.java"/>
</fileset>
</copy>
</target>
<target name="clean">
<delete dir="bin"/>
</target>
<target depends="clean" name="cleanall"/>
<target depends="build-subprojects,build-project" name="build"/>
<target name="build-subprojects"/>
<target depends="init" name="build-project">
<echo message="${ant.project.name}: ${ant.file}"/>
<javac debug="true" debuglevel="${debuglevel}" destdir="bin"
source="${source}" target="${target}">
<src path="src"/>
<classpath refid="client.classpath"/>
</javac>
</target>
<target name="jar" depends="init">
<mkdir dir="build/jar" />
<jar destfile="client.jar" basedir="bin">
<manifest>
<attribute name="Main-Class" value="src.Client" />
</manifest>
</jar>
</target>
<target description="Build all projects which reference this project.
Useful to propagate changes." name="build-refprojects"/>
<target description="copy Eclipse compiler jars to ant lib directory"
name="init-eclipse-compiler">
<copy todir="${ant.library.dir}">
<fileset dir="${ECLIPSE_HOME}/plugins"
includes="org.eclipse.jdt.core_*.jar"/>
</copy>
<unzip dest="${ant.library.dir}">
<patternset includes="jdtCompilerAdapter.jar"/>
<fileset dir="${ECLIPSE_HOME}/plugins"
includes="org.eclipse.jdt.core_*.jar"/>
</unzip>
</target>
<target description="compile project with Eclipse compiler"
name="build-eclipse-compiler">
<property name="build.compiler"
value="org.eclipse.jdt.core.JDTCompilerAdapter"/>
<antcall target="build"/>
</target>
<target name="Client">
<java classname="Client" failonerror="true" fork="yes">
<classpath refid="client.classpath"/>
</java>
</target>
<target name="run" depends="jar">
<java jar="client.jar" fork="true">
</java>
</target>
</project>
Can anybody spot the mistake for me?
Sound effects library
Sound effects library
I am trying to add some Audio effect to a stream. namely Echo and Chorus.
I can't find any library that can allow me to add effects to sound. Does
anyone know about any good library?
Google didn't help much :-(
I am trying to add some Audio effect to a stream. namely Echo and Chorus.
I can't find any library that can allow me to add effects to sound. Does
anyone know about any good library?
Google didn't help much :-(
Apply border to uiBarButtonItem in ios7
Apply border to uiBarButtonItem in ios7
I have seen UIBarButtonItem,UIButtons are borderless in ios7.But I want to
have the appearance of UIBarButtonItem like in <=ios6.At the same time I
cannot apply a particular backgroundimage because navigationbar tint
colour changes from some set of views to other views. How can I set
borderstyle in [UIBarButtonItem appearance] may be by using some CALayer
properties or so ..?
Any help would be appreciated..
I have seen UIBarButtonItem,UIButtons are borderless in ios7.But I want to
have the appearance of UIBarButtonItem like in <=ios6.At the same time I
cannot apply a particular backgroundimage because navigationbar tint
colour changes from some set of views to other views. How can I set
borderstyle in [UIBarButtonItem appearance] may be by using some CALayer
properties or so ..?
Any help would be appreciated..
Tuesday, 1 October 2013
open specific part of table of contents of chm file c# or vb.net
open specific part of table of contents of chm file c# or vb.net
I have a .chm file called help, In that file I have a structure like:
Introduction
-item1
-item2
Topic1
-item1
-item2
Topic2
-item1
-item2
Topic3
Now I want to open Topic1 inside c# or vb.net I have tried:
Help.ShowHelp(ParentForm, "Help.chm", HelpNavigator.Index, "Topic1")
Help.ShowHelp(ParentForm, "Help.chm", HelpNavigator.TableOfContents,
"Topic1")
but is not working, then I tried to give inside chm file an index to
Topic1 (31) and tried:
Help.ShowHelp(ParentForm, "Help.chm", HelpNavigator.Index, "31")
Help.ShowHelp(ParentForm, "Help.chm", HelpNavigator.Index, "Item1")
It gives execption, only working code is:
Help.ShowHelp(ParentForm, "Help.chm", HelpNavigator.TableOfContents,
Nothing)
How to open Topic1 ?
I have a .chm file called help, In that file I have a structure like:
Introduction
-item1
-item2
Topic1
-item1
-item2
Topic2
-item1
-item2
Topic3
Now I want to open Topic1 inside c# or vb.net I have tried:
Help.ShowHelp(ParentForm, "Help.chm", HelpNavigator.Index, "Topic1")
Help.ShowHelp(ParentForm, "Help.chm", HelpNavigator.TableOfContents,
"Topic1")
but is not working, then I tried to give inside chm file an index to
Topic1 (31) and tried:
Help.ShowHelp(ParentForm, "Help.chm", HelpNavigator.Index, "31")
Help.ShowHelp(ParentForm, "Help.chm", HelpNavigator.Index, "Item1")
It gives execption, only working code is:
Help.ShowHelp(ParentForm, "Help.chm", HelpNavigator.TableOfContents,
Nothing)
How to open Topic1 ?
What would the perl commands be for this script?
What would the perl commands be for this script?
I have a short bash script that finds the release ID in /etc/os-release,
and prints a string based on that result. I would like to convert it to
perl, if possible. I'll appreciate any help with this.
Here is the script that I'm using:
#!/bin/bash
grep "ID=fedora" /etc/os-release > /dev/null 2>&1
if [ $? = 0 ]; then
echo "You are running Fedora"
else
echo "You are running Ubuntu"
fi
Thanks, and have a great day.:) Patrick.
I have a short bash script that finds the release ID in /etc/os-release,
and prints a string based on that result. I would like to convert it to
perl, if possible. I'll appreciate any help with this.
Here is the script that I'm using:
#!/bin/bash
grep "ID=fedora" /etc/os-release > /dev/null 2>&1
if [ $? = 0 ]; then
echo "You are running Fedora"
else
echo "You are running Ubuntu"
fi
Thanks, and have a great day.:) Patrick.
Windows Deployment Server Answer Files for PC's with RAID Controllers
Windows Deployment Server Answer Files for PC's with RAID Controllers
I currently have a Windows Deployment Server running on Windows Server
2008 R2 Standard, and so far it has worked without any issues. I am able
to capture and deploy images to the majority of the computers my company
maintains.
However, we just began ordering new Dell Precision T3600 PC's that come
with RAID controllers. At first when we tried applying one of our images
to the machine, it did not detect the hard drive. Simple enough fix, I
injected the correct drivers to my boot images and install images. But now
when I try to apply an image to one of these RAID controller pcs, it tells
me that I do not have enough space on the partition to install Windows:
Windows cannot be installed to the selected partition. Installation requires
at least 15199 MB of free space. To install Windows, free up additional space
and restart the installation.
I have spoken to a few people about the issue and some theories are that
it is following a deprecated Windows NT rule and creating 2gb partitions,
or that PC's with a RAID configuration require special switches in the
answer file.
Here is the DiskConfiguration section of my answer file (the part I
believe to be in question):
<DiskConfiguration>
<Disk wcm:action="add">
<WillWipeDisk>true</WillWipeDisk>
<CreatePartitions>
<CreatePartition wcm:action="add">
<Order>1</Order>
<Type>Primary</Type>
</CreatePartition>
</CreatePartitions>
<ModifyPartitions>
<ModifyPartition wcm:action="add">
<Active>true</Active>
<Extend>false</Extend>
<Format>NTFS</Format>
<Label>Local Disk</Label>
<Letter>C</Letter>
<Order>1</Order>
<PartitionID>1</PartitionID>
</ModifyPartition>
</ModifyPartitions>
<DiskID>0</DiskID>
</Disk>
<WillShowUI>OnError</WillShowUI>
</DiskConfiguration>
I have tried change the 'Extend' field to True, the 'Modify Partition
wcm:action' field to Modify, and changed the order of the Create and
Modify partition trees. I have also tried completely removing the RAID
controller from the PC, but I then receive an error about being unable to
read my answer files element
Does anyone have any insight to if I need special conditions when
deploying to a raid configuration? I have scoured through a ton of TechNet
articles on the subject, and I believe I have the correct configuration,
but I have been unable to find any documentation for issues with RAID
configurations
When deploying to a machine without a RAID configuration, the answer file
works perfectly.
After messing around with some more answer file flags, I decided to take a
look at what it is actually doing to the partitions on the drive. With my
current answer file the drives end up like this:
Disk 1 Partition 1: Local Disk - 100.00MB - System
Disk 1 Partition 2 - 232.30GB - Primary
So it looks like it's trying to install on the smaller partition, so I
either need to make that one larger, reduce the install to one partition,
or install to the second partition. Would any of these be acceptable
workarounds?
Thank you for looking into my question, let me know if you need any
additional information.
I currently have a Windows Deployment Server running on Windows Server
2008 R2 Standard, and so far it has worked without any issues. I am able
to capture and deploy images to the majority of the computers my company
maintains.
However, we just began ordering new Dell Precision T3600 PC's that come
with RAID controllers. At first when we tried applying one of our images
to the machine, it did not detect the hard drive. Simple enough fix, I
injected the correct drivers to my boot images and install images. But now
when I try to apply an image to one of these RAID controller pcs, it tells
me that I do not have enough space on the partition to install Windows:
Windows cannot be installed to the selected partition. Installation requires
at least 15199 MB of free space. To install Windows, free up additional space
and restart the installation.
I have spoken to a few people about the issue and some theories are that
it is following a deprecated Windows NT rule and creating 2gb partitions,
or that PC's with a RAID configuration require special switches in the
answer file.
Here is the DiskConfiguration section of my answer file (the part I
believe to be in question):
<DiskConfiguration>
<Disk wcm:action="add">
<WillWipeDisk>true</WillWipeDisk>
<CreatePartitions>
<CreatePartition wcm:action="add">
<Order>1</Order>
<Type>Primary</Type>
</CreatePartition>
</CreatePartitions>
<ModifyPartitions>
<ModifyPartition wcm:action="add">
<Active>true</Active>
<Extend>false</Extend>
<Format>NTFS</Format>
<Label>Local Disk</Label>
<Letter>C</Letter>
<Order>1</Order>
<PartitionID>1</PartitionID>
</ModifyPartition>
</ModifyPartitions>
<DiskID>0</DiskID>
</Disk>
<WillShowUI>OnError</WillShowUI>
</DiskConfiguration>
I have tried change the 'Extend' field to True, the 'Modify Partition
wcm:action' field to Modify, and changed the order of the Create and
Modify partition trees. I have also tried completely removing the RAID
controller from the PC, but I then receive an error about being unable to
read my answer files element
Does anyone have any insight to if I need special conditions when
deploying to a raid configuration? I have scoured through a ton of TechNet
articles on the subject, and I believe I have the correct configuration,
but I have been unable to find any documentation for issues with RAID
configurations
When deploying to a machine without a RAID configuration, the answer file
works perfectly.
After messing around with some more answer file flags, I decided to take a
look at what it is actually doing to the partitions on the drive. With my
current answer file the drives end up like this:
Disk 1 Partition 1: Local Disk - 100.00MB - System
Disk 1 Partition 2 - 232.30GB - Primary
So it looks like it's trying to install on the smaller partition, so I
either need to make that one larger, reduce the install to one partition,
or install to the second partition. Would any of these be acceptable
workarounds?
Thank you for looking into my question, let me know if you need any
additional information.
How can I make (some) $money$ out of my TeX skills=?iso-8859-1?Q?=3F_=96_tex.stackexchange.com?=
How can I make (some) $money$ out of my TeX skills? – tex.stackexchange.com
I by no means intend to stop contributing what I can to TeX.SE, but a
recent experience begs the question... After helping a friend designing a
flyer for a telecom company (for which she got decent …
I by no means intend to stop contributing what I can to TeX.SE, but a
recent experience begs the question... After helping a friend designing a
flyer for a telecom company (for which she got decent …
Monday, 30 September 2013
Show that the determinant of $A$ is equal to the product of its eigenvalues. math.stackexchange.com
Show that the determinant of $A$ is equal to the product of its
eigenvalues. – math.stackexchange.com
Show that the determinant of $A$ is equal to the product of its
eigenvalues $\lambda_i$. So I'm having a tough time figuring this one out.
I know that I have to work with the characteristic ...
eigenvalues. – math.stackexchange.com
Show that the determinant of $A$ is equal to the product of its
eigenvalues $\lambda_i$. So I'm having a tough time figuring this one out.
I know that I have to work with the characteristic ...
Ubuntu dual boot with Windows 8 installation problem
Ubuntu dual boot with Windows 8 installation problem
Dell 7440
256 G SSD HD
4 G RAM
windows 8
I'm trying to install 12.04 side by side.
I altered the BIOS, created the USB stick which allowed me to "try" with
success. Installation was another story. I am unable to install side by
side - have followed the instructions at:
http://www.ubuntu.com/download/desktop/install-desktop-long-term-support
http://www.ubuntu.com/download/desktop/create-a-usb-stick-on-windows
https://help.ubuntu.com/community/UEFI
I am not using secure boot, have disabled Windows 8 fast start and am
running legacy not UEFI across the board...
I have run boot repair three times (I tried disabling additional stuff in
BIOS):
http://paste.ubuntu.com/6173133
http://paste.ubuntu.com/6173179
http://paste.ubuntu.com/6173267
any thoughts?
Dell 7440
256 G SSD HD
4 G RAM
windows 8
I'm trying to install 12.04 side by side.
I altered the BIOS, created the USB stick which allowed me to "try" with
success. Installation was another story. I am unable to install side by
side - have followed the instructions at:
http://www.ubuntu.com/download/desktop/install-desktop-long-term-support
http://www.ubuntu.com/download/desktop/create-a-usb-stick-on-windows
https://help.ubuntu.com/community/UEFI
I am not using secure boot, have disabled Windows 8 fast start and am
running legacy not UEFI across the board...
I have run boot repair three times (I tried disabling additional stuff in
BIOS):
http://paste.ubuntu.com/6173133
http://paste.ubuntu.com/6173179
http://paste.ubuntu.com/6173267
any thoughts?
image loading in c++ using opengl
image loading in c++ using opengl
I am trying to develop a mario game using openGL in c++ and i searched for
codes that could load image(.png, .bmp or .jpg) in the console but could
find none. It would be appreciable if you help me with the code. I don't
want any search engines for loading. Is it a must that the image has to be
textured to load it?
I am trying to develop a mario game using openGL in c++ and i searched for
codes that could load image(.png, .bmp or .jpg) in the console but could
find none. It would be appreciable if you help me with the code. I don't
want any search engines for loading. Is it a must that the image has to be
textured to load it?
RemovalListener callback in guava caching api does not work correctly
RemovalListener callback in guava caching api does not work correctly
I write following codes for test cache expiretion with using guava caching
support. in following code i create a cache, add 20 entry to it from key
11000 to 30000, after some sleep traverse exist keies in cache and search
for two key (19000 and 29000)
import com.google.common.cache.*;
import java.util.concurrent.TimeUnit;
public class TestGuavaCache {
public static int evictCount = 0;
public static void main(String[] args) throws InterruptedException {
Cache<Integer, Record> myCache = CacheBuilder.newBuilder()
.expireAfterAccess(10, TimeUnit.SECONDS)
.expireAfterWrite(15, TimeUnit.SECONDS)
.concurrencyLevel(4)
.maximumSize(100)
.removalListener(new RemovalListener<Object, Object>() {
@Override
public void onRemoval(RemovalNotification<Object, Object>
notification) {
evictCount++;
System.out.println(evictCount + "th removed key >> " +
notification.getKey()
+ " with cause " + notification.getCause());
}
})
.recordStats()
.build();
int nextKey = 10000;
for (int i = 0; i < 20; i++) {
nextKey = nextKey + 1000;
myCache.put(nextKey, new Record(nextKey, i + " >> " + nextKey));
Thread.sleep(1000);
}
System.out.println("=============================");
System.out.println("now go to sleep for 20 second");
Thread.sleep(20000);
System.out.println("myCache.size() = " + myCache.size());
for (Integer key : myCache.asMap().keySet()) {
System.out.println("next exist key in cache is" + key);
}
System.out.println("search for key " + 19000 + " : " +
myCache.getIfPresent(19000));
System.out.println("search for key " + 29000 + " : " +
myCache.getIfPresent(29000));
}
}
class Record {
int key;
String value;
Record(int key, String value) {
this.key = key;
this.value = value;
}
}
After running above main method i see following result
1th removed key >> 11000 with cause EXPIRED
2th removed key >> 13000 with cause EXPIRED
3th removed key >> 12000 with cause EXPIRED
4th removed key >> 15000 with cause EXPIRED
5th removed key >> 14000 with cause EXPIRED
6th removed key >> 16000 with cause EXPIRED
7th removed key >> 18000 with cause EXPIRED
8th removed key >> 20000 with cause EXPIRED
=============================
now go to sleep for 20 second
myCache.size() = 12
search for key 19000 : null
search for key 29000 : null
I have 3 Question
why others key similar 17000,19000,25000 does not notified in RemovalListener
why iteration on cache keyset is empty while cache size is 12
why search for 19000 and 29000 is null while cache size is 12
I write following codes for test cache expiretion with using guava caching
support. in following code i create a cache, add 20 entry to it from key
11000 to 30000, after some sleep traverse exist keies in cache and search
for two key (19000 and 29000)
import com.google.common.cache.*;
import java.util.concurrent.TimeUnit;
public class TestGuavaCache {
public static int evictCount = 0;
public static void main(String[] args) throws InterruptedException {
Cache<Integer, Record> myCache = CacheBuilder.newBuilder()
.expireAfterAccess(10, TimeUnit.SECONDS)
.expireAfterWrite(15, TimeUnit.SECONDS)
.concurrencyLevel(4)
.maximumSize(100)
.removalListener(new RemovalListener<Object, Object>() {
@Override
public void onRemoval(RemovalNotification<Object, Object>
notification) {
evictCount++;
System.out.println(evictCount + "th removed key >> " +
notification.getKey()
+ " with cause " + notification.getCause());
}
})
.recordStats()
.build();
int nextKey = 10000;
for (int i = 0; i < 20; i++) {
nextKey = nextKey + 1000;
myCache.put(nextKey, new Record(nextKey, i + " >> " + nextKey));
Thread.sleep(1000);
}
System.out.println("=============================");
System.out.println("now go to sleep for 20 second");
Thread.sleep(20000);
System.out.println("myCache.size() = " + myCache.size());
for (Integer key : myCache.asMap().keySet()) {
System.out.println("next exist key in cache is" + key);
}
System.out.println("search for key " + 19000 + " : " +
myCache.getIfPresent(19000));
System.out.println("search for key " + 29000 + " : " +
myCache.getIfPresent(29000));
}
}
class Record {
int key;
String value;
Record(int key, String value) {
this.key = key;
this.value = value;
}
}
After running above main method i see following result
1th removed key >> 11000 with cause EXPIRED
2th removed key >> 13000 with cause EXPIRED
3th removed key >> 12000 with cause EXPIRED
4th removed key >> 15000 with cause EXPIRED
5th removed key >> 14000 with cause EXPIRED
6th removed key >> 16000 with cause EXPIRED
7th removed key >> 18000 with cause EXPIRED
8th removed key >> 20000 with cause EXPIRED
=============================
now go to sleep for 20 second
myCache.size() = 12
search for key 19000 : null
search for key 29000 : null
I have 3 Question
why others key similar 17000,19000,25000 does not notified in RemovalListener
why iteration on cache keyset is empty while cache size is 12
why search for 19000 and 29000 is null while cache size is 12
Sunday, 29 September 2013
gets() not taking input
gets() not taking input
I have some college work and as i noticed that the gets() is not working
but i can't figure out why.
I tried putting getch() and getchar() before gets() but there is something
else wrong.
When i write a code implementing gets() before do-while (labeled -----> 3)
it works!!!
Can somebody help me?
#include<iostream>
#include<stdio.h>
#include<conio.h>
using namespace std;
class student
{
int rollNo;
char department[20];
int year;
int semester;
public:
student()
{
rollNo=0;
year=0;
semester=0;
}
void getData();
void promote();
void changeDepartment();
void display();
};
void student::changeDepartment()
{
if(rollNo!=0)
{
cout<<"\nEnter the new Department\n";
gets(department); -------------->1
}
else
{
cout<<"\nStudent not confirmed\n";
}
}
void student::getData()
{
cout<<"\nEnter the roll no\n";
cin>>rollNo;
cout<<"\nEnter the year\n";
cin>>year;
cout<<"\nEnter the semester\n";
cin>>semester;
cout<<"\nEnter the department\n";
gets(department); ----------------> 2
}
void student::promote()
{
if(rollNo!=0)
{
semester+=1;
if(semester%2==1)
{
year+=1;
}
}
else
{
cout<<"\nStudent not confirmed\n";
}
}
void student::display()
{
if(rollNo!=0)
{
cout<<"\nRoll No : "<<rollNo;
cout<<"\nYear : "<<year;
cout<<"\nSemester : "<<semester;
cout<<"\nDepartment : "<<department;
}
else
{
cout<<"\nStudent not confirmed";
}
}
int main()
{
student s;
int ch;
char choice;
----------------> 3
do
{
cout<<"\nMain Menu";
cout<<"\n1. Enter student details";
cout<<"\n2. Change department of student ";
cout<<"\n3. Promote student ";
cout<<"\n4. Display student details ";
cout<<"\nEnter your choice ";
cin>>ch;
switch(ch)
{
case 1 : s.getData();
s.display();
break;
case 2 : s.changeDepartment();
s.display();
break;
case 3 : s.promote();
s.display();
break;
case 4 : s.display();
break;
}
cout<<"\nDo you want to continue? (Y/n)\n";
cin>>choice;
}while((choice=='y')||(choice=='Y'));
return(0);
}
I have some college work and as i noticed that the gets() is not working
but i can't figure out why.
I tried putting getch() and getchar() before gets() but there is something
else wrong.
When i write a code implementing gets() before do-while (labeled -----> 3)
it works!!!
Can somebody help me?
#include<iostream>
#include<stdio.h>
#include<conio.h>
using namespace std;
class student
{
int rollNo;
char department[20];
int year;
int semester;
public:
student()
{
rollNo=0;
year=0;
semester=0;
}
void getData();
void promote();
void changeDepartment();
void display();
};
void student::changeDepartment()
{
if(rollNo!=0)
{
cout<<"\nEnter the new Department\n";
gets(department); -------------->1
}
else
{
cout<<"\nStudent not confirmed\n";
}
}
void student::getData()
{
cout<<"\nEnter the roll no\n";
cin>>rollNo;
cout<<"\nEnter the year\n";
cin>>year;
cout<<"\nEnter the semester\n";
cin>>semester;
cout<<"\nEnter the department\n";
gets(department); ----------------> 2
}
void student::promote()
{
if(rollNo!=0)
{
semester+=1;
if(semester%2==1)
{
year+=1;
}
}
else
{
cout<<"\nStudent not confirmed\n";
}
}
void student::display()
{
if(rollNo!=0)
{
cout<<"\nRoll No : "<<rollNo;
cout<<"\nYear : "<<year;
cout<<"\nSemester : "<<semester;
cout<<"\nDepartment : "<<department;
}
else
{
cout<<"\nStudent not confirmed";
}
}
int main()
{
student s;
int ch;
char choice;
----------------> 3
do
{
cout<<"\nMain Menu";
cout<<"\n1. Enter student details";
cout<<"\n2. Change department of student ";
cout<<"\n3. Promote student ";
cout<<"\n4. Display student details ";
cout<<"\nEnter your choice ";
cin>>ch;
switch(ch)
{
case 1 : s.getData();
s.display();
break;
case 2 : s.changeDepartment();
s.display();
break;
case 3 : s.promote();
s.display();
break;
case 4 : s.display();
break;
}
cout<<"\nDo you want to continue? (Y/n)\n";
cin>>choice;
}while((choice=='y')||(choice=='Y'));
return(0);
}
Blind deconvolution application issues
Blind deconvolution application issues
I have the output from an inverse filter
b = y- (FIR filter)
where y is corrupted with eta as the gaussian noise and b is the measured
output signal;
y is the received signal corrupted with gaussian noise of unknown varaince
and mean.
Let the FIR filter be Hx. A are the unknown parameters and x is the true
signal that is unknown. b is projected to a higher dimensional space ie,
embedded into a higher dimensional space. where the objective function is
min Z= ||b||_2 ^2. In pg 3 of the pdf the Gauss Newton example is
provided. Following from the paper
http://www.optimization-online.org/DB_FILE/2012/02/3351.pdf .
I have not understood anything and having a tough time to do the coding.
So, can somebody please explain how I may apply Gauss Newton method in my
case?
I have the output from an inverse filter
b = y- (FIR filter)
where y is corrupted with eta as the gaussian noise and b is the measured
output signal;
y is the received signal corrupted with gaussian noise of unknown varaince
and mean.
Let the FIR filter be Hx. A are the unknown parameters and x is the true
signal that is unknown. b is projected to a higher dimensional space ie,
embedded into a higher dimensional space. where the objective function is
min Z= ||b||_2 ^2. In pg 3 of the pdf the Gauss Newton example is
provided. Following from the paper
http://www.optimization-online.org/DB_FILE/2012/02/3351.pdf .
I have not understood anything and having a tough time to do the coding.
So, can somebody please explain how I may apply Gauss Newton method in my
case?
Toggle and change class using jQuery
Toggle and change class using jQuery
I'm trying to change $mobile-nav-button's class to .navon and make effect
to slide it from left and add another class to another div. The part where
$mobile-nav-button's class changes works, and my animation works first
time, but then it doesn't hide, why? And the part where I try to change
another div's class doesn't work neither. And the # symbol appears in URL
bar from link which shouldnt..
I aprriciate any help!
$(document).ready(function() {
$("#mobile-nav-button").click(function() {
$("#mobile-nav-button").toggleClass("navon");
if($("#mobile-nav-button").hasClass("navon")) {
$("#mobile-nav").toggle('slide', {
direction: "left"
}, 1000);
$("mobile-content-panel").toggleClass("show-nav");
} else {
$("#mobile-nav").toggle('slide', {
direction: "left"
}, 1000);
$("mobile-content-panel").toggleClass("hide-nav");
}
});
});
I'm trying to change $mobile-nav-button's class to .navon and make effect
to slide it from left and add another class to another div. The part where
$mobile-nav-button's class changes works, and my animation works first
time, but then it doesn't hide, why? And the part where I try to change
another div's class doesn't work neither. And the # symbol appears in URL
bar from link which shouldnt..
I aprriciate any help!
$(document).ready(function() {
$("#mobile-nav-button").click(function() {
$("#mobile-nav-button").toggleClass("navon");
if($("#mobile-nav-button").hasClass("navon")) {
$("#mobile-nav").toggle('slide', {
direction: "left"
}, 1000);
$("mobile-content-panel").toggleClass("show-nav");
} else {
$("#mobile-nav").toggle('slide', {
direction: "left"
}, 1000);
$("mobile-content-panel").toggleClass("hide-nav");
}
});
});
Saturday, 28 September 2013
WinDivert passthru example returns "warning: failed to reinject packet (1237)"
WinDivert passthru example returns "warning: failed to reinject packet
(1237)"
I am running Windows 7 Ultimate with SP1. I downloaded the
WinDivert-1.0.5-MSVC package and ran the passthru.exe file with command
"E:\lib\WinDivert-1.0.5-MSVC\x86>passthru.exe true 1". Then it gave me the
error: "warning: failed to reinject packet (1237)". And the network got
broken, too. Can anybody tell me why? Thx.
E:\lib\WinDivert-1.0.5-MSVC\x86>passthru.exe "true" 1
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
^C
E:\lib\WinDivert-1.0.5-MSVC\x86>
(1237)"
I am running Windows 7 Ultimate with SP1. I downloaded the
WinDivert-1.0.5-MSVC package and ran the passthru.exe file with command
"E:\lib\WinDivert-1.0.5-MSVC\x86>passthru.exe true 1". Then it gave me the
error: "warning: failed to reinject packet (1237)". And the network got
broken, too. Can anybody tell me why? Thx.
E:\lib\WinDivert-1.0.5-MSVC\x86>passthru.exe "true" 1
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
warning: failed to reinject packet (1237)
^C
E:\lib\WinDivert-1.0.5-MSVC\x86>
Makefile environment variable changes between recipes
Makefile environment variable changes between recipes
I'm attempting to create a single log file that tracks and reports the
results of each recipe as the make process moves through the makefile.
To do this, I'm creating an environment variable to hold my logfile
reference like so:
LOGDIR = logs
LOGFILE = $(LOGDIR)/$(shell date --iso=seconds).log
The intention is then to add relevant messaging to the log file by using
echo "message" >> $(LOGFILE)
Trouble is, when processing moves from one recipe to the next, the
environment variable is re-evaluated, resulting in a new log file from
every recipe in my makefile.
Why does the environment variable get re-evaluated, and how can I prevent
this to use a single global reference to a logfile?
I thought that using the $(shell operator) syntax prevents re-evaluation
of the variable, based on Aaron's answer here.
I'm attempting to create a single log file that tracks and reports the
results of each recipe as the make process moves through the makefile.
To do this, I'm creating an environment variable to hold my logfile
reference like so:
LOGDIR = logs
LOGFILE = $(LOGDIR)/$(shell date --iso=seconds).log
The intention is then to add relevant messaging to the log file by using
echo "message" >> $(LOGFILE)
Trouble is, when processing moves from one recipe to the next, the
environment variable is re-evaluated, resulting in a new log file from
every recipe in my makefile.
Why does the environment variable get re-evaluated, and how can I prevent
this to use a single global reference to a logfile?
I thought that using the $(shell operator) syntax prevents re-evaluation
of the variable, based on Aaron's answer here.
Strategy For Scheduling Email Alerts in PHP
Strategy For Scheduling Email Alerts in PHP
I'm writing a PHP project in Laravel. The admin can queue email alerts to
be sent at a specific date/time. The natural choice was to use Laravel's
Queue class with Beanstalkd (Laravel uses Pheanstalk internally).
However, the admin can choose to reschedule or delete email alerts that
have not yet been sent. I could not find a way yet to delete a specific
task so that I can insert a new one with the new timing.
What is the usual technique to accomplish something like this? I'm open to
other ideas as well. I don't want to use CRON since the volumes of these
emails would be pretty high, and I'd rather reuse an already tested
solution for managing a task queue.
I'm writing a PHP project in Laravel. The admin can queue email alerts to
be sent at a specific date/time. The natural choice was to use Laravel's
Queue class with Beanstalkd (Laravel uses Pheanstalk internally).
However, the admin can choose to reschedule or delete email alerts that
have not yet been sent. I could not find a way yet to delete a specific
task so that I can insert a new one with the new timing.
What is the usual technique to accomplish something like this? I'm open to
other ideas as well. I don't want to use CRON since the volumes of these
emails would be pretty high, and I'd rather reuse an already tested
solution for managing a task queue.
csv file not creating
csv file not creating
I want to create a csv file with fetched data>its creating the file but
showing only one date and also showing html of page.
CODE:
$sss=mysql_query("SELECT DATE(pdate),COUNT(*) AS mycount FROM
qchat_sessions WHERE MONTH(pdate)='09' GROUP BY DATE(pdate)");
while($rows = mysql_fetch_array($sss)){
$array = array(array($rows[0], $row[1]));
}
// open raw memory as file so no temp files needed, you might run out
of memory though
$f = fopen('php://memory', 'w');
$de=";";
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line,$de );
}
// rewrind the "file" with the csv lines
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachement; filename="stats.csv"');
// make php send the generated csv lines to the browser
fpassthru($f);
It should show data as:
2013-09-26 ; 1
2013-09-27 ; 2
But showing only 2013-09-27 ; 2
Thanks
I want to create a csv file with fetched data>its creating the file but
showing only one date and also showing html of page.
CODE:
$sss=mysql_query("SELECT DATE(pdate),COUNT(*) AS mycount FROM
qchat_sessions WHERE MONTH(pdate)='09' GROUP BY DATE(pdate)");
while($rows = mysql_fetch_array($sss)){
$array = array(array($rows[0], $row[1]));
}
// open raw memory as file so no temp files needed, you might run out
of memory though
$f = fopen('php://memory', 'w');
$de=";";
// loop over the input array
foreach ($array as $line) {
// generate csv lines from the inner arrays
fputcsv($f, $line,$de );
}
// rewrind the "file" with the csv lines
fseek($f, 0);
// tell the browser it's going to be a csv file
header('Content-Type: application/csv');
// tell the browser we want to save it instead of displaying it
header('Content-Disposition: attachement; filename="stats.csv"');
// make php send the generated csv lines to the browser
fpassthru($f);
It should show data as:
2013-09-26 ; 1
2013-09-27 ; 2
But showing only 2013-09-27 ; 2
Thanks
Friday, 27 September 2013
Beginner Python: Format Output
Beginner Python: Format Output
I was trying to finish an assignment until I reached this small issue. My
dilemma is: My output is printed correctly, but how do I get the key # and
its respective output to be printed together neatly (for example: key 1:
ABCDEB , Key 2: EFGFHI, etc.) Attached is my code.
def main():
# hardcode
phrase = raw_input ("Enter the phrase you would like to decode: ")
# 1-26 alphabets (+3: A->D)
# A starts at 65, and we want the ordinals to be from 0-25
# everything must be in uppercase
phrase = phrase.upper()
# this makes up a list of the words in the phrase
splitWords = phrase.split()
output = ""
for key in range(0,26):
# this function will split each word from the phrase
for ch in splitWords:
# split the words furthur into letters
for x in ch:
number = ((ord(x)-65) + key) % 26
letter = (chr(number+65))
# update accumulator variable
output = output + letter
# add a space after the word
output = output + " "
print "Key", key, ":", output
main()
I was trying to finish an assignment until I reached this small issue. My
dilemma is: My output is printed correctly, but how do I get the key # and
its respective output to be printed together neatly (for example: key 1:
ABCDEB , Key 2: EFGFHI, etc.) Attached is my code.
def main():
# hardcode
phrase = raw_input ("Enter the phrase you would like to decode: ")
# 1-26 alphabets (+3: A->D)
# A starts at 65, and we want the ordinals to be from 0-25
# everything must be in uppercase
phrase = phrase.upper()
# this makes up a list of the words in the phrase
splitWords = phrase.split()
output = ""
for key in range(0,26):
# this function will split each word from the phrase
for ch in splitWords:
# split the words furthur into letters
for x in ch:
number = ((ord(x)-65) + key) % 26
letter = (chr(number+65))
# update accumulator variable
output = output + letter
# add a space after the word
output = output + " "
print "Key", key, ":", output
main()
Placement of alignas in using/typedef
Placement of alignas in using/typedef
Where should I place alignas in the following:
using Flt4 = alignas(16) std::array<float, 4>;
or
using Flt4 = std::array<float, 4> alignas(16);
Thanks
Where should I place alignas in the following:
using Flt4 = alignas(16) std::array<float, 4>;
or
using Flt4 = std::array<float, 4> alignas(16);
Thanks
Dynamic queue implementation
Dynamic queue implementation
I am new with linked lists. Every time I code I get a run time error. Same
is with this also I am getting run time error in this program. Kindly
explain the error in the code. I tried finding the error but every thing
seems fine to me . Kindly explain.
# include <iostream>
using namespace std;
struct node
{
int a;
struct node *next;
};
typedef struct node node;
node *front = NULL;
node *rear = NULL;
void enqu(int b)
{
node *p;
p->a = b;
if(front == NULL)
{
p->next = NULL;
front = p;
rear = p;
}
else
{
p->next = NULL;
rear->next = p;
rear = p;
}
}
void dequ()
{
node *p;
if (front != NULL)
{
if(front == rear)
{
front = NULL;
rear = NULL;
}
else
{
front=front->next;
}
cout<<"no deleated is"<<p->a<<"\n";
}
else
{
cout<<"queue is empty";
}
}
void display()
{
node *p;
if(p!=NULL)
{
p=front;
while(p!=NULL)
{
cout<<p->a;
p=p->next;
}
}
else
{
cout<<"queue is empty";
}
}
int main()
{
enqu(1);
enqu(2);
enqu(5);
enqu(6);
enqu(7);
enqu(8);
display();
dequ();
dequ();
display();
return 0;
}
I am new with linked lists. Every time I code I get a run time error. Same
is with this also I am getting run time error in this program. Kindly
explain the error in the code. I tried finding the error but every thing
seems fine to me . Kindly explain.
# include <iostream>
using namespace std;
struct node
{
int a;
struct node *next;
};
typedef struct node node;
node *front = NULL;
node *rear = NULL;
void enqu(int b)
{
node *p;
p->a = b;
if(front == NULL)
{
p->next = NULL;
front = p;
rear = p;
}
else
{
p->next = NULL;
rear->next = p;
rear = p;
}
}
void dequ()
{
node *p;
if (front != NULL)
{
if(front == rear)
{
front = NULL;
rear = NULL;
}
else
{
front=front->next;
}
cout<<"no deleated is"<<p->a<<"\n";
}
else
{
cout<<"queue is empty";
}
}
void display()
{
node *p;
if(p!=NULL)
{
p=front;
while(p!=NULL)
{
cout<<p->a;
p=p->next;
}
}
else
{
cout<<"queue is empty";
}
}
int main()
{
enqu(1);
enqu(2);
enqu(5);
enqu(6);
enqu(7);
enqu(8);
display();
dequ();
dequ();
display();
return 0;
}
Create UserControl with CodeBehind at runtime in Asp.Net
Create UserControl with CodeBehind at runtime in Asp.Net
How to create a usercontrol and its codebehind from source file(s) at
runtime and load into a panel? I'm pretty sure using CodeDom could solve
this, but not quite sure how to go about it. Can anyone provide a
simplified example for this? Thanks in advance.
How to create a usercontrol and its codebehind from source file(s) at
runtime and load into a panel? I'm pretty sure using CodeDom could solve
this, but not quite sure how to go about it. Can anyone provide a
simplified example for this? Thanks in advance.
Using WCF for view service (either with or without using PRISM)
Using WCF for view service (either with or without using PRISM)
Currently we are developing a WPF client which is exposing a WCF service
to receive the request of opening a new report window, by window I mean a
WPF Window with a UserControl we defined. So the initial idea is WCF
generates the UserControl. However, I am having some threading problem of
generating the UserControl:
Since WCF is servicing in a background thread, it is forbidden to generate
a UserControl there. I can work it around by setting the
UseSynchronizationContext to True for the ServiceBehavior. So the service
will be ran on the thread specified by the SynchronizaitonContext, which
in my case is the UI thread. However, there are two questions here.
using SynchronizationContext seems to make it impossible to have a WCF
service with callback (the open new window service doesn't return any
value. But I need some other operation which does), see this:
UseSynchronizationContext=false
I am not sure of executing WCF in UI thread, because it means I must make
extra effort to keep UI responsible (I admit this reason might not be
valid. I don't know, please point out whether it is a good practice).
I know that by using for example PRISM, we can have a view service to
compose ViewModel and View. I mean I can generate a ViewModel in WCF
service and pop it up to the view service (which is executing on UI
thread) to find and generate the corresponding View. But the truth is we
are still hesitating about using PRISM so such view service is not
available at least in the near future.
So I was wondering, what would be a good structure of such a requirement,
i.e., having a WCF to take a request and initialize a new Window hosing a
View?
Currently we are developing a WPF client which is exposing a WCF service
to receive the request of opening a new report window, by window I mean a
WPF Window with a UserControl we defined. So the initial idea is WCF
generates the UserControl. However, I am having some threading problem of
generating the UserControl:
Since WCF is servicing in a background thread, it is forbidden to generate
a UserControl there. I can work it around by setting the
UseSynchronizationContext to True for the ServiceBehavior. So the service
will be ran on the thread specified by the SynchronizaitonContext, which
in my case is the UI thread. However, there are two questions here.
using SynchronizationContext seems to make it impossible to have a WCF
service with callback (the open new window service doesn't return any
value. But I need some other operation which does), see this:
UseSynchronizationContext=false
I am not sure of executing WCF in UI thread, because it means I must make
extra effort to keep UI responsible (I admit this reason might not be
valid. I don't know, please point out whether it is a good practice).
I know that by using for example PRISM, we can have a view service to
compose ViewModel and View. I mean I can generate a ViewModel in WCF
service and pop it up to the view service (which is executing on UI
thread) to find and generate the corresponding View. But the truth is we
are still hesitating about using PRISM so such view service is not
available at least in the near future.
So I was wondering, what would be a good structure of such a requirement,
i.e., having a WCF to take a request and initialize a new Window hosing a
View?
Thursday, 26 September 2013
GPS miles calculation from set of co-ordinates
GPS miles calculation from set of co-ordinates
I have 100s of GPS co-ordinates in excel sheets which I need to use it to
generate total straight line GPS miles between all of those coordinates
added. I am looking for a website which will help me do that or even a web
service which can be of help.
Please help me in finding one.
Thanks,
SKU
I have 100s of GPS co-ordinates in excel sheets which I need to use it to
generate total straight line GPS miles between all of those coordinates
added. I am looking for a website which will help me do that or even a web
service which can be of help.
Please help me in finding one.
Thanks,
SKU
Wednesday, 25 September 2013
iOS7 - How to turn off the automatic gesture to go back a view with a navigation controller?
iOS7 - How to turn off the automatic gesture to go back a view with a
navigation controller?
So I'm noticing all of my views are receiving the gesture to go back (pop
a view) when the user swipes on the very left side of the screen (in
either orientation).
I've tried so far with no avail to turn it off using:
[self.navigationItem setHidesBackButton:YES];
Within the init of the NavigationController itself (as the delegate seems
to be using that).
navigation controller?
So I'm noticing all of my views are receiving the gesture to go back (pop
a view) when the user swipes on the very left side of the screen (in
either orientation).
I've tried so far with no avail to turn it off using:
[self.navigationItem setHidesBackButton:YES];
Within the init of the NavigationController itself (as the delegate seems
to be using that).
Thursday, 19 September 2013
What is the iBeacon Bluetooth Profile [on hold]
What is the iBeacon Bluetooth Profile [on hold]
Apple has yet to release a specification for iBeacons, however a few
hardware guys have reverse Engineered the iBeacon from the AirLocate
Sample code and started selling iBeacon dev kits. I'd like to create my
own iBeacon with some bluetooth dev kits of my own.
So What is the iBeacon Bluetooth Profile?
Heres some assumptions I've made from the discussion on Apple's forums and
through the docs.
You only need to see the Advertisement of a Bluetooth peripheral to know
it is an iBeacon.
The Major and Minor keys are encoded somewhere in this advertisement, most
likely the manufacturers data
iBeacons are only available to the app in the foreground, in powersave
mode not all the keys of a Core Bluetooth Peripheral Manager are sent in
the advertisement. Therefore iBeacons cannot be created and maintained
while your app is backgrounded
Heres some companies with iBeacon Dev Kits that seem to have this figure
out already:
http://redbearlab.com/ibeacon/
http://kontakt.io/
Apple has yet to release a specification for iBeacons, however a few
hardware guys have reverse Engineered the iBeacon from the AirLocate
Sample code and started selling iBeacon dev kits. I'd like to create my
own iBeacon with some bluetooth dev kits of my own.
So What is the iBeacon Bluetooth Profile?
Heres some assumptions I've made from the discussion on Apple's forums and
through the docs.
You only need to see the Advertisement of a Bluetooth peripheral to know
it is an iBeacon.
The Major and Minor keys are encoded somewhere in this advertisement, most
likely the manufacturers data
iBeacons are only available to the app in the foreground, in powersave
mode not all the keys of a Core Bluetooth Peripheral Manager are sent in
the advertisement. Therefore iBeacons cannot be created and maintained
while your app is backgrounded
Heres some companies with iBeacon Dev Kits that seem to have this figure
out already:
http://redbearlab.com/ibeacon/
http://kontakt.io/
How does JMS Queue decide which listener will receive a particular message?
How does JMS Queue decide which listener will receive a particular message?
I have a program that has about 500 messages going to a JMS Queue. Then I
have 3 other programs all listening to the same queue. The interesting
thing is, if i start one listener and then run the program to send all the
messages and then wait until the listener receives 50 of them and then
start the other two listeners, each of the latter two listeners only
receive one message and then stop, while the first listener receives the
other 498. Why does this happen? And what can I do to fix it? If its
relevant, the broker is running on a Glassfish server.
I have a program that has about 500 messages going to a JMS Queue. Then I
have 3 other programs all listening to the same queue. The interesting
thing is, if i start one listener and then run the program to send all the
messages and then wait until the listener receives 50 of them and then
start the other two listeners, each of the latter two listeners only
receive one message and then stop, while the first listener receives the
other 498. Why does this happen? And what can I do to fix it? If its
relevant, the broker is running on a Glassfish server.
Python Console with Logging
Python Console with Logging
I'm in the process of rewriting a server program, and I want to add into
it a simple console input.
At the moment, it just serves data and prints out one or two lines for
each thing it does, as a descriptive measure for anyone
watching/debugging.
What I want is to have a "sticky" input bar that is always at the bottom,
above which my debug prints appear, so that I can enter commands at any
point while the program is printing. This would look a bit like:
...
[88.88.88.88] Handling Connection on Port 11452
[12.12.12.12] Received Data
[44.44.44.44] Sending Disconnect Sequence
>>>Enter Data Here at Any Time
Ideally, this would be done without curses as this would complicate
matters. I feel like I must be missing a simple solution.
Thanks in Advance,
Freddy.
I'm in the process of rewriting a server program, and I want to add into
it a simple console input.
At the moment, it just serves data and prints out one or two lines for
each thing it does, as a descriptive measure for anyone
watching/debugging.
What I want is to have a "sticky" input bar that is always at the bottom,
above which my debug prints appear, so that I can enter commands at any
point while the program is printing. This would look a bit like:
...
[88.88.88.88] Handling Connection on Port 11452
[12.12.12.12] Received Data
[44.44.44.44] Sending Disconnect Sequence
>>>Enter Data Here at Any Time
Ideally, this would be done without curses as this would complicate
matters. I feel like I must be missing a simple solution.
Thanks in Advance,
Freddy.
Host Ruby required error while installing ruby 1.9.3
Host Ruby required error while installing ruby 1.9.3
I am installing ruby 1.9.3 on Ubuntu 12.04 and receive the following error
executable host ruby is required. use --with-baseruby option
After some research I found that I need an older version of ruby to
install ruby. Many solutions involved using ruby 1.8 as a base, compiling
and installing it from source, then installing 1.9 BUT ruby version 1.8
has been removed...farewell. What can I use as a base, or any solution to
overcome the above error?
I am installing ruby 1.9.3 on Ubuntu 12.04 and receive the following error
executable host ruby is required. use --with-baseruby option
After some research I found that I need an older version of ruby to
install ruby. Many solutions involved using ruby 1.8 as a base, compiling
and installing it from source, then installing 1.9 BUT ruby version 1.8
has been removed...farewell. What can I use as a base, or any solution to
overcome the above error?
Give a sequential number for each GROUP BY values
Give a sequential number for each GROUP BY values
I have a table with many rows (Table A). I collect it rows to another
table (Table B) with GROUP BY clause. But I stuck here, I need to give
sequential number for each GROUPED rows on Table B. How to achieve this
problem. Thanks for your helps.
I have a table with many rows (Table A). I collect it rows to another
table (Table B) with GROUP BY clause. But I stuck here, I need to give
sequential number for each GROUPED rows on Table B. How to achieve this
problem. Thanks for your helps.
How to create a temporary text file in C
How to create a temporary text file in C
I have a text file to read. I would like to read from that file and store
into a temporary file. I am not sure how to do this. How do I create a
temporary file and do I use fprintf to store in that file?
I have a text file to read. I would like to read from that file and store
into a temporary file. I am not sure how to do this. How do I create a
temporary file and do I use fprintf to store in that file?
Recuva horizontal and vertical scrolling window hard to screenshoot
Recuva horizontal and vertical scrolling window hard to screenshoot
Piriform - Recuva allows the found-files list to be exported to a text
file, at least partly (the Last Modified, State, and Comment columns are
missing).
Hence, as I had a need for some of the rows in these missing columns, I
tried using the below programs to attempt to capture the information in an
image.
PicPic
FastStone Capture
SnagIt
However, all but SnagIt didn't vertically or horitzontally scroll the
list. Snagit showed a non-wider-than-the-window list being scrolled, and
actually captured all lines, however when the list was wider than the
window, while Snagit showed the list being scrollled down, then moved
across, and down again, etc, it produces an image wide enough, but with
almost the whole bottom half of the image cut off.
Instead of trying to get a screenshot program working with whatever
difficult to automatic-scroll ?Window form? Recuva is using, I had
wondered if there was a way (As I have seen eluded to in the past) to grab
the information from the Windows form directly, like out of RAM?
Piriform - Recuva allows the found-files list to be exported to a text
file, at least partly (the Last Modified, State, and Comment columns are
missing).
Hence, as I had a need for some of the rows in these missing columns, I
tried using the below programs to attempt to capture the information in an
image.
PicPic
FastStone Capture
SnagIt
However, all but SnagIt didn't vertically or horitzontally scroll the
list. Snagit showed a non-wider-than-the-window list being scrolled, and
actually captured all lines, however when the list was wider than the
window, while Snagit showed the list being scrollled down, then moved
across, and down again, etc, it produces an image wide enough, but with
almost the whole bottom half of the image cut off.
Instead of trying to get a screenshot program working with whatever
difficult to automatic-scroll ?Window form? Recuva is using, I had
wondered if there was a way (As I have seen eluded to in the past) to grab
the information from the Windows form directly, like out of RAM?
Wednesday, 18 September 2013
didReceiveResponse delegate method in Restkit 0.20
didReceiveResponse delegate method in Restkit 0.20
I am using Restkit 0.20 for my project. I make a request like this.
NSData *postData = [params dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:baseUrl];
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:path relativeToURL:url]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json"
forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
RKObjectManager *manager = [[RestKit sharedDataManager] objectManager];
RKManagedObjectRequestOperation *operation = [manager
managedObjectRequestOperationWithRequest:request
managedObjectContext:manager.managedObjectStore.persistentStoreManagedObjectContext
success:^(RKObjectRequestOperation *operation1, RKMappingResult
*mappingResult) {
block ([mappingResult array]);
} failure:^(RKObjectRequestOperation *operation1, NSError *error) {
RKLogDebug(@"Failure %@",error.debugDescription);
block (error);
}];
After competing mapping operation, i am returning an array using block. Is
there any method similar to didReceiveResponse in Restkit0.10 and also i
am aware of this thread
https://groups.google.com/forum/#!topic/restkit/TrWH5GR-gFU in which blake
mentioned that we have full control over the headers via the NSURLRequest
object.But how can i make use of NSURLRequest when i am using
RKManagedObjectRequestOperation. can anyone post some example.
Thanks
I am using Restkit 0.20 for my project. I make a request like this.
NSData *postData = [params dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:baseUrl];
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:path relativeToURL:url]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json"
forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
RKObjectManager *manager = [[RestKit sharedDataManager] objectManager];
RKManagedObjectRequestOperation *operation = [manager
managedObjectRequestOperationWithRequest:request
managedObjectContext:manager.managedObjectStore.persistentStoreManagedObjectContext
success:^(RKObjectRequestOperation *operation1, RKMappingResult
*mappingResult) {
block ([mappingResult array]);
} failure:^(RKObjectRequestOperation *operation1, NSError *error) {
RKLogDebug(@"Failure %@",error.debugDescription);
block (error);
}];
After competing mapping operation, i am returning an array using block. Is
there any method similar to didReceiveResponse in Restkit0.10 and also i
am aware of this thread
https://groups.google.com/forum/#!topic/restkit/TrWH5GR-gFU in which blake
mentioned that we have full control over the headers via the NSURLRequest
object.But how can i make use of NSURLRequest when i am using
RKManagedObjectRequestOperation. can anyone post some example.
Thanks
How to iterate through a Map[B,Int] in Scala
How to iterate through a Map[B,Int] in Scala
I have a Map[B,Int] that I am trying to iterate over: So I do something like:
map foreach { case (k,v) => println(k + " " + v)}
However I keep getting the error that there is a type mismatch: Found:
Unit Expected: B
I have read several times on different tutorials that traversing a map is
always the same regardless of what type is point to another.
I am not sure how to fix this.
I have a Map[B,Int] that I am trying to iterate over: So I do something like:
map foreach { case (k,v) => println(k + " " + v)}
However I keep getting the error that there is a type mismatch: Found:
Unit Expected: B
I have read several times on different tutorials that traversing a map is
always the same regardless of what type is point to another.
I am not sure how to fix this.
GROUP BY only rows with a certain condition and date
GROUP BY only rows with a certain condition and date
I have a basic table in my database that has a simple transactions history
such as depositing money to an account, withdrawing money, and having
money refunded. Each entry has a date associated with it.
I have a php page that displays this transactional information row by row
and it looks great. However, is there a way within the mySQL query that I
can "collapse" all "refunded" money transactions into groupings by day?
It's quite easy to do a GROUP_BY on the transaction type but I only want
to group by on if the transaction_type is of type "refund" and those
refunds happened on the same day. Thanks!
My Current Example Table:
Jan 3, Deposit, $100
Jan 3, Deposit, $200
Jan 2, Withdraw, $50
Jan 2, Refund, $100
Jan 2, Refund, $100
Jan 2, Deposit, $200
Jan 2, Refund, $100
Jan 1, Deposit, $100
How I would like the data to display
Jan 3, Deposit, $100
Jan 3, Deposit, $200
Jan 2, Withdraw, $50
Jan 2, Refund, $300 < this row has collapsed all Refunds for Jan 2nd into
1 row
Jan 2, Deposit, $200
Jan 1, Deposit, $100
The current SQL is something like:
SELECT transaction_date, transaction_type, transaction_amount
FROM transaction_history
WHERE customer_id = $customer_id
ORDER BY transaction_date DESC
I have a basic table in my database that has a simple transactions history
such as depositing money to an account, withdrawing money, and having
money refunded. Each entry has a date associated with it.
I have a php page that displays this transactional information row by row
and it looks great. However, is there a way within the mySQL query that I
can "collapse" all "refunded" money transactions into groupings by day?
It's quite easy to do a GROUP_BY on the transaction type but I only want
to group by on if the transaction_type is of type "refund" and those
refunds happened on the same day. Thanks!
My Current Example Table:
Jan 3, Deposit, $100
Jan 3, Deposit, $200
Jan 2, Withdraw, $50
Jan 2, Refund, $100
Jan 2, Refund, $100
Jan 2, Deposit, $200
Jan 2, Refund, $100
Jan 1, Deposit, $100
How I would like the data to display
Jan 3, Deposit, $100
Jan 3, Deposit, $200
Jan 2, Withdraw, $50
Jan 2, Refund, $300 < this row has collapsed all Refunds for Jan 2nd into
1 row
Jan 2, Deposit, $200
Jan 1, Deposit, $100
The current SQL is something like:
SELECT transaction_date, transaction_type, transaction_amount
FROM transaction_history
WHERE customer_id = $customer_id
ORDER BY transaction_date DESC
Converting a float to float*
Converting a float to float*
I have QStandardItem* list in my code
QList<QStandardItem*> lst
Now this is acceptable and works
float a = lst[0]->text().toFloat();
However the following does not work
float* a = &(lst[0]->text().toFloat());
I get an intellisense error stating
Expression must be an lvalue or a function designator
I need a pointer here since I am using an external library that requires a
reference that looks like this
some_class.add_variable(const std::string& variable_name, float& t);
So if I get a pointer I could simply pass it as *a
Any suggetsions on how I could resolve this issue ?
I have QStandardItem* list in my code
QList<QStandardItem*> lst
Now this is acceptable and works
float a = lst[0]->text().toFloat();
However the following does not work
float* a = &(lst[0]->text().toFloat());
I get an intellisense error stating
Expression must be an lvalue or a function designator
I need a pointer here since I am using an external library that requires a
reference that looks like this
some_class.add_variable(const std::string& variable_name, float& t);
So if I get a pointer I could simply pass it as *a
Any suggetsions on how I could resolve this issue ?
Where to put log files for tempdb?
Where to put log files for tempdb?
In my current project we came up with a question where to put log file for
tempdb. Usually we put data file and log file on a dedicated drive in
folder like t:\tempdb.
On one server we have tempdb logs that were put in the log folder for user
user databases.
Is there any best practice on where to put log file for temp db?
Is it bad or good to keep it together with tempdb data file or with user
log files?
Thanks!
In my current project we came up with a question where to put log file for
tempdb. Usually we put data file and log file on a dedicated drive in
folder like t:\tempdb.
On one server we have tempdb logs that were put in the log folder for user
user databases.
Is there any best practice on where to put log file for temp db?
Is it bad or good to keep it together with tempdb data file or with user
log files?
Thanks!
Math.acos(0.26311) gives 1.3045519539106323. But using calculator we get 74.74degree. How to Convert the value to degrees?
Math.acos(0.26311) gives 1.3045519539106323. But using calculator we get
74.74degree. How to Convert the value to degrees?
Using the code Math.acos(0.26311) gives 1.3045519539106323. But using
calculator, we get 74.74 degree.
How to Convert the value to degrees? Please help.
74.74degree. How to Convert the value to degrees?
Using the code Math.acos(0.26311) gives 1.3045519539106323. But using
calculator, we get 74.74 degree.
How to Convert the value to degrees? Please help.
Missing parameters with RESTful request when upgrading to Grails 2.3.0
Missing parameters with RESTful request when upgrading to Grails 2.3.0
I am using Grails with RESTful to develop my web application. Everything
works fine, till I upgrade my application to Grails 2.3. Here is my
UrlMappings: I still send request, submit or do some other things
normally, but in POST, PUT requests, the parameters are missing. Server
just recognize only the parameters I put on the URL directly, but the
remain I enclose in form or model when submit cannot be found in the
"params" variable. He is my UrlMappings:
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?"{ constraints {} }
name apiSingle: "/api/$controller/$id"(parseRequest:true){
action = [GET: "show", PUT: "update", DELETE: "delete"]
constraints { id(matches:/\d+/) }
}
name apiCollection: "/api/$controller"(parseRequest:true){
action = [GET: "list", POST: "save"]
}
name api2: "/api/$controller/$action"(parseRequest:true)
name api3: "/api/$controller/$action/$id"(parseRequest:true)
"/"(view:"/welcome")
"500"(view:'/error')
}
}
I have read the latest document of Grails 2.3, at
http://grails.org/doc/latest/guide/theWebLayer.html#restfulMappings
but I think it is not clear. I have tried it follow the documentation but
have no result. And there are no any sample about using Grails 2.3 with
RESTful for me to refer.
How can I make it work normally as before, and can access all parameter
values in REST request? Thank you so much!
I am using Grails with RESTful to develop my web application. Everything
works fine, till I upgrade my application to Grails 2.3. Here is my
UrlMappings: I still send request, submit or do some other things
normally, but in POST, PUT requests, the parameters are missing. Server
just recognize only the parameters I put on the URL directly, but the
remain I enclose in form or model when submit cannot be found in the
"params" variable. He is my UrlMappings:
class UrlMappings {
static mappings = {
"/$controller/$action?/$id?"{ constraints {} }
name apiSingle: "/api/$controller/$id"(parseRequest:true){
action = [GET: "show", PUT: "update", DELETE: "delete"]
constraints { id(matches:/\d+/) }
}
name apiCollection: "/api/$controller"(parseRequest:true){
action = [GET: "list", POST: "save"]
}
name api2: "/api/$controller/$action"(parseRequest:true)
name api3: "/api/$controller/$action/$id"(parseRequest:true)
"/"(view:"/welcome")
"500"(view:'/error')
}
}
I have read the latest document of Grails 2.3, at
http://grails.org/doc/latest/guide/theWebLayer.html#restfulMappings
but I think it is not clear. I have tried it follow the documentation but
have no result. And there are no any sample about using Grails 2.3 with
RESTful for me to refer.
How can I make it work normally as before, and can access all parameter
values in REST request? Thank you so much!
Android Support Library not being detected by wizard - Cannot create MasterDetailFlow
Android Support Library not being detected by wizard - Cannot create
MasterDetailFlow
I have created a few projects with the MasterDetailFlow using API 11
earlier. I needed to add LoginActivity so I downloaded the needed SDKs and
updated the SDK tools to rev 22.2
http://prntscr.com/1rzb9j
Now that it is updated, when I use the wizard to create a new
MasterDetailFlow project, or when adding an Activity template such as
LoginActivity (to my previously created project having MasterDetailFlow
layout) it says that the Android Support Library is not available or is
outdated.
http://prntscr.com/1rzbc5
This template depends on the Android Support library, which is either not
installed, or the template depends on a more recent version than the one
you have installed.
Required version: 8
Installed version: 18
I have tried Uninstalling and reinstalling via the Wizard, to no avail (as
advised here Not able to create new Project with ADT version 20) After I
uninstall and run the wizard- the Installed version shows "not available"
and thus I click on "Install/Upgrade"; where it installs and shows that
the Installed version is 18 but the next and finish buttons are disabled,
and "Check Again" does nothing.
I have also tried manually installing also, going back to version 8, even
then it says:
Required version: 8
Installed version: 8
Here too, the next button is disabled, and check again does nothing.
I repeated the above said solutions many times, and no luck. I am thinking
it might be something else that is wrong. Any ideas?
MasterDetailFlow
I have created a few projects with the MasterDetailFlow using API 11
earlier. I needed to add LoginActivity so I downloaded the needed SDKs and
updated the SDK tools to rev 22.2
http://prntscr.com/1rzb9j
Now that it is updated, when I use the wizard to create a new
MasterDetailFlow project, or when adding an Activity template such as
LoginActivity (to my previously created project having MasterDetailFlow
layout) it says that the Android Support Library is not available or is
outdated.
http://prntscr.com/1rzbc5
This template depends on the Android Support library, which is either not
installed, or the template depends on a more recent version than the one
you have installed.
Required version: 8
Installed version: 18
I have tried Uninstalling and reinstalling via the Wizard, to no avail (as
advised here Not able to create new Project with ADT version 20) After I
uninstall and run the wizard- the Installed version shows "not available"
and thus I click on "Install/Upgrade"; where it installs and shows that
the Installed version is 18 but the next and finish buttons are disabled,
and "Check Again" does nothing.
I have also tried manually installing also, going back to version 8, even
then it says:
Required version: 8
Installed version: 8
Here too, the next button is disabled, and check again does nothing.
I repeated the above said solutions many times, and no luck. I am thinking
it might be something else that is wrong. Any ideas?
Tuesday, 17 September 2013
Is it possible to update a table using WHERE email = $_SESSION['email']
Is it possible to update a table using WHERE email = $_SESSION['email']
I want to update an already existing table it only has email and I want to
add first name and last name does this code work to do so?
UPDATE table
SET fname='$fname', lname='$lname'
WHERE email= '$_SESSION['email'].';
Or can I also use this
$sql="INSERT INTO $tbl_name(fname, lname)VALUES( '$fname,
$lname')" WHERE email= '$_SESSION['email'].';
I want to update an already existing table it only has email and I want to
add first name and last name does this code work to do so?
UPDATE table
SET fname='$fname', lname='$lname'
WHERE email= '$_SESSION['email'].';
Or can I also use this
$sql="INSERT INTO $tbl_name(fname, lname)VALUES( '$fname,
$lname')" WHERE email= '$_SESSION['email'].';
implement token for Laravel 4 RESTful API authentication
implement token for Laravel 4 RESTful API authentication
I'm learning Laravel 4 framework and PHP.
Currently, I'm trying to do a simple authentication process between client
application and server
Below is my planning approach:
1) Client login to server by a get request with username and password
2) Server will validate and return a token string if successful. The token
string will be encoded (hashed ???) with username,password and expired
time
3) The token will be sent together with requests to server for example:
/server/getProduct/ABC/para1/para2
So for all methods, the first parameter will always be the token string,
in this case is 'ABC'
4) Before processing request from client, method has to validate the token
(decode the token -> check username/password and expired time ) like
below:
public function getProduct($token,$para1,$para2)
{
if(validateToken($token)
{
.....
}
}
So for every method I have to put validateToken and obviously, it's not a
good way to go. Is there any way that I can check the token for every
requests sent from client without putting it in every methods and what is
the best way to generate the token with the parameters given.
I'm certainly open to other implemented solutions or packages as I think
this is the common approach and I prefer not to reinvent the wheel.
Thank you and appreciate for your time and help.
I'm learning Laravel 4 framework and PHP.
Currently, I'm trying to do a simple authentication process between client
application and server
Below is my planning approach:
1) Client login to server by a get request with username and password
2) Server will validate and return a token string if successful. The token
string will be encoded (hashed ???) with username,password and expired
time
3) The token will be sent together with requests to server for example:
/server/getProduct/ABC/para1/para2
So for all methods, the first parameter will always be the token string,
in this case is 'ABC'
4) Before processing request from client, method has to validate the token
(decode the token -> check username/password and expired time ) like
below:
public function getProduct($token,$para1,$para2)
{
if(validateToken($token)
{
.....
}
}
So for every method I have to put validateToken and obviously, it's not a
good way to go. Is there any way that I can check the token for every
requests sent from client without putting it in every methods and what is
the best way to generate the token with the parameters given.
I'm certainly open to other implemented solutions or packages as I think
this is the common approach and I prefer not to reinvent the wheel.
Thank you and appreciate for your time and help.
save checkbox values with pdo in mysql db
save checkbox values with pdo in mysql db
I can't save the values in checkbox into my db...always save "array" and
not the values..
in fiddler I see that the form catch the values but when the data go to
save.php file the values change to array... can you give me a hand with
this please?
here is the form:
<form name="esq" id="esq" method="post">
<div class="row-fluid grid">
<div class="span4">
<label><b><?php echo $translate->__('Gestas Previas'); ?>:
</b></label><input type="text" class="span3" value="" name="gestas"
/></div>
<div class="span4">
<label><b><?php echo $translate->__('Abortos'); ?>: </b></label><input
type="text" class="span3" value="" name="abortos" /></div>
<div class="span4">
<label><b><?php echo $translate->__('3 espontaneos consecutivos'); ?>:
</b></label><input type="text" class="span3" value="" name="esp_conse"
/></div>
</div>
----------HERE START THE CHECKBOX-------------
<div class="row-fluid grid">
<label class="control-label"><b><?php echo $translate->__('Ultimo
Previo'); ?></b></label>
<div class="controls">
<label class="checkbox inline">
<div id="uniform-inlineCheckbox1" class="checker"><span><input
style="opacity: 0;" id="inlineCheckbox1" value="2500g"
name="seleccion[]" type="checkbox"></span></div> <?php echo
$translate->__('2500 g'); ?>
</label>
<label class="checkbox inline">
<div id="uniform-inlineCheckbox2" class="checker"><span><input
style="opacity: 0;" id="inlineCheckbox2" value="4500g"
name="seleccion[]" type="checkbox"></span></div> <?php echo
$translate->__('4500 g'); ?>
</label>
<label class="checkbox inline">
<div id="uniform-inlineCheckbox3" class="checker"><span><input
style="opacity: 0;" id="inlineCheckbox3" value="pre_eclam"
name="seleccion[]" type="checkbox"></span></div> <?php echo
$translate->__('Preclampsia-eclampsia'); ?>
</label>
<label class="checkbox inline">
<div id="uniform-inlineCheckbox4" class="checker"><span><input
style="opacity: 0;" id="inlineCheckbox4" value="cesarea"
name="seleccion[]" type="checkbox"></span></div> <?php echo
$translate->__('Cesárea'); ?>
</label>
</div>
</div><br />
----------HERE FINISH THE CHECKBOX-------------
..............
here is the code:
<?php
include_once("confs.php");
if (!empty($_POST)) {
try{
$statement = $conn->prepare("INSERT INTO GESTACION (gestas, abortos,
esp_conse, seleccion, partos, vaginal, cesareas, nac_vivos,
nac_muertos, viven, semana, des_semana, f_ult_parto, f_ult_pap, fur,
fpp, edad_gesta, pesofeto, tallafeto, imc, toxoide, influenza, otras,
medicament) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?)");
if ($statement->execute(array($_POST['gestas'], $_POST['abortos'],
$_POST['esp_conse'], $_POST['seleccion'], $_POST['partos'],
$_POST['vaginal'], $_POST['cesareas'], $_POST['nac_vivos'],
$_POST['nac_muertos'], $_POST['viven'], $_POST['semana'],
$_POST['des_semana'], $_POST['f_ult_parto'], $_POST['f_ult_pap'],
$_POST['fur'], $_POST['fpp'], $_POST['edad_gesta'],
$_POST['pesofeto'], $_POST['tallafeto'], $_POST['imc'],
$_POST['toxoide'], $_POST['influenza'], $_POST['otras'],
$_POST['medicament'])));
$dbSuccess = true;
} catch (Exception $e) {
$return['databaseException'] = $e->getMessage();
}
$dbh = null;
}
?>
all other data save nice into db.
I can't save the values in checkbox into my db...always save "array" and
not the values..
in fiddler I see that the form catch the values but when the data go to
save.php file the values change to array... can you give me a hand with
this please?
here is the form:
<form name="esq" id="esq" method="post">
<div class="row-fluid grid">
<div class="span4">
<label><b><?php echo $translate->__('Gestas Previas'); ?>:
</b></label><input type="text" class="span3" value="" name="gestas"
/></div>
<div class="span4">
<label><b><?php echo $translate->__('Abortos'); ?>: </b></label><input
type="text" class="span3" value="" name="abortos" /></div>
<div class="span4">
<label><b><?php echo $translate->__('3 espontaneos consecutivos'); ?>:
</b></label><input type="text" class="span3" value="" name="esp_conse"
/></div>
</div>
----------HERE START THE CHECKBOX-------------
<div class="row-fluid grid">
<label class="control-label"><b><?php echo $translate->__('Ultimo
Previo'); ?></b></label>
<div class="controls">
<label class="checkbox inline">
<div id="uniform-inlineCheckbox1" class="checker"><span><input
style="opacity: 0;" id="inlineCheckbox1" value="2500g"
name="seleccion[]" type="checkbox"></span></div> <?php echo
$translate->__('2500 g'); ?>
</label>
<label class="checkbox inline">
<div id="uniform-inlineCheckbox2" class="checker"><span><input
style="opacity: 0;" id="inlineCheckbox2" value="4500g"
name="seleccion[]" type="checkbox"></span></div> <?php echo
$translate->__('4500 g'); ?>
</label>
<label class="checkbox inline">
<div id="uniform-inlineCheckbox3" class="checker"><span><input
style="opacity: 0;" id="inlineCheckbox3" value="pre_eclam"
name="seleccion[]" type="checkbox"></span></div> <?php echo
$translate->__('Preclampsia-eclampsia'); ?>
</label>
<label class="checkbox inline">
<div id="uniform-inlineCheckbox4" class="checker"><span><input
style="opacity: 0;" id="inlineCheckbox4" value="cesarea"
name="seleccion[]" type="checkbox"></span></div> <?php echo
$translate->__('Cesárea'); ?>
</label>
</div>
</div><br />
----------HERE FINISH THE CHECKBOX-------------
..............
here is the code:
<?php
include_once("confs.php");
if (!empty($_POST)) {
try{
$statement = $conn->prepare("INSERT INTO GESTACION (gestas, abortos,
esp_conse, seleccion, partos, vaginal, cesareas, nac_vivos,
nac_muertos, viven, semana, des_semana, f_ult_parto, f_ult_pap, fur,
fpp, edad_gesta, pesofeto, tallafeto, imc, toxoide, influenza, otras,
medicament) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?)");
if ($statement->execute(array($_POST['gestas'], $_POST['abortos'],
$_POST['esp_conse'], $_POST['seleccion'], $_POST['partos'],
$_POST['vaginal'], $_POST['cesareas'], $_POST['nac_vivos'],
$_POST['nac_muertos'], $_POST['viven'], $_POST['semana'],
$_POST['des_semana'], $_POST['f_ult_parto'], $_POST['f_ult_pap'],
$_POST['fur'], $_POST['fpp'], $_POST['edad_gesta'],
$_POST['pesofeto'], $_POST['tallafeto'], $_POST['imc'],
$_POST['toxoide'], $_POST['influenza'], $_POST['otras'],
$_POST['medicament'])));
$dbSuccess = true;
} catch (Exception $e) {
$return['databaseException'] = $e->getMessage();
}
$dbh = null;
}
?>
all other data save nice into db.
What is the correct way to update a read url in the dataBinding event?
What is the correct way to update a read url in the dataBinding event?
For a grid, when I get the dataBinding event, I can change the url using:
this.dataSource.transport.options.read.url = 'data.acme.com/new/data';
Is this the best way to do this? Or are there getter/setter calls I should
use?
Code:
<div id="example4" class="k-content">
<div id="grid"></div>
<script>
$(document).ready(function() {
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read:
"http://demos.kendoui.com/service/Northwind.svc/Orders"
},
For a grid, when I get the dataBinding event, I can change the url using:
this.dataSource.transport.options.read.url = 'data.acme.com/new/data';
Is this the best way to do this? Or are there getter/setter calls I should
use?
Code:
<div id="example4" class="k-content">
<div id="grid"></div>
<script>
$(document).ready(function() {
$("#grid").kendoGrid({
dataSource: {
type: "odata",
transport: {
read:
"http://demos.kendoui.com/service/Northwind.svc/Orders"
},
Filter index for CanCan
Filter index for CanCan
I am trying to filter the index according to the ability. I am using the
wice_grid gem to make a table in the index, and to add a condition to
tickets, we could use something called :conditions.
I have tried to put it like that:
@tickets_grid = initialize_grid(Ticket,
:include => [:user, :employee_department,
:state],
:conditions =>
[Ticket.accessible_by(current_ability)])
This is not working, though. I'm looking for any suggestions.
I am trying to filter the index according to the ability. I am using the
wice_grid gem to make a table in the index, and to add a condition to
tickets, we could use something called :conditions.
I have tried to put it like that:
@tickets_grid = initialize_grid(Ticket,
:include => [:user, :employee_department,
:state],
:conditions =>
[Ticket.accessible_by(current_ability)])
This is not working, though. I'm looking for any suggestions.
Is it possible to install perl prerequisites before distribution testing and how?
Is it possible to install perl prerequisites before distribution testing
and how?
I try to build a Perl distribution for a home-made module, from the
Module::Starter base. Every test pass on my machine, but when I upload it
to CPAN to get some more universal tests from cpantesters.org, some test
failed on other architectures or OS. I can see in test reports that some
of my prerequisites are not installed before testing but I would like it
to.
I've tried to list these dependencies into the Makefile.PL PREREQ_PM hash
and then in the TEST_REQUIRES hash, but it didn't changed a lot of
results.
Then, when I've removed the dependencies from my local machine and tried
to install my module using Cpanm, it downloads dependencies first, test
passed and install has been a success.
This is my first try for a module, so I think I am missing something,
maybe I am too used of the Cpanm magic. Thanks for any help.
and how?
I try to build a Perl distribution for a home-made module, from the
Module::Starter base. Every test pass on my machine, but when I upload it
to CPAN to get some more universal tests from cpantesters.org, some test
failed on other architectures or OS. I can see in test reports that some
of my prerequisites are not installed before testing but I would like it
to.
I've tried to list these dependencies into the Makefile.PL PREREQ_PM hash
and then in the TEST_REQUIRES hash, but it didn't changed a lot of
results.
Then, when I've removed the dependencies from my local machine and tried
to install my module using Cpanm, it downloads dependencies first, test
passed and install has been a success.
This is my first try for a module, so I think I am missing something,
maybe I am too used of the Cpanm magic. Thanks for any help.
Sunday, 15 September 2013
Call java collections use an interface of an object instead of the object's class?
Call java collections use an interface of an object instead of the
object's class?
I want to call a method using a collection of objects that all implement
the same interface. Is this possible?
public class GenericsTest {
public void main() {
ArrayList<Strange> thisWorks = new ArrayList<>();
isAllStrange(thisWorks);
ArrayList<Person> thisDoesNot = new ArrayList<>();
isAllStrange(thisDoesNot);
}
public boolean isAllStrange(ArrayList<Strange> strangeCollection) {
for (Strange object : strangeCollection) {
if (object.isStrange())
return true;
}
return false;
}
public interface Strange {
public boolean isStrange();
}
public class Person implements Strange {
public boolean isStrange() {
return true;
}
}
}
object's class?
I want to call a method using a collection of objects that all implement
the same interface. Is this possible?
public class GenericsTest {
public void main() {
ArrayList<Strange> thisWorks = new ArrayList<>();
isAllStrange(thisWorks);
ArrayList<Person> thisDoesNot = new ArrayList<>();
isAllStrange(thisDoesNot);
}
public boolean isAllStrange(ArrayList<Strange> strangeCollection) {
for (Strange object : strangeCollection) {
if (object.isStrange())
return true;
}
return false;
}
public interface Strange {
public boolean isStrange();
}
public class Person implements Strange {
public boolean isStrange() {
return true;
}
}
}
why does this jquery code hide my paragraphs
why does this jquery code hide my paragraphs
Why does this code output 4 and all the other content does not get outputted?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery</title>
<script src="jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
var par = $("p");
document.write(par.length);
});
</script>
</head>
<body>
<p>I am one</p>
<p>I am two</p>
<p>I am three</p>
<p>I am four</p>
</body>
</html>
Why does this code output 4 and all the other content does not get outputted?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>jQuery</title>
<script src="jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
var par = $("p");
document.write(par.length);
});
</script>
</head>
<body>
<p>I am one</p>
<p>I am two</p>
<p>I am three</p>
<p>I am four</p>
</body>
</html>
How can I extend an object in Clojurescript?
How can I extend an object in Clojurescript?
I do not want to extend a class, just a one instance of a class with a
protocol. is this possible?
I do not want to extend a class, just a one instance of a class with a
protocol. is this possible?
regex for match more than one word enclosed in double quotes
regex for match more than one word enclosed in double quotes
I am trying to create editor as in stockoverflow. for that, i could not
construct the regex for match the match more than one word enclosed with
**. Looking for the pattern that can be used in javascript/jquery.
Can any please help me on this?
I am trying to create editor as in stockoverflow. for that, i could not
construct the regex for match the match more than one word enclosed with
**. Looking for the pattern that can be used in javascript/jquery.
Can any please help me on this?
Symfony2 messaging bundle
Symfony2 messaging bundle
I am using symfony2 with FOSUserBundle
I would like to add the features which are like facebook's message.
I am searching the messaging bundle here
However,couldn't find good bundles.
I am not sure which word should I use for searching 'messaging' is suitable?
Is there good messaging bundle for FOSUserBundle and symfony2 ?
I am using symfony2 with FOSUserBundle
I would like to add the features which are like facebook's message.
I am searching the messaging bundle here
However,couldn't find good bundles.
I am not sure which word should I use for searching 'messaging' is suitable?
Is there good messaging bundle for FOSUserBundle and symfony2 ?
Getting the max template instantation deph used during a compilation
Getting the max template instantation deph used during a compilation
As the title says, is there any compiler logging settings which provides
the max instantation deph reached by the compiler during the compilation?
If the compilation exceds the max template deph (Which GCC's default value
is 900 in C++11 mode), compilation fails. But what I need is to get the
maximum template instantation depth which the compiler has reached during
a successfull compilation.
As the title says, is there any compiler logging settings which provides
the max instantation deph reached by the compiler during the compilation?
If the compilation exceds the max template deph (Which GCC's default value
is 900 in C++11 mode), compilation fails. But what I need is to get the
maximum template instantation depth which the compiler has reached during
a successfull compilation.
Using Auryn or Pimple as a DIC in a simple MVC use case
Using Auryn or Pimple as a DIC in a simple MVC use case
I have the following example:
# bootstrap.php
define(DICTIONARY_PATH, '/dictionary/en_EN.dic');
------------------------------------------------------------------------
# /Model/User.php (active record)
class User {
public $Id;
public $Language;
public static function LoadById($intId) {
...
}
}
------------------------------------------------------------------------
# /Controller/UserController.php
class UserController {
protected $objUser;
public function __construct() {
$this->objUser = User::LoadById($_GET['id'));
}
public function showPage() {
$objDictionary = new Dictionary(DICTIONARY_PATH,
$this->objUser->Language);
...
}
}
------------------------------------------------------------------------
# /Model/Dictionary.php
class Dictionary {
public function __construct($strPath, $strLanguage) {
...
}
}
What I wish to know is how to use properly a PHP DIC library to solve the
following problems:
create the dictionary object inside the bootstrap file, because it's used
a lot in the application(the main problem is the second constructor param:
language is variable)
how can I pass the user object to the UserController in the constructor?
I have the following example:
# bootstrap.php
define(DICTIONARY_PATH, '/dictionary/en_EN.dic');
------------------------------------------------------------------------
# /Model/User.php (active record)
class User {
public $Id;
public $Language;
public static function LoadById($intId) {
...
}
}
------------------------------------------------------------------------
# /Controller/UserController.php
class UserController {
protected $objUser;
public function __construct() {
$this->objUser = User::LoadById($_GET['id'));
}
public function showPage() {
$objDictionary = new Dictionary(DICTIONARY_PATH,
$this->objUser->Language);
...
}
}
------------------------------------------------------------------------
# /Model/Dictionary.php
class Dictionary {
public function __construct($strPath, $strLanguage) {
...
}
}
What I wish to know is how to use properly a PHP DIC library to solve the
following problems:
create the dictionary object inside the bootstrap file, because it's used
a lot in the application(the main problem is the second constructor param:
language is variable)
how can I pass the user object to the UserController in the constructor?
Saturday, 14 September 2013
soming about the adt, virtual devices
soming about the adt, virtual devices
I'm first time to use the adt
when i unfold the target option, there is no android 2.3 or below version
therefore I would like to know how and where should I add these version in
the Target
thanks a lot!
http://s24.postimg.org/adavkl49f/123.png
I'm first time to use the adt
when i unfold the target option, there is no android 2.3 or below version
therefore I would like to know how and where should I add these version in
the Target
thanks a lot!
http://s24.postimg.org/adavkl49f/123.png
Is there a way to check if jobject is a local or global reference?
Is there a way to check if jobject is a local or global reference?
I cannot find an answer if there is a way to test an arbitrary jobject in
order to detect if it is a local or global reference. I do not see it in
JNI documentation.
The reason for this question is to add some error checking and logic for
my custom JNI utilities. In my code jobject reference can come from
different places (including from other users/modules) so I am looking for
a way to test it.
For example I want to have a utility to "promote" a local to global
reference, but it also should work with global references (that is it
shouldn't crash or anything if a global reference is passed). I could try
exception check but I don't know i can avoid false positives.
What can happen if DeleteLocalRef is called on a global reference.
Documentation says either global or local can be passed to NewGlobalRef
but I assume there will be a problem with deleting a wrong one.
jobject toGlobalRef(jobject& locRef)
{
JNIEnv* env = jniEnv(); //gets correct JNIEnv* here
if (locRef == NULL)
return NULL;
jobject globalRef = env->NewGlobalRef(locRef);
env->DeleteLocalRef(locRef);
locRef = NULL;
return globalRef;
}
I cannot find an answer if there is a way to test an arbitrary jobject in
order to detect if it is a local or global reference. I do not see it in
JNI documentation.
The reason for this question is to add some error checking and logic for
my custom JNI utilities. In my code jobject reference can come from
different places (including from other users/modules) so I am looking for
a way to test it.
For example I want to have a utility to "promote" a local to global
reference, but it also should work with global references (that is it
shouldn't crash or anything if a global reference is passed). I could try
exception check but I don't know i can avoid false positives.
What can happen if DeleteLocalRef is called on a global reference.
Documentation says either global or local can be passed to NewGlobalRef
but I assume there will be a problem with deleting a wrong one.
jobject toGlobalRef(jobject& locRef)
{
JNIEnv* env = jniEnv(); //gets correct JNIEnv* here
if (locRef == NULL)
return NULL;
jobject globalRef = env->NewGlobalRef(locRef);
env->DeleteLocalRef(locRef);
locRef = NULL;
return globalRef;
}
get selected marker google maps api 3
get selected marker google maps api 3
in the following code generated an undetermined number of markers, this
works well.
for(i=0;i<idr.length;i++){
var LatLng = new google.maps.LatLng(lat[i], lng[i]);
m[i] = new google.maps.Marker({
position: LatLng,
icon: image,
map: map,
draggable: false,
val: idr[i]
});
}
I want to get the properties of the corresponding marker when the mouse
passes over this
This does not apply for you should create a function for each marker and
can not be that many This function only access the first marker
google.maps.event.addListener(m[0], "click", function(e) {
var latitud = e.latLng.lat();
alert(latitud);
});
in the following code generated an undetermined number of markers, this
works well.
for(i=0;i<idr.length;i++){
var LatLng = new google.maps.LatLng(lat[i], lng[i]);
m[i] = new google.maps.Marker({
position: LatLng,
icon: image,
map: map,
draggable: false,
val: idr[i]
});
}
I want to get the properties of the corresponding marker when the mouse
passes over this
This does not apply for you should create a function for each marker and
can not be that many This function only access the first marker
google.maps.event.addListener(m[0], "click", function(e) {
var latitud = e.latLng.lat();
alert(latitud);
});
Accessing clicked cell instead of all cells using JQuery and Ajax
Accessing clicked cell instead of all cells using JQuery and Ajax
I am trying to edit a specific cell once it's clicked. When I click a cell
currently it turns all the td into textboxes. I would like only the
clicked cell do that. How can I access just the clicked cell? Here is my
current code: (ignore the .change function for now; I haven't fixed it
yet.
$(document).ready(function()
{
$(".edit_tr").click(function()
{
$(".text").hide();
$(".editbox").show();
}).change(function()
{
var ID=$(this).attr("#datanum");
for (var i = 0; i < ID; i++)
{
var input=$("#input_"+ID).val();
var text=$("#span_" + ID).val();
var dataString = 'id='+ ID
+'&firstname='+first+'&lastname='+last;
$("#first_"+ID).html('<img src="load.gif" />'); //
Loading image
if(input != text)
{
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#first_"+ID).html(first);
$("#last_"+ID).html(last);
}
});
}
else
{
alert('Enter something.');
}
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
This is my PHP code:
public function displayTable($table)
{
//connect to DB
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
echo "<table id='table' border='1'>"; //start an HTML table
$dbtable = $table;
$fields =array();
$result = mysqli_query($con, "SHOW COLUMNS FROM ".$dbtable);
//fill fields array with fields from table in database
while ($x = mysqli_fetch_assoc($result))
{
$fields[] = $x['Field'];
}
$fieldsnum = count($fields); //number of fields in array
//create table header from dbtable fields
foreach ($fields as $f)
{
echo "<th>".$f."</th>";
}
//create table rows from dbtable rows
$result = mysqli_query($con, "SELECT * FROM ".$dbtable);
$i = 0;
while ($row = mysqli_fetch_array($result))
{
$j = 0;
echo "<tr class='edit_tr' id='".$j."'>";
foreach ($fields as $f)
{
echo "<td class='edit_td'><span id='span_".$i."'
class='text'>".$row[$f]."</span>
<input type='text' value='".$row[$f]."' class='editbox'
id='input_".$i."'/> </td>";
$i++;
}
$j++;
echo "</tr>";
}
echo "</table>"; //close the HTML table
echo "<label id='datanum'>".$i."</label>";
//close connection
mysqli_close($con);
}
I am trying to edit a specific cell once it's clicked. When I click a cell
currently it turns all the td into textboxes. I would like only the
clicked cell do that. How can I access just the clicked cell? Here is my
current code: (ignore the .change function for now; I haven't fixed it
yet.
$(document).ready(function()
{
$(".edit_tr").click(function()
{
$(".text").hide();
$(".editbox").show();
}).change(function()
{
var ID=$(this).attr("#datanum");
for (var i = 0; i < ID; i++)
{
var input=$("#input_"+ID).val();
var text=$("#span_" + ID).val();
var dataString = 'id='+ ID
+'&firstname='+first+'&lastname='+last;
$("#first_"+ID).html('<img src="load.gif" />'); //
Loading image
if(input != text)
{
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#first_"+ID).html(first);
$("#last_"+ID).html(last);
}
});
}
else
{
alert('Enter something.');
}
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
This is my PHP code:
public function displayTable($table)
{
//connect to DB
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
echo "<table id='table' border='1'>"; //start an HTML table
$dbtable = $table;
$fields =array();
$result = mysqli_query($con, "SHOW COLUMNS FROM ".$dbtable);
//fill fields array with fields from table in database
while ($x = mysqli_fetch_assoc($result))
{
$fields[] = $x['Field'];
}
$fieldsnum = count($fields); //number of fields in array
//create table header from dbtable fields
foreach ($fields as $f)
{
echo "<th>".$f."</th>";
}
//create table rows from dbtable rows
$result = mysqli_query($con, "SELECT * FROM ".$dbtable);
$i = 0;
while ($row = mysqli_fetch_array($result))
{
$j = 0;
echo "<tr class='edit_tr' id='".$j."'>";
foreach ($fields as $f)
{
echo "<td class='edit_td'><span id='span_".$i."'
class='text'>".$row[$f]."</span>
<input type='text' value='".$row[$f]."' class='editbox'
id='input_".$i."'/> </td>";
$i++;
}
$j++;
echo "</tr>";
}
echo "</table>"; //close the HTML table
echo "<label id='datanum'>".$i."</label>";
//close connection
mysqli_close($con);
}
javascript to achive the same result as css ellipsis
javascript to achive the same result as css ellipsis
due to some reason I cant use the css method
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
width: 100px;
the above make my user define text in a li if reached 100px, it will add
'...', can it be achieve using jquery?
due to some reason I cant use the css method
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
width: 100px;
the above make my user define text in a li if reached 100px, it will add
'...', can it be achieve using jquery?
Creation date of a file from multiple os
Creation date of a file from multiple os
I created a text file in linux, ubuntu, and modified and changed the file
multiple times.
Is there anyway that I can figure out the creation date of this file?
It doesn't matter how hard or bruteforce the method is; is there
physically any way to
see the creation date?
If I see the file in windows, can I see the creation date?
I created a text file in linux, ubuntu, and modified and changed the file
multiple times.
Is there anyway that I can figure out the creation date of this file?
It doesn't matter how hard or bruteforce the method is; is there
physically any way to
see the creation date?
If I see the file in windows, can I see the creation date?
Replacement of youtube iframe with its thumbnail
Replacement of youtube iframe with its thumbnail
In this pen there are two post one is with title,image and some text and
second one is having a youtube iframe,title and text.I do not want text to
be appear and I've hide that but the problem is that youtube iframe is
showing but I want its thumbnail not the iframe.
Do some implementations in the following Jquery for youtube thumbnail.
$(function () {
$(".post").each(function () {
var posthead = $(this).find("h2.post-title").text(),
postlink = $(this).find("h2.posttitle a").attr("href");
var imageThumb = $(this).find("img:first"),
imageSrc=imageThumb.attr('src');
$(this).replaceWith("<div class='post'><img class='thumb' src='"
+ imageSrc + "'/><h2 class='hometitle'><a href='" + postlink +
"'>" + posthead + "</a></h2></div>");
});
});
In this pen there are two post one is with title,image and some text and
second one is having a youtube iframe,title and text.I do not want text to
be appear and I've hide that but the problem is that youtube iframe is
showing but I want its thumbnail not the iframe.
Do some implementations in the following Jquery for youtube thumbnail.
$(function () {
$(".post").each(function () {
var posthead = $(this).find("h2.post-title").text(),
postlink = $(this).find("h2.posttitle a").attr("href");
var imageThumb = $(this).find("img:first"),
imageSrc=imageThumb.attr('src');
$(this).replaceWith("<div class='post'><img class='thumb' src='"
+ imageSrc + "'/><h2 class='hometitle'><a href='" + postlink +
"'>" + posthead + "</a></h2></div>");
});
});
Friday, 13 September 2013
How to Publish ASP.Net Web service on my Server?
How to Publish ASP.Net Web service on my Server?
As i am New in Web service, I have successfully Created web service with
ASP>net and Run in local machine. Also i have Successfully publish in IIS
Server. But Now i want to publish web service on my Server.
Can anyone give me steps how to do? Thank You.
As i am New in Web service, I have successfully Created web service with
ASP>net and Run in local machine. Also i have Successfully publish in IIS
Server. But Now i want to publish web service on my Server.
Can anyone give me steps how to do? Thank You.
Can you help me fix the average portion of my code?
Can you help me fix the average portion of my code?
When I run this code and input numbers whose sum>100 the output is correct
for the count and the sum but the average is wrong. For example; input
8,10,99... the count is 3, the sum is 117 and should return an average of
39... the actual output returned is count 3, sum 117 and average 58.5. I
have come to realize this is because the average is being done using a
count of 2 instead of 3(or always one less than it should be with
different values). Why is this? It works perfect for inputs sum<=100.
PLEASE HELP :)
public static void main(String[] args) {
//Use Main Method for gathering input
float input = 1;
// Declare variable for sum
float theSum = 0;
// Declare variable for average
float average = 0;
// Declare variable for counting the number of user inputs
int counter = 0;
/* Initialize the while loop using an input of 0 as a sentinel value
* to exit the loop*/
while (input != 0) {
// Use JOptionPane method to accept input from user
input = Float.parseFloat(
JOptionPane.showInputDialog(
null, "Please enter a number. Enter 0 to quit: "));
// Invoke sum method and pass input and summation to sum method
theSum = (sum(input, theSum));
// Invoke avg method and pass summation and counter to avg
average = (avg(theSum, counter));
// Increment the counter variable
counter++;
if (theSum > 100)
{
JOptionPane.showMessageDialog(null, "The sum of your numbers "
+ "are greater than 100!");
break;
}
}
// Invoke display method and pass summation, average, and counter
variables to it
display(theSum, average, counter);
}
public static float sum(float num1, float sum) {
//Add the user's input number to the sum variable
sum += num1;
//Return value of sum variable as new summation variable
return sum;
}
public static float avg(float num1, int num2) {
//Declare and initialize variable for average
float average = 0;
//Calculate average
average = num1 / num2;
//Return value of average variable
return average;
}
public static void display(float sum, float average, int counter) {
/* I am subtracting 1 from variable counter so as not to include the
sentinel value
* of 0 that the user had to enter to exit the input loop in the
overall count*/
// Display the count, sum, and average to the user
if (sum > 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter) + ",
Sum = " + sum + ", Average = " + average);
}
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) +
", Sum = " + sum + ", Average = " + average);
}
}
}
When I run this code and input numbers whose sum>100 the output is correct
for the count and the sum but the average is wrong. For example; input
8,10,99... the count is 3, the sum is 117 and should return an average of
39... the actual output returned is count 3, sum 117 and average 58.5. I
have come to realize this is because the average is being done using a
count of 2 instead of 3(or always one less than it should be with
different values). Why is this? It works perfect for inputs sum<=100.
PLEASE HELP :)
public static void main(String[] args) {
//Use Main Method for gathering input
float input = 1;
// Declare variable for sum
float theSum = 0;
// Declare variable for average
float average = 0;
// Declare variable for counting the number of user inputs
int counter = 0;
/* Initialize the while loop using an input of 0 as a sentinel value
* to exit the loop*/
while (input != 0) {
// Use JOptionPane method to accept input from user
input = Float.parseFloat(
JOptionPane.showInputDialog(
null, "Please enter a number. Enter 0 to quit: "));
// Invoke sum method and pass input and summation to sum method
theSum = (sum(input, theSum));
// Invoke avg method and pass summation and counter to avg
average = (avg(theSum, counter));
// Increment the counter variable
counter++;
if (theSum > 100)
{
JOptionPane.showMessageDialog(null, "The sum of your numbers "
+ "are greater than 100!");
break;
}
}
// Invoke display method and pass summation, average, and counter
variables to it
display(theSum, average, counter);
}
public static float sum(float num1, float sum) {
//Add the user's input number to the sum variable
sum += num1;
//Return value of sum variable as new summation variable
return sum;
}
public static float avg(float num1, int num2) {
//Declare and initialize variable for average
float average = 0;
//Calculate average
average = num1 / num2;
//Return value of average variable
return average;
}
public static void display(float sum, float average, int counter) {
/* I am subtracting 1 from variable counter so as not to include the
sentinel value
* of 0 that the user had to enter to exit the input loop in the
overall count*/
// Display the count, sum, and average to the user
if (sum > 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter) + ",
Sum = " + sum + ", Average = " + average);
}
if (sum <= 100) {
JOptionPane.showMessageDialog(null, "Count = " + (counter - 1) +
", Sum = " + sum + ", Average = " + average);
}
}
}
Allowing user to stablish IP address using oscP5 with Processing Android
Allowing user to stablish IP address using oscP5 with Processing Android
Hello fellow processing developers,
I'm using OSCP5 to link two processing sketches, one from an android
device and the other in my computer, via WiFi.
I already tried it typing my computer's IP address directly on the new
NetAddress that's on the setup() and it works just fine. However, I think
it is best to give the user the chance to change the IP address of the
computer to where the message is sent (it may change IP or change network
and then the android app would not work).
I'm using a text field for the user to enter the IP address and then using
this in a string called ipAddress that goes into the NetAddress that goes
into the myRemoteLocation.
Here's my code (this goes on the phone):
import oscP5.*;
import netP5.*;
import apwidgets.*;
OscP5 oscP5;
NetAddress myRemoteLocation;
PWidgetContainer widgetContainer;
PEditText textField;
PButton button1;
PImage fondo;
boolean ValidIP = false;
String ipAddress = "192.168.0.107";
void setup() {
size(480,800);
smooth();
fondo = loadImage("fondoAnd.jpg");
widgetContainer = new PWidgetContainer(this);
textField = new PEditText(10,40,380,120);
button1 = new PButton(10,190,200,100,"Conectar");
widgetContainer.addWidget(textField);
widgetContainer.addWidget(button1);
oscP5 = new OscP5(this,12000);
myRemoteLocation = new NetAddress(ipAddress,12000);
}
void draw() {
if (ValidIP == true){
widgetContainer.hide();
myRemoteLocation = new NetAddress(ipAddress,12000);
background(fondo);
}
else if (ValidIP == false){
background(0);
textSize(20);
text("Ingrese un IP válido",10,30);
widgetContainer.show();
}
}
void mousePressed(){
OscMessage myMessage = new OscMessage("/test");
myMessage.add(8);
oscP5.send(myMessage, myRemoteLocation);
println("enviomensaje"); //I print this in the console to know if it
sends a message
}
void onClickWidget(PWidget widget){
if(widget == button1){
ipAddress = textField.getText();
myRemoteLocation = new NetAddress(ipAddress,12000);
ValidIP = true;
}
}
Hello fellow processing developers,
I'm using OSCP5 to link two processing sketches, one from an android
device and the other in my computer, via WiFi.
I already tried it typing my computer's IP address directly on the new
NetAddress that's on the setup() and it works just fine. However, I think
it is best to give the user the chance to change the IP address of the
computer to where the message is sent (it may change IP or change network
and then the android app would not work).
I'm using a text field for the user to enter the IP address and then using
this in a string called ipAddress that goes into the NetAddress that goes
into the myRemoteLocation.
Here's my code (this goes on the phone):
import oscP5.*;
import netP5.*;
import apwidgets.*;
OscP5 oscP5;
NetAddress myRemoteLocation;
PWidgetContainer widgetContainer;
PEditText textField;
PButton button1;
PImage fondo;
boolean ValidIP = false;
String ipAddress = "192.168.0.107";
void setup() {
size(480,800);
smooth();
fondo = loadImage("fondoAnd.jpg");
widgetContainer = new PWidgetContainer(this);
textField = new PEditText(10,40,380,120);
button1 = new PButton(10,190,200,100,"Conectar");
widgetContainer.addWidget(textField);
widgetContainer.addWidget(button1);
oscP5 = new OscP5(this,12000);
myRemoteLocation = new NetAddress(ipAddress,12000);
}
void draw() {
if (ValidIP == true){
widgetContainer.hide();
myRemoteLocation = new NetAddress(ipAddress,12000);
background(fondo);
}
else if (ValidIP == false){
background(0);
textSize(20);
text("Ingrese un IP válido",10,30);
widgetContainer.show();
}
}
void mousePressed(){
OscMessage myMessage = new OscMessage("/test");
myMessage.add(8);
oscP5.send(myMessage, myRemoteLocation);
println("enviomensaje"); //I print this in the console to know if it
sends a message
}
void onClickWidget(PWidget widget){
if(widget == button1){
ipAddress = textField.getText();
myRemoteLocation = new NetAddress(ipAddress,12000);
ValidIP = true;
}
}
How to copy data from one database/table to another database/table in oracle using toad
How to copy data from one database/table to another database/table in
oracle using toad
I am trying to copy a table data from dev box db to uat db which are 2
different data bases . I am trying in toad.All the connection details are
correct but its not working and throwing the following error.
[Error] Execution (12: 1): ORA-00900: invalid SQL statement
This is what i am trying
copy from abc/cde@//abc.abc.com:1521/devbox to
abc/cde@//abc.abc.com/uatbox INSERT TOOL_SERVICE_MAPPING (*) USING (SELECT
* FROM TOOL_SERVICE_MAPPING)
oracle using toad
I am trying to copy a table data from dev box db to uat db which are 2
different data bases . I am trying in toad.All the connection details are
correct but its not working and throwing the following error.
[Error] Execution (12: 1): ORA-00900: invalid SQL statement
This is what i am trying
copy from abc/cde@//abc.abc.com:1521/devbox to
abc/cde@//abc.abc.com/uatbox INSERT TOOL_SERVICE_MAPPING (*) USING (SELECT
* FROM TOOL_SERVICE_MAPPING)
PsExec: Win7-to-Win7 Access Denied (psexesvc remains)
PsExec: Win7-to-Win7 Access Denied (psexesvc remains)
I have a problem, and the Internet doesn't seem to have a solution, so
maybe someone here can help.
I'm trying to start a command-line prompt on a remote machine using
PsExec, but I keep getting an "Access is Denied" error. Both my local and
the remote machine are running Windows 7 Enterprise (local: x64, remote
x86) and I'm using PsExec 1.98. I use the following command:
psexec \\remote -u domain\user -p password -i -d cmd.exe
I have also tried other commands (such as using -s, -h, etc.), it doesn't
seem to make a difference. I have access to the admin$ share of the remote
machine from my local one. The Event Viewer tells me that a logon (and
logoff) occurs on the remote machine.
Also, PsExec creates the PSEXESVC.EXE in the windows directory, but does
not delete it! Interestingly, the same command works just fine on a
Win-7-Professional (x64) and it also works perfectly fine in reverse (i.e.
when executed from the remote machine to start cmd on the local one).
Deactivating anti-virus and firewall on the remote machine did not make a
difference. I cannot deactivate it on the local one, but I have my doubts
that the error is caused there.
Does anyone have any ideas?
I have a problem, and the Internet doesn't seem to have a solution, so
maybe someone here can help.
I'm trying to start a command-line prompt on a remote machine using
PsExec, but I keep getting an "Access is Denied" error. Both my local and
the remote machine are running Windows 7 Enterprise (local: x64, remote
x86) and I'm using PsExec 1.98. I use the following command:
psexec \\remote -u domain\user -p password -i -d cmd.exe
I have also tried other commands (such as using -s, -h, etc.), it doesn't
seem to make a difference. I have access to the admin$ share of the remote
machine from my local one. The Event Viewer tells me that a logon (and
logoff) occurs on the remote machine.
Also, PsExec creates the PSEXESVC.EXE in the windows directory, but does
not delete it! Interestingly, the same command works just fine on a
Win-7-Professional (x64) and it also works perfectly fine in reverse (i.e.
when executed from the remote machine to start cmd on the local one).
Deactivating anti-virus and firewall on the remote machine did not make a
difference. I cannot deactivate it on the local one, but I have my doubts
that the error is caused there.
Does anyone have any ideas?
Rails how to convert user input to normal "#{user.id}"
Rails how to convert user input to normal "#{user.id}"
I created an little app for me, where i can send birthday cards to
diffrent persons.
In my settings model i have two fields salutation and text.
So when i create an new card i would like to write into the salutation form:
"Happy Birthday, Mr.#{@friend.name}"
My problem is that when i want to print my salutation the #{@friend.name}
gets not evaluated.
I tried diffrent things to solve this problem eg:
puts salutation.to_s
puts "#{salutation}"
But it didnt worked! I hope somebody can help me with this! Thanks
I created an little app for me, where i can send birthday cards to
diffrent persons.
In my settings model i have two fields salutation and text.
So when i create an new card i would like to write into the salutation form:
"Happy Birthday, Mr.#{@friend.name}"
My problem is that when i want to print my salutation the #{@friend.name}
gets not evaluated.
I tried diffrent things to solve this problem eg:
puts salutation.to_s
puts "#{salutation}"
But it didnt worked! I hope somebody can help me with this! Thanks
Thursday, 12 September 2013
How to count no. of existing tables in mysql database
How to count no. of existing tables in mysql database
I am sometimes curious just to do a quick command line query to count the
number of tables in my database. Is that possible in MySQL? If so, what is
the query?
I am sometimes curious just to do a quick command line query to count the
number of tables in my database. Is that possible in MySQL? If so, what is
the query?
SQL Management Studio connects, but can't perform a select against Azure database?
SQL Management Studio connects, but can't perform a select against Azure
database?
I've successfully connected to an Azure hosted SQL database in SQL
Management studio, but I can't perform any queries that I can perform in
web matrix.
The following query works just fine in web matrix:
SELECT *
FROM [junglegymSQL].dbo.Action AS a
But when I try to execute it in SQL Management Studio I receive the
following error:
Msg 40515, Level 15, State 1, Line 16 Reference to database and/or server
name in 'junglegymSQL.dbo.Action' is not supported in this version of SQL
Server.
database?
I've successfully connected to an Azure hosted SQL database in SQL
Management studio, but I can't perform any queries that I can perform in
web matrix.
The following query works just fine in web matrix:
SELECT *
FROM [junglegymSQL].dbo.Action AS a
But when I try to execute it in SQL Management Studio I receive the
following error:
Msg 40515, Level 15, State 1, Line 16 Reference to database and/or server
name in 'junglegymSQL.dbo.Action' is not supported in this version of SQL
Server.
Reduce window automatically when you enter a website from a URL
Reduce window automatically when you enter a website from a URL
It is possible that when one enters a website from url, this is reduced to
a certain extent automatically with option to maximize or minimize, etc..
using jquery javascript...
How can I do it?
It is possible that when one enters a website from url, this is reduced to
a certain extent automatically with option to maximize or minimize, etc..
using jquery javascript...
How can I do it?
Celeryd - send an email on log level error and above
Celeryd - send an email on log level error and above
We have django configured to send us emails on any error or above which is
triggered. This is done using the standard LOGGING configuration in
Django. I want this same behavior in celery. I have it working to send me
emails on Exceptions ([CELERY_SEND_TASK_ERROR_EMAILS][2]), but I want an
email on any defined level - coincidentally error and above.
For example in any django files we can do this.
log = logging.getLogger(__name__)
log.error("Oh No!")
And voilà it will send us an email assuming the following is setup in
settings.
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': "[%(asctime)s] %(levelname)s
[%(name)s.%(funcName)s:%(lineno)d] %(message)s",
'datefmt': "%d/%b/%Y %H:%M:%S"
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'include_html': True,
},
},
'loggers': {
'': {
'handlers': ['logfile', 'mail_admins'],
'level': os.environ.get('DEBUG_LEVEL', 'ERROR'),
},
}
}
And for clarity I am calling celeryd like so.
../bin/python manage.py celeryd --settings=DJANGO_SETTINGS_MODULE \
--broker=amqp://RABBITMQ_USER:RABBITMQ_PASSWORD@localhost:5672/axis \
--beat --events --pidfile=/home/var/celeryd.pid \
--logfile=/home/logs/celeryd.log \
--loglevel=WARNING > /dev/null 2>&1
And the necessary celery related settings.
CELERY_SEND_EVENTS = True
CELERY_TRACK_STARTED = True
CELERYD_CONCURRENCY = 2
CELERYD_TASK_TIME_LIMIT = 60 * 60 * 2 # Kill anything longer than 2 hours
CELERY_TASK_RESULT_EXPIRES = 60 * 60 * 2
CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler"
CELERY_SEND_TASK_ERROR_EMAILS = True
CELERY_MAX_PREPARING = 600
And finally a basic test case which I feel should send two emails. One for
the error and the other for the exception..
from django.contrib.auth.models import User
import celery
from celery.schedules import crontab
from celery.utils.serialization import UnpickleableExceptionWrapper
from celery.utils.log import get_task_logger
log = get_task_logger(__name__)
@periodic_task(run_every=datetime.timedelta(minutes=5))
def noise_test(**kwargs):
log.info("Info NOISE TEST")
log.warning("Warning NOISE TEST")
log.error("Error NOISE TEST")
try:
User.objects.get(id=9999999)
except Exception as err:
from celery import current_app
err.args = list(err.args) + ["Crap"]
raise UnpickleableExceptionWrapper(
err.__class__.__module__, err.__class__.__name__, err.args)
We have django configured to send us emails on any error or above which is
triggered. This is done using the standard LOGGING configuration in
Django. I want this same behavior in celery. I have it working to send me
emails on Exceptions ([CELERY_SEND_TASK_ERROR_EMAILS][2]), but I want an
email on any defined level - coincidentally error and above.
For example in any django files we can do this.
log = logging.getLogger(__name__)
log.error("Oh No!")
And voilà it will send us an email assuming the following is setup in
settings.
LOGGING = {
'version': 1,
'disable_existing_loggers': True,
'formatters': {
'standard': {
'format': "[%(asctime)s] %(levelname)s
[%(name)s.%(funcName)s:%(lineno)d] %(message)s",
'datefmt': "%d/%b/%Y %H:%M:%S"
},
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'class': 'django.utils.log.AdminEmailHandler',
'include_html': True,
},
},
'loggers': {
'': {
'handlers': ['logfile', 'mail_admins'],
'level': os.environ.get('DEBUG_LEVEL', 'ERROR'),
},
}
}
And for clarity I am calling celeryd like so.
../bin/python manage.py celeryd --settings=DJANGO_SETTINGS_MODULE \
--broker=amqp://RABBITMQ_USER:RABBITMQ_PASSWORD@localhost:5672/axis \
--beat --events --pidfile=/home/var/celeryd.pid \
--logfile=/home/logs/celeryd.log \
--loglevel=WARNING > /dev/null 2>&1
And the necessary celery related settings.
CELERY_SEND_EVENTS = True
CELERY_TRACK_STARTED = True
CELERYD_CONCURRENCY = 2
CELERYD_TASK_TIME_LIMIT = 60 * 60 * 2 # Kill anything longer than 2 hours
CELERY_TASK_RESULT_EXPIRES = 60 * 60 * 2
CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler"
CELERY_SEND_TASK_ERROR_EMAILS = True
CELERY_MAX_PREPARING = 600
And finally a basic test case which I feel should send two emails. One for
the error and the other for the exception..
from django.contrib.auth.models import User
import celery
from celery.schedules import crontab
from celery.utils.serialization import UnpickleableExceptionWrapper
from celery.utils.log import get_task_logger
log = get_task_logger(__name__)
@periodic_task(run_every=datetime.timedelta(minutes=5))
def noise_test(**kwargs):
log.info("Info NOISE TEST")
log.warning("Warning NOISE TEST")
log.error("Error NOISE TEST")
try:
User.objects.get(id=9999999)
except Exception as err:
from celery import current_app
err.args = list(err.args) + ["Crap"]
raise UnpickleableExceptionWrapper(
err.__class__.__module__, err.__class__.__name__, err.args)
How to get %userprofile%\My Documents\
How to get %userprofile%\My Documents\
The following function will work if \My Documents\ is omitted, but I need
to get to my documents.
OpenTextFile("test.txt");
function OpenTextFile(file) {
var ObjShell = new ActiveXObject("Shell.Application");
var wShell = new ActiveXObject("WScript.Shell");
var path = wShell.ExpandEnvironmentStrings("%userprofile%\My
Documents\");
ObjShell.ShellExecute("Notepad.exe", file, path, "Open", "1");
}
as is, it gives me an error: Unterminated string constant Line 7 Char 80
The following function will work if \My Documents\ is omitted, but I need
to get to my documents.
OpenTextFile("test.txt");
function OpenTextFile(file) {
var ObjShell = new ActiveXObject("Shell.Application");
var wShell = new ActiveXObject("WScript.Shell");
var path = wShell.ExpandEnvironmentStrings("%userprofile%\My
Documents\");
ObjShell.ShellExecute("Notepad.exe", file, path, "Open", "1");
}
as is, it gives me an error: Unterminated string constant Line 7 Char 80
What are the benefits of using a version control for code?
What are the benefits of using a version control for code?
I'm trying to convince my boss to use something such as Git
I'm trying to convince my boss to use something such as Git
How to get the value from the database in android?
How to get the value from the database in android?
Hi am creating database in the android and adding values in the
database.while retrieving data ,am successfully retrieved.And i get data
in the for loop it contains 16 values.how can i separate this value.
dataBaseHelper db = new dataBaseHelper(this);
List<String> studentInfo = db.getContact(eid);
for(Iterator<String> i = studentInfo.iterator();
i.hasNext(); ) {
String item = i.next();
Toast.makeText(getApplicationContext(),item,
Toast.LENGTH_LONG).show();
in this code i have 14 values in item i want to separate each value.how to
do this?
Hi am creating database in the android and adding values in the
database.while retrieving data ,am successfully retrieved.And i get data
in the for loop it contains 16 values.how can i separate this value.
dataBaseHelper db = new dataBaseHelper(this);
List<String> studentInfo = db.getContact(eid);
for(Iterator<String> i = studentInfo.iterator();
i.hasNext(); ) {
String item = i.next();
Toast.makeText(getApplicationContext(),item,
Toast.LENGTH_LONG).show();
in this code i have 14 values in item i want to separate each value.how to
do this?
How to move an entire GPen object?
How to move an entire GPen object?
In Java using the acm.graphics GPen is there any way to move the entire
drawn sequence of lines? I've read the manual thoroughly and I'm beginning
to think it's not possible which brings me to my second question. Are
there any other graphics objects in Java that work very similar to a pen
that can also be moved. The reason I'm asking is because I've been working
on a graphing program that allows mouse gestures to be used to pan around
and zoom in and out. After building functionality for implicit functions I
realized simply clearing the drawing board and redrawing everything is not
going to cut it anymore so I really need to work on more efficient ways to
handle intermediate changes of the graph without having to recalculate
everything.
In Java using the acm.graphics GPen is there any way to move the entire
drawn sequence of lines? I've read the manual thoroughly and I'm beginning
to think it's not possible which brings me to my second question. Are
there any other graphics objects in Java that work very similar to a pen
that can also be moved. The reason I'm asking is because I've been working
on a graphing program that allows mouse gestures to be used to pan around
and zoom in and out. After building functionality for implicit functions I
realized simply clearing the drawing board and redrawing everything is not
going to cut it anymore so I really need to work on more efficient ways to
handle intermediate changes of the graph without having to recalculate
everything.
How to strip a part of the text obtained from web harvest
How to strip a part of the text obtained from web harvest
I am new to webharvest and am using it to get the article data from a
website, using the following statement:
let $text := data($doc//div[@id="articleBody"])
and this is the data that I get from the above statement :
The Refine Spa (Furman's Mill) was built as a stone grist mill along the
on a tributary of Capoolong Creek by Moore Furman, quartermaster general
of George Washington's army
Notable people
Notable current and former residents of Pittstown include:
My question is that, is it possible to remove the entire content which is
after "Notable people" using the configuration. Is it possible to do this
way? If its possible please let me know how. Thanks.
I am new to webharvest and am using it to get the article data from a
website, using the following statement:
let $text := data($doc//div[@id="articleBody"])
and this is the data that I get from the above statement :
The Refine Spa (Furman's Mill) was built as a stone grist mill along the
on a tributary of Capoolong Creek by Moore Furman, quartermaster general
of George Washington's army
Notable people
Notable current and former residents of Pittstown include:
My question is that, is it possible to remove the entire content which is
after "Notable people" using the configuration. Is it possible to do this
way? If its possible please let me know how. Thanks.
Wednesday, 11 September 2013
Wicked gem shows only one step
Wicked gem shows only one step
I have watched Wicked forms with wizard and I am trying to do my own form,
I have the following:
Employees_controller.rb
class EmployeesController < ApplicationController
def index
@employees = Employee.all
end
def show
@employee = Employee.find(params[:id])
end
def new
@employee = Employee.new
end
def create
@employee = Employee.new(params[:employee])
if @employee.save
flash[:notice] = 'An employee has been created.'
redirect_to employee_admission_steps_path(:employee_id =>
@employee.id)
else
flash[:error] = 'An error occurred please try again!'
redirect_to '/dashboard'
end
end
def edit
end
def update
end
def destroy
end
end
Employee_admission_steps_controller.rb
class EmployeeAdmissionStepsController < ApplicationController
include Wicked::Wizard
steps :employee_admission1 , :employee_admission2
def show
@employee = Employee.find(params[:employee_id])
render_wizard
end
def update
@employee = Employee.find(params[:employee_id])
@employee.update_attributes(params[:employee])
render_wizard(@employee)
end
private
def finish_wizard_path
users_path
end
end
employee_admission1.html.erb and employee_admission2.html.erb
both files have the following line in the begining:
<%= simple_form_for @employee, url: wizard_path(employee_id:
@employee.id), method: :put do |f| %>
and the following line in the end:
<%= f.submit 'Next', :class => "btn btn-success" %>
<% end %>
routes.rb
resources :employees
scope 'employees/:employee_id' do
resources :employee_admission_steps
end
1- Now my main problem is after filling employee_admission1.html.erb and
press next , it goes to finish wizard. how to make it go to
employee_admission2.html.erb ?
2- the second problem i tried to add flash message into
def finish_wizard_path
users_path
end
but it didn't work.
3- the after_save in my employee.rb model is not working
def add_to_users
new_user = User.new
new_user.user_name = self.first_name
new_user.first_name = self.first_name
new_user.last_name = self.last_name
new_user.email = self.email
new_user.password = "123456"
new_user.password_confirmation = "123456"
new_user.user_type_id = 2
end
although I have the same method in student.rb and it works successfully
but student doesn't use wicked so i though it could the problem.
I have watched Wicked forms with wizard and I am trying to do my own form,
I have the following:
Employees_controller.rb
class EmployeesController < ApplicationController
def index
@employees = Employee.all
end
def show
@employee = Employee.find(params[:id])
end
def new
@employee = Employee.new
end
def create
@employee = Employee.new(params[:employee])
if @employee.save
flash[:notice] = 'An employee has been created.'
redirect_to employee_admission_steps_path(:employee_id =>
@employee.id)
else
flash[:error] = 'An error occurred please try again!'
redirect_to '/dashboard'
end
end
def edit
end
def update
end
def destroy
end
end
Employee_admission_steps_controller.rb
class EmployeeAdmissionStepsController < ApplicationController
include Wicked::Wizard
steps :employee_admission1 , :employee_admission2
def show
@employee = Employee.find(params[:employee_id])
render_wizard
end
def update
@employee = Employee.find(params[:employee_id])
@employee.update_attributes(params[:employee])
render_wizard(@employee)
end
private
def finish_wizard_path
users_path
end
end
employee_admission1.html.erb and employee_admission2.html.erb
both files have the following line in the begining:
<%= simple_form_for @employee, url: wizard_path(employee_id:
@employee.id), method: :put do |f| %>
and the following line in the end:
<%= f.submit 'Next', :class => "btn btn-success" %>
<% end %>
routes.rb
resources :employees
scope 'employees/:employee_id' do
resources :employee_admission_steps
end
1- Now my main problem is after filling employee_admission1.html.erb and
press next , it goes to finish wizard. how to make it go to
employee_admission2.html.erb ?
2- the second problem i tried to add flash message into
def finish_wizard_path
users_path
end
but it didn't work.
3- the after_save in my employee.rb model is not working
def add_to_users
new_user = User.new
new_user.user_name = self.first_name
new_user.first_name = self.first_name
new_user.last_name = self.last_name
new_user.email = self.email
new_user.password = "123456"
new_user.password_confirmation = "123456"
new_user.user_type_id = 2
end
although I have the same method in student.rb and it works successfully
but student doesn't use wicked so i though it could the problem.
Align elements with list-type:outside style to the content border consistently
Align elements with list-type:outside style to the content border
consistently
I wonder if there exists an easy and solid way to style ul and li elements
so that when using list-style: outside , the li elements lign up with the
content above it, or with the content box in which it is in without
margins or padding.
Condider this: ( http://jsfiddle.net/Um5L9/2/ )
<div id = "container1">
<span>Something</span>
<ul>
<li>
<div>One</div>
<div>Some more text or content here</div>
</li>
<li>
<div>One</div>
<div>Some more text or content here</div>
</li>
<li>
<div>One</div>
<div>Some more text or content here</div>
</li>
</ul>
</div>
body {
margin:20px;
border: 1px solid #333;
}
ul {
list-style: square outside none;
}
The result will be this:
What I want is this:
And it's easy to do by just adding some padding:
ul {
list-style: square outside none;
padding-left:15px;
}
But there has to be a better way surely than setting pixel margins. Maybe
something that would work for all font sizes?
Thanks!
consistently
I wonder if there exists an easy and solid way to style ul and li elements
so that when using list-style: outside , the li elements lign up with the
content above it, or with the content box in which it is in without
margins or padding.
Condider this: ( http://jsfiddle.net/Um5L9/2/ )
<div id = "container1">
<span>Something</span>
<ul>
<li>
<div>One</div>
<div>Some more text or content here</div>
</li>
<li>
<div>One</div>
<div>Some more text or content here</div>
</li>
<li>
<div>One</div>
<div>Some more text or content here</div>
</li>
</ul>
</div>
body {
margin:20px;
border: 1px solid #333;
}
ul {
list-style: square outside none;
}
The result will be this:
What I want is this:
And it's easy to do by just adding some padding:
ul {
list-style: square outside none;
padding-left:15px;
}
But there has to be a better way surely than setting pixel margins. Maybe
something that would work for all font sizes?
Thanks!
Ojective-C @protocol equivalent in C++
Ojective-C @protocol equivalent in C++
Class A has an instance of class B as a member. Sometimes the instance of
class B wants to talk to class A. In Objective-C I can do:
// A.h
@interface A : NSObject <BDelegate>
@property (nonatomic, retain) B *b;
@end
// A.m
- (void) classBsays {
}
// B.h
@protocol BDelegate
- (void) classBsays;
@end
@interface B : NSObject
@property (nonatomic, assign) id<BDelegate> delegate;
@end
// B.m
@implementation B
- (void) f {
[delegate classBsays];
}
@end
I've done something similar in C++ using a void pointer on class B. But
this misses the part that says "class B's delegate should implement such
and such methods".
How can I imitate Objective-C's protocol in C++?
Class A has an instance of class B as a member. Sometimes the instance of
class B wants to talk to class A. In Objective-C I can do:
// A.h
@interface A : NSObject <BDelegate>
@property (nonatomic, retain) B *b;
@end
// A.m
- (void) classBsays {
}
// B.h
@protocol BDelegate
- (void) classBsays;
@end
@interface B : NSObject
@property (nonatomic, assign) id<BDelegate> delegate;
@end
// B.m
@implementation B
- (void) f {
[delegate classBsays];
}
@end
I've done something similar in C++ using a void pointer on class B. But
this misses the part that says "class B's delegate should implement such
and such methods".
How can I imitate Objective-C's protocol in C++?
Parse Multiple checkbox value Jquery ajax
Parse Multiple checkbox value Jquery ajax
I need to parse with ajax to php file the following form. I can't use use
serialize().
< input type="checkbox" name="Filter[0]" value="Train" id="Filter">
< input type="checkbox" name="Filter[1]" value="Airplane" id="Filter1">
I was thinking
var Filter = $('#Filter').val();
.....
data: {..., ..., Filter:Filter}
it doesn't work. Any Idea?
I need to parse with ajax to php file the following form. I can't use use
serialize().
< input type="checkbox" name="Filter[0]" value="Train" id="Filter">
< input type="checkbox" name="Filter[1]" value="Airplane" id="Filter1">
I was thinking
var Filter = $('#Filter').val();
.....
data: {..., ..., Filter:Filter}
it doesn't work. Any Idea?
Tcl switch statement and -regexp quoting?
Tcl switch statement and -regexp quoting?
There must be an extra level of evaluation when using the Tcl switch
command. Here's an example session at the repl to show what I mean:
$ tclsh
% regexp {^\s*foo} " foo"
1
% regexp {^\\s*foo} " foo"
0
% switch -regexp " foo" {^\\s*foo {puts "match"}}
match
% switch -regexp " foo" {{^\s*foo} {puts "match"}}
match
...There needed to be an extra backslash added inside the first "switch"
version. This is consistent between 8.5.0 and 8.6.0 on Windows. Can
someone point me to the section of the manual where this and similar
instances of extra levels of unquoting are described? My first thought was
that the curly brackets in the first "switch" version would have protected
the backslash, but "switch" itself must be applying an extra level of
backslash susbtitution to the patterns. Unless I'm misunderstanding the
nuances of something else.
There must be an extra level of evaluation when using the Tcl switch
command. Here's an example session at the repl to show what I mean:
$ tclsh
% regexp {^\s*foo} " foo"
1
% regexp {^\\s*foo} " foo"
0
% switch -regexp " foo" {^\\s*foo {puts "match"}}
match
% switch -regexp " foo" {{^\s*foo} {puts "match"}}
match
...There needed to be an extra backslash added inside the first "switch"
version. This is consistent between 8.5.0 and 8.6.0 on Windows. Can
someone point me to the section of the manual where this and similar
instances of extra levels of unquoting are described? My first thought was
that the curly brackets in the first "switch" version would have protected
the backslash, but "switch" itself must be applying an extra level of
backslash susbtitution to the patterns. Unless I'm misunderstanding the
nuances of something else.
SAS Proc Rank by score: min number of a counts of target variable
SAS Proc Rank by score: min number of a counts of target variable
I have used SAS PROC Rank to rank a population based on score and create
groups of equal size. I would like to create groups such that there is a
minimum number of target variable (Goods and Bads) in each bin. Is there a
way to do that using proc rank? I understand that the size of each bin
would be different.
For example in the table below, I have created 10 groups based on a
certain score. As you can see the non cures in the lower deciles are
sparse. I would like to create groups such there there are at least 10 Non
cures in each group.
Cures and Non cures are based on same variable: Cure = 1 and Cure = 0
Decile cures non cures
0 262 94
1 314 44
2 340 19
3 340 13
4 353 10
5 373 5
6 308 3
7 342 3
8 440 4
9 305 3
Thanks,
Pradeep
I have used SAS PROC Rank to rank a population based on score and create
groups of equal size. I would like to create groups such that there is a
minimum number of target variable (Goods and Bads) in each bin. Is there a
way to do that using proc rank? I understand that the size of each bin
would be different.
For example in the table below, I have created 10 groups based on a
certain score. As you can see the non cures in the lower deciles are
sparse. I would like to create groups such there there are at least 10 Non
cures in each group.
Cures and Non cures are based on same variable: Cure = 1 and Cure = 0
Decile cures non cures
0 262 94
1 314 44
2 340 19
3 340 13
4 353 10
5 373 5
6 308 3
7 342 3
8 440 4
9 305 3
Thanks,
Pradeep
Subscript out of range (Error 9)
Subscript out of range (Error 9)
SourceBook = ActiveWorkbook.Name
SourceSheet = Workbooks(SourceBook).Worksheets(2).Name
If Workbooks(SourceBook).Sheets(SourceSheet).Range("B10") = "SM" Then
Workbooks(SourceBook).Worksheets(SourceSheet).Range("D11:D3000,K11:K3000,N11:AC3000,CX11:CX3000,DD11:DD3000").Select
Selection.Copy
When i type code above, i am getting result. But later, when i type code,
ElseIf Workbooks(SourceWorkbook).Sheets(SourceSheet).Range("B1") =
"Status" Then MsgBox ("okay....")
it shows "Subscript out of range (Error 9)".
can you help?
SourceBook = ActiveWorkbook.Name
SourceSheet = Workbooks(SourceBook).Worksheets(2).Name
If Workbooks(SourceBook).Sheets(SourceSheet).Range("B10") = "SM" Then
Workbooks(SourceBook).Worksheets(SourceSheet).Range("D11:D3000,K11:K3000,N11:AC3000,CX11:CX3000,DD11:DD3000").Select
Selection.Copy
When i type code above, i am getting result. But later, when i type code,
ElseIf Workbooks(SourceWorkbook).Sheets(SourceSheet).Range("B1") =
"Status" Then MsgBox ("okay....")
it shows "Subscript out of range (Error 9)".
can you help?
Passing function as arguments in Matlab
Passing function as arguments in Matlab
I've just started to program and i've had some problems in passing
function as arguments using Matlab. I've to implementate Lagrange
Algorithm for interpolation. C1 and C2 are vectors that represent points
to interpolate coordinates.
My main problem is that I don't know how to explain in my f1 definition
that temp1 and temp2 are not variables but values determined on every for
loop (for i and j). I think the code remaining part could be almost
correct.
function [ ] = lagrange( C1,C2 )
n=length(C1);
f2=inline('');
g=inline('');
for i=1:n
temp0=C2(i);
temp1=C1(i);
for j=1:n
if (i~=j)
temp2=C1(j);
temp3=C2(j);
f1=inline('(x-temp2/(temp1-temp2)','x','temp1','temp2');
f2=f2.*f1
end
g=g+temp0*f2;
end
end
%plot g
end
I've just started to program and i've had some problems in passing
function as arguments using Matlab. I've to implementate Lagrange
Algorithm for interpolation. C1 and C2 are vectors that represent points
to interpolate coordinates.
My main problem is that I don't know how to explain in my f1 definition
that temp1 and temp2 are not variables but values determined on every for
loop (for i and j). I think the code remaining part could be almost
correct.
function [ ] = lagrange( C1,C2 )
n=length(C1);
f2=inline('');
g=inline('');
for i=1:n
temp0=C2(i);
temp1=C1(i);
for j=1:n
if (i~=j)
temp2=C1(j);
temp3=C2(j);
f1=inline('(x-temp2/(temp1-temp2)','x','temp1','temp2');
f2=f2.*f1
end
g=g+temp0*f2;
end
end
%plot g
end
Tuesday, 10 September 2013
How to Justify the text in asp.net
How to Justify the text in asp.net
I am Using asp.net and i have the following Data :
Users are prohibited from posting or transmitting any unlawful,
threatening,libelous, defamatory, obscene, scandalous, inflammatory,
abusive, hateful, pornographic, or profane material, or any material that
could constitute or encourage conduct that would be considered a criminal
offense, give rise to civil liability, or otherwise violate any law. We
reserve the right, in our sole and absolute discretion, to terminate,
suspend or restrict your access to this Site, unilaterally and without
notice, in the event you violate any of the terms of this Agreement. In
addition, if asked to do so, you agree that you will not attempt to access
this Site. We also reserve any and all remedies at law or equity in
connection with any violation of this Agreement. You agree, at your own
expense, to indemnify, defend and hold the Company (and its subsidiaries,
affiliates, officers, directors, agents, employees and third parties
providing content) harmless from and against any claim or demand and all
losses incurred related to the use of the Site.
We use a diverse range of information, text, photographs, designs,
graphics, images, sound and video recordings, animation, content,
advertisement and other materials and effects (collectively "Materials")
for the search services on the Media. We provide the Material through the
Media FOR YOUR PERSONAL AND NON-COMMERCIAL USE ONLY.
I have tried this but the result is the text are align to left. I want to
justify the text. Is there any attribute for justifying the text in
asp.net using css? Please help.
I am Using asp.net and i have the following Data :
Users are prohibited from posting or transmitting any unlawful,
threatening,libelous, defamatory, obscene, scandalous, inflammatory,
abusive, hateful, pornographic, or profane material, or any material that
could constitute or encourage conduct that would be considered a criminal
offense, give rise to civil liability, or otherwise violate any law. We
reserve the right, in our sole and absolute discretion, to terminate,
suspend or restrict your access to this Site, unilaterally and without
notice, in the event you violate any of the terms of this Agreement. In
addition, if asked to do so, you agree that you will not attempt to access
this Site. We also reserve any and all remedies at law or equity in
connection with any violation of this Agreement. You agree, at your own
expense, to indemnify, defend and hold the Company (and its subsidiaries,
affiliates, officers, directors, agents, employees and third parties
providing content) harmless from and against any claim or demand and all
losses incurred related to the use of the Site.
We use a diverse range of information, text, photographs, designs,
graphics, images, sound and video recordings, animation, content,
advertisement and other materials and effects (collectively "Materials")
for the search services on the Media. We provide the Material through the
Media FOR YOUR PERSONAL AND NON-COMMERCIAL USE ONLY.
I have tried this but the result is the text are align to left. I want to
justify the text. Is there any attribute for justifying the text in
asp.net using css? Please help.
Subscribe to:
Comments (Atom)