Cannot find my data in lost+found folder in home folder
I am using Ubuntu 12.0. I kept all my data in lost+found folder in home
folder. If I open this folder, it is coming that I do not have permission
to open this folder. Here are the commands I am getting:
srujana@srujana-desktop:/home$ ls -l /home
total 20
drwx------ 2 srujana srujana 16384 Jul 22 00:40 lost+found
drwxr-xr-x 32 srujana srujana 4096 Sep 28 17:43 srujana
I don't understand where has all my data gone.
Please help me... Thank you.
Monday, 30 September 2013
Why is one stack piece in the Stack Overflow logo slightly off=?iso-8859-1?Q?=3F_=96_meta.stackoverflow.com?=
Why is one stack piece in the Stack Overflow logo slightly off? –
meta.stackoverflow.com
I understand this question has already been asked but in this I have
expounded on the issue and explain more unsightly features of the Stack
Overflow logo. I'm not sure why but every time I visit …
meta.stackoverflow.com
I understand this question has already been asked but in this I have
expounded on the issue and explain more unsightly features of the Stack
Overflow logo. I'm not sure why but every time I visit …
Uinput virtual device doesn't open android
Uinput virtual device doesn't open android
I'm trying to create a virtual device on Android but despite my efforts i
can't seem to be able to open /dev/uinput.
I've created a native library and with it i can open the devices from
dev/input and can even monitor, inject and block events. Most of it came
from
http://www.pocketmagic.net/2013/01/programmatically-injecting-events-on-android-part-2/#.UkmnRtKfjz9.
int fd;
fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
I've checked and there is /dev/uinput and i've also granted permissions
666 to /dev/uinput.
Any ideas?
I'm trying to create a virtual device on Android but despite my efforts i
can't seem to be able to open /dev/uinput.
I've created a native library and with it i can open the devices from
dev/input and can even monitor, inject and block events. Most of it came
from
http://www.pocketmagic.net/2013/01/programmatically-injecting-events-on-android-part-2/#.UkmnRtKfjz9.
int fd;
fd = open("/dev/uinput", O_WRONLY | O_NONBLOCK);
I've checked and there is /dev/uinput and i've also granted permissions
666 to /dev/uinput.
Any ideas?
Ading Formula to a cell using macro
Ading Formula to a cell using macro
Dim dflrow As Integer
ActiveWorkbook.Sheets("ElecTM").Range("I1048576").Select
dflrow = Selection.End(xlUp).Row
' ActiveWorkbook.Sheets("ElecTM").Range("AG" & dflrow & ":" & "AJ"
& dflrow).Select
ActiveWorkbook.Sheets("ElecTM").Range("AG6").Formula =
"=CONCATENATE(Year(I6),"w",WeekNum(I6))"
Selection.FillDown
Here i am getting an error saying syntax error on fifth line.I have
tried'.value' instead of '.Formula'.But that didn't help.Can u help?
Dim dflrow As Integer
ActiveWorkbook.Sheets("ElecTM").Range("I1048576").Select
dflrow = Selection.End(xlUp).Row
' ActiveWorkbook.Sheets("ElecTM").Range("AG" & dflrow & ":" & "AJ"
& dflrow).Select
ActiveWorkbook.Sheets("ElecTM").Range("AG6").Formula =
"=CONCATENATE(Year(I6),"w",WeekNum(I6))"
Selection.FillDown
Here i am getting an error saying syntax error on fifth line.I have
tried'.value' instead of '.Formula'.But that didn't help.Can u help?
Sunday, 29 September 2013
$near requires geojson point, given geojson point
$near requires geojson point, given geojson point
I have documents which contain a geo field like the below.
"geo" : {
"type" : "Point",
"coordinates" : [
37.44609999,
-121.88355687
]
},
I have created a spatial index, proof below.
db.collection.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "db.collection",
"name" : "_id_"
},
{
"v" : 1,
"key" : {
"geo.coordinates" : "2dsphere"
},
"ns" : "db.collection",
"name" : "geo.coordinates_2dsphere"
}
]
However when I execute the following query (verbatim from the MongoDB
manual ).
db.collection.find( { 'geo.coordinates': { $near:
{ $geometry :
{ type : "Point",
coordinates: [
37.44609999,
-121.88355687 ] } },
$maxDistance: 1000
} } )
I get the following error.
error: {
"$err" : "$near requires geojson point, given { type: \"Point\",
coordinates: [ 37.44609999, -121.88355687 ] }",
"code" : 16681
}
Can someone enlighten me as to why?
I have documents which contain a geo field like the below.
"geo" : {
"type" : "Point",
"coordinates" : [
37.44609999,
-121.88355687
]
},
I have created a spatial index, proof below.
db.collection.getIndexes()
[
{
"v" : 1,
"key" : {
"_id" : 1
},
"ns" : "db.collection",
"name" : "_id_"
},
{
"v" : 1,
"key" : {
"geo.coordinates" : "2dsphere"
},
"ns" : "db.collection",
"name" : "geo.coordinates_2dsphere"
}
]
However when I execute the following query (verbatim from the MongoDB
manual ).
db.collection.find( { 'geo.coordinates': { $near:
{ $geometry :
{ type : "Point",
coordinates: [
37.44609999,
-121.88355687 ] } },
$maxDistance: 1000
} } )
I get the following error.
error: {
"$err" : "$near requires geojson point, given { type: \"Point\",
coordinates: [ 37.44609999, -121.88355687 ] }",
"code" : 16681
}
Can someone enlighten me as to why?
Does anyone have a recommendation for a single Processor solution enterprise SQL server setup
Does anyone have a recommendation for a single Processor solution
enterprise SQL server setup
I am trying to put together a starting point for the hardware requirements
on a basic Redundant Enterprise level Sql server solution that would be
connected to a pool of application servers.
From my research so far I have identified the following:
Each server will need a processor license of about $7K (for 2008 - but I
may be wrong) but What I need to know is what is a TYPICAL hardware
configuration to expect. And before anyone answers " Well every situation
is different...", etc, I am not putting a man on the moon. I want just
need 1 solution that is middle of the road that works, not the most
expensive, not the cheapest, but it works in +75% of the environments it
may be needed for.
So I am thinking I may need some storage needs that need to be taken into
consideration (RAID Arrays), and then the server to run the SQL server,
and then anything else people might think I may need. (If I want
redundancy, i believe that I would need a second license for the backup
server - but not sure about that)
Thanks!
Steve
enterprise SQL server setup
I am trying to put together a starting point for the hardware requirements
on a basic Redundant Enterprise level Sql server solution that would be
connected to a pool of application servers.
From my research so far I have identified the following:
Each server will need a processor license of about $7K (for 2008 - but I
may be wrong) but What I need to know is what is a TYPICAL hardware
configuration to expect. And before anyone answers " Well every situation
is different...", etc, I am not putting a man on the moon. I want just
need 1 solution that is middle of the road that works, not the most
expensive, not the cheapest, but it works in +75% of the environments it
may be needed for.
So I am thinking I may need some storage needs that need to be taken into
consideration (RAID Arrays), and then the server to run the SQL server,
and then anything else people might think I may need. (If I want
redundancy, i believe that I would need a second license for the backup
server - but not sure about that)
Thanks!
Steve
Aligning output in Python?
Aligning output in Python?
Is there a way where I can right-align my output in such a way like this:
Item: $ 13.69
Tax: $ 5.30
Oth: $ 2.50
---------------
Total: $ 99.80
Please note that I am using Python 3.
Is there a way where I can right-align my output in such a way like this:
Item: $ 13.69
Tax: $ 5.30
Oth: $ 2.50
---------------
Total: $ 99.80
Please note that I am using Python 3.
Need Regular Expression that Validate Decimal (18,3)
Need Regular Expression that Validate Decimal (18,3)
first thanks for helping in advanced :D , i need a Regular that validate
Decimal (18,3) this mean max number of digits before comma is 15 and
accept 3 numbers after comma . 18 precision 3 scale .
Valid
123456789.123
123456789123456.12
12345.1
123456789123456
not valid
1234567891234567
123.1234
1.12345
.1234
Thank you .
first thanks for helping in advanced :D , i need a Regular that validate
Decimal (18,3) this mean max number of digits before comma is 15 and
accept 3 numbers after comma . 18 precision 3 scale .
Valid
123456789.123
123456789123456.12
12345.1
123456789123456
not valid
1234567891234567
123.1234
1.12345
.1234
Thank you .
Saturday, 28 September 2013
How to add a Search button?
How to add a Search button?
I have a search input on my site that works by clicking 'Enter', but for
some reason I can't figure out how to simply implement a clickable
'Search' button (image button) to go along next to it. How do I do this?
Here is my search code:
<div id="searchwrap">
<li id="search">
<form id="search-form" name="search" action="/products" method="get">
<input id="search-input" name="search" type="text">
</form>
</li></div>
I have a search input on my site that works by clicking 'Enter', but for
some reason I can't figure out how to simply implement a clickable
'Search' button (image button) to go along next to it. How do I do this?
Here is my search code:
<div id="searchwrap">
<li id="search">
<form id="search-form" name="search" action="/products" method="get">
<input id="search-input" name="search" type="text">
</form>
</li></div>
How to make a PHP Twitter API 1.1 delete tweet tool faster?
How to make a PHP Twitter API 1.1 delete tweet tool faster?
Hello :) I have been trying out ways to make my Tweet delete script faster
at deleting Tweets. I've tried using foreach and while loops, to loop
through an array of Tweet IDs and POST them to the Twitter API, but this
only deletes one Tweet every 2 seconds, roughly, and this speed does not
increase even if I cache the Tweet IDs beforehand using a text file or
MySQL.
The Twitter API requires that only one Tweet ID at a time is POSTed, and
the API returns a summary of all the Tweets that were deleted once the
POST process has completed.
How can I use PHP to send multiple single requests at the same time to the
API for faster deletion, instead of sending one Tweet ID at a time? The
Twitter API library I am using, uses cURL. Here is the deletion script
using a foreach loop.
$url =
'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = "?screen_name=" . $myscreenname . "&count=200";
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$results = json_decode($response, true);
foreach ($results as $arrSearchResult)
{
$post['id'] = $arrSearchResult['id_str'];
$url = "https://api.twitter.com/1.1/statuses/destroy/%s.json";
$postfields = array
(
"id" => null,
"trim_user" => true
);
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->buildOauth(sprintf($url,
$arrSearchResult['id_str']), "POST")
->setPostfields($postfields)
->performRequest();
}
Hello :) I have been trying out ways to make my Tweet delete script faster
at deleting Tweets. I've tried using foreach and while loops, to loop
through an array of Tweet IDs and POST them to the Twitter API, but this
only deletes one Tweet every 2 seconds, roughly, and this speed does not
increase even if I cache the Tweet IDs beforehand using a text file or
MySQL.
The Twitter API requires that only one Tweet ID at a time is POSTed, and
the API returns a summary of all the Tweets that were deleted once the
POST process has completed.
How can I use PHP to send multiple single requests at the same time to the
API for faster deletion, instead of sending one Tweet ID at a time? The
Twitter API library I am using, uses cURL. Here is the deletion script
using a foreach loop.
$url =
'https://api.twitter.com/1.1/statuses/user_timeline.json';
$getfield = "?screen_name=" . $myscreenname . "&count=200";
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
$results = json_decode($response, true);
foreach ($results as $arrSearchResult)
{
$post['id'] = $arrSearchResult['id_str'];
$url = "https://api.twitter.com/1.1/statuses/destroy/%s.json";
$postfields = array
(
"id" => null,
"trim_user" => true
);
$twitter = new TwitterAPIExchange($settings);
$response = $twitter->buildOauth(sprintf($url,
$arrSearchResult['id_str']), "POST")
->setPostfields($postfields)
->performRequest();
}
RunTime Data for dependency injection?
RunTime Data for dependency injection?
I have the following interface
public interface ISender
{
void SendMessage(string msg);
}
along with the following implementation
public class EmailSender : ISender
{
private EmailSettings _emailSettings;
EmailSender(EmailSettings _emailSettings)
public SendMessage(string msg);
}
public class EventLogSender : ISender
{
void SendMessage(string msg);
}
public class QuerySetting
{
string statementToExecute;
int MStoWaitBeforeExecute;
// if set to true then use email settings to perform notification
through email
bool UseEmail;
EmailSettings EmailSettings;
}
public class EmailSettings
{
string serverip;
int port;
string username;
string password;
string MailToAddress;
}
At runtime, a list of queries are loaded into the application. Each query
contains information about how often to execute the query, information
about when to fire an alarm for the query, and email information on who to
email when an alarm occurs( or if not set, the alarm should just write to
the event log ). How do i use dependency injection, at runtime, to know
what instanation of ISender to create ( EmailSender or EventLogSender )
and also to new up the appropriate email settings for the query if they
opted to use email notification instead of eventlog notification?
I have the following interface
public interface ISender
{
void SendMessage(string msg);
}
along with the following implementation
public class EmailSender : ISender
{
private EmailSettings _emailSettings;
EmailSender(EmailSettings _emailSettings)
public SendMessage(string msg);
}
public class EventLogSender : ISender
{
void SendMessage(string msg);
}
public class QuerySetting
{
string statementToExecute;
int MStoWaitBeforeExecute;
// if set to true then use email settings to perform notification
through email
bool UseEmail;
EmailSettings EmailSettings;
}
public class EmailSettings
{
string serverip;
int port;
string username;
string password;
string MailToAddress;
}
At runtime, a list of queries are loaded into the application. Each query
contains information about how often to execute the query, information
about when to fire an alarm for the query, and email information on who to
email when an alarm occurs( or if not set, the alarm should just write to
the event log ). How do i use dependency injection, at runtime, to know
what instanation of ISender to create ( EmailSender or EventLogSender )
and also to new up the appropriate email settings for the query if they
opted to use email notification instead of eventlog notification?
Deleting multiple rows from a table
Deleting multiple rows from a table
I have a table and I want to delete all rows with a specific card serial .
There are multiple rows with the same card serial .So I wrote this code
but it seems that's not working:
try
{
using (SqlConnection con = new
SqlConnection(WF_AbsPres.Properties.Settings.Default.DbConnectionString))
{
con.Open();
SqlCommand command2 = new SqlCommand("DELETE FORM DevInOut where
Cardserial='" + textBox5.Text + "'", con);
command2.ExecuteNonQuery();
con.Close();
}
}
catch (SqlException ex)
{
}
how can assure all the rows will be deleted . Should I use procedure? How
do I use procedure?
I have a table and I want to delete all rows with a specific card serial .
There are multiple rows with the same card serial .So I wrote this code
but it seems that's not working:
try
{
using (SqlConnection con = new
SqlConnection(WF_AbsPres.Properties.Settings.Default.DbConnectionString))
{
con.Open();
SqlCommand command2 = new SqlCommand("DELETE FORM DevInOut where
Cardserial='" + textBox5.Text + "'", con);
command2.ExecuteNonQuery();
con.Close();
}
}
catch (SqlException ex)
{
}
how can assure all the rows will be deleted . Should I use procedure? How
do I use procedure?
Friday, 27 September 2013
Can I load a function from the came controller in Codeigniter?
Can I load a function from the came controller in Codeigniter?
I have this basic function a controller:
public function index(){
if($this->input->ip_address() == XX.XX.XXX.XXX){
$this->status(0);
}
}
protected function status($status_no){
echo $status_no;
}
But the status function does nothing. It doesn't even load. I can confirm
my IP is correct and my IF statement & controller index is okay.
I will be looking forward to some help.
Peter
I have this basic function a controller:
public function index(){
if($this->input->ip_address() == XX.XX.XXX.XXX){
$this->status(0);
}
}
protected function status($status_no){
echo $status_no;
}
But the status function does nothing. It doesn't even load. I can confirm
my IP is correct and my IF statement & controller index is okay.
I will be looking forward to some help.
Peter
jQuery- walk through YouTube URLs and add options
jQuery- walk through YouTube URLs and add options
I have a series of YouTube URLs on the page, that each look like one of
these:
<iframe width="640" height="360"
src="//www.youtube.com/embed/XFMjR2SgEP0?list=PLd4hww6QWFS5HMUQzSs3r-90jMRtCiCdi"
frameborder="0" allowfullscreen></iframe>
<iframe width="640" height="360" src="//www.youtube.com/embed/DVPP1elkhKU"
frameborder="0" allowfullscreen></iframe>
As you can see, the first tag above has a 'list' parameter at the end of
the URL; the second tag has no parameters on the URL.
I need to use jQuery to append a new parameter, showinfo=0, to every
YouTube URL on the page. And obviously this needs to be preceded with
either ? or &, depending on if there are other parameters before it.
How?
I have a series of YouTube URLs on the page, that each look like one of
these:
<iframe width="640" height="360"
src="//www.youtube.com/embed/XFMjR2SgEP0?list=PLd4hww6QWFS5HMUQzSs3r-90jMRtCiCdi"
frameborder="0" allowfullscreen></iframe>
<iframe width="640" height="360" src="//www.youtube.com/embed/DVPP1elkhKU"
frameborder="0" allowfullscreen></iframe>
As you can see, the first tag above has a 'list' parameter at the end of
the URL; the second tag has no parameters on the URL.
I need to use jQuery to append a new parameter, showinfo=0, to every
YouTube URL on the page. And obviously this needs to be preceded with
either ? or &, depending on if there are other parameters before it.
How?
How do you use a webbrowser control for styling but have the logic in C#?
How do you use a webbrowser control for styling but have the logic in C#?
I have seen a few applications do this. They use HTML/CSS/Javascript for
the styling (which is a million times easier than creating the same thing
natively), but they have the logic of the program in C#, I have no idea
how to interconnect the two. I was trying to google around, but I couldn't
find anything with my phrasing. Any quick explanation or example would be
awesome!
Thanks, Jon
I have seen a few applications do this. They use HTML/CSS/Javascript for
the styling (which is a million times easier than creating the same thing
natively), but they have the logic of the program in C#, I have no idea
how to interconnect the two. I was trying to google around, but I couldn't
find anything with my phrasing. Any quick explanation or example would be
awesome!
Thanks, Jon
Whats worng with this code?
Whats worng with this code?
I expected this program to stop the loop when i press enter button but
instead the terminal become blank and do not show anything. Whats wrong
with this?
#include <stdio.h>
int main()
{
int c;
printf("Enter a char(To exit loop press enter)");
for(c=' ';c!='\n';)
{
scanf("%d",&c);
putchar(c);
}
return 0;
}
I expected this program to stop the loop when i press enter button but
instead the terminal become blank and do not show anything. Whats wrong
with this?
#include <stdio.h>
int main()
{
int c;
printf("Enter a char(To exit loop press enter)");
for(c=' ';c!='\n';)
{
scanf("%d",&c);
putchar(c);
}
return 0;
}
Why dictionary is faster than HashTable
Why dictionary is faster than HashTable
Consider this code:
[TestClass]
public class MyTestClass
{
private TestContext testContextInstance;
public TestContext TestContext
{
get { return testContextInstance; }
set { testContextInstance = value; }
}
[TestMethod]
[DeploymentItem("SampleData.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
"|DataDirectory|\\SampleData.xml",
"Row", DataAccessMethod.Sequential)]
public void MyTestMethod1()
{
int value = Convert.ToInt32(testContextInstance.DataRow["Data"]);
Stopwatch watch = new Stopwatch();
// Testing Dictionary for Reading and writing.
watch.Restart();
var dictionary = LoadDataTestForDictionary(value);
watch.Stop();
System.Diagnostics.Trace.WriteLine("Elapsed Milliseconds(Load
Dictionary): " +
watch.ElapsedMilliseconds.ToString());
watch.Restart();
ReadEachElementOfDictionary(dictionary);
watch.Stop();
System.Diagnostics.Trace.WriteLine("Elapsed Milliseconds(Read
Dictionary): " +
watch.ElapsedMilliseconds.ToString());
// Testing HashTable for Reading and writing.
watch.Restart();
var hash = LoadDataTestForHashTable(value);
watch.Stop();
System.Diagnostics.Trace.WriteLine("Elapsed Milliseconds(Load
HashTable): " +
watch.ElapsedMilliseconds.ToString());
watch.Restart();
ReadEachElementOfHashTable(hash);
watch.Stop();
System.Diagnostics.Trace.WriteLine("Elapsed Milliseconds(Read
HashTable): " +
watch.ElapsedMilliseconds.ToString());
}
public Dictionary<int, string> LoadDataTestForDictionary(int
totalRecords)
{
// Create Dictionary object.
Dictionary<int, string> dict = new Dictionary<int, string>();
for (int i = 0; i < totalRecords; i++)
{
dict.Add(i, "this is test data");
}
return dict;
}
public void ReadEachElementOfDictionary(Dictionary<int, string> dict)
{
for (int i = 0; i < dict.Count; i++)
{
var value = dict[i];
}
}
public Hashtable LoadDataTestForHashTable(int totalRecords)
{
Hashtable hTable = new Hashtable();
for (int i = 0; i < totalRecords; i++)
{
hTable.Add(i, "this is test data");
}
return hTable;
}
public void ReadEachElementOfHashTable(Hashtable htable)
{
for (Int64 i = 0; i < htable.Count; i++)
{
var value = htable[i];
}
}
}
This is my result:
We can seet taht dictonary is so faster than HashTable.Why? Source
Consider this code:
[TestClass]
public class MyTestClass
{
private TestContext testContextInstance;
public TestContext TestContext
{
get { return testContextInstance; }
set { testContextInstance = value; }
}
[TestMethod]
[DeploymentItem("SampleData.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
"|DataDirectory|\\SampleData.xml",
"Row", DataAccessMethod.Sequential)]
public void MyTestMethod1()
{
int value = Convert.ToInt32(testContextInstance.DataRow["Data"]);
Stopwatch watch = new Stopwatch();
// Testing Dictionary for Reading and writing.
watch.Restart();
var dictionary = LoadDataTestForDictionary(value);
watch.Stop();
System.Diagnostics.Trace.WriteLine("Elapsed Milliseconds(Load
Dictionary): " +
watch.ElapsedMilliseconds.ToString());
watch.Restart();
ReadEachElementOfDictionary(dictionary);
watch.Stop();
System.Diagnostics.Trace.WriteLine("Elapsed Milliseconds(Read
Dictionary): " +
watch.ElapsedMilliseconds.ToString());
// Testing HashTable for Reading and writing.
watch.Restart();
var hash = LoadDataTestForHashTable(value);
watch.Stop();
System.Diagnostics.Trace.WriteLine("Elapsed Milliseconds(Load
HashTable): " +
watch.ElapsedMilliseconds.ToString());
watch.Restart();
ReadEachElementOfHashTable(hash);
watch.Stop();
System.Diagnostics.Trace.WriteLine("Elapsed Milliseconds(Read
HashTable): " +
watch.ElapsedMilliseconds.ToString());
}
public Dictionary<int, string> LoadDataTestForDictionary(int
totalRecords)
{
// Create Dictionary object.
Dictionary<int, string> dict = new Dictionary<int, string>();
for (int i = 0; i < totalRecords; i++)
{
dict.Add(i, "this is test data");
}
return dict;
}
public void ReadEachElementOfDictionary(Dictionary<int, string> dict)
{
for (int i = 0; i < dict.Count; i++)
{
var value = dict[i];
}
}
public Hashtable LoadDataTestForHashTable(int totalRecords)
{
Hashtable hTable = new Hashtable();
for (int i = 0; i < totalRecords; i++)
{
hTable.Add(i, "this is test data");
}
return hTable;
}
public void ReadEachElementOfHashTable(Hashtable htable)
{
for (Int64 i = 0; i < htable.Count; i++)
{
var value = htable[i];
}
}
}
This is my result:
We can seet taht dictonary is so faster than HashTable.Why? Source
Thursday, 26 September 2013
Hide group of rows in excel
Hide group of rows in excel
I want to hide certain group of rows where 1st row after blank row is
"xyz" untill next blank row occours. eg
heloo a b
xyz as df
hello g j
xyz ghj gh jk jk
I want output to be as
heloo a b
hello g
I want to hide certain group of rows where 1st row after blank row is
"xyz" untill next blank row occours. eg
heloo a b
xyz as df
hello g j
xyz ghj gh jk jk
I want output to be as
heloo a b
hello g
Wednesday, 25 September 2013
Extjs4 Load data in grid from server
Extjs4 Load data in grid from server
How to load data in grid from server I am able to load data from Store to
grid but not able to load data from server to the store and then into grid
Server API Details :
http://192.1681.102:8080/Petcrumbs/member/getMemberList
Request Parameters :
{"pageNumber":5}
Response Success :
{ "listOfMembers": [ { "address": { "state": "MH", "country": "India",
"city": "Pune", "addressId": 52, "streetName": "Karve Road",
"streetNameTwo": "Nal Stop", "zipCode": "412042" }, "name": "Test Mmber4",
"password": "287974", "authKey": "99710ff8d98346f51a7b3df83c16257",
"gender": "Male", "deviceToken":
"ldjhakjhdkjahn42,n4lk2jedlkandmandlkand", "community": "Kothrud",
"emailId": "r.pekam@mb.com", "phone": "9096305571", "image": null,
"memberId": 41, "active": 1, "deleted": false, "myPackage": "Gold",
"joinedDate": "09-17-2013" } ], "message": "Member retrieved
successfully.", "success": true }
Response Failure :
{ "listOfMembers": null, "message": "Unable to retrieve members.",
"success": false
}
In EXTJS Store
Ext.define('PetCrumbs.store.Members', {
extend : 'Ext.data.ArrayStore',
model : 'PetCrumbs.model.Member',
autoLoad : true,
//storeId : 'Data',
proxy : {
type : 'ajax',
url : '/Petcrumbs/member/getMemberList',
method : 'POST',
headers : {
'Content-Type' : 'application/json',
'Accept' : 'application/json'
},
jsonData : {
pageNumber : "5"
},
reader : {
type : 'json',
root: 'listOfMembers',
successProperty: 'success'
}
}
});
When I have Store like this ( Hard Coded Data ) grid displays data :
Ext.define('PetCrumbs.store.Members', {
extend: 'Ext.data.ArrayStore',
model: 'PetCrumbs.model.Member',
data: [
['1','1002','Asin','kothroud@gmail.com','kothrud,Pune','MH',
'Pune','411051','Male','Gold','Kothrud','1'],['2','1012','Karina','Pashan@gmail.com',
'Pashan,Pune','MH','Pune','411051','Female','Silver','Pashan','0']
]
});
Please tell me what is wrong with the above code ?
How to load data in grid from server I am able to load data from Store to
grid but not able to load data from server to the store and then into grid
Server API Details :
http://192.1681.102:8080/Petcrumbs/member/getMemberList
Request Parameters :
{"pageNumber":5}
Response Success :
{ "listOfMembers": [ { "address": { "state": "MH", "country": "India",
"city": "Pune", "addressId": 52, "streetName": "Karve Road",
"streetNameTwo": "Nal Stop", "zipCode": "412042" }, "name": "Test Mmber4",
"password": "287974", "authKey": "99710ff8d98346f51a7b3df83c16257",
"gender": "Male", "deviceToken":
"ldjhakjhdkjahn42,n4lk2jedlkandmandlkand", "community": "Kothrud",
"emailId": "r.pekam@mb.com", "phone": "9096305571", "image": null,
"memberId": 41, "active": 1, "deleted": false, "myPackage": "Gold",
"joinedDate": "09-17-2013" } ], "message": "Member retrieved
successfully.", "success": true }
Response Failure :
{ "listOfMembers": null, "message": "Unable to retrieve members.",
"success": false
}
In EXTJS Store
Ext.define('PetCrumbs.store.Members', {
extend : 'Ext.data.ArrayStore',
model : 'PetCrumbs.model.Member',
autoLoad : true,
//storeId : 'Data',
proxy : {
type : 'ajax',
url : '/Petcrumbs/member/getMemberList',
method : 'POST',
headers : {
'Content-Type' : 'application/json',
'Accept' : 'application/json'
},
jsonData : {
pageNumber : "5"
},
reader : {
type : 'json',
root: 'listOfMembers',
successProperty: 'success'
}
}
});
When I have Store like this ( Hard Coded Data ) grid displays data :
Ext.define('PetCrumbs.store.Members', {
extend: 'Ext.data.ArrayStore',
model: 'PetCrumbs.model.Member',
data: [
['1','1002','Asin','kothroud@gmail.com','kothrud,Pune','MH',
'Pune','411051','Male','Gold','Kothrud','1'],['2','1012','Karina','Pashan@gmail.com',
'Pashan,Pune','MH','Pune','411051','Female','Silver','Pashan','0']
]
});
Please tell me what is wrong with the above code ?
Thursday, 19 September 2013
Code that should't loop is looping
Code that should't loop is looping
So I have the following C code:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
int i = 0, n;
n = 5;
pid_t pid;
printf("i=%d Right before the loop\n", i, getpid(), getppid());
for (i = 0; i < n; i++){
pid = fork();
if (pid <= 0){
printf("shit happens in loop #%d. pid = %d\n", i, pid);
break;
}
printf("End of loop #%d\n", i);
}
printf("i=%d My process ID = %d and my parent's ID = %d\n", i,
getpid(), getppid());
return 0;
}
I have only one question: Why does
printf("i=%d My process ID = %d and my parent's ID = %d\n", i, getpid(),
getppid());
get executed many times as if it was inside the loop? I have tried to
figure out through so many ways but I cannot find the reason.
So I have the following C code:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
int i = 0, n;
n = 5;
pid_t pid;
printf("i=%d Right before the loop\n", i, getpid(), getppid());
for (i = 0; i < n; i++){
pid = fork();
if (pid <= 0){
printf("shit happens in loop #%d. pid = %d\n", i, pid);
break;
}
printf("End of loop #%d\n", i);
}
printf("i=%d My process ID = %d and my parent's ID = %d\n", i,
getpid(), getppid());
return 0;
}
I have only one question: Why does
printf("i=%d My process ID = %d and my parent's ID = %d\n", i, getpid(),
getppid());
get executed many times as if it was inside the loop? I have tried to
figure out through so many ways but I cannot find the reason.
Benefits of Composer if already using a PHP framework
Benefits of Composer if already using a PHP framework
Dropbox's PHP SDK heavy-handedly suggests that one should use Composer to
install and load their SDK. Also, version 2 of AWS's PHP SDK also offers
Composer as a installation/loader (fortunately without the bias).
I'm using the Codeigniter (CI) framework which has a built in "vendor"
folder (called "third_party" by CI, "vendor" by Composer) which I can
easily control module loading with CI's built in loading handlers, e.g.,
$this->load->library("blah_blah), or with vanilla PHP include/require
"blah/blah.php" statements for edge cases.
I don't know other PHP frameworks well, but I'd assume they handle
dependencies in a similarly simple manner.
It would seem that one of the main points of a framework is to handle
dependencies so my question is, are their additional benefits to Composer
beyond what the frameworks provide?
Dropbox's PHP SDK heavy-handedly suggests that one should use Composer to
install and load their SDK. Also, version 2 of AWS's PHP SDK also offers
Composer as a installation/loader (fortunately without the bias).
I'm using the Codeigniter (CI) framework which has a built in "vendor"
folder (called "third_party" by CI, "vendor" by Composer) which I can
easily control module loading with CI's built in loading handlers, e.g.,
$this->load->library("blah_blah), or with vanilla PHP include/require
"blah/blah.php" statements for edge cases.
I don't know other PHP frameworks well, but I'd assume they handle
dependencies in a similarly simple manner.
It would seem that one of the main points of a framework is to handle
dependencies so my question is, are their additional benefits to Composer
beyond what the frameworks provide?
fetch data from a url in javascript
fetch data from a url in javascript
I am trying to fetch a data file from a URL given by the user, but I don't
know how to do. Actually, I can get data from my server successfully. Here
is my code:
$("button#btn-demo").click(function() {
$.get('/file', {
'filename' : 'vase.rti',
},
function(json) {
var data = window.atob(json);
// load HSH raw file
floatPixels = loadHSH(data);
render();
});
});
It can fetch the binary data from my server, parse the file and render it
into an image. But now I want it work without any server, which means
users can give a URL and javascript can get the file and render it. I know
it's about the cross-site request. Can you tell me about it and how to
realize it? Thanks in advance!
I am trying to fetch a data file from a URL given by the user, but I don't
know how to do. Actually, I can get data from my server successfully. Here
is my code:
$("button#btn-demo").click(function() {
$.get('/file', {
'filename' : 'vase.rti',
},
function(json) {
var data = window.atob(json);
// load HSH raw file
floatPixels = loadHSH(data);
render();
});
});
It can fetch the binary data from my server, parse the file and render it
into an image. But now I want it work without any server, which means
users can give a URL and javascript can get the file and render it. I know
it's about the cross-site request. Can you tell me about it and how to
realize it? Thanks in advance!
Display posts of a Sub Category of my taxonomy
Display posts of a Sub Category of my taxonomy
I created a Shortcode to display Term of my Taxonomy. But for one of my
taxonomy i have a sub term or sub category. And i don't understand how can
i dusplay posts of a Sub Category of my Taxonomy. Can i help Me please !
Thanks in advance. My Code in functions.php
/*============================================================ LASTS
ARTICLES ============================================================*/
function theme_lasts_posts_shortcode( $atts, $content = null ) {
extract( shortcode_atts( array(
"posttype" => '',
"taxonomy" => '',
"term" => '',
"class" => '',
"exclude" => '',
), $atts));
$output = '<div class="derniersarticles">';
if ( $posttype != '' ) {
$loop = new WP_Query( array( 'post_type' => $posttype, 'taxonomy' =>
$taxonomy,'term' => $term, 'posts_per_page' => 100, 'post__not_in'
=> array($exclude) ) );
} else {
$loop = new WP_Query( array( 'post_type' => $posttype,
'posts_per_page' => 100 ) );
}
while ( $loop->have_posts() ) : $loop->the_post();
$output .= '<div class="'. $class .'">';
$output .= '<div class="thumb">';
$output .= '<a href="' . get_permalink() . '">' .
get_the_post_thumbnail() . '</a>';
$output .= '</div>';
$output .= '<h3><a href="' . get_permalink() . '">' .
get_the_title() . '</a></h3>';
$output .= '</div>';
endwhile;
$output .= '</div>';
return $output;
}
add_shortcode( 'DerniersArticles', 'theme_lasts_posts_shortcode' );
I created a Shortcode to display Term of my Taxonomy. But for one of my
taxonomy i have a sub term or sub category. And i don't understand how can
i dusplay posts of a Sub Category of my Taxonomy. Can i help Me please !
Thanks in advance. My Code in functions.php
/*============================================================ LASTS
ARTICLES ============================================================*/
function theme_lasts_posts_shortcode( $atts, $content = null ) {
extract( shortcode_atts( array(
"posttype" => '',
"taxonomy" => '',
"term" => '',
"class" => '',
"exclude" => '',
), $atts));
$output = '<div class="derniersarticles">';
if ( $posttype != '' ) {
$loop = new WP_Query( array( 'post_type' => $posttype, 'taxonomy' =>
$taxonomy,'term' => $term, 'posts_per_page' => 100, 'post__not_in'
=> array($exclude) ) );
} else {
$loop = new WP_Query( array( 'post_type' => $posttype,
'posts_per_page' => 100 ) );
}
while ( $loop->have_posts() ) : $loop->the_post();
$output .= '<div class="'. $class .'">';
$output .= '<div class="thumb">';
$output .= '<a href="' . get_permalink() . '">' .
get_the_post_thumbnail() . '</a>';
$output .= '</div>';
$output .= '<h3><a href="' . get_permalink() . '">' .
get_the_title() . '</a></h3>';
$output .= '</div>';
endwhile;
$output .= '</div>';
return $output;
}
add_shortcode( 'DerniersArticles', 'theme_lasts_posts_shortcode' );
removing nodes from xml incomplete, needs several runs
removing nodes from xml incomplete, needs several runs
I have a very strange bug I am trying to figure out. I load in an xml,
find a specific node, then delete it, then save the file. But when I run
it, it only catches SOME of those nodes on the first run, then some more
on the second and third runs until it finally finishes. There is no reason
I can figure why this is happening. Here is my code:
foreach(glob("*.xml") as $filename) {
$domsrc = file_get_contents($filename, FILE_TEXT);
$MYdom = new DomDocument();
$MYdom->loadXML($domsrc);
foreach ($MYdom->getElementsByTagName('URL') as $virttour) {
if($virttour->getAttribute('Type') == 'Virtual Tour') {
$virttour->parentNode->removeChild($virttour);
}
}
$MYdom->save($filename);
I have a very strange bug I am trying to figure out. I load in an xml,
find a specific node, then delete it, then save the file. But when I run
it, it only catches SOME of those nodes on the first run, then some more
on the second and third runs until it finally finishes. There is no reason
I can figure why this is happening. Here is my code:
foreach(glob("*.xml") as $filename) {
$domsrc = file_get_contents($filename, FILE_TEXT);
$MYdom = new DomDocument();
$MYdom->loadXML($domsrc);
foreach ($MYdom->getElementsByTagName('URL') as $virttour) {
if($virttour->getAttribute('Type') == 'Virtual Tour') {
$virttour->parentNode->removeChild($virttour);
}
}
$MYdom->save($filename);
HTTP module re-writing the URL with some encryption
HTTP module re-writing the URL with some encryption
I am writing one class with the help of HTTPModule to check userIdentity
in session before he access any page.If the variable in the session is
null or empty i am redirecting the user in session expired page.
Code in Class:
public class SessionUserValidation : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication application)
{
application.PreRequestHandlerExecute += new
EventHandler(application_PreRequestHandlerExecute);
}
private void application_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
IHttpHandler handler = application.Context.Handler;
Page reqPage = handler as Page;
if (reqPage != null)
{
reqPage.PreInit += new EventHandler(CustomModule_Init);
}
}
private void CustomModule_Init(object sender, EventArgs e)
{
Page Page = sender as Page;
if (!Page.Request.Url.ToString().Contains("mySessionExpired.aspx") &&
!Page.Request.Url.ToString().Contains("myLogin.aspx"))
{
if (HttpContext.Current.Session["encryptedUserId"] == null)
{
HttpContext.Current.Response.Redirect("../Modulenames/mySessionExpired.aspx",
false);
}
}
}
}
everything is working fine , only issue is that its adding some kind of
encryption in URL for which my Breadcrumbs are not working in the page.
The url transforms like :
://thewebsite/Project/(S(jnd4o5ljdgs0vq1zd4niby4a))/Pages/mySessionExpired.aspx
no idea why this fragment of text has been added ... please help
--Attu
I am writing one class with the help of HTTPModule to check userIdentity
in session before he access any page.If the variable in the session is
null or empty i am redirecting the user in session expired page.
Code in Class:
public class SessionUserValidation : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication application)
{
application.PreRequestHandlerExecute += new
EventHandler(application_PreRequestHandlerExecute);
}
private void application_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
IHttpHandler handler = application.Context.Handler;
Page reqPage = handler as Page;
if (reqPage != null)
{
reqPage.PreInit += new EventHandler(CustomModule_Init);
}
}
private void CustomModule_Init(object sender, EventArgs e)
{
Page Page = sender as Page;
if (!Page.Request.Url.ToString().Contains("mySessionExpired.aspx") &&
!Page.Request.Url.ToString().Contains("myLogin.aspx"))
{
if (HttpContext.Current.Session["encryptedUserId"] == null)
{
HttpContext.Current.Response.Redirect("../Modulenames/mySessionExpired.aspx",
false);
}
}
}
}
everything is working fine , only issue is that its adding some kind of
encryption in URL for which my Breadcrumbs are not working in the page.
The url transforms like :
://thewebsite/Project/(S(jnd4o5ljdgs0vq1zd4niby4a))/Pages/mySessionExpired.aspx
no idea why this fragment of text has been added ... please help
--Attu
moving html table content to sql database
moving html table content to sql database
So I've got a table (grabbed from another website using php) but now I
want to import it's content into my database (instead of just printing out
the table).
this is the printout (http://i.stack.imgur.com/NnbAo.png) from the table
using the following code:
<?php
$uitvoer = getTable();
echo "<table">;
foreach ($uitvoer as $row) {
echo "<tr>";
foreach ($row as $col) {
echo "<td>" . $col . "</td>";
}
echo "</tr>";
}
echo"</table>";
?>
And when I try this nothing happens to my database:
<?php
$con = mysqli_connect("mysql1.000webhost.com","a2902119_lowavol","pswd")
$uitvoer = getTable();
foreach ($uitvoer as $row) {
foreach ($row as $col) {
$querry += "'" . $col . "', ";
}
$sql="INSERT INTO test (cel1, cel2, cel3, cel4, cel5, cel6, cel7, cel8,
cel9) VALUES ($querry)";
mysqli_query($con,$sql);
}
?>
I have little to no knowledge about PHP. Thanks for helping me!
So I've got a table (grabbed from another website using php) but now I
want to import it's content into my database (instead of just printing out
the table).
this is the printout (http://i.stack.imgur.com/NnbAo.png) from the table
using the following code:
<?php
$uitvoer = getTable();
echo "<table">;
foreach ($uitvoer as $row) {
echo "<tr>";
foreach ($row as $col) {
echo "<td>" . $col . "</td>";
}
echo "</tr>";
}
echo"</table>";
?>
And when I try this nothing happens to my database:
<?php
$con = mysqli_connect("mysql1.000webhost.com","a2902119_lowavol","pswd")
$uitvoer = getTable();
foreach ($uitvoer as $row) {
foreach ($row as $col) {
$querry += "'" . $col . "', ";
}
$sql="INSERT INTO test (cel1, cel2, cel3, cel4, cel5, cel6, cel7, cel8,
cel9) VALUES ($querry)";
mysqli_query($con,$sql);
}
?>
I have little to no knowledge about PHP. Thanks for helping me!
Wednesday, 18 September 2013
A white bar below my app after Xcode 5 upgrade
A white bar below my app after Xcode 5 upgrade
As iOS7 and xcode 5 is out, I am assuming we can talk about them. Today I
upgraded to XCode 5 and suddenly on my mapView.xib I see a white bar
below. I did not touch the xib file, what exactly is going on here and how
I can fix it.
As iOS7 and xcode 5 is out, I am assuming we can talk about them. Today I
upgraded to XCode 5 and suddenly on my mapView.xib I see a white bar
below. I did not touch the xib file, what exactly is going on here and how
I can fix it.
how to read json file into a php array and plot a graph by using this array?
how to read json file into a php array and plot a graph by using this array?
i am able to read a json file into an array and display the output but i
want to use that array directly to give it as a input to another php
function to plot a graph,
how to read json file into a php array and plot a graph by using this array ?
<?php
$string = file_get_contents("json.json");
$example_data=json_decode($string,true);
foreach ($example_data as $k => $v) {
echo $k, ' : ', $v;
}
?>
but instead of displaying it as an output text, i want to give this
example_data as an input array to another php function,
<?php
//Include the code
require_once 'C:/xampp/htdocs/formattool/phplot-6.1.0/phplot.php';
//Define the object
$plot = new PHPlot();
//Define some data
$example_data = array(
array('a',3),
array('b',5),
array('c',7),
array('d',8),
array('e',2),
array('f',6),
array('g',7)
);
$plot->SetDataValues($example_data);
//Turn off X axis ticks and labels because they get in the way:
$plot->SetXTickLabelPos('none');
$plot->SetXTickPos('none');
//Draw it
$plot->DrawGraph();
?>
in the above code, instead of declaring the example_data, i want to read
it from another json file as i did in the first code, can anyone give me a
solution to this ?
i am able to read a json file into an array and display the output but i
want to use that array directly to give it as a input to another php
function to plot a graph,
how to read json file into a php array and plot a graph by using this array ?
<?php
$string = file_get_contents("json.json");
$example_data=json_decode($string,true);
foreach ($example_data as $k => $v) {
echo $k, ' : ', $v;
}
?>
but instead of displaying it as an output text, i want to give this
example_data as an input array to another php function,
<?php
//Include the code
require_once 'C:/xampp/htdocs/formattool/phplot-6.1.0/phplot.php';
//Define the object
$plot = new PHPlot();
//Define some data
$example_data = array(
array('a',3),
array('b',5),
array('c',7),
array('d',8),
array('e',2),
array('f',6),
array('g',7)
);
$plot->SetDataValues($example_data);
//Turn off X axis ticks and labels because they get in the way:
$plot->SetXTickLabelPos('none');
$plot->SetXTickPos('none');
//Draw it
$plot->DrawGraph();
?>
in the above code, instead of declaring the example_data, i want to read
it from another json file as i did in the first code, can anyone give me a
solution to this ?
JQuery not running in views
JQuery not running in views
Some Jquery scripts are not running in the views while others are running.
I want to hide a certain div "#all_lists" and make it appear on click of
the "#add_lists" div. The character counter is also not working! All Help
is appreciated.
Here is my view;
<%= provide(:title, 'Send Message') %>
<div class="send_sms_form">
<%= simple_form_for(@message, :html => {:multipart => true}) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :from, placeholder: "Max 11 characters" %>
<%= f.input :to, :input_html => {:value => params[:to], :id => "to"},
placeholder: "Separate Numbers with Comma", hint: "Include atleast one
number in this section" %>
<div id="add_lists"> <span class="button"> Add List </span></div>
<div id="all_lists"> <%= f.collection_check_boxes :lists, @lists,
:id, :name, as: :select %></div>
<%= f.input :message, :as => :text, :input_html => {:cols => 60, :rows
=> 7, :onkeypress => "if (this.value.length > 160) { return false; }",
id: "compose_message"} %>
<div><span id="char_count">160</span></div>
<%= f.input :user_id, :as => :hidden, :input_html => {:value =>
@current_user.id} %>
<%= f.input :status, :as => :hidden, :input_html => {:value =>
"Queued"} %>
<%= f.button :submit, "Send Message" %>
<% end %>
</div>
And here is the message.js with the jQuery to run in the views
$(document).ready(function () {
$('#to').tagsInput({
// 'autocomplete_url': '/contacts/autocomplete_contact_phone_number',
'defaultText': 'Add a Number',
'height': '50px',
'width': '400px',
'validator': function (value) {
console.log(value.length, value);
if (value.substring(0, 3) == "256" || value.substring(0, 3) ==
"255" || value.substring(0, 3) == "254") {
if (value.length >= 11) {
return true;
}
}
return false;
}
});
$(".listbox").click(function () {
var numbers_string = $(this).data("numbers");
numbers = numbers_string.split(",");
if ($(this).is(':checked')) {
for (var i = 0; i < numbers.length; i++) {
$('#to').addTag(numbers[i]);
}
} else {
for (var i = 0; i < numbers.length; i++) {
// if ($('#to').tagExist(numbers[i])) {
$('#to').removeTag(numbers[i]);
// }
}
}
});
$('#messages_table').dataTable() ({
sPaginationType: "full_numbers"
});
$('#compose_message').live('keyup keydown', function(e) {
var maxLen = 160;
var left = maxLen - $(this).val().length;
$('#char_count').html(left);
});
$('#all_lists').hide();
$('#add_lists').click( function(event){
event.stopPropagation();
$('#add_lists').toggle();
});
$(document).click( function(){
$('#all_lists').hide();
});
});
Some Jquery scripts are not running in the views while others are running.
I want to hide a certain div "#all_lists" and make it appear on click of
the "#add_lists" div. The character counter is also not working! All Help
is appreciated.
Here is my view;
<%= provide(:title, 'Send Message') %>
<div class="send_sms_form">
<%= simple_form_for(@message, :html => {:multipart => true}) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :from, placeholder: "Max 11 characters" %>
<%= f.input :to, :input_html => {:value => params[:to], :id => "to"},
placeholder: "Separate Numbers with Comma", hint: "Include atleast one
number in this section" %>
<div id="add_lists"> <span class="button"> Add List </span></div>
<div id="all_lists"> <%= f.collection_check_boxes :lists, @lists,
:id, :name, as: :select %></div>
<%= f.input :message, :as => :text, :input_html => {:cols => 60, :rows
=> 7, :onkeypress => "if (this.value.length > 160) { return false; }",
id: "compose_message"} %>
<div><span id="char_count">160</span></div>
<%= f.input :user_id, :as => :hidden, :input_html => {:value =>
@current_user.id} %>
<%= f.input :status, :as => :hidden, :input_html => {:value =>
"Queued"} %>
<%= f.button :submit, "Send Message" %>
<% end %>
</div>
And here is the message.js with the jQuery to run in the views
$(document).ready(function () {
$('#to').tagsInput({
// 'autocomplete_url': '/contacts/autocomplete_contact_phone_number',
'defaultText': 'Add a Number',
'height': '50px',
'width': '400px',
'validator': function (value) {
console.log(value.length, value);
if (value.substring(0, 3) == "256" || value.substring(0, 3) ==
"255" || value.substring(0, 3) == "254") {
if (value.length >= 11) {
return true;
}
}
return false;
}
});
$(".listbox").click(function () {
var numbers_string = $(this).data("numbers");
numbers = numbers_string.split(",");
if ($(this).is(':checked')) {
for (var i = 0; i < numbers.length; i++) {
$('#to').addTag(numbers[i]);
}
} else {
for (var i = 0; i < numbers.length; i++) {
// if ($('#to').tagExist(numbers[i])) {
$('#to').removeTag(numbers[i]);
// }
}
}
});
$('#messages_table').dataTable() ({
sPaginationType: "full_numbers"
});
$('#compose_message').live('keyup keydown', function(e) {
var maxLen = 160;
var left = maxLen - $(this).val().length;
$('#char_count').html(left);
});
$('#all_lists').hide();
$('#add_lists').click( function(event){
event.stopPropagation();
$('#add_lists').toggle();
});
$(document).click( function(){
$('#all_lists').hide();
});
});
Mail sending in php with attachment
Mail sending in php with attachment
I am new to PHP.I Have Form where the user have to Enter e-mail.And an
attachment file will send to his specified e-mail id with submitting the
form. Plz help me.
I am new to PHP.I Have Form where the user have to Enter e-mail.And an
attachment file will send to his specified e-mail id with submitting the
form. Plz help me.
SUMIFS + VLOOKUP tricky use in excel
SUMIFS + VLOOKUP tricky use in excel
I've got two files with excel sheets
The first one consists of 2 columns
First one is ARTICLE (with article numbers), second one is QUANTITY (with
product quantity)
Second file consists of two sheets
First sheet contains two columns is CODE (code numbers), second one is
QUANTITY (with product quantity)
Second sheet consists of two columns CODE and ARTICLE
The thing is one code, for instance "2111", can contain up to 5-10
different articles
My goal is to find the right articles in the first file depending on the
code in the second one and calculate the quantity in the second one.
THANK YOU SO MUCH for any insights!
I've got two files with excel sheets
The first one consists of 2 columns
First one is ARTICLE (with article numbers), second one is QUANTITY (with
product quantity)
Second file consists of two sheets
First sheet contains two columns is CODE (code numbers), second one is
QUANTITY (with product quantity)
Second sheet consists of two columns CODE and ARTICLE
The thing is one code, for instance "2111", can contain up to 5-10
different articles
My goal is to find the right articles in the first file depending on the
code in the second one and calculate the quantity in the second one.
THANK YOU SO MUCH for any insights!
Android Call log with the operator info
Android Call log with the operator info
Most of us, from Portugal, have in our phones, plans of calls by operator.
It means, for example, that you're allowed to do 5000 minutes to Vodafone,
2000 for TMN and 1000 to Optimus. My question is: is there a way of doing
an app or a file in our android phone that show us the call we've made by
operators? One thing: phone numbers here doesn't tell you wich operator
you belong because of the portability. That means, if my number stars with
91 i can be an Optimus operator or TMN and not a Vodafone, wich is the
origin. Hope i make my question clear, as well i hope you guys have the
solution. Tks in advance Best regards Pedro
Most of us, from Portugal, have in our phones, plans of calls by operator.
It means, for example, that you're allowed to do 5000 minutes to Vodafone,
2000 for TMN and 1000 to Optimus. My question is: is there a way of doing
an app or a file in our android phone that show us the call we've made by
operators? One thing: phone numbers here doesn't tell you wich operator
you belong because of the portability. That means, if my number stars with
91 i can be an Optimus operator or TMN and not a Vodafone, wich is the
origin. Hope i make my question clear, as well i hope you guys have the
solution. Tks in advance Best regards Pedro
Creation of weekly calender in php
Creation of weekly calender in php
I have created a php calender which will show one week at a time.Here is
the code i have created
<?php
$week = date("W");
$year = (isset($_GET['year']))?$_GET['year']:date("Y");
$week = (isset($_GET['week']))?$_GET['week']:Date('W');
if($week>53){
$year+= 1;
$week=1;}
?>
<a href="<?php echo
$_SERVER['PHP_SELF'].'?week='.($week+1).'&year='.$year; ?>">Next Week</a>
<!--Next week-->
<a href="<?php echo
$_SERVER['PHP_SELF'].'?week='.($week-1).'&year='.$year; ?>">Pre Week</a>
<!--Previous week-->
<table border="1px">
<tr>
<td>Employee</td>
<?php
for($day=1; $day<=7; $day++)
{
$d = strtotime($year."W".$week.$day);
echo "<td>".date('l',$d )."<br>";
echo date('d M',$d)."</td>";
}
?>
</tr>
when i am trying to go to the next week it is working correctly. But when
the year is changing it is not working for the next year.
I have created a php calender which will show one week at a time.Here is
the code i have created
<?php
$week = date("W");
$year = (isset($_GET['year']))?$_GET['year']:date("Y");
$week = (isset($_GET['week']))?$_GET['week']:Date('W');
if($week>53){
$year+= 1;
$week=1;}
?>
<a href="<?php echo
$_SERVER['PHP_SELF'].'?week='.($week+1).'&year='.$year; ?>">Next Week</a>
<!--Next week-->
<a href="<?php echo
$_SERVER['PHP_SELF'].'?week='.($week-1).'&year='.$year; ?>">Pre Week</a>
<!--Previous week-->
<table border="1px">
<tr>
<td>Employee</td>
<?php
for($day=1; $day<=7; $day++)
{
$d = strtotime($year."W".$week.$day);
echo "<td>".date('l',$d )."<br>";
echo date('d M',$d)."</td>";
}
?>
</tr>
when i am trying to go to the next week it is working correctly. But when
the year is changing it is not working for the next year.
Tuesday, 17 September 2013
Selecting all friends using friend picker - .net SDK for facebook
Selecting all friends using friend picker - .net SDK for facebook
I am developing a Windows Phone 8 app. I am using a Friend Picker control
(.NET SDK for Facebook) to display list of friends for a Facebook User.
Can anyone help me on how to select all friends in the list through C#
code ? There is a SelectedItems property on the Friend Picker control, but
that is read only.
I am developing a Windows Phone 8 app. I am using a Friend Picker control
(.NET SDK for Facebook) to display list of friends for a Facebook User.
Can anyone help me on how to select all friends in the list through C#
code ? There is a SelectedItems property on the Friend Picker control, but
that is read only.
Which would be best to use setMessage(null) or StringUtils.EMPTY?
Which would be best to use setMessage(null) or StringUtils.EMPTY?
I need to clear the warning or say error message,which will be the best
one to choose setMessage(null) or by using StringUtils.EMPTY - i just want
to know the exact way of using StringUtils.EMPTY,it would be helpful...
Thanks & Regards.
I need to clear the warning or say error message,which will be the best
one to choose setMessage(null) or by using StringUtils.EMPTY - i just want
to know the exact way of using StringUtils.EMPTY,it would be helpful...
Thanks & Regards.
Connecting third-party library to Qt
Connecting third-party library to Qt
I am trying to get the LIBS and INCLUDEPATH commands working, and I'm not
sure I'm going about this in the right way.
I have a directory, with an arbitrary name of "testinclude", and inside it
contains a .lib called "Connect.lib", and a .dll called
"ConnectLibrary.dll" and another directory called "include" with a bunch
of header files. I need to be able to write code in Qt that uses these
header files, which then in turn use the compiled symbols in the .lib/.dll
files.
So I added this to my .pro:
INCLUDEPATH+="testinclude"
LIBS=Connect.lib
..but I'm just guessing on what the correct layout of information should
be here, especially for LIBS. Is it the name of the .lib or of the .dll?
Is the extension included? I don't really understand what is happening
here. When I try to build, it just says that "error: Connect.lib: No file
or directory"
My understanding is that the .lib is the actual library info needed for
connecting to the dll, is that right? Therefore, it is what Qt needs to
know about? It's all fairly confusing for a newbie.
I am trying to get the LIBS and INCLUDEPATH commands working, and I'm not
sure I'm going about this in the right way.
I have a directory, with an arbitrary name of "testinclude", and inside it
contains a .lib called "Connect.lib", and a .dll called
"ConnectLibrary.dll" and another directory called "include" with a bunch
of header files. I need to be able to write code in Qt that uses these
header files, which then in turn use the compiled symbols in the .lib/.dll
files.
So I added this to my .pro:
INCLUDEPATH+="testinclude"
LIBS=Connect.lib
..but I'm just guessing on what the correct layout of information should
be here, especially for LIBS. Is it the name of the .lib or of the .dll?
Is the extension included? I don't really understand what is happening
here. When I try to build, it just says that "error: Connect.lib: No file
or directory"
My understanding is that the .lib is the actual library info needed for
connecting to the dll, is that right? Therefore, it is what Qt needs to
know about? It's all fairly confusing for a newbie.
How to copy from a list of items using multiple command buttons in Excel?
How to copy from a list of items using multiple command buttons in Excel?
I am looking to build an Excel worksheet that has a list of items in
column A, each paired with a command button in column B. Ideally it would
look like this:
When pressing a button, the value in the adjacent column A would be copied
to a different worksheet. I understand this is possible to do with a
CommandButton_Click() sub, but I will have around 200 buttons and from my
understanding, I'd have to do a different sub for each one. Is there a way
to avoid this? Is there some code that would apply to all buttons and if a
button is pressed it would copy the adjacent column? An example of my
current sub is:
Sub CommandButton_Click()
Dim rs As Integer
rs = ActiveSheet.Buttons(1).TopLeftCell.Row
Worksheets("Sheet1").Range("A" & rs).Copy _
Worksheets("Sheet2").Range("A" & rs)
End Sub
Hopefully you guys understand what I'm trying to do here. Any help is
appreciated!
I am looking to build an Excel worksheet that has a list of items in
column A, each paired with a command button in column B. Ideally it would
look like this:
When pressing a button, the value in the adjacent column A would be copied
to a different worksheet. I understand this is possible to do with a
CommandButton_Click() sub, but I will have around 200 buttons and from my
understanding, I'd have to do a different sub for each one. Is there a way
to avoid this? Is there some code that would apply to all buttons and if a
button is pressed it would copy the adjacent column? An example of my
current sub is:
Sub CommandButton_Click()
Dim rs As Integer
rs = ActiveSheet.Buttons(1).TopLeftCell.Row
Worksheets("Sheet1").Range("A" & rs).Copy _
Worksheets("Sheet2").Range("A" & rs)
End Sub
Hopefully you guys understand what I'm trying to do here. Any help is
appreciated!
Copy autofiltered range, vba excel
Copy autofiltered range, vba excel
I have written the code that does the following: 1) applies autofilter to
specific sheet in the selected workbook 2) copies data from autofiltered
range except the header to another workbook
Here is the code:
m = 2
For i = 1 To work_book.Worksheets.Count
With work_book.Sheets(i)
If (.UsedRange.Rows.Count > 1) Then
'apply filters
.UsedRange.AutoFilter field:=2,
Criteria1:=array_of_account_numbers, Operator:=xlFilterValues
.UsedRange.AutoFilter field:=1,
Criteria1:=array_of_debit_or_credits, Operator:=xlFilterValues
'select only visible cells after autofilter is applied
On Error Goto a
m = destination_workbook.Sheets(1).UsedRange.Rows.Count + 1
Intersect(.UsedRange,
.UsedRange.Offset(1)).SpecialCells(xlCellTypeVisible).Copy
destination_workbook.Sheets(1).Range("A" & m)
a:
End If
End With
However, macro persistently copies some garbage. It means that it copies
from each sheet first three rows in addition to autofiltered range. How
can I solve this issue? I will appreciate for your help and your answers.
I have written the code that does the following: 1) applies autofilter to
specific sheet in the selected workbook 2) copies data from autofiltered
range except the header to another workbook
Here is the code:
m = 2
For i = 1 To work_book.Worksheets.Count
With work_book.Sheets(i)
If (.UsedRange.Rows.Count > 1) Then
'apply filters
.UsedRange.AutoFilter field:=2,
Criteria1:=array_of_account_numbers, Operator:=xlFilterValues
.UsedRange.AutoFilter field:=1,
Criteria1:=array_of_debit_or_credits, Operator:=xlFilterValues
'select only visible cells after autofilter is applied
On Error Goto a
m = destination_workbook.Sheets(1).UsedRange.Rows.Count + 1
Intersect(.UsedRange,
.UsedRange.Offset(1)).SpecialCells(xlCellTypeVisible).Copy
destination_workbook.Sheets(1).Range("A" & m)
a:
End If
End With
However, macro persistently copies some garbage. It means that it copies
from each sheet first three rows in addition to autofiltered range. How
can I solve this issue? I will appreciate for your help and your answers.
Sunday, 15 September 2013
egmentation fault in insertion into binary search tree
egmentation fault in insertion into binary search tree
I wrote the following code to insert into binary search tree which can
have duplicate entries but i get segmentation fault for larger inputs like
greater than 30 ....plz help!!The duplicate entries are stored in the
right branch of the node
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
typedef struct vertex{
int num;
struct vertex* r;
struct vertex* l;
} node;
void insert(node* T,int x)
{
if(x < T->num)
{
if(T->l == NULL)
{
T->l = (node*)malloc(sizeof(node));
T->l->num = x;
printf("%4d ",x);
return;
}
else
{
insert(T->l,x);
}
}
else if(x >= T->num)
{
if(x == T -> num)
if(T->r == NULL)
{
T->r = (node*)malloc(sizeof(node));
T->r->num = x;
printf("%4d ",x);
return;
}
else
insert(T->r,x);
}
}
main()
{
srand((unsigned int)time(NULL));
int i,n,m,x;
node* T;
printf("n = ");
scanf("%d",&n);
printf("\nm = ",&m);
scanf("%d",&m);
printf("\n\n\n+++ Inserting %d random integers between 1 and %d\n",n,m);
x = 1 + rand() % m;
T = (node*)malloc(sizeof(node));
T->num = x;
printf("%4d (1)",x);
for(i=1;i<n;i++)
{
x = 1+rand() % m;
insert(T,x);
if(i%8 == 7)
printf("\n");
}
printf("\n\n");
}
I wrote the following code to insert into binary search tree which can
have duplicate entries but i get segmentation fault for larger inputs like
greater than 30 ....plz help!!The duplicate entries are stored in the
right branch of the node
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
typedef struct vertex{
int num;
struct vertex* r;
struct vertex* l;
} node;
void insert(node* T,int x)
{
if(x < T->num)
{
if(T->l == NULL)
{
T->l = (node*)malloc(sizeof(node));
T->l->num = x;
printf("%4d ",x);
return;
}
else
{
insert(T->l,x);
}
}
else if(x >= T->num)
{
if(x == T -> num)
if(T->r == NULL)
{
T->r = (node*)malloc(sizeof(node));
T->r->num = x;
printf("%4d ",x);
return;
}
else
insert(T->r,x);
}
}
main()
{
srand((unsigned int)time(NULL));
int i,n,m,x;
node* T;
printf("n = ");
scanf("%d",&n);
printf("\nm = ",&m);
scanf("%d",&m);
printf("\n\n\n+++ Inserting %d random integers between 1 and %d\n",n,m);
x = 1 + rand() % m;
T = (node*)malloc(sizeof(node));
T->num = x;
printf("%4d (1)",x);
for(i=1;i<n;i++)
{
x = 1+rand() % m;
insert(T,x);
if(i%8 == 7)
printf("\n");
}
printf("\n\n");
}
Proper way to use JLabels to update an image
Proper way to use JLabels to update an image
I am creating a GUI, and am fairly new to swing and awt. I am trying to
create a gui that, upon launch, sets the background to an image, then uses
a method to create a slideshow of sorts. I have attempted it, and I am not
attached to the code so I am able to take both revisions and/or whole new
concepts.
Here is my current code.
public class MainFrame extends JFrame{
JLabel backgroundL = null;
private JLabel bakckgroundL;
BufferedImage backimg;
Boolean busy;
double width;
double height;
public MainFrame() throws IOException {
initMainframe();
}
public void initMainframe() throws IOException {
//misc setup code, loads a default jpg as background
setTitle("Pemin's Aura");
busy = true;
String backgroundDir = "resources/frame/background.jpg";
backimg = ImageIO.read(new File(backgroundDir));
backgroundL = new JLabel(new ImageIcon(backimg));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
refreshframe();
setVisible(true);
busy = false;
}
public void adjSize() { // the attempted start of a fullscreen mode
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(this);
width = this.getWidth();
height = this.getHeight();
setVisible(true);
}
public void setmastheadText() {//unfinished code
busy = true;
busy = false;
}
public void setbackground() {
add(backgroundL);
}
public void refreshframe() { //should refresh image?
setSize(2049, 2049);
setSize(2048, 2048);
}
public void loadingscreen() throws IOException, InterruptedException {
//this is the code in question that is faulty.
if (busy == false) {
busy = true;
String backgroundDir1 = "resources/frame/background.jpg";
String backgroundDir2 = "resources/frame/scr1.jpg";
String backgroundDir3 = "resources/frame/scr2.jpg";
BufferedImage backimg1 = ImageIO.read(new File(backgroundDir1));
BufferedImage backimg2 = ImageIO.read(new File(backgroundDir2));
BufferedImage backimg3 = ImageIO.read(new File(backgroundDir3));
backgroundL = new JLabel(new ImageIcon(backimg1));
Thread.sleep(2000);
setbackground();
setVisible(true);
backgroundL = new JLabel(new ImageIcon(backimg2));
setbackground();
setVisible(true);
Thread.sleep(2000);
bakckgroundL = new JLabel(new ImageIcon(backimg3));
setbackground();
setVisible(true);
if(backimg != null) {
backgroundL = new JLabel(new ImageIcon(backimg));;
}
}
busy = false;
}//end of loading screen
I am creating a GUI, and am fairly new to swing and awt. I am trying to
create a gui that, upon launch, sets the background to an image, then uses
a method to create a slideshow of sorts. I have attempted it, and I am not
attached to the code so I am able to take both revisions and/or whole new
concepts.
Here is my current code.
public class MainFrame extends JFrame{
JLabel backgroundL = null;
private JLabel bakckgroundL;
BufferedImage backimg;
Boolean busy;
double width;
double height;
public MainFrame() throws IOException {
initMainframe();
}
public void initMainframe() throws IOException {
//misc setup code, loads a default jpg as background
setTitle("Pemin's Aura");
busy = true;
String backgroundDir = "resources/frame/background.jpg";
backimg = ImageIO.read(new File(backgroundDir));
backgroundL = new JLabel(new ImageIcon(backimg));
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
refreshframe();
setVisible(true);
busy = false;
}
public void adjSize() { // the attempted start of a fullscreen mode
GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().setFullScreenWindow(this);
width = this.getWidth();
height = this.getHeight();
setVisible(true);
}
public void setmastheadText() {//unfinished code
busy = true;
busy = false;
}
public void setbackground() {
add(backgroundL);
}
public void refreshframe() { //should refresh image?
setSize(2049, 2049);
setSize(2048, 2048);
}
public void loadingscreen() throws IOException, InterruptedException {
//this is the code in question that is faulty.
if (busy == false) {
busy = true;
String backgroundDir1 = "resources/frame/background.jpg";
String backgroundDir2 = "resources/frame/scr1.jpg";
String backgroundDir3 = "resources/frame/scr2.jpg";
BufferedImage backimg1 = ImageIO.read(new File(backgroundDir1));
BufferedImage backimg2 = ImageIO.read(new File(backgroundDir2));
BufferedImage backimg3 = ImageIO.read(new File(backgroundDir3));
backgroundL = new JLabel(new ImageIcon(backimg1));
Thread.sleep(2000);
setbackground();
setVisible(true);
backgroundL = new JLabel(new ImageIcon(backimg2));
setbackground();
setVisible(true);
Thread.sleep(2000);
bakckgroundL = new JLabel(new ImageIcon(backimg3));
setbackground();
setVisible(true);
if(backimg != null) {
backgroundL = new JLabel(new ImageIcon(backimg));;
}
}
busy = false;
}//end of loading screen
The sticky.js works, but in a wrong position
The sticky.js works, but in a wrong position
My sticky element was working perfect, after I have modified menu css, it
does wrong position!!
Please see my code: http://codepen.io/bard/pen/ydrfC
I have worked 2 hours on this, just don't see the problem.
The sticky:http://stickyjs.com/
My sticky element was working perfect, after I have modified menu css, it
does wrong position!!
Please see my code: http://codepen.io/bard/pen/ydrfC
I have worked 2 hours on this, just don't see the problem.
The sticky:http://stickyjs.com/
Disable another button once it has successfully submitted the form
Disable another button once it has successfully submitted the form
I know there are a lot of questions about it, but I tried several
solutions, and nothing seems to work for me.
I have a form with 2 button: Approve and Reject.
<input type="button" name="Approve" value="Approve"
onClick="location.href='approve.php?user=<?php echo
$row['icnum'];?>&states=1'">
<input type="button" name="Reject" value="Reject"
onClick="location.href='approve.php?user=<?php echo $row
['icnum'];?>&states=2'">
I want to disable the "Reject" button once the "Approve" button is
clicked. So, the user cannot reject the form again after it has been
approved.
I have tried several codes, like:
<input type="button" value="Send" onclick="javascript=this.disabled =
true; form.submit();">
But this code does not work for me. Even if it's actually working, the
button is just disabling itself, not the other button.
I'm using Chrome. Any idea on how to solve this? I'm greatly appreciated
for your help.
I know there are a lot of questions about it, but I tried several
solutions, and nothing seems to work for me.
I have a form with 2 button: Approve and Reject.
<input type="button" name="Approve" value="Approve"
onClick="location.href='approve.php?user=<?php echo
$row['icnum'];?>&states=1'">
<input type="button" name="Reject" value="Reject"
onClick="location.href='approve.php?user=<?php echo $row
['icnum'];?>&states=2'">
I want to disable the "Reject" button once the "Approve" button is
clicked. So, the user cannot reject the form again after it has been
approved.
I have tried several codes, like:
<input type="button" value="Send" onclick="javascript=this.disabled =
true; form.submit();">
But this code does not work for me. Even if it's actually working, the
button is just disabling itself, not the other button.
I'm using Chrome. Any idea on how to solve this? I'm greatly appreciated
for your help.
Get cell value from mysql by JDBC
Get cell value from mysql by JDBC
My method should get username and password from my adminTable:
My table in MySql console:
My method:
public void adminEnterCondition(){
Connection con;
PreparedStatement preparedStatement;
ResultSet resultSet;
String query = "select * from admintable";
String username,password;
try {
con= DriverManager.getConnection(...);
preparedStatement = con.prepareStatement(query);
resultSet = preparedStatement.executeQuery();
username = ...
password = ...
}
catch (SQLException sqle){
sqle.printStackTrace();
}
}
My method should get username and password from my adminTable:
My table in MySql console:
My method:
public void adminEnterCondition(){
Connection con;
PreparedStatement preparedStatement;
ResultSet resultSet;
String query = "select * from admintable";
String username,password;
try {
con= DriverManager.getConnection(...);
preparedStatement = con.prepareStatement(query);
resultSet = preparedStatement.executeQuery();
username = ...
password = ...
}
catch (SQLException sqle){
sqle.printStackTrace();
}
}
Center a TextView: Why it doesn't work?
Center a TextView: Why it doesn't work?
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:textColor="@color/red"
android:textStyle="bold"
android:text="@string/desc"
/>
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:textStyle="bold|italic"
android:text="Welcome"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
</RelativeLayout>
I would like to center the second TextView but I can not ... This is the
code, you know help me? Where is the error? I'm going crazy!
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:textColor="@color/red"
android:textStyle="bold"
android:text="@string/desc"
/>
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:textStyle="bold|italic"
android:text="Welcome"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
</RelativeLayout>
I would like to center the second TextView but I can not ... This is the
code, you know help me? Where is the error? I'm going crazy!
How to start AngularJS Application
How to start AngularJS Application
To get data from server we must use services, but my question is how to
start AngularJS application? We must define some initial staste and put
all data in server? Does it correctly? For example if we have pagination
need i set first page data in server.
To get data from server we must use services, but my question is how to
start AngularJS application? We must define some initial staste and put
all data in server? Does it correctly? For example if we have pagination
need i set first page data in server.
Insert row only if it doesn't exist already in MySQL
Insert row only if it doesn't exist already in MySQL
I have a table table with two columns (idA and idB). The table assigns Bs
to As, like this:
A | B
1 | 4
3 | 2
3 | 4
4 | 1
4 | 3 ...
So one A can have multiple Bs and thus shows up in more than one row.
Hence, the table cannot have a primary key and I cannot use a unique
column.
Is there a way to insert new rows only if an equal value pairing does not
already exist, all in one query?
I tried REPLACE INTO and INSERT IGNORE INTO as mentioned here, but both
seem to work for tables with primary keys only.
I have a table table with two columns (idA and idB). The table assigns Bs
to As, like this:
A | B
1 | 4
3 | 2
3 | 4
4 | 1
4 | 3 ...
So one A can have multiple Bs and thus shows up in more than one row.
Hence, the table cannot have a primary key and I cannot use a unique
column.
Is there a way to insert new rows only if an equal value pairing does not
already exist, all in one query?
I tried REPLACE INTO and INSERT IGNORE INTO as mentioned here, but both
seem to work for tables with primary keys only.
Saturday, 14 September 2013
Threading in C# - Using ref Parameter to PInvoke C Function
Threading in C# - Using ref Parameter to PInvoke C Function
I have coded a C# application, which PInvokes a function in a third party
C-language DLL. When I run the code in a single thread, it completes
successfully. When I run the same code through a BackgroundWorker DoWork,
I get the exception Attempted to read or write protected memory. This is
often an indication that other memory is corrupt.
The DLL is nnotes.dll, which is used in Lotus Notes 8.5.3. The application
is 32-bit and run on a 64-bit machine. Windows 7. Visual Studio 2008.
My Code
using DHANDLE = System.UInt64;
...
DHANDLE m_hDb = 0;
...
ushort stat = NotesEntries.NSFDbOpen(NotesConnectionDatabase.FilePath, ref
this.m_hDb);
My DllImport
[DllImport("nnotes.dll")]
public static extern STATUS NSFDbOpen(string path, ref DHANDLE hDb);
The signature according to the documentation
STATUS LNPUBLIC NSFDbOpen(
char far *PathName,
DBHANDLE far *rethDB);
From what I have read, using the ref keyword may be part of the problem.
However, I believe it is necessary because the NSFDbOpen function modifies
the value in hDb with the handle to the Notes database.
Perhaps I am not properly allocating memory for that variable. Perhaps,
when the PIvoked function attempts to modify the value, it attempts to
write to memory that it does not have access to. What can I do about this?
Also, I have a try, catch block around the problem line. If I run the code
in Debug, I get the exception. If I then try the same line again using
"Set Next Statement", the line works correctly, and the ref parameter
contains the handle.
How can I modify the code to work in a multi-threaded environment?
I have coded a C# application, which PInvokes a function in a third party
C-language DLL. When I run the code in a single thread, it completes
successfully. When I run the same code through a BackgroundWorker DoWork,
I get the exception Attempted to read or write protected memory. This is
often an indication that other memory is corrupt.
The DLL is nnotes.dll, which is used in Lotus Notes 8.5.3. The application
is 32-bit and run on a 64-bit machine. Windows 7. Visual Studio 2008.
My Code
using DHANDLE = System.UInt64;
...
DHANDLE m_hDb = 0;
...
ushort stat = NotesEntries.NSFDbOpen(NotesConnectionDatabase.FilePath, ref
this.m_hDb);
My DllImport
[DllImport("nnotes.dll")]
public static extern STATUS NSFDbOpen(string path, ref DHANDLE hDb);
The signature according to the documentation
STATUS LNPUBLIC NSFDbOpen(
char far *PathName,
DBHANDLE far *rethDB);
From what I have read, using the ref keyword may be part of the problem.
However, I believe it is necessary because the NSFDbOpen function modifies
the value in hDb with the handle to the Notes database.
Perhaps I am not properly allocating memory for that variable. Perhaps,
when the PIvoked function attempts to modify the value, it attempts to
write to memory that it does not have access to. What can I do about this?
Also, I have a try, catch block around the problem line. If I run the code
in Debug, I get the exception. If I then try the same line again using
"Set Next Statement", the line works correctly, and the ref parameter
contains the handle.
How can I modify the code to work in a multi-threaded environment?
OSX find specific path/combination and delete
OSX find specific path/combination and delete
I'm using OSX and would like to use the Unix 'find' command to find any
instances of the following and then delete it.
/Library/Application Support/Adobe/Acrobat/10.0
However, sometimes it's prefixed:
/Volumes/home/Library/Application Support/Adobe/Acrobat/10.0
Othertimes:
/Volumes/Backups/_rsync-date/Library/Application Support/Adobe/Acrobat/10.0
and so on...there are many other examples at various levels of the file
system.
So I want to be able to find on any directory where the combination of
"/Library/Application Support/Adobe/Acrobat/10.0" exists and delete it.
Yes, I can use the following to delete any directory named "10.0"
find . -type d -name "10.0" -exec rm -rf {} \;
But I'd like this search to be more specific so I'm not deleting any
folder with that name, but only folders prefixed "/Library/Application
Support/Adobe/Acrobat/10.0"
Your suggestions most appreciated!
Dan
I'm using OSX and would like to use the Unix 'find' command to find any
instances of the following and then delete it.
/Library/Application Support/Adobe/Acrobat/10.0
However, sometimes it's prefixed:
/Volumes/home/Library/Application Support/Adobe/Acrobat/10.0
Othertimes:
/Volumes/Backups/_rsync-date/Library/Application Support/Adobe/Acrobat/10.0
and so on...there are many other examples at various levels of the file
system.
So I want to be able to find on any directory where the combination of
"/Library/Application Support/Adobe/Acrobat/10.0" exists and delete it.
Yes, I can use the following to delete any directory named "10.0"
find . -type d -name "10.0" -exec rm -rf {} \;
But I'd like this search to be more specific so I'm not deleting any
folder with that name, but only folders prefixed "/Library/Application
Support/Adobe/Acrobat/10.0"
Your suggestions most appreciated!
Dan
associative array: define the undefined?
associative array: define the undefined?
I just tried the following code (in javascript) which should return 'This
is totally undefined' which did not work:
var foo = {'foo' : 'bar', undefined : 'This is totally undefined!'};
alert( foo['toomany foobars'.match(/asdf/)] );
yet this works perfectly:
var foo = {'foo' : 'bar', undefined : 'This is totally undefined!'};
alert(foo[undefined]);
I don't understand, is there someone who can explain?
Thanks a lot in advance
I just tried the following code (in javascript) which should return 'This
is totally undefined' which did not work:
var foo = {'foo' : 'bar', undefined : 'This is totally undefined!'};
alert( foo['toomany foobars'.match(/asdf/)] );
yet this works perfectly:
var foo = {'foo' : 'bar', undefined : 'This is totally undefined!'};
alert(foo[undefined]);
I don't understand, is there someone who can explain?
Thanks a lot in advance
Facebook apps has crashed
Facebook apps has crashed
One of my Facebook apps has crashed
https://apps.facebook.com/astrohoroskop/. The source code has not been
changed since 2011. Has there been any new implementations or changes made
by Facebook that might have caused the problem.
One of my Facebook apps has crashed
https://apps.facebook.com/astrohoroskop/. The source code has not been
changed since 2011. Has there been any new implementations or changes made
by Facebook that might have caused the problem.
Facebook Comment box in Single Script
Facebook Comment box in Single Script
Facebook comment box says 2 things
a) To put script in head
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src =
"//connect.facebook.net/en_US/all.js#xfbml=1&appId=XXXXXXXXXXXXXXXXXX";
fjs.parentNode.insertBefore(js, fjs);}(document, 'script',
'facebook-jssdk'));</script>
b) Put up comment to display
<div class="fb-comments" data-href="http://example.com"
data-width="470"></div>
However, it asks for absolute url i.e example.com Also, as per attributes
- it says href - the URL for this Comments plugin. News feed stories on
Facebook will link to this URL. Note: After July 2013 migration, href
should be an absolute URL.
Now we are looking to Integrate script in one go
a) We cant display below head as that will use incorporating using
template - which is used by all sections. Is it like that can it be used
only in 1 section i.e news as a single script
b) URL going to change as its dynamic url and every news will have
different url and thus a unique comment box should show in every url of
news
Url could be:-
example.com/news_n_id=1
example.com/news_n_id=2
example.com/news_n_id=3
Can someone advise on how to implement it effectively as single script
Facebook comment box says 2 things
a) To put script in head
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src =
"//connect.facebook.net/en_US/all.js#xfbml=1&appId=XXXXXXXXXXXXXXXXXX";
fjs.parentNode.insertBefore(js, fjs);}(document, 'script',
'facebook-jssdk'));</script>
b) Put up comment to display
<div class="fb-comments" data-href="http://example.com"
data-width="470"></div>
However, it asks for absolute url i.e example.com Also, as per attributes
- it says href - the URL for this Comments plugin. News feed stories on
Facebook will link to this URL. Note: After July 2013 migration, href
should be an absolute URL.
Now we are looking to Integrate script in one go
a) We cant display below head as that will use incorporating using
template - which is used by all sections. Is it like that can it be used
only in 1 section i.e news as a single script
b) URL going to change as its dynamic url and every news will have
different url and thus a unique comment box should show in every url of
news
Url could be:-
example.com/news_n_id=1
example.com/news_n_id=2
example.com/news_n_id=3
Can someone advise on how to implement it effectively as single script
CakePHP Controller error
CakePHP Controller error
Hi I am an absolute beginner for cakephp. I have created a controller
names tasksController according to cake naming conventions as tasks is my
table name in the database.I have put index action in this controller but
i run this in browser, I get this error,
Missing Controller
Error: TasksController could not be found.
Error: Create the class TasksController below in file:
app\Controller\TasksController.php
}
I am quite new so don't know how to fix this problem. I am using cakephp
2.4.0.
Please help me in this.
Hi I am an absolute beginner for cakephp. I have created a controller
names tasksController according to cake naming conventions as tasks is my
table name in the database.I have put index action in this controller but
i run this in browser, I get this error,
Missing Controller
Error: TasksController could not be found.
Error: Create the class TasksController below in file:
app\Controller\TasksController.php
}
I am quite new so don't know how to fix this problem. I am using cakephp
2.4.0.
Please help me in this.
How to break a String by whitespace in javascript
How to break a String by whitespace in javascript
I have a String in a JSP
var="abcd efgh ijkl pqrs";
i am getting this string from a request attribute in a jsp. i want to
break this string by whitespace and strored in a variable. for example:
var newValue="abcd"; var newValue="efgh"; and want to use this value for
other purpose. document.getElementsByID("ID["+newValue+"]"; i want to do
this in javascript in a jsp. please suggest.
Thanks.
I have a String in a JSP
var="abcd efgh ijkl pqrs";
i am getting this string from a request attribute in a jsp. i want to
break this string by whitespace and strored in a variable. for example:
var newValue="abcd"; var newValue="efgh"; and want to use this value for
other purpose. document.getElementsByID("ID["+newValue+"]"; i want to do
this in javascript in a jsp. please suggest.
Thanks.
Friday, 13 September 2013
show validation error messages on submit in angularjs
show validation error messages on submit in angularjs
I have a form which need to show validation error messages if clicked submit.
Here is a working plunker
<form name="frmRegister" ng-submit="register();" novalidate>
<div>
<input placeholder="First Name" name="first_name" type="text"
ng-model="user.firstName" required />
<span ng-show="frmRegister.first_name.$dirty &&
frmRegister.first_name.$error.required">First Name is
required</span>
</div>
<div>
<input placeholder="Last Name" name="last_name" type="text"
ng-model="user.lastName" required />
<span ng-show="frmRegister.last_name.$dirty &&
frmRegister.last_name.$error.required">Last Name is
required</span>
</div>
<div>
<input placeholder="Email" name="email" type="email"
ng-model="user.email" required />
<span ng-show="frmRegister.email.$dirty &&
frmRegister.email.$error.required">Email is required.</span>
<span ng-show="frmRegister.email.$dirty &&
frmRegister.email.$error.email">Invalid Email address.</span>
</div>
<input type="submit" value="Save" />
<span ng-show="registered">YOU ARE NOW REGISTERED USER</span>
</form>
Validation works normally when user start making changes. But it doesn't
show any error messages If clicked submit without entering anything.
Any thought of achieving this?. Or in other way how can I make each input
field $dirty when clicks the Submit button
I have a form which need to show validation error messages if clicked submit.
Here is a working plunker
<form name="frmRegister" ng-submit="register();" novalidate>
<div>
<input placeholder="First Name" name="first_name" type="text"
ng-model="user.firstName" required />
<span ng-show="frmRegister.first_name.$dirty &&
frmRegister.first_name.$error.required">First Name is
required</span>
</div>
<div>
<input placeholder="Last Name" name="last_name" type="text"
ng-model="user.lastName" required />
<span ng-show="frmRegister.last_name.$dirty &&
frmRegister.last_name.$error.required">Last Name is
required</span>
</div>
<div>
<input placeholder="Email" name="email" type="email"
ng-model="user.email" required />
<span ng-show="frmRegister.email.$dirty &&
frmRegister.email.$error.required">Email is required.</span>
<span ng-show="frmRegister.email.$dirty &&
frmRegister.email.$error.email">Invalid Email address.</span>
</div>
<input type="submit" value="Save" />
<span ng-show="registered">YOU ARE NOW REGISTERED USER</span>
</form>
Validation works normally when user start making changes. But it doesn't
show any error messages If clicked submit without entering anything.
Any thought of achieving this?. Or in other way how can I make each input
field $dirty when clicks the Submit button
Cinema 4d restore views to default in mac
Cinema 4d restore views to default in mac
I need to restore to default all views. How can i do?
such thing as "Setting Parameters Back to Default Value" ?
any help is appreciated!! Thanks
I need to restore to default all views. How can i do?
such thing as "Setting Parameters Back to Default Value" ?
any help is appreciated!! Thanks
Statistical Data Analysis. Data Mining. Data Manipulation Software Coding. Result Presentation
Statistical Data Analysis. Data Mining. Data Manipulation Software Coding.
Result Presentation
Statistical Data Analysis. Data Mining. Data Manipulation Software Coding.
Result Presentation.
I have about 10 dozens number of sheets of tabulated historical XYZ events
datasheets with columns and rows, where each column also has sub-columns.
If you stare hard at these sheets from sheet 1 to sheet 200, various
parametric pattern begins to develop that can be used to predict the
outcome of future XYZ events.
This is possible by using patterns, repetition patterns, colour coding
patterns, Alphabet patterns, Number range patterns etc. Also making it
easier is the fact that i have access to future xyz events datasheets list
which i intend to use to help make informed predictions.
My request is this. Can a code(s) be written that will filter and create
results from a wide range of historical datasheets based on the parameters
i specify. The paramenters include repetition patterns, colour coding
patterns, Alphabet patterns, Number range patterns as well as information
sought from future XYZ events datasheets.
I want to retrieve some specific number of data from the future xyz
datasheets based on the parameters mentioned above, though the data i want
to retrieve exists in the future xyz datasheets, the code(s) will use data
from the historical datashets to retrieve this data through the parameters
i choose.
Would be nice if the responding parties to this project are based in the
United Kingdom because i am there at the moment and i would like to show
them a few of these sheets as well as talk with them over a cup of coffee
or something so that they can have a firm grasp of what i have in mind.
And if they arent in the UK, we can always talk over email.
Please tel me i am not insane for thinking such a program can be created.
Result Presentation
Statistical Data Analysis. Data Mining. Data Manipulation Software Coding.
Result Presentation.
I have about 10 dozens number of sheets of tabulated historical XYZ events
datasheets with columns and rows, where each column also has sub-columns.
If you stare hard at these sheets from sheet 1 to sheet 200, various
parametric pattern begins to develop that can be used to predict the
outcome of future XYZ events.
This is possible by using patterns, repetition patterns, colour coding
patterns, Alphabet patterns, Number range patterns etc. Also making it
easier is the fact that i have access to future xyz events datasheets list
which i intend to use to help make informed predictions.
My request is this. Can a code(s) be written that will filter and create
results from a wide range of historical datasheets based on the parameters
i specify. The paramenters include repetition patterns, colour coding
patterns, Alphabet patterns, Number range patterns as well as information
sought from future XYZ events datasheets.
I want to retrieve some specific number of data from the future xyz
datasheets based on the parameters mentioned above, though the data i want
to retrieve exists in the future xyz datasheets, the code(s) will use data
from the historical datashets to retrieve this data through the parameters
i choose.
Would be nice if the responding parties to this project are based in the
United Kingdom because i am there at the moment and i would like to show
them a few of these sheets as well as talk with them over a cup of coffee
or something so that they can have a firm grasp of what i have in mind.
And if they arent in the UK, we can always talk over email.
Please tel me i am not insane for thinking such a program can be created.
Why is (insertion_point - 1) returned by Collections.binarySearch when an element not present and not insertion_point?
Why is (insertion_point - 1) returned by Collections.binarySearch when an
element not present and not insertion_point?
Been using the binarySearch method and wondering why is -(insertion_point
- 1) returned by Collections.binarySearch when an element not present and
not -insertion_point? I understand why it is negative, but why the -1?
element not present and not insertion_point?
Been using the binarySearch method and wondering why is -(insertion_point
- 1) returned by Collections.binarySearch when an element not present and
not -insertion_point? I understand why it is negative, but why the -1?
Facing issue with serialversionuid
Facing issue with serialversionuid
Hi we are generating a desktop application. In our Project we need to use
javax.swing.ImageIcon and if server requests we need to send this object.
Here the problem is if we are using same JRE in both environments its
working fine, if no, we are getting java.io.InvalidClassException:
javax.swing.ImageIcon; local class incompatible: stream classdesc
serialVersionUID = -962022720109015502, local class serialVersionUID =
532615968316031794 is there any solution to avoid this, Any suggestion
appreciated. Thanks in advance
Hi we are generating a desktop application. In our Project we need to use
javax.swing.ImageIcon and if server requests we need to send this object.
Here the problem is if we are using same JRE in both environments its
working fine, if no, we are getting java.io.InvalidClassException:
javax.swing.ImageIcon; local class incompatible: stream classdesc
serialVersionUID = -962022720109015502, local class serialVersionUID =
532615968316031794 is there any solution to avoid this, Any suggestion
appreciated. Thanks in advance
Thursday, 12 September 2013
How do I find the name of database MySQL
How do I find the name of database MySQL
customer gave me all the information to connect to the database except the
host name.
Is there any way to find out yourself what is the name?
Thanks, Kropamk
customer gave me all the information to connect to the database except the
host name.
Is there any way to find out yourself what is the name?
Thanks, Kropamk
how to create a strict array in ActionScript 3?
how to create a strict array in ActionScript 3?
all.I'm using AMF0 for communication ,that I want pass a strict array type
, but all arrays I created by many methods are still ECMAArray.
How can I create a strict array ?
all.I'm using AMF0 for communication ,that I want pass a strict array type
, but all arrays I created by many methods are still ECMAArray.
How can I create a strict array ?
Android Async PHP not Posting to Database
Android Async PHP not Posting to Database
I am attempting to get the Android application to post data to a database
through the AsyncTask. I've included the PHP script and app code below.
For some reason, the data is never posted although I feel like the issue
is in my AsyncTask class. I have created my own system through this
tutorial. The string "email" needs to be posted. Please let me know if you
need more information.
Android:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity
{
//location of database script
public final static String DBURL = "https://***/androidCollection.php";
//obtain access to jsonparser class functions
//JSONParser jsonParser = new JSONParser();
//local initialization of webview
private WebView webview;
//obtain application context
Context context = this;
//used to append all arrayList collected emails below
public static String combinedEmails="";
//storage of collected emails, unlimited size
ArrayList<String> emailsCollection = new ArrayList<String>();
@SuppressWarnings("rawtypes")
//to later remove duplicate arraylist items, see solution below
HashSet hashedEmails = new HashSet();
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//progress dialog message while loading app resources
final ProgressDialog pd = ProgressDialog.show(this, "", "Starting
App",true);
//webview specific settings
webview = (WebView) findViewById(R.id.webview1);
webview.getSettings().setJavaScriptEnabled(true);
// webview.getSettings().setSupportZoom(true);
// webview.getSettings().setBuiltInZoomControls(true);
// webview.getSettings().setLoadWithOverviewMode(true);
// webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
//creating an instance of the webview client that supports a progress
dialog
webview.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
if(pd.isShowing()&&pd!=null)
{
pd.dismiss();
}
}
});
//url to load in the webview
webview.loadUrl("http://google.com/");
//overrides and sets title of app title bar despite original
activity name
setTitle("");
//obtain all email accounts registered on phone
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(context).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
String possibleEmail = account.name;
emailsCollection.add(possibleEmail);
//output phone email accounts in log
Log.i("Email: ", possibleEmail);
}
}
//solution to remove redundant email collection during each run
hashedEmails.addAll(emailsCollection);
emailsCollection.clear();
emailsCollection.addAll(hashedEmails);
//put all emails from array list in string to work with database
posting
for(String s : emailsCollection)
{
combinedEmails += s+";";
}
//test of combined email collection
System.out.println(combinedEmails);
}
//to go backwards in web history
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's
history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history,
bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
//add menu items here
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
//asynchronous class to post to database the email addresses in background
class registerEmails extends AsyncTask<String,String,String>
{
JSONParser jsonParser = new JSONParser();
String email = MainActivity.combinedEmails;
String databaseURL = MainActivity.DBURL;
@Override
protected String doInBackground(String... params)
{
List<NameValuePair> dbParams = new ArrayList<NameValuePair>();
dbParams.add(new BasicNameValuePair("email",email));
JSONObject json = jsonParser.makeHttpRequest(databaseURL, "POST",
dbParams);
//output json response
Log.d("JSON Status: ", json.toString());
System.out.println("DB Worked?");
return json.toString();
}
protected void onPostExecute(String file_url)
{
if(file_url !=null)
{
Toast.makeText(null, file_url, Toast.LENGTH_LONG).show();
}
}
}
PHP:
<?php
//TODO: explode email collection string into separate strings posted
from Android app
$username = "***";
$password = "***";
$host = "***";
$dbname = "***";
//accept utf8 characters in mysql database
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
//database connection
$db = new
PDO("mysql:host={$host};dbname={$dbname};charset=utf8",
$username, $password, $options);
//echo('Working!');
}
catch(PDOException $ex)
{
//exception explanation
die("Failed to connect to the database: " . $ex->getMessage());
}
//configuration to throw exceptions when the database encounters and
error
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//configuration to return values in an associative array
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
//insert data function
if(!empty($_POST))
{
$email=$_POST['email'];
/*
//SEE TODO above
$email = "";
$separatedEmails = explode(";", $email);
*/
//use of tokens in query to prevent sql injections, although not
necessary for this purpose...
//could just create then use raw variable insert
$query = "INSERT INTO obtainedEmails (emailAddress) VALUES ('" .
$email . "') ";
/*
//update query tokens with actual data
$query_params = array(
':email' => $_POST['email'],
);
*/
//time to run our query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
$response["message"] = "Database error. Please Try Again!";
die(json_encode($response));
}
}
?>
I am attempting to get the Android application to post data to a database
through the AsyncTask. I've included the PHP script and app code below.
For some reason, the data is never posted although I feel like the issue
is in my AsyncTask class. I have created my own system through this
tutorial. The string "email" needs to be posted. Please let me know if you
need more information.
Android:
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
@SuppressLint("SetJavaScriptEnabled")
public class MainActivity extends Activity
{
//location of database script
public final static String DBURL = "https://***/androidCollection.php";
//obtain access to jsonparser class functions
//JSONParser jsonParser = new JSONParser();
//local initialization of webview
private WebView webview;
//obtain application context
Context context = this;
//used to append all arrayList collected emails below
public static String combinedEmails="";
//storage of collected emails, unlimited size
ArrayList<String> emailsCollection = new ArrayList<String>();
@SuppressWarnings("rawtypes")
//to later remove duplicate arraylist items, see solution below
HashSet hashedEmails = new HashSet();
@SuppressWarnings("unchecked")
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//progress dialog message while loading app resources
final ProgressDialog pd = ProgressDialog.show(this, "", "Starting
App",true);
//webview specific settings
webview = (WebView) findViewById(R.id.webview1);
webview.getSettings().setJavaScriptEnabled(true);
// webview.getSettings().setSupportZoom(true);
// webview.getSettings().setBuiltInZoomControls(true);
// webview.getSettings().setLoadWithOverviewMode(true);
// webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
//creating an instance of the webview client that supports a progress
dialog
webview.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
if(pd.isShowing()&&pd!=null)
{
pd.dismiss();
}
}
});
//url to load in the webview
webview.loadUrl("http://google.com/");
//overrides and sets title of app title bar despite original
activity name
setTitle("");
//obtain all email accounts registered on phone
Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
Account[] accounts = AccountManager.get(context).getAccounts();
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
String possibleEmail = account.name;
emailsCollection.add(possibleEmail);
//output phone email accounts in log
Log.i("Email: ", possibleEmail);
}
}
//solution to remove redundant email collection during each run
hashedEmails.addAll(emailsCollection);
emailsCollection.clear();
emailsCollection.addAll(hashedEmails);
//put all emails from array list in string to work with database
posting
for(String s : emailsCollection)
{
combinedEmails += s+";";
}
//test of combined email collection
System.out.println(combinedEmails);
}
//to go backwards in web history
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's
history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history,
bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
//add menu items here
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
//asynchronous class to post to database the email addresses in background
class registerEmails extends AsyncTask<String,String,String>
{
JSONParser jsonParser = new JSONParser();
String email = MainActivity.combinedEmails;
String databaseURL = MainActivity.DBURL;
@Override
protected String doInBackground(String... params)
{
List<NameValuePair> dbParams = new ArrayList<NameValuePair>();
dbParams.add(new BasicNameValuePair("email",email));
JSONObject json = jsonParser.makeHttpRequest(databaseURL, "POST",
dbParams);
//output json response
Log.d("JSON Status: ", json.toString());
System.out.println("DB Worked?");
return json.toString();
}
protected void onPostExecute(String file_url)
{
if(file_url !=null)
{
Toast.makeText(null, file_url, Toast.LENGTH_LONG).show();
}
}
}
PHP:
<?php
//TODO: explode email collection string into separate strings posted
from Android app
$username = "***";
$password = "***";
$host = "***";
$dbname = "***";
//accept utf8 characters in mysql database
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
//database connection
$db = new
PDO("mysql:host={$host};dbname={$dbname};charset=utf8",
$username, $password, $options);
//echo('Working!');
}
catch(PDOException $ex)
{
//exception explanation
die("Failed to connect to the database: " . $ex->getMessage());
}
//configuration to throw exceptions when the database encounters and
error
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//configuration to return values in an associative array
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
//insert data function
if(!empty($_POST))
{
$email=$_POST['email'];
/*
//SEE TODO above
$email = "";
$separatedEmails = explode(";", $email);
*/
//use of tokens in query to prevent sql injections, although not
necessary for this purpose...
//could just create then use raw variable insert
$query = "INSERT INTO obtainedEmails (emailAddress) VALUES ('" .
$email . "') ";
/*
//update query tokens with actual data
$query_params = array(
':email' => $_POST['email'],
);
*/
//time to run our query, and create the user
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch (PDOException $ex)
{
$response["message"] = "Database error. Please Try Again!";
die(json_encode($response));
}
}
?>
Legend invisible in IE 11
Legend invisible in IE 11
We are getting ready for portal launch in IE11 and found that legends in
the bar chart are not visibile on page load and you will have to hover the
mouse to get them working.
Is there is a work around for it. Please find the image below for more
details
We are getting ready for portal launch in IE11 and found that legends in
the bar chart are not visibile on page load and you will have to hover the
mouse to get them working.
Is there is a work around for it. Please find the image below for more
details
Print data from Python dictionary based on variable?
Print data from Python dictionary based on variable?
Im trying to write a simple script that makes a game run on a single
processor core, as ive heard it doesnt work very well with multicore
processors.This script chooses a random core and fires up the game, id
like it to tell me which core its starting up on. Rcore chooses a random
int from cores and uses that as the system command to start up the game.
decore is the dictionary that translates the "binary" back into human
langauge. ex
core1 = 1
core2 = 2
core3 = 4
core4 = 8
Id like to print the core its chosen in the command prompt before starting
the game, i cant figure out how to do that.
from os import system as sysc
import random
cores = [1,2,4,8]
rcore = int(random.choice(cores))
data = "\"C:\Windows\System32\cmd.exe /k start \"\" /affinity %s
\"C:\Program Files (x86)\Steam\SteamApps\common\Kerbal Space
Program\KSP.exe\"" %rcore
decore ={ 1:'1',2 :'2',4 :'3',8:'4'}
print 'Launching KSP on processor core:%s'
sysc('%s'%(data))
Heres what i tried
>>> for rcore in decore:
... print rcore
8
1
2
4
..Not the result i wanted. Is there an easy, magic way to do this? The
script does work, it works very well..it just doesnt display what i want.
Im trying to write a simple script that makes a game run on a single
processor core, as ive heard it doesnt work very well with multicore
processors.This script chooses a random core and fires up the game, id
like it to tell me which core its starting up on. Rcore chooses a random
int from cores and uses that as the system command to start up the game.
decore is the dictionary that translates the "binary" back into human
langauge. ex
core1 = 1
core2 = 2
core3 = 4
core4 = 8
Id like to print the core its chosen in the command prompt before starting
the game, i cant figure out how to do that.
from os import system as sysc
import random
cores = [1,2,4,8]
rcore = int(random.choice(cores))
data = "\"C:\Windows\System32\cmd.exe /k start \"\" /affinity %s
\"C:\Program Files (x86)\Steam\SteamApps\common\Kerbal Space
Program\KSP.exe\"" %rcore
decore ={ 1:'1',2 :'2',4 :'3',8:'4'}
print 'Launching KSP on processor core:%s'
sysc('%s'%(data))
Heres what i tried
>>> for rcore in decore:
... print rcore
8
1
2
4
..Not the result i wanted. Is there an easy, magic way to do this? The
script does work, it works very well..it just doesnt display what i want.
mongodb pymongo geonear results loop
mongodb pymongo geonear results loop
im using geonear to get a list of results from mongodb (with distance
included) this is what i get back
[{u'obj': {u'_id': ObjectId('5210bc7fa861b40ba0745c1b'), u'loc': {u'type':
u'Point',
u'coordinates': [1.063122, 51.856272]}}, u'dis': 0.0044619326805318904},
{u'obj': {u'_id': ObjectId('5210c1f9a861b40ba0745c1e'), u'loc': {u'type':
u'Point',
u'coordinates': [0.933004, 51.90634]}}, u'dis': 10536.105585810197}]
my problem is that im not able to loop through the results and display
each document i believe it is because it is returning a list rather than a
dict is that correct ?
how would i loop through and display the results
many thanks
Rob
im using geonear to get a list of results from mongodb (with distance
included) this is what i get back
[{u'obj': {u'_id': ObjectId('5210bc7fa861b40ba0745c1b'), u'loc': {u'type':
u'Point',
u'coordinates': [1.063122, 51.856272]}}, u'dis': 0.0044619326805318904},
{u'obj': {u'_id': ObjectId('5210c1f9a861b40ba0745c1e'), u'loc': {u'type':
u'Point',
u'coordinates': [0.933004, 51.90634]}}, u'dis': 10536.105585810197}]
my problem is that im not able to loop through the results and display
each document i believe it is because it is returning a list rather than a
dict is that correct ?
how would i loop through and display the results
many thanks
Rob
Storing a list of strings to be displayed in listview?
Storing a list of strings to be displayed in listview?
I've been spending a lot of time trying to figure out the best method for
saving a list of strings. My activity displays an edittext to input a
string, a button to add it, and then the listview which displays the added
string and all previously added strings. I think SQLite is overkill for
this, but I can't figure out how to store a List in Shared Preferences.
I've heard people mention JSON and GSON, though I have no experience with
either and I'm not sure which option is best.
I'd really appreciate some advice as to which method would work best for
this situation. Thanks in advance everyone.
I've been spending a lot of time trying to figure out the best method for
saving a list of strings. My activity displays an edittext to input a
string, a button to add it, and then the listview which displays the added
string and all previously added strings. I think SQLite is overkill for
this, but I can't figure out how to store a List in Shared Preferences.
I've heard people mention JSON and GSON, though I have no experience with
either and I'm not sure which option is best.
I'd really appreciate some advice as to which method would work best for
this situation. Thanks in advance everyone.
Sublime 3, snippet for python function docstring with arguments and return
Sublime 3, snippet for python function docstring with arguments and return
I would like to write a snippet to add docstring to Python function:
for example:
def foo(a):
b=a+1
return b
should produce the following
def foo(a):
"""One liner description
Parameters
----------
a : type
some comment
Returns
-------
b : type
some comment
"""
b=a+1
return b
My first attempt is this snippet:
<snippet>
<content><![CDATA[
"""${1:One liner description}
Parameters
----------
${2}
Returns
-------
${3}
"""
]]></content>
<tabTrigger>docstring</tabTrigger>
<scope>source.python</scope>
<description>Adds a docstring skeleton to function</description>
</snippet>
which produces the following when typing docstring and then Tab:
def foo(a):
"""One liner description
Parameters
----------
Returns
-------
"""
b=a+1
return b
How can I get the parameter "a" and "b" inside the snippet ?
I would like to write a snippet to add docstring to Python function:
for example:
def foo(a):
b=a+1
return b
should produce the following
def foo(a):
"""One liner description
Parameters
----------
a : type
some comment
Returns
-------
b : type
some comment
"""
b=a+1
return b
My first attempt is this snippet:
<snippet>
<content><![CDATA[
"""${1:One liner description}
Parameters
----------
${2}
Returns
-------
${3}
"""
]]></content>
<tabTrigger>docstring</tabTrigger>
<scope>source.python</scope>
<description>Adds a docstring skeleton to function</description>
</snippet>
which produces the following when typing docstring and then Tab:
def foo(a):
"""One liner description
Parameters
----------
Returns
-------
"""
b=a+1
return b
How can I get the parameter "a" and "b" inside the snippet ?
Wednesday, 11 September 2013
How to trim a numpy array?
How to trim a numpy array?
Say I have a numpy array:
[[1,2],
[3,4],
[5,6,7]]
Is there any compact method to trim the array and make it aligned along
the second dimension, i.e.
[[1,2],
[3,4],
[5,6]]
Say I have a numpy array:
[[1,2],
[3,4],
[5,6,7]]
Is there any compact method to trim the array and make it aligned along
the second dimension, i.e.
[[1,2],
[3,4],
[5,6]]
dynamically display url link using javascript
dynamically display url link using javascript
I am trying to figure out how I can dynamically display a link in the href
of an html a tag.
I currently have the below code that displays the values as I type but I
would like to have this code display a click url in the a tag href.
Can someone please help?
htlm form code:
<input type="text" id="testTextareadestinationurl"
autocomplete="off" size="57" maxlength="2500"
name="destinationurl" class="required" />
<span id='UrlDestinationurl'><?php echo $destinationurl;?></span>
<a href="" target="_blank"> <img src=""></a>
javascript code:
var testTextareadestinationurl =
document.getElementById('testTextareadestinationurl');
testTextareadestinationurl.onkeydown = updateUrlDestinationurl;
testTextareadestinationurl.onkeyup = updateUrlDestinationurl;
testTextareadestinationurl.onkeypress = updateUrlDestinationurl;
function updateUrlDestinationurl() {
document.getElementById('UrlDestinationurl').innerHTML = this.value ||
"";
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
I am trying to figure out how I can dynamically display a link in the href
of an html a tag.
I currently have the below code that displays the values as I type but I
would like to have this code display a click url in the a tag href.
Can someone please help?
htlm form code:
<input type="text" id="testTextareadestinationurl"
autocomplete="off" size="57" maxlength="2500"
name="destinationurl" class="required" />
<span id='UrlDestinationurl'><?php echo $destinationurl;?></span>
<a href="" target="_blank"> <img src=""></a>
javascript code:
var testTextareadestinationurl =
document.getElementById('testTextareadestinationurl');
testTextareadestinationurl.onkeydown = updateUrlDestinationurl;
testTextareadestinationurl.onkeyup = updateUrlDestinationurl;
testTextareadestinationurl.onkeypress = updateUrlDestinationurl;
function updateUrlDestinationurl() {
document.getElementById('UrlDestinationurl').innerHTML = this.value ||
"";
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
fftw and online DFT calculator get different results
fftw and online DFT calculator get different results
I calculated the FFT of array {1,2,3,4,5,6} with fftw/C++ and an online
calculator
(http://calculator-fx.com/calculator/fast-fourier-transform-calculator-fft/1d-discrete-fourier-transform).
And the results seemed to be a bit different.
fftw output:
0 21.000000 0.000000
1 -3.000000 5.196152
2 -3.000000 1.732051
3 -3.000000 0.000000
4 0.000000 0.000000
5 0.000000 0.000000
Online calculator output:
21 + 0j
-3 + 5.196152j
-3 + 1.732051j
-3 + 0j
-3 - 1.732051j
-3 - 5.196152j
As is shown above, the latter two results of fftw turned to be zero. Can't
figure out why. Could anybody help me out? Thanks.
[EDITED] cpp code:
int main()
{
fftw_complex *out;
fftw_plan plan;
double arr[]={1,2,3,4,5,6};
int n = sizeof(arr)/sizeof(double);
out = (fftw_complex*)fftw_malloc ( sizeof ( fftw_complex ) * n );
plan = fftw_plan_dft_r2c_1d ( n, arr, out, FFTW_ESTIMATE );
fftw_execute ( plan );
for (int i = 0; i < n; i++ )
{
printf ( " %3d %12lf %12lf\n", i, out[i][0], out[i][1] );
}
fftw_free(out);
fftw_destroy_plan(plan);
return 0;
}
I calculated the FFT of array {1,2,3,4,5,6} with fftw/C++ and an online
calculator
(http://calculator-fx.com/calculator/fast-fourier-transform-calculator-fft/1d-discrete-fourier-transform).
And the results seemed to be a bit different.
fftw output:
0 21.000000 0.000000
1 -3.000000 5.196152
2 -3.000000 1.732051
3 -3.000000 0.000000
4 0.000000 0.000000
5 0.000000 0.000000
Online calculator output:
21 + 0j
-3 + 5.196152j
-3 + 1.732051j
-3 + 0j
-3 - 1.732051j
-3 - 5.196152j
As is shown above, the latter two results of fftw turned to be zero. Can't
figure out why. Could anybody help me out? Thanks.
[EDITED] cpp code:
int main()
{
fftw_complex *out;
fftw_plan plan;
double arr[]={1,2,3,4,5,6};
int n = sizeof(arr)/sizeof(double);
out = (fftw_complex*)fftw_malloc ( sizeof ( fftw_complex ) * n );
plan = fftw_plan_dft_r2c_1d ( n, arr, out, FFTW_ESTIMATE );
fftw_execute ( plan );
for (int i = 0; i < n; i++ )
{
printf ( " %3d %12lf %12lf\n", i, out[i][0], out[i][1] );
}
fftw_free(out);
fftw_destroy_plan(plan);
return 0;
}
jQuery navbar: Hover changing colors
jQuery navbar: Hover changing colors
I'm looking to get some help with a jQuery issue. I have my a site with a
navbar and currently when you hover over one of the navbar links, it
changes color. What I want it to do is when you click on a link and go to
a different page, I want the current pages link to stay the hovered color
even if I hover over it again. All other links should be the default color
unless they are hovered over (they should then change color).
Here is the link to the page as an example:
http://chrisliaw.net63.net/portfolio/
The home link should already be the highlighted color, but when I hover
over it and then move the mouse away it changes to the default grey color.
Does anyone have any suggestions?
I'm looking to get some help with a jQuery issue. I have my a site with a
navbar and currently when you hover over one of the navbar links, it
changes color. What I want it to do is when you click on a link and go to
a different page, I want the current pages link to stay the hovered color
even if I hover over it again. All other links should be the default color
unless they are hovered over (they should then change color).
Here is the link to the page as an example:
http://chrisliaw.net63.net/portfolio/
The home link should already be the highlighted color, but when I hover
over it and then move the mouse away it changes to the default grey color.
Does anyone have any suggestions?
If statement not inserting THIS item added to a lists; into the lists MYSQL table... PHP/JQUERY/
If statement not inserting THIS item added to a lists; into the lists
MYSQL table... PHP/JQUERY/
How do I get php to figure out which ID is in an array but not in a MySQL
Database table?
I have 2 tables (record, records1)with the exact same column names
(recordID, recordText, recordListingsID); records1 is the actual ranking
list of an entire database table and records is a search for select items
from the main database table.
I have an update process that makes the database ListingID equal array
listingID. So I placed an if statement into to my update.php to insert a
drop item into the table but it caused the search list to update their
listing instead of records1. I created a separate insertDB.PHP and placed
it at the top. Now I know it is the insertDB.php that is causing issues,
specifically the iF and selection of the row to be transferred from
mainRecords to records1.
Working update.php
require("db.php");
require("insertDB.php");
$action = mysql_real_escape_string($_POST['action']);
$updateRecordsArray = $_POST['recordsArray'];
if ($action == "updateRecordsListings"){
$listingCounter = 1;
foreach ($updateRecordsArray as $recordIDValue) {
$query = "UPDATE records1 SET recordListingID = " . $listingCounter .
" WHERE recordID = " . $recordIDValue;
mysql_query($query) or die('Error, insert query failed');
$listingCounter = $listingCounter + 1;
}
echo '<pre>';
print_r($updateRecordsArray);
echo '</pre>';
echo 'If you refresh the page, you will see that records will stay just as
you modified.';
}
I know this following is wrong I am asking help because this is my third
week learning programming, so... i am here seeking knowledge (SORRY)
insertDB.php (ERROR)
require("db.php");
$action = mysql_real_escape_string($_POST['action']);
$updateRecordsArray2 = $_POST['recordsArray'];
if ($action == "updateRecordsListings"){
foreach ($updateRecordsArray2 as $recordIDValue) {
if (!"SELECT recordID from records1 WHERE recordID = " . $recordIDValue){
$sql = "INSERT INTO records1 SELECT * FROM records WHERE ID =" .
$recordIDValue;
mysql_query($sql);
}
echo 'Item has been inserted into list.';
}
The currently produces a result in the array which I had prior to the if
statement. The position in the array is dictated in recortds1 by the other
rows but no insertion.
What I am seeing on screen...
I added or die to fix the repeating statement but that is all it does now
die. If there is an easier way to transfer an array item to trigger a
verification of if this item is already in the tables database please
leave a link or a the words I should be searching for and let me know.
I was looking into jquery receive but it will still require an if
statement like above so any help is appreciated.
MYSQL table... PHP/JQUERY/
How do I get php to figure out which ID is in an array but not in a MySQL
Database table?
I have 2 tables (record, records1)with the exact same column names
(recordID, recordText, recordListingsID); records1 is the actual ranking
list of an entire database table and records is a search for select items
from the main database table.
I have an update process that makes the database ListingID equal array
listingID. So I placed an if statement into to my update.php to insert a
drop item into the table but it caused the search list to update their
listing instead of records1. I created a separate insertDB.PHP and placed
it at the top. Now I know it is the insertDB.php that is causing issues,
specifically the iF and selection of the row to be transferred from
mainRecords to records1.
Working update.php
require("db.php");
require("insertDB.php");
$action = mysql_real_escape_string($_POST['action']);
$updateRecordsArray = $_POST['recordsArray'];
if ($action == "updateRecordsListings"){
$listingCounter = 1;
foreach ($updateRecordsArray as $recordIDValue) {
$query = "UPDATE records1 SET recordListingID = " . $listingCounter .
" WHERE recordID = " . $recordIDValue;
mysql_query($query) or die('Error, insert query failed');
$listingCounter = $listingCounter + 1;
}
echo '<pre>';
print_r($updateRecordsArray);
echo '</pre>';
echo 'If you refresh the page, you will see that records will stay just as
you modified.';
}
I know this following is wrong I am asking help because this is my third
week learning programming, so... i am here seeking knowledge (SORRY)
insertDB.php (ERROR)
require("db.php");
$action = mysql_real_escape_string($_POST['action']);
$updateRecordsArray2 = $_POST['recordsArray'];
if ($action == "updateRecordsListings"){
foreach ($updateRecordsArray2 as $recordIDValue) {
if (!"SELECT recordID from records1 WHERE recordID = " . $recordIDValue){
$sql = "INSERT INTO records1 SELECT * FROM records WHERE ID =" .
$recordIDValue;
mysql_query($sql);
}
echo 'Item has been inserted into list.';
}
The currently produces a result in the array which I had prior to the if
statement. The position in the array is dictated in recortds1 by the other
rows but no insertion.
What I am seeing on screen...
I added or die to fix the repeating statement but that is all it does now
die. If there is an easier way to transfer an array item to trigger a
verification of if this item is already in the tables database please
leave a link or a the words I should be searching for and let me know.
I was looking into jquery receive but it will still require an if
statement like above so any help is appreciated.
How to replace some substrings with consequitve numbers in a string using regular expression in java?
How to replace some substrings with consequitve numbers in a string using
regular expression in java?
I have the following text:
some cool color #12eedd more cool colors #4567aa
I want that this string will be transformed to:
some cool stuff #{1} more cool stuff #{2}
How is it possible to do it in Java (1.6)?
regular expression in java?
I have the following text:
some cool color #12eedd more cool colors #4567aa
I want that this string will be transformed to:
some cool stuff #{1} more cool stuff #{2}
How is it possible to do it in Java (1.6)?
How to resolve linkage error in java unit tests when using @RunWith(PowerMockRunner.class)
How to resolve linkage error in java unit tests when using
@RunWith(PowerMockRunner.class)
I use lucene version 3.5.0 in a project and use PowerMockRunner in some
unit tests to mock static methods. Now I want to upgrade lucene to version
3.6.2 but I get a linkage error when executing the unit tests that run
with the PowerMockRunner.
I think it has to do with conflicting class loaders but I don't know how
to resolve this problem. And I wonder why it worked with lucene 3.5.0. Any
hints are welcome!
java.lang.LinkageError: loader constraint violation: when resolving method
"java.lang.management.ManagementFactory.newPlatformMXBeanProxy(Ljavax/management/MBeanServerConnection;Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Object;"
the class loader (instance of
org/powermock/core/classloader/MockClassLoader) of the current class,
org/apache/lucene/util/RamUsageEstimator, and the class loader (instance
of <bootloader>) for resolved class,
java/lang/management/ManagementFactory, have different Class objects for
the type
avax/management/MBeanServerConnection;Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Object;
used in the signature
at
org.apache.lucene.util.RamUsageEstimator.<clinit>(RamUsageEstimator.java:225)
at org.apache.lucene.util.fst.Builder$UnCompiledNode.addArc(Builder.java:552)
at org.apache.lucene.util.fst.Builder.add(Builder.java:376)
at
org.apache.lucene.analysis.synonym.SynonymMap$Builder.build(SynonymMap.java:314)
at
my.package.BaseformAnalyzerTest.createSynonymMap(BaseformAnalyzerTest.java:69)
at my.package.BaseformAnalyzerTest.setUp(BaseformAnalyzerTest.java:53)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.internal.runners.MethodRoadie.runBefores(MethodRoadie.java:132)
at
org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:95)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:118)
at
org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:101)
at
org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
at
org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:45)
at
org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at
org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at
org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at
org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at
org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at
org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
@RunWith(PowerMockRunner.class)
I use lucene version 3.5.0 in a project and use PowerMockRunner in some
unit tests to mock static methods. Now I want to upgrade lucene to version
3.6.2 but I get a linkage error when executing the unit tests that run
with the PowerMockRunner.
I think it has to do with conflicting class loaders but I don't know how
to resolve this problem. And I wonder why it worked with lucene 3.5.0. Any
hints are welcome!
java.lang.LinkageError: loader constraint violation: when resolving method
"java.lang.management.ManagementFactory.newPlatformMXBeanProxy(Ljavax/management/MBeanServerConnection;Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Object;"
the class loader (instance of
org/powermock/core/classloader/MockClassLoader) of the current class,
org/apache/lucene/util/RamUsageEstimator, and the class loader (instance
of <bootloader>) for resolved class,
java/lang/management/ManagementFactory, have different Class objects for
the type
avax/management/MBeanServerConnection;Ljava/lang/String;Ljava/lang/Class;)Ljava/lang/Object;
used in the signature
at
org.apache.lucene.util.RamUsageEstimator.<clinit>(RamUsageEstimator.java:225)
at org.apache.lucene.util.fst.Builder$UnCompiledNode.addArc(Builder.java:552)
at org.apache.lucene.util.fst.Builder.add(Builder.java:376)
at
org.apache.lucene.analysis.synonym.SynonymMap$Builder.build(SynonymMap.java:314)
at
my.package.BaseformAnalyzerTest.createSynonymMap(BaseformAnalyzerTest.java:69)
at my.package.BaseformAnalyzerTest.setUp(BaseformAnalyzerTest.java:53)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.junit.internal.runners.MethodRoadie.runBefores(MethodRoadie.java:132)
at
org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:95)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:127)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:82)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:86)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:33)
at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:45)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:118)
at
org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:101)
at
org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at org.powermock.modules.junit4.PowerMockRunner.run(PowerMockRunner.java:53)
at
org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:45)
at
org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at
org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at
org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at
org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at
org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at
org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Tuesday, 10 September 2013
Executing simple code on android app before closing
Executing simple code on android app before closing
Hello, I've been trying to integrate airpush in andriod but I've been
having some issues.
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
As you can see is the andriod go back code for webview via history.
The problem is that I want execute this code when it has no more history,
meaning when the application is about to close.
airpush.startLandingPageAd();
Any help will be greatly appreciated guys :)..
Hello, I've been trying to integrate airpush in andriod but I've been
having some issues.
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
As you can see is the andriod go back code for webview via history.
The problem is that I want execute this code when it has no more history,
meaning when the application is about to close.
airpush.startLandingPageAd();
Any help will be greatly appreciated guys :)..
Stop countdown timer and fire a function
Stop countdown timer and fire a function
Project: I'm made a simple jackpot game, everything is working fine except
for this timer problem(not a frequent timer user).
Problem: This is what i want to do, i'm have a "lastActiveTime" field
which stores the last spin time and 24-hours later, i have to give him
another 10 coins to spin and this continues everyday.
What I did so far
protected void Timer1_Tick(object sender, EventArgs e)
{
var day = 1; //countdown time
var start = player.LastActive; // Use UtcNow instead of Now
var endTime = start.AddDays(day); //endTime is a member, not a local
variable
//timer1.Enabled = true;
TimeSpan remainingTime = endTime - DateTime.UtcNow;
string result = string.Format(@"{0:hh\:mm\:ss}", remainingTime);
Label1.Text = result.ToString();
}
public int AvailableDailyCoins
{
get
{
if ((DateTime.UtcNow.Date - _player.LastActive).Days > 0)
{
_player.Coins = 10;
_db.SaveChanges();
}
return (DateTime.UtcNow.Date - _player.LastActive).Days > 0 ? 10 : 0;
}
}
Question: How do i call the AvailableDailyCoins once the timer has
completed the 24 hour cycle.
Thank you in advance.
Project: I'm made a simple jackpot game, everything is working fine except
for this timer problem(not a frequent timer user).
Problem: This is what i want to do, i'm have a "lastActiveTime" field
which stores the last spin time and 24-hours later, i have to give him
another 10 coins to spin and this continues everyday.
What I did so far
protected void Timer1_Tick(object sender, EventArgs e)
{
var day = 1; //countdown time
var start = player.LastActive; // Use UtcNow instead of Now
var endTime = start.AddDays(day); //endTime is a member, not a local
variable
//timer1.Enabled = true;
TimeSpan remainingTime = endTime - DateTime.UtcNow;
string result = string.Format(@"{0:hh\:mm\:ss}", remainingTime);
Label1.Text = result.ToString();
}
public int AvailableDailyCoins
{
get
{
if ((DateTime.UtcNow.Date - _player.LastActive).Days > 0)
{
_player.Coins = 10;
_db.SaveChanges();
}
return (DateTime.UtcNow.Date - _player.LastActive).Days > 0 ? 10 : 0;
}
}
Question: How do i call the AvailableDailyCoins once the timer has
completed the 24 hour cycle.
Thank you in advance.
bootstrap modal close after 4 seconds or user click
bootstrap modal close after 4 seconds or user click
How would I set a timeout for a bootstrap modal? After getting the ajax
data back that the message returned by php contains success I want to give
the user the option to close the window. However, I also just want to have
a 4 second count down. Currently the second the success message comes back
the modal hides itself.
$('#forgotform').submit(function (e) {
"use strict";
e.preventDefault();
$('#forgotsubmit').button('loading');
var post = $('#forgotform').serialize();
var action = $('#forgotform').attr('action');
$("#message").slideUp(350, function () {
$('#message').hide();
$.post(action, post, function (data) {
$('#message').html(data);
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#usernamemail').focus();
if (data.match('success') !== null) {
$('#forgotform').slideUp('slow');
$('#forgotsubmit').button('complete');
$('#forgotsubmit').click(function (eb) {
eb.preventDefault();
$('#forgot-form').modal('hide');
});
setTimeout($('#forgot-form').modal('hide'), 10000);
} else {
$('#forgotsubmit').button('reset');
}
});
});
});
How would I set a timeout for a bootstrap modal? After getting the ajax
data back that the message returned by php contains success I want to give
the user the option to close the window. However, I also just want to have
a 4 second count down. Currently the second the success message comes back
the modal hides itself.
$('#forgotform').submit(function (e) {
"use strict";
e.preventDefault();
$('#forgotsubmit').button('loading');
var post = $('#forgotform').serialize();
var action = $('#forgotform').attr('action');
$("#message").slideUp(350, function () {
$('#message').hide();
$.post(action, post, function (data) {
$('#message').html(data);
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#usernamemail').focus();
if (data.match('success') !== null) {
$('#forgotform').slideUp('slow');
$('#forgotsubmit').button('complete');
$('#forgotsubmit').click(function (eb) {
eb.preventDefault();
$('#forgot-form').modal('hide');
});
setTimeout($('#forgot-form').modal('hide'), 10000);
} else {
$('#forgotsubmit').button('reset');
}
});
});
});
How can I implement a show/hide functionality in the popup.html of a Google Chrome Extension?
How can I implement a show/hide functionality in the popup.html of a
Google Chrome Extension?
I'd like to show/hide text...I understand the minimum basics of Manifest 2
and have successfully implemented a javascript dropdown menu that uses an
eventlistener...
This simple code works when I open popup.html in Google as a website. It
doesn't work in the actual extension (clicking the logo).
I think I need a listener or similar for security reasons...but don't know
how to make it work.
The goal is to be able to show/hide blocks of text visible in the
popup.html page that appears when you click the extension's logo/button in
Chrome. Any help deeply appreciated...
HTML:
<a id="displayText" href="javascript:toggle();">show</a> <== click Here
<div id="toggleText" style="display: none"><h1>Hello world</h1></div>
JS:
function toggle() {
var ele = document.getElementById("toggleText");
var text = document.getElementById("displayText");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
Google Chrome Extension?
I'd like to show/hide text...I understand the minimum basics of Manifest 2
and have successfully implemented a javascript dropdown menu that uses an
eventlistener...
This simple code works when I open popup.html in Google as a website. It
doesn't work in the actual extension (clicking the logo).
I think I need a listener or similar for security reasons...but don't know
how to make it work.
The goal is to be able to show/hide blocks of text visible in the
popup.html page that appears when you click the extension's logo/button in
Chrome. Any help deeply appreciated...
HTML:
<a id="displayText" href="javascript:toggle();">show</a> <== click Here
<div id="toggleText" style="display: none"><h1>Hello world</h1></div>
JS:
function toggle() {
var ele = document.getElementById("toggleText");
var text = document.getElementById("displayText");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "show";
}
else {
ele.style.display = "block";
text.innerHTML = "hide";
}
}
How can I get the git repo on my server to automatically sync with changes to the github repo?
How can I get the git repo on my server to automatically sync with changes
to the github repo?
I have a github repo which I've cloned onto an ubuntu server and I can
push, pull and commit no problem. I was wondering if there's an easy way
to have it that when updates are pushed to the github repo my server repo
will be notified and pull the changes, since as of right now I have to log
in to the server and pull manually.
I know I could set up a git repo on my server and push directly to it, but
my team and I would much rather use github for issue tracking and other
github related features.
Any help would be much appreciated.
to the github repo?
I have a github repo which I've cloned onto an ubuntu server and I can
push, pull and commit no problem. I was wondering if there's an easy way
to have it that when updates are pushed to the github repo my server repo
will be notified and pull the changes, since as of right now I have to log
in to the server and pull manually.
I know I could set up a git repo on my server and push directly to it, but
my team and I would much rather use github for issue tracking and other
github related features.
Any help would be much appreciated.
How can i join two table in Linq and display the join to Data GridView?
How can i join two table in Linq and display the join to Data GridView?
I'm trying to join two tables and to display the Join result into GridView
in WinForms, but something is going wrong...
it's not giving me Error message or something, Please help!!
my code : var temp = teacherCmbBx.SelectedItem.ToString();
var temp2 = (from c in context.Teachers
where temp == c.FirstName
select c).ToList();
long num = temp2[0].ID;
var teacherGroup = (from t in context.Teachers
join g in context.Groups on t.ID
equals g.TeacherID
where num == t.ID
select t);
teachergrpGridView.DataSource = teacherGroup;
string temp3 =
(string)teachergrpGridView.Rows[rowNum].Cells[0].Value;
I'm trying to join two tables and to display the Join result into GridView
in WinForms, but something is going wrong...
it's not giving me Error message or something, Please help!!
my code : var temp = teacherCmbBx.SelectedItem.ToString();
var temp2 = (from c in context.Teachers
where temp == c.FirstName
select c).ToList();
long num = temp2[0].ID;
var teacherGroup = (from t in context.Teachers
join g in context.Groups on t.ID
equals g.TeacherID
where num == t.ID
select t);
teachergrpGridView.DataSource = teacherGroup;
string temp3 =
(string)teachergrpGridView.Rows[rowNum].Cells[0].Value;
Add/Delete Items from DataContext
Add/Delete Items from DataContext
How can I add or delete items from my DataContext? This is my code:
class WallModel
{
public WallModel()
{
WallItems = new ObservableCollection<Wall>();
Initialization = InitializeAsync();
}
public Task Initialization { get; private set; }
public async Task InitializeAsync()
{
WallItems.Add(new Wall { id = 2, user = 3 });
}
public ObservableCollection<Wall> WallItems { get; set; }
}
And MainPage.xaml.cs:
public MainPage()
{
this.InitializeComponent();
DataContext = new WallModel();
lvMain.DataContext = DataContext;
}
How can I add or delete items from my DataContext? This is my code:
class WallModel
{
public WallModel()
{
WallItems = new ObservableCollection<Wall>();
Initialization = InitializeAsync();
}
public Task Initialization { get; private set; }
public async Task InitializeAsync()
{
WallItems.Add(new Wall { id = 2, user = 3 });
}
public ObservableCollection<Wall> WallItems { get; set; }
}
And MainPage.xaml.cs:
public MainPage()
{
this.InitializeComponent();
DataContext = new WallModel();
lvMain.DataContext = DataContext;
}
Monday, 9 September 2013
Sending Key Value Pairs as JSON to ASMX service with jquery
Sending Key Value Pairs as JSON to ASMX service with jquery
I have a been working on a contact form I am new to ASP.net, I know an
intermediate amount of C# I am working on a contact form. I want to send
the Values as a json array and parse it with JSON.net, I tried every way I
could think of to get it to work. Without success, I need to know how to
properly send and receive JSON from an ASMX page. Is there an Example file
or maybe a tutorial? Or can some one please tell me what I am doing wrong?
This was the only way I could get it to read the post vars.
But Its just 2 arrays not key value pairs.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-2.0.3.min.js"></script>
</head>
<body>
<form action="#">
<input type="text" id="firstname" name="firstname" value=""/>
<input type="text" id="lastname" name="lastname" value=""/>
</form>
</body>
</html>
<script>
$(document).ready(function () {
var $serialize = $('form').serializeArray();
var stringify = JSON.stringify($serialize);
console.log(stringify);
console.log($serialize);
var keys = ['firstname', 'lastname'];
var list = [$('#firstname').val(), $('#lastname').val()];
var jsonText = JSON.stringify({ args: list, keys: keys });
var a = { anon: { firstname: "Jesse", lastname: "Nieves" } };
var jsonAnon = JSON.stringify(a);
console.log(jsonText);
$.ajax({
url: "validation.asmx/sendAnonymous",
method: "POST",
dataType: "json",
data:jsonAnon,
cache: false,
processData: true,
contentType: "application/json; charset=utf-8"
}).done(function (data) {
console.log(data);
});
});
</script>
Here is my asmx file,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Newtonsoft.Json;
using System.Web.Script.Services;
using System.Data;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class validation : System.Web.Services.WebService {
public validation () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string sendRequest(List<string> args, List<string> keys)
{
var arg = args;
var key = keys;
return args[0];
}
}
here is my web config file
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
</configuration>
I have a been working on a contact form I am new to ASP.net, I know an
intermediate amount of C# I am working on a contact form. I want to send
the Values as a json array and parse it with JSON.net, I tried every way I
could think of to get it to work. Without success, I need to know how to
properly send and receive JSON from an ASMX page. Is there an Example file
or maybe a tutorial? Or can some one please tell me what I am doing wrong?
This was the only way I could get it to read the post vars.
But Its just 2 arrays not key value pairs.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-2.0.3.min.js"></script>
</head>
<body>
<form action="#">
<input type="text" id="firstname" name="firstname" value=""/>
<input type="text" id="lastname" name="lastname" value=""/>
</form>
</body>
</html>
<script>
$(document).ready(function () {
var $serialize = $('form').serializeArray();
var stringify = JSON.stringify($serialize);
console.log(stringify);
console.log($serialize);
var keys = ['firstname', 'lastname'];
var list = [$('#firstname').val(), $('#lastname').val()];
var jsonText = JSON.stringify({ args: list, keys: keys });
var a = { anon: { firstname: "Jesse", lastname: "Nieves" } };
var jsonAnon = JSON.stringify(a);
console.log(jsonText);
$.ajax({
url: "validation.asmx/sendAnonymous",
method: "POST",
dataType: "json",
data:jsonAnon,
cache: false,
processData: true,
contentType: "application/json; charset=utf-8"
}).done(function (data) {
console.log(data);
});
});
</script>
Here is my asmx file,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using Newtonsoft.Json;
using System.Web.Script.Services;
using System.Data;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class validation : System.Web.Services.WebService {
public validation () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string sendRequest(List<string> args, List<string> keys)
{
var arg = args;
var key = keys;
return args[0];
}
}
here is my web config file
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5"/>
<httpRuntime targetFramework="4.5"/>
<webServices>
<protocols>
<add name="HttpGet"/>
<add name="HttpPost"/>
</protocols>
</webServices>
</system.web>
</configuration>
Subscribe to:
Comments (Atom)