Problem in the Installation
I am a one of the new User to Ubuntu and downloaded the Ubuntu 12.04 ,I
installed to My Laptop 7 or 8 times but I could not see anything in the
screen which means screen is coming black color ,and i asked from my
friend they said that problem is in the Drivers of the Laptop,My Laptop
Requirements as Follows Hp Pavilion g series , Ram-2Gb, VGA-Radeon tm HD
6470 Please friend give the best answers ,i am waiting for your answers
pleaseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
Monday, 30 September 2013
Distinction between linear and nonlinear model stats.stackexchange.com
Distinction between linear and nonlinear model – stats.stackexchange.com
I have read some explanations about the properties of linear vs nonlinear
models, but still I am sometimes not sure if a model on hand is a linear
or a nonlinear one. For example, is the following ...
I have read some explanations about the properties of linear vs nonlinear
models, but still I am sometimes not sure if a model on hand is a linear
or a nonlinear one. For example, is the following ...
can I base my asp membership provider 'applications' by a guid
can I base my asp membership provider 'applications' by a guid
I created an asp portal for my customers. They all access the same website
and pass in a tokenid, which is a guid. This guid tells me what company
they belong to and what they have access to.
I have the membership provider set up to not allow duplicate email
addresses and everyone under the same application. So, with this in mind,
I figured I could do the following to allow them to register with more
than one company with the same email account.
Create an membership provider application for each tokens (for each company).
Write a script that finds all of the accounts that are based on this guid
and place them under appropriate application
Will this work? Will it allow my customers to create a login for each
token/company using the same email address?
Thanks for the help!
I created an asp portal for my customers. They all access the same website
and pass in a tokenid, which is a guid. This guid tells me what company
they belong to and what they have access to.
I have the membership provider set up to not allow duplicate email
addresses and everyone under the same application. So, with this in mind,
I figured I could do the following to allow them to register with more
than one company with the same email account.
Create an membership provider application for each tokens (for each company).
Write a script that finds all of the accounts that are based on this guid
and place them under appropriate application
Will this work? Will it allow my customers to create a login for each
token/company using the same email address?
Thanks for the help!
Calling a webservice via application
Calling a webservice via application
I have a question for you. I hope you will answer it.
Criteria:
I have a third party webservice..
IS it good to call that webservice by creating my own service and then
implement in application
or
Directly implement that third party webservice in my application.
I googled a lot and couldn't identify the pros and cons.Hope you will help
me.
I have a question for you. I hope you will answer it.
Criteria:
I have a third party webservice..
IS it good to call that webservice by creating my own service and then
implement in application
or
Directly implement that third party webservice in my application.
I googled a lot and couldn't identify the pros and cons.Hope you will help
me.
Sunday, 29 September 2013
subclass's sharedClient Method
subclass's sharedClient Method
In the superClass,i defined a method called "sharedClient"
+ (id)sharedClient
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc]init];
});
return instance;
}
at this method i want to dispatch the object once .then i defined two
subclasses of the superClassBclass A,and class B.
i hope that after i've called the method sharedClient of A, there's a
sharedClient of A, and I"ve called the sharedClient of B, there's an
object of B.but it seems that if A and B called the method both, there
always be one object of the previously called classB
In the superClass,i defined a method called "sharedClient"
+ (id)sharedClient
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[self alloc]init];
});
return instance;
}
at this method i want to dispatch the object once .then i defined two
subclasses of the superClassBclass A,and class B.
i hope that after i've called the method sharedClient of A, there's a
sharedClient of A, and I"ve called the sharedClient of B, there's an
object of B.but it seems that if A and B called the method both, there
always be one object of the previously called classB
How should I display download links to only certain users in ActiveAdmin rails?
How should I display download links to only certain users in ActiveAdmin
rails?
I want to hide download links according to user role of logged in user in
Active Admin
rails?
I want to hide download links according to user role of logged in user in
Active Admin
Division of two binary numbers
Division of two binary numbers
So here I am facing a problem.I have only 25 instructions in my
instruction set.(no multiply,divide,subtract, increment instruction). now,
I am trying to preform a binary division.My problem is, how can I know if
the divisor is smaller then the dividend in order to subtract them both
(in 2's compliment form)?
INSTRUCTION SET:
So here I am facing a problem.I have only 25 instructions in my
instruction set.(no multiply,divide,subtract, increment instruction). now,
I am trying to preform a binary division.My problem is, how can I know if
the divisor is smaller then the dividend in order to subtract them both
(in 2's compliment form)?
INSTRUCTION SET:
C++ code compiles without include
C++ code compiles without include
Why I don't need to include cstdlib and how do I disable this? I'm using
Code::Blocks with GCC compiler on Windows 7.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
cout << "Hello" << endl;
system("pause");
return 0;
}
Why I don't need to include cstdlib and how do I disable this? I'm using
Code::Blocks with GCC compiler on Windows 7.
#include <iostream>
using std::cout;
using std::endl;
int main()
{
cout << "Hello" << endl;
system("pause");
return 0;
}
Saturday, 28 September 2013
Bootstrap datepicker not working after build in Durandal 2.0
Bootstrap datepicker not working after build in Durandal 2.0
After building main-built.js with 'weyland build' my durandal application
fails with 'object doesn't support property or method 'datepicker''. If I
run the app with <script src="lib/require/require.js"
data-main="app/main"> everything is just fine, but if I run from
main-built.js the application stops working after navigating to a page
with bootstrap datepicker.
Can someone help me on this one?
After building main-built.js with 'weyland build' my durandal application
fails with 'object doesn't support property or method 'datepicker''. If I
run the app with <script src="lib/require/require.js"
data-main="app/main"> everything is just fine, but if I run from
main-built.js the application stops working after navigating to a page
with bootstrap datepicker.
Can someone help me on this one?
Scrolling down on a Mobile Phone
Scrolling down on a Mobile Phone
http://54.200.76.33:8080/
I've got this working on desktop browsers.If you scroll down, you'll see a
search bar shows up at the bottom of the screen and becomes fixed to the
bottom.
If you look at this on a mobile phone, when you scroll down, the bar
doesn't immediately stick to the bottom. It'll wait until the user stops
scrolling, and then it becomes fixed to the bottom.
Is there any way to fix this? Thanks.
http://54.200.76.33:8080/
I've got this working on desktop browsers.If you scroll down, you'll see a
search bar shows up at the bottom of the screen and becomes fixed to the
bottom.
If you look at this on a mobile phone, when you scroll down, the bar
doesn't immediately stick to the bottom. It'll wait until the user stops
scrolling, and then it becomes fixed to the bottom.
Is there any way to fix this? Thanks.
filepath comparsion through if condition
filepath comparsion through if condition
I am getting the two different path that are basically file path ,
injected through xml by spring ioc..
private String FilePath1; //it consists path c:\abc folder
private String FilePath2; //it consists of c:\abc\def
now I need to check that if they two are equal then they should go inside
the condition otherwise not
please advise how to achieve this..
what I have tried is ..
if (FilePath1 =! FilePath2)
{
filemove(mcrpFilePath, zipfileName); //i want if two file paths are not
wqula then it // should go inside
filemove
}
I am getting the two different path that are basically file path ,
injected through xml by spring ioc..
private String FilePath1; //it consists path c:\abc folder
private String FilePath2; //it consists of c:\abc\def
now I need to check that if they two are equal then they should go inside
the condition otherwise not
please advise how to achieve this..
what I have tried is ..
if (FilePath1 =! FilePath2)
{
filemove(mcrpFilePath, zipfileName); //i want if two file paths are not
wqula then it // should go inside
filemove
}
Check if listbox contains textbox
Check if listbox contains textbox
I know I could use .FindString for this but for some reason it is not
working.
Basically,if listbox items contains just a PART of textbox text,it does
action.
Here's the example of not-working code :
Dim x As Integer = -1
x = ListBox1.FindString(TextBox1.Text)
If x > -1 Then
'dont add
ListBox2.Items.Add("String found at " & x.ToString)
Else
End If
I know I could use .FindString for this but for some reason it is not
working.
Basically,if listbox items contains just a PART of textbox text,it does
action.
Here's the example of not-working code :
Dim x As Integer = -1
x = ListBox1.FindString(TextBox1.Text)
If x > -1 Then
'dont add
ListBox2.Items.Add("String found at " & x.ToString)
Else
End If
Friday, 27 September 2013
merge lines of a txt file using shell script
merge lines of a txt file using shell script
I invoke a program from shell script and it creates an output file with
this format:
aaaaa\
bbbbb\
ccccc\
I would like to change this to:
aaaaabbbbbccccc
In VI editor I can just do ggVGJ and then replace all \ with "". But I
want to get this done via a script.
I invoke a program from shell script and it creates an output file with
this format:
aaaaa\
bbbbb\
ccccc\
I would like to change this to:
aaaaabbbbbccccc
In VI editor I can just do ggVGJ and then replace all \ with "". But I
want to get this done via a script.
Getting DNS address of IPV4 address using PHP
Getting DNS address of IPV4 address using PHP
I want to access the DNS address of of a IPV4 address. I have set the
manual address in connection settings. I want to get the set DNS address
using PHP.
I want to access the DNS address of of a IPV4 address. I have set the
manual address in connection settings. I want to get the set DNS address
using PHP.
Call an event inside a function c#
Call an event inside a function c#
How do i call an event inside a function? Because i am having an error
Object reference not set to instance of an object and the error pointed at
: _e.RowIndex
And i was wondering how do i call an event inside a function. Now what i
could is call an event from new EventHandler(....) , but now i want call a
event inside a function and it is gave me the error Object reference not
set to instance of an object
Here is the code:
private void UpdateQuantityDataGridView(object sender, EventArgs e)
{
DataGridViewCellEventArgs _e = null;
cmdSelect.Parameters.Add( "ProductCode" ,
System.Data.OleDb.OleDbType.VarChar ) ;
cmdSelect.Parameters[ "ProductCode" ].Value = dataGridView1[ "Product
Code" , _e.RowIndex].Value;
}
Is the code above was correct way to do that?
How do i call an event inside a function? Because i am having an error
Object reference not set to instance of an object and the error pointed at
: _e.RowIndex
And i was wondering how do i call an event inside a function. Now what i
could is call an event from new EventHandler(....) , but now i want call a
event inside a function and it is gave me the error Object reference not
set to instance of an object
Here is the code:
private void UpdateQuantityDataGridView(object sender, EventArgs e)
{
DataGridViewCellEventArgs _e = null;
cmdSelect.Parameters.Add( "ProductCode" ,
System.Data.OleDb.OleDbType.VarChar ) ;
cmdSelect.Parameters[ "ProductCode" ].Value = dataGridView1[ "Product
Code" , _e.RowIndex].Value;
}
Is the code above was correct way to do that?
How to make test with UIInterfaceOrientation enum values
How to make test with UIInterfaceOrientation enum values
I'm a little bit lost in the bitwise ;)
My goal is to retrieve the whole set of orientations supported by an
application and to test each result value to update a custom variable. My
problem is that I don't know how to make the comparison (I got a
conversion/test problem...)
First I read this article : Testing for bitwise Enum values But it doesn't
bring me the light...
Let say I have the following orientation declare for my application
(following is the log output for my variable supportedOrientations) :
supported orientations = ( UIInterfaceOrientationPortrait )
So my first attempt was to try some test on integer values but it does not
work (even if the application is declared to be in portrait mode the test
return 'false') :
NSArray *supportedOrientations = [[NSBundle mainBundle]
objectForInfoDictionaryKey:@"UISupportedInterfaceOrientations"];
NSLog(@"[supported orientations = %@", supportedOrientations);
// for clarity just make a test on the first orientation we found
if ((NSInteger)supportedOrientations[0] == UIInterfaceOrientationPortrait) {
NSLog(@"We detect Portrait mode!");
}
My second attempt was to try the bitwise thing but this time it always
return 'true' (even if the supported orientation is not
UIInterfaceOrientationPortrait). :
NSArray *supportedOrientations = [[NSBundle mainBundle]
objectForInfoDictionaryKey:@"UISupportedInterfaceOrientations"];
NSLog(@"[supported orientations = %@", supportedOrientations);
// for clarity just make a test on the first orientation we found
if ((NSInteger)supportedOrientations[0] | UIInterfaceOrientationPortrait)
{ // <-- I also test with UIInterfaceOrientationMaskPortrait but no more
success
NSLog(@"We detect Portrait mode!");
}
So my question is :
How to test the orientation in my case?
Is it a way to use a test by using a bitwise thing (using | operand)?
I'm a little bit lost in the bitwise ;)
My goal is to retrieve the whole set of orientations supported by an
application and to test each result value to update a custom variable. My
problem is that I don't know how to make the comparison (I got a
conversion/test problem...)
First I read this article : Testing for bitwise Enum values But it doesn't
bring me the light...
Let say I have the following orientation declare for my application
(following is the log output for my variable supportedOrientations) :
supported orientations = ( UIInterfaceOrientationPortrait )
So my first attempt was to try some test on integer values but it does not
work (even if the application is declared to be in portrait mode the test
return 'false') :
NSArray *supportedOrientations = [[NSBundle mainBundle]
objectForInfoDictionaryKey:@"UISupportedInterfaceOrientations"];
NSLog(@"[supported orientations = %@", supportedOrientations);
// for clarity just make a test on the first orientation we found
if ((NSInteger)supportedOrientations[0] == UIInterfaceOrientationPortrait) {
NSLog(@"We detect Portrait mode!");
}
My second attempt was to try the bitwise thing but this time it always
return 'true' (even if the supported orientation is not
UIInterfaceOrientationPortrait). :
NSArray *supportedOrientations = [[NSBundle mainBundle]
objectForInfoDictionaryKey:@"UISupportedInterfaceOrientations"];
NSLog(@"[supported orientations = %@", supportedOrientations);
// for clarity just make a test on the first orientation we found
if ((NSInteger)supportedOrientations[0] | UIInterfaceOrientationPortrait)
{ // <-- I also test with UIInterfaceOrientationMaskPortrait but no more
success
NSLog(@"We detect Portrait mode!");
}
So my question is :
How to test the orientation in my case?
Is it a way to use a test by using a bitwise thing (using | operand)?
How to include a dynamic variable in javascript element's "src" attribute in asp.net?
How to include a dynamic variable in javascript element's "src" attribute
in asp.net?
i want to add a javascript file in aspx page <head> section, but this
javascript file name changes dynamically. Can i use a variable for src
attribute in script element as shown in below example
e.g., var jsFileName = "JScript1"
<script type="text/javascript" src="jsFolder/' + jsFileName + '.js"></script>
this is not working for me. Any help is appreciated.
in asp.net?
i want to add a javascript file in aspx page <head> section, but this
javascript file name changes dynamically. Can i use a variable for src
attribute in script element as shown in below example
e.g., var jsFileName = "JScript1"
<script type="text/javascript" src="jsFolder/' + jsFileName + '.js"></script>
this is not working for me. Any help is appreciated.
Thursday, 26 September 2013
Searching NodeList by an Array
Searching NodeList by an Array
I have a document that I'm searching through for specific instances,
however those instances are specified by the user and there are more than
one. Other than a for loop inside a for loop searching a Nodelist against
an array, is there a way I'm missing that wouldn't bog down the system? Or
an easier way?
So far, my code looks like this in abstract:
public void sortDoc(Document doc){
NodeList list = doc.getFirstChild().getChildNodes();
ArrayList<String> typeList = otherSorter.getTypes();
for(int i=0; i<list.getLength(); i++){
for(int j=0; j<typeList.size(); j++){
if(list.item(i).getNodeName()==typeList.get(j)){
doTheThing();
}
}
}
}
Thanks for any help you can give.
I have a document that I'm searching through for specific instances,
however those instances are specified by the user and there are more than
one. Other than a for loop inside a for loop searching a Nodelist against
an array, is there a way I'm missing that wouldn't bog down the system? Or
an easier way?
So far, my code looks like this in abstract:
public void sortDoc(Document doc){
NodeList list = doc.getFirstChild().getChildNodes();
ArrayList<String> typeList = otherSorter.getTypes();
for(int i=0; i<list.getLength(); i++){
for(int j=0; j<typeList.size(); j++){
if(list.item(i).getNodeName()==typeList.get(j)){
doTheThing();
}
}
}
}
Thanks for any help you can give.
Wednesday, 25 September 2013
Find the number data in table in yii
Find the number data in table in yii
I want to get the number of data present in the table but not to fetch
them. In yii how to count the number of data present in table.
I want to get the number of data present in the table but not to fetch
them. In yii how to count the number of data present in table.
Thursday, 19 September 2013
What does the following code do in php?
What does the following code do in php?
Please explain the following code. I can't understand what is happening.
return !$test
Please explain the following code. I can't understand what is happening.
return !$test
How can I make my UINavigationBar totally transparent on iOS7?
How can I make my UINavigationBar totally transparent on iOS7?
I'm working on making an application iOS7-compatible, and I'm encountering
a problem with UINavigationBar that's driving me crazy :
I want to make my navigationBar totally transparent, without any blur or
backgroundPicture, but containing and displaying navigationItem buttons.
In iOS6, I used to make that this way :
UIImage *maskedImage = [UIImage imageNamed:@"transparent_image.png"]
[navigationBar setBackgroundImage:maskedImage
forBarMetrics:UIBarMetricsDefault];
But it doesn't work anymore on iOS7...
Any suggestions ?
I'm working on making an application iOS7-compatible, and I'm encountering
a problem with UINavigationBar that's driving me crazy :
I want to make my navigationBar totally transparent, without any blur or
backgroundPicture, but containing and displaying navigationItem buttons.
In iOS6, I used to make that this way :
UIImage *maskedImage = [UIImage imageNamed:@"transparent_image.png"]
[navigationBar setBackgroundImage:maskedImage
forBarMetrics:UIBarMetricsDefault];
But it doesn't work anymore on iOS7...
Any suggestions ?
Why is my dynamic mock not working
Why is my dynamic mock not working
I am trying to test a C# method that uses a dynamic property from a C++
CLR wrapper. The interface I am trying to mock is
property Object^ DynamicValueItem
{
[returnvalue: System::Runtime::CompilerServices::DynamicAttribute]
Object^ get () ;
}
The method I am trying to test is
public void GetBillInfo (IConfigurationItem item)
{
dynamic ValueItem = item.DynamicValueItem;
string Curr = ValueItem.Currency;
string Ser = ValueItem.BillSeries;
}
My test method is
[TestMethod()]
public void GetBillInfoTest()
{
BnrHelperMethods target = new BnrHelperMethods();
var ValueItem = new
{
Currency = "USD",
BillValue = 100,
};
var mockItem = new Mock<IConfigurationItem>();
mockItem.Setup(i => i.DynamicValueItem).Returns(ValueItem);
target.GetBillInfo(mockItem.Object);
}
I got the method for mocking the dynamic property from
http://blogs.clariusconsulting.net/kzu/how-to-mock-a-dynamic-object/
The example was for a standard C# dynamic property so I have had to adapt
my C++ CLR property to try and get the same effect. My problem is that
when I perform the test I get a RuntimeBinderException stating that the
object does not contain the definition of for Currency. If I look at the
Locals window it shows both Currency and BillValue
-ValueItem { Currency = USD, BillValue = 100 } dynamic{<>f__AnonymousType1}
-BillValue 0x00000064 int
-Currency "USD" string
When using the method normally it works. The only difference I see is that
Currency and BillValue are under a Dynamic View item in the Local window
-ValueItem {} dynamic {MEIConfiguration.ConfigurationValueItem}
-Dynamic View Expanding the Dynamic View will get the dynamic members for
the object
-BillValue 0x000003e8 System.Int32
-Currency "GBP" System.String
Have I defined the C++ property correctly? Am I creating the mock
correctly? Can anyone tell me what I am doing wrong?
Thanks Trevor
I am trying to test a C# method that uses a dynamic property from a C++
CLR wrapper. The interface I am trying to mock is
property Object^ DynamicValueItem
{
[returnvalue: System::Runtime::CompilerServices::DynamicAttribute]
Object^ get () ;
}
The method I am trying to test is
public void GetBillInfo (IConfigurationItem item)
{
dynamic ValueItem = item.DynamicValueItem;
string Curr = ValueItem.Currency;
string Ser = ValueItem.BillSeries;
}
My test method is
[TestMethod()]
public void GetBillInfoTest()
{
BnrHelperMethods target = new BnrHelperMethods();
var ValueItem = new
{
Currency = "USD",
BillValue = 100,
};
var mockItem = new Mock<IConfigurationItem>();
mockItem.Setup(i => i.DynamicValueItem).Returns(ValueItem);
target.GetBillInfo(mockItem.Object);
}
I got the method for mocking the dynamic property from
http://blogs.clariusconsulting.net/kzu/how-to-mock-a-dynamic-object/
The example was for a standard C# dynamic property so I have had to adapt
my C++ CLR property to try and get the same effect. My problem is that
when I perform the test I get a RuntimeBinderException stating that the
object does not contain the definition of for Currency. If I look at the
Locals window it shows both Currency and BillValue
-ValueItem { Currency = USD, BillValue = 100 } dynamic{<>f__AnonymousType1}
-BillValue 0x00000064 int
-Currency "USD" string
When using the method normally it works. The only difference I see is that
Currency and BillValue are under a Dynamic View item in the Local window
-ValueItem {} dynamic {MEIConfiguration.ConfigurationValueItem}
-Dynamic View Expanding the Dynamic View will get the dynamic members for
the object
-BillValue 0x000003e8 System.Int32
-Currency "GBP" System.String
Have I defined the C++ property correctly? Am I creating the mock
correctly? Can anyone tell me what I am doing wrong?
Thanks Trevor
Code runs slowly parsing large xml files w/ python
Code runs slowly parsing large xml files w/ python
I've got 2 very large xml files that hold different data for the same
place/building/room combinations. I am currently using python etree parse
on the first large file then looping through it to extract the
place/building/room ids (along with other information) to then use those
ids to loop through the second large xml file (same structure as the
first) which I'm currenlty using lxml iterparse to find and extract the
Place element in the second file pertainent to the specific place from the
first file. Then it loops through that place element to find the pertinent
data It works, but it continues to get slower and slower as I loop through
further and further into the first file.
I've done everything I can to clear() elements not pertainent in the
iterparse of the second large file which helped, but I've got 5000 places
to loop through and the first 100 are processed very quickly (less than a
minute) then the next 400 take 30 minutes, and so on. After 15 hours I was
at about 4000 facilities and moving very slowly. I suspect the parsing of
one of the files is holding too much data.
Here's the simplified code (sorry I couldn't simplify it further) with
genericified xml.
# get_place_elem function
def get_place_elem(pplaceid,largefile2):
Placenode = ET.iterparse(Largefile2, events=("end",), tag='Place')
for event, Place in Placenode:
for PlaceId in Place.findall('PlaceIdentification'):
placeid = PlaceId.find('PlaceIdentifier').text
if placeid == pplaceid:
del Placenode
return Place
Place.clear()
while Place.getprevious() is not None:
del Place.getparent()[0]
del Placenode
# getfacdata function
def getfacdata(pplaceid,pbuildid,proomid,Place):
for Build in Place.findall('Building'):
euid = ' '
for BuildId in Build.findall('BuildingIdentification'):
bid = BuildId.find('Identifier').text
if bid ==pbid:
for Room in Build.findall('Room'):
roomid = ' '
for RoomId in Room.findall('RoomIdentification'):
roomid = RoomId.find('Identifier').text
if roomid == proomid:
...Collect data from Room element...
... do some simple math with if statements
return data; # list of 15 data values
main code
largefile1 = "largefile1.xml"
largefile2 = "largeFile2.xml"
ptree = ET.parse (largefile1)
proot = ptree.getroot()
o = open('output.txt', 'w')
for pPlace in proot.findall('.//Place'):
for pPlaceId in pPlace.findall
('cer:FacilityIdentification',namespaces=namespaces):
pplaceid = pPlaceId.find('PlaceIdentifier').text
if placeid == pplaceid:
placecnt += 1
#... get some data
for pBuild in pPlace.findall('Buidling'):
for pBuildId in pBuild.findall('BuildingIdentification'):
pbid = pBuildId.find('Identifier').text
# cycle through each ProcessIdentification element of the
EmissionUnit element in the point inventory file and assign the
SCC code
for pRoom in pBuild.findall('Room'):
for pRoomId in pRoom.findall('RoomIdentification'):
proomid = pRoom.find('Identifier').text
if prevpplaceid != pplaceid:
if placecnt != 1:Place.clear()
Place = get_fac_elem(pplaceid,largefile2)
prevpplaceid = pplaceid
data = getfacdata(pplaceid,pbid,proomid,Place)
#...Collect data from Room element...
#... do some simple math with if statements
writer = csv.writer(o)
writer.writerow( ( # data from proom and from 'data' list
from processing largefile2 in csv format##))
break
prevpplaceid = pplaceid
o.close()
genericified xml
<Payload>
<Place>
<PlaceName>Place1</PlaceName>
<PlaceStatusCode>OP</PlaceStatusCode>
<PlaceStatusCodeYear>2011</PlaceStatusCodeYear>
<PlaceComment/>
<PlaceIdentification>
<PlaceIdentifier>id001</PlaceIdentifier>
<StateAndCountyFIPSCode>77702</StateAndCountyFIPSCode>
</PlaceIdentification>
<PlaceAddress>
<LocationAddressText>111 Main</LocationAddressText>
<SupplementalLocationText/>
<LocalityName>City1</LocalityName>
<LocationAddressStateCode>State1</LocationAddressStateCode>
<LocationAddressPostalCode>12345</LocationAddressPostalCode>
<LocationAddressCountryCode>USA</LocationAddressCountryCode>
</PlaceAddress>
<PlaceGeographicCoordinates>
<LatitudeMeasure>88.888</LatitudeMeasure>
<LongitudeMeasure>-99.999</LongitudeMeasure>
</PlaceGeographicCoordinates>
<Building>
<BuildingDescription>Building1</BuildingDescription>
<BuildingTypeCode>999</BuildingTypeCode>
<BuildingIdentification>
<Identifier>Building1</Identifier>
</BuildingIdentification>
<Room>
<RoomIdentification>
<Identifier>Room1</Identifier>
</RoomIdentification>
... More data ...
</Room>
<Room>
<RoomIdentification>
<Identifier>Room2</Identifier>
</RoomIdentification>
... More data ...
</Room>
...
</Building>
<Building>
<BuildingDescription>Building2</BuildingDescription>
<BuildingTypeCode>999</BuildingTypeCode>
<BuildingIdentification>
<Identifier>Building2</Identifier>
</BuildingIdentification>
<Room>
<RoomIdentification>
<Identifier>Room1</Identifier>
</RoomIdentification>
... More data ...
</Room>
<Room>
<RoomIdentification>
<Identifier>Room4</Identifier>
</RoomIdentification>
... More data ...
</Room>
...
</Building>
...
</Place>
<Place>
...
</Place>
I've got 2 very large xml files that hold different data for the same
place/building/room combinations. I am currently using python etree parse
on the first large file then looping through it to extract the
place/building/room ids (along with other information) to then use those
ids to loop through the second large xml file (same structure as the
first) which I'm currenlty using lxml iterparse to find and extract the
Place element in the second file pertainent to the specific place from the
first file. Then it loops through that place element to find the pertinent
data It works, but it continues to get slower and slower as I loop through
further and further into the first file.
I've done everything I can to clear() elements not pertainent in the
iterparse of the second large file which helped, but I've got 5000 places
to loop through and the first 100 are processed very quickly (less than a
minute) then the next 400 take 30 minutes, and so on. After 15 hours I was
at about 4000 facilities and moving very slowly. I suspect the parsing of
one of the files is holding too much data.
Here's the simplified code (sorry I couldn't simplify it further) with
genericified xml.
# get_place_elem function
def get_place_elem(pplaceid,largefile2):
Placenode = ET.iterparse(Largefile2, events=("end",), tag='Place')
for event, Place in Placenode:
for PlaceId in Place.findall('PlaceIdentification'):
placeid = PlaceId.find('PlaceIdentifier').text
if placeid == pplaceid:
del Placenode
return Place
Place.clear()
while Place.getprevious() is not None:
del Place.getparent()[0]
del Placenode
# getfacdata function
def getfacdata(pplaceid,pbuildid,proomid,Place):
for Build in Place.findall('Building'):
euid = ' '
for BuildId in Build.findall('BuildingIdentification'):
bid = BuildId.find('Identifier').text
if bid ==pbid:
for Room in Build.findall('Room'):
roomid = ' '
for RoomId in Room.findall('RoomIdentification'):
roomid = RoomId.find('Identifier').text
if roomid == proomid:
...Collect data from Room element...
... do some simple math with if statements
return data; # list of 15 data values
main code
largefile1 = "largefile1.xml"
largefile2 = "largeFile2.xml"
ptree = ET.parse (largefile1)
proot = ptree.getroot()
o = open('output.txt', 'w')
for pPlace in proot.findall('.//Place'):
for pPlaceId in pPlace.findall
('cer:FacilityIdentification',namespaces=namespaces):
pplaceid = pPlaceId.find('PlaceIdentifier').text
if placeid == pplaceid:
placecnt += 1
#... get some data
for pBuild in pPlace.findall('Buidling'):
for pBuildId in pBuild.findall('BuildingIdentification'):
pbid = pBuildId.find('Identifier').text
# cycle through each ProcessIdentification element of the
EmissionUnit element in the point inventory file and assign the
SCC code
for pRoom in pBuild.findall('Room'):
for pRoomId in pRoom.findall('RoomIdentification'):
proomid = pRoom.find('Identifier').text
if prevpplaceid != pplaceid:
if placecnt != 1:Place.clear()
Place = get_fac_elem(pplaceid,largefile2)
prevpplaceid = pplaceid
data = getfacdata(pplaceid,pbid,proomid,Place)
#...Collect data from Room element...
#... do some simple math with if statements
writer = csv.writer(o)
writer.writerow( ( # data from proom and from 'data' list
from processing largefile2 in csv format##))
break
prevpplaceid = pplaceid
o.close()
genericified xml
<Payload>
<Place>
<PlaceName>Place1</PlaceName>
<PlaceStatusCode>OP</PlaceStatusCode>
<PlaceStatusCodeYear>2011</PlaceStatusCodeYear>
<PlaceComment/>
<PlaceIdentification>
<PlaceIdentifier>id001</PlaceIdentifier>
<StateAndCountyFIPSCode>77702</StateAndCountyFIPSCode>
</PlaceIdentification>
<PlaceAddress>
<LocationAddressText>111 Main</LocationAddressText>
<SupplementalLocationText/>
<LocalityName>City1</LocalityName>
<LocationAddressStateCode>State1</LocationAddressStateCode>
<LocationAddressPostalCode>12345</LocationAddressPostalCode>
<LocationAddressCountryCode>USA</LocationAddressCountryCode>
</PlaceAddress>
<PlaceGeographicCoordinates>
<LatitudeMeasure>88.888</LatitudeMeasure>
<LongitudeMeasure>-99.999</LongitudeMeasure>
</PlaceGeographicCoordinates>
<Building>
<BuildingDescription>Building1</BuildingDescription>
<BuildingTypeCode>999</BuildingTypeCode>
<BuildingIdentification>
<Identifier>Building1</Identifier>
</BuildingIdentification>
<Room>
<RoomIdentification>
<Identifier>Room1</Identifier>
</RoomIdentification>
... More data ...
</Room>
<Room>
<RoomIdentification>
<Identifier>Room2</Identifier>
</RoomIdentification>
... More data ...
</Room>
...
</Building>
<Building>
<BuildingDescription>Building2</BuildingDescription>
<BuildingTypeCode>999</BuildingTypeCode>
<BuildingIdentification>
<Identifier>Building2</Identifier>
</BuildingIdentification>
<Room>
<RoomIdentification>
<Identifier>Room1</Identifier>
</RoomIdentification>
... More data ...
</Room>
<Room>
<RoomIdentification>
<Identifier>Room4</Identifier>
</RoomIdentification>
... More data ...
</Room>
...
</Building>
...
</Place>
<Place>
...
</Place>
FTGL: Characters do not show up on rendering
FTGL: Characters do not show up on rendering
My application does some text output with OpenGL and FTGL. I set up a font
like this:
Impl::font = new
FTTextureFont("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf");
if (Impl::font->Error() != 0) {
delete Impl::font;
throw std::runtime_error("Could not load font DejaVuSans.ttf!");
}
if (!Impl::font->FaceSize(72)) {
delete Impl::font;
throw std::runtime_error("Could not use DejaVuSans with size 72!");
}
I render like this:
glColor3f(1.0, 1.0, 1.0);
Impl::font->Render(my_string.c_str());
Now I have a major problem: There is one string which I create pretty
early in the program, which renders correctly. Then there's another string
which gets created later, and it renders only those letters which are also
contained in the first string. I can only assume that the texture font
does only create textures for the letters of the first string, but not for
those of the second string.
What could be the cause for this? Do I need to make it load all characters
I will use early? Is there something I'm missing?
(It would be quite some effort to boil my code down to a minimal example
that reproduces the error, so I ask first for something obvious I'm doing
wrong.)
My application does some text output with OpenGL and FTGL. I set up a font
like this:
Impl::font = new
FTTextureFont("/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf");
if (Impl::font->Error() != 0) {
delete Impl::font;
throw std::runtime_error("Could not load font DejaVuSans.ttf!");
}
if (!Impl::font->FaceSize(72)) {
delete Impl::font;
throw std::runtime_error("Could not use DejaVuSans with size 72!");
}
I render like this:
glColor3f(1.0, 1.0, 1.0);
Impl::font->Render(my_string.c_str());
Now I have a major problem: There is one string which I create pretty
early in the program, which renders correctly. Then there's another string
which gets created later, and it renders only those letters which are also
contained in the first string. I can only assume that the texture font
does only create textures for the letters of the first string, but not for
those of the second string.
What could be the cause for this? Do I need to make it load all characters
I will use early? Is there something I'm missing?
(It would be quite some effort to boil my code down to a minimal example
that reproduces the error, so I ask first for something obvious I'm doing
wrong.)
Javascript Detect Click event outside of div
Javascript Detect Click event outside of div
I have a div with id content-area, when some one click outside of that
div, i would like to alert user that you clicked outside of content area.
I don't know how can i do it in JavaScript. Please help me to solve this
issue. You help is much appreciated. Thanks in advance.
<div id = "outer-container">
<div id = "content-area">
Display Conents
</div>
</div>
I have a div with id content-area, when some one click outside of that
div, i would like to alert user that you clicked outside of content area.
I don't know how can i do it in JavaScript. Please help me to solve this
issue. You help is much appreciated. Thanks in advance.
<div id = "outer-container">
<div id = "content-area">
Display Conents
</div>
</div>
Android lock orientation to starting orientation
Android lock orientation to starting orientation
I've searched for a long time but nothing works.I have an activity and I
want its orientation locked while activity's whole lifecycle.This
orientation may be portrait or landscape it doesnt matter.I mean, when
activity starts on any orientation , it must ignore orientation
changes.How Can I do this ? Thanks for replies..
I've searched for a long time but nothing works.I have an activity and I
want its orientation locked while activity's whole lifecycle.This
orientation may be portrait or landscape it doesnt matter.I mean, when
activity starts on any orientation , it must ignore orientation
changes.How Can I do this ? Thanks for replies..
Wednesday, 18 September 2013
REDDIT api - Couldnt able to submit a link to reddit using http://www.reddit.com/api/submit?
REDDIT api - Couldnt able to submit a link to reddit using
http://www.reddit.com/api/submit?
I am trying to post a link to reddit using api in android but its
returning a json response like below
{"json": {"errors": [["USER_REQUIRED", "please login to do that", null]]}}
Here is my peice of code
response2=UrltoValue.getValuefromUrl("http://www.reddit.com/api/login"+"?api_type="+"json"+"&passwd="+"********"+"&user="+"sudheer21");
try {
jo1=new JSONObject(response2);
jo2=jo1.getJSONObject("json");
for(int i=0;i<jo2.length();i++)
{
if(i==1)
{
jo3=jo2.getJSONObject("data");
modhash=jo3.getString("modhash");
}
}
response=UrltoValue.getValuefromUrl("http://www.reddit.com/api/submit"+"?api_type="+"json"+
"&captcha="+""+"&extension="+""+"&iden="+""+"&kind="+"link"+"&resubmit="+"false"+"&save="+"false"+"&sendreplies="+"true"
+"&sr="+"science"+"&text="+"Havetodo"+"&then="+"excellentpost"+"&title="+"&uh/X-Modhashheader="+modhash+
"&url="+"http://www.heraldsun.com.au/technology/sci-tech/geniuses-predict-how-the-world-will-end-and-how-to-avoid-it/story-fni0c0qs-1226718860033");
please find me a solution
http://www.reddit.com/api/submit?
I am trying to post a link to reddit using api in android but its
returning a json response like below
{"json": {"errors": [["USER_REQUIRED", "please login to do that", null]]}}
Here is my peice of code
response2=UrltoValue.getValuefromUrl("http://www.reddit.com/api/login"+"?api_type="+"json"+"&passwd="+"********"+"&user="+"sudheer21");
try {
jo1=new JSONObject(response2);
jo2=jo1.getJSONObject("json");
for(int i=0;i<jo2.length();i++)
{
if(i==1)
{
jo3=jo2.getJSONObject("data");
modhash=jo3.getString("modhash");
}
}
response=UrltoValue.getValuefromUrl("http://www.reddit.com/api/submit"+"?api_type="+"json"+
"&captcha="+""+"&extension="+""+"&iden="+""+"&kind="+"link"+"&resubmit="+"false"+"&save="+"false"+"&sendreplies="+"true"
+"&sr="+"science"+"&text="+"Havetodo"+"&then="+"excellentpost"+"&title="+"&uh/X-Modhashheader="+modhash+
"&url="+"http://www.heraldsun.com.au/technology/sci-tech/geniuses-predict-how-the-world-will-end-and-how-to-avoid-it/story-fni0c0qs-1226718860033");
please find me a solution
Calling non-Action methods from view-MVC .NET
Calling non-Action methods from view-MVC .NET
I want to call a non-action method in a view. Can I do that? In other
words, there is a method in my controller which returns a string. I want
to call that method in my view (.cshtml) and show it in the view. All I
could see was, the methods should return an ActionResult. But in my case I
do not need a view returned just a string.
I want to call a non-action method in a view. Can I do that? In other
words, there is a method in my controller which returns a string. I want
to call that method in my view (.cshtml) and show it in the view. All I
could see was, the methods should return an ActionResult. But in my case I
do not need a view returned just a string.
NSSplitView sync with other interface elements
NSSplitView sync with other interface elements
In my Mac OS X application, I want to have a window with a content border
at the bottom (a sort of a status bar) and a split view, and I want to
synchronise the position of some elements on the status bar with the
position of the divider in the split view. Say, I want to have a vertical
separator in the status bar exactly under the splitter in the split view.
I tried observing the coordinates and the frames of the subviews of the
split view, and setting the frame of the elements in the status bar
accordingly, but that is quite glitchy, even though the arithmetics is
correct (sometimes the separator jumps a few pixels off the spot,
sometimes it doesn't get drawn, and when i move the split view divider
about, it flickers). I don't like that.
Is there a better way of doing what i want?
For example, i noticed that i can place my split view over the content
bar, and all the elements i put over the content bar behave correctly.
However, is this the right way of doing it?
In my Mac OS X application, I want to have a window with a content border
at the bottom (a sort of a status bar) and a split view, and I want to
synchronise the position of some elements on the status bar with the
position of the divider in the split view. Say, I want to have a vertical
separator in the status bar exactly under the splitter in the split view.
I tried observing the coordinates and the frames of the subviews of the
split view, and setting the frame of the elements in the status bar
accordingly, but that is quite glitchy, even though the arithmetics is
correct (sometimes the separator jumps a few pixels off the spot,
sometimes it doesn't get drawn, and when i move the split view divider
about, it flickers). I don't like that.
Is there a better way of doing what i want?
For example, i noticed that i can place my split view over the content
bar, and all the elements i put over the content bar behave correctly.
However, is this the right way of doing it?
Waiting for request to be processed
Waiting for request to be processed
I was wondering if I could wait for request to be processed with
afnetworking.
Lets say I got this method
- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser
photoAtIndex:(NSUInteger)index {
//Request goes here, so the method doesn't return anything before it's
processed
}
Is that doable?
I was wondering if I could wait for request to be processed with
afnetworking.
Lets say I got this method
- (MWPhoto *)photoBrowser:(MWPhotoBrowser *)photoBrowser
photoAtIndex:(NSUInteger)index {
//Request goes here, so the method doesn't return anything before it's
processed
}
Is that doable?
Duplicate variables (null copy) in loop?
Duplicate variables (null copy) in loop?
I've never seen this before.. I have the following code, a simple nested
loop assigning an object from one ArrayList to an object of another.
But, inside the inner loop, the object has some (not all) duplicate
variables with null values?!? What am I doing wrong?!?
The first image shows the local variable "member", a reference to an
object inside the ArrayList "members". This is the object with duplicate
variables with null values.
The second image show the other object "offer", looking like one would
expect.
Code below. Help?
public static void setMembersForOffers(ArrayList<WPMemberPost> members,
ArrayList<WPOfferPost> offers)
{
int memberCount = members.size();
int offerCount = offers.size();
for (int i=0; i<offerCount; i++)
{
WPOfferPost offer = offers.get(i);
if (offer.memberIdentifier != null)
{
for (int j=0; j<memberCount; j++)
{
WPMemberPost member = members.get(j);
String id = member.identifier; // NULL?!? (Expected "436")
if (offer.memberIdentifier.equalsIgnoreCase(id))
{
offer.member = member;
break;
}
}
}
}
}
I've never seen this before.. I have the following code, a simple nested
loop assigning an object from one ArrayList to an object of another.
But, inside the inner loop, the object has some (not all) duplicate
variables with null values?!? What am I doing wrong?!?
The first image shows the local variable "member", a reference to an
object inside the ArrayList "members". This is the object with duplicate
variables with null values.
The second image show the other object "offer", looking like one would
expect.
Code below. Help?
public static void setMembersForOffers(ArrayList<WPMemberPost> members,
ArrayList<WPOfferPost> offers)
{
int memberCount = members.size();
int offerCount = offers.size();
for (int i=0; i<offerCount; i++)
{
WPOfferPost offer = offers.get(i);
if (offer.memberIdentifier != null)
{
for (int j=0; j<memberCount; j++)
{
WPMemberPost member = members.get(j);
String id = member.identifier; // NULL?!? (Expected "436")
if (offer.memberIdentifier.equalsIgnoreCase(id))
{
offer.member = member;
break;
}
}
}
}
}
How to to paint option inside select tag?
How to to paint option inside select tag?
I have so option code:
<option value="2" selected class="ololool">write contract</option>
class:
<style type="text/css">
.ololool {color:green}
</style>
but I see this variant:
but if I click:
I want to see green color on two views. How can I make so?
I have so option code:
<option value="2" selected class="ololool">write contract</option>
class:
<style type="text/css">
.ololool {color:green}
</style>
but I see this variant:
but if I click:
I want to see green color on two views. How can I make so?
When saving a model, data in $.ajaxSetup is not merged
When saving a model, data in $.ajaxSetup is not merged
I have an Ember.js app backed by a RESTful API. Session control is done
through an authentication token: once a user logs in, he appends his
authentication token to each request he makes to the server. I do this by
adding the authentication to the data in $.ajaxSetup.
$.ajaxSetup({
data: { auth_token: this.get('authToken') }
});
Now, this works fine for GET requests. However, when saving models to the
server through a POST or PUT request, the Ember Data RESTAdapter
stringifies the data object. In DS.RESTAdapter.ajax it does
....
if (hash.data && type !== 'GET') {
hash.contentType = 'application/json; charset=utf-8';
hash.data = JSON.stringify(hash.data);
}
...
Because of this, the authentication token is not merged into the data. In
this jQuery ticket they say that it's something they are never going to
support.
What's the most elegant way of solving this? I'd rather not override the
Ember's RESTAdapter.ajax function because the code is changing so quickly
so my overridden function might not be compatible with the rest of the
codebase at the next release.
I have an Ember.js app backed by a RESTful API. Session control is done
through an authentication token: once a user logs in, he appends his
authentication token to each request he makes to the server. I do this by
adding the authentication to the data in $.ajaxSetup.
$.ajaxSetup({
data: { auth_token: this.get('authToken') }
});
Now, this works fine for GET requests. However, when saving models to the
server through a POST or PUT request, the Ember Data RESTAdapter
stringifies the data object. In DS.RESTAdapter.ajax it does
....
if (hash.data && type !== 'GET') {
hash.contentType = 'application/json; charset=utf-8';
hash.data = JSON.stringify(hash.data);
}
...
Because of this, the authentication token is not merged into the data. In
this jQuery ticket they say that it's something they are never going to
support.
What's the most elegant way of solving this? I'd rather not override the
Ember's RESTAdapter.ajax function because the code is changing so quickly
so my overridden function might not be compatible with the rest of the
codebase at the next release.
Tuesday, 17 September 2013
Verify that a new record is inserted to the database successfully
Verify that a new record is inserted to the database successfully
How do i verify that an object A added to the database successfully?
MongoTemplate.save() method doesn't return any value to verify its action
result. I found a way is to initiate value if A.Id before i save A to
database using MongoTemplate.save() method, and the retrieve back the
saved record using that Id value, but that way doesn't satisfy me. How do
i verify that while keep the Id field generated by the database?
How do i verify that an object A added to the database successfully?
MongoTemplate.save() method doesn't return any value to verify its action
result. I found a way is to initiate value if A.Id before i save A to
database using MongoTemplate.save() method, and the retrieve back the
saved record using that Id value, but that way doesn't satisfy me. How do
i verify that while keep the Id field generated by the database?
Delegate Using "this"
Delegate Using "this"
I'd like to create a class that has overrideable methods in the form of
delegates.
I basically would like to create an interface, but not have to create a
new class every time I want to make it slightly different.
Further, I would like to bundle the delegate with a number of other
variables in a struct.
Now here are some more specifics.
class Gun
{
public delegate void ShootDelegate;
public double fireRate; //There are more variables, I'm just using
this one as an example
public Gun(GunStats stats)
{
this.Shoot = stats.Shoot;
this.fireRate = stats.fireRate;
}
public ShootDelegate Shoot;
}
struct GunStats
{
public ShootDelegate Shoot;
public double fireRate;
}
then, what I'd like to be able to do is make a gun like this
GunStats stats;
stats.fireRate = 3;
stats.Shoot = new delegate() { this.fireRate++; /* stupid example */ };
new Gun(stats);
however, when I create the delegate, it obviously can't interact with the
inner class variables.
What's the best way to handle this?
I'd like to create a class that has overrideable methods in the form of
delegates.
I basically would like to create an interface, but not have to create a
new class every time I want to make it slightly different.
Further, I would like to bundle the delegate with a number of other
variables in a struct.
Now here are some more specifics.
class Gun
{
public delegate void ShootDelegate;
public double fireRate; //There are more variables, I'm just using
this one as an example
public Gun(GunStats stats)
{
this.Shoot = stats.Shoot;
this.fireRate = stats.fireRate;
}
public ShootDelegate Shoot;
}
struct GunStats
{
public ShootDelegate Shoot;
public double fireRate;
}
then, what I'd like to be able to do is make a gun like this
GunStats stats;
stats.fireRate = 3;
stats.Shoot = new delegate() { this.fireRate++; /* stupid example */ };
new Gun(stats);
however, when I create the delegate, it obviously can't interact with the
inner class variables.
What's the best way to handle this?
Is it normal to store large pieces of HTML-code in properties file?
Is it normal to store large pieces of HTML-code in properties file?
I need to store a quietly big piece of HTML-code as a static resource. Is
it normal to put it into properties file? Or would it be better if it
stored in separate HTML-file? Storing in properties file seems to be more
convenient since Spring has build-in mechanism to work with it, but I'm
not sure this is a good approach.
Thanks.
I need to store a quietly big piece of HTML-code as a static resource. Is
it normal to put it into properties file? Or would it be better if it
stored in separate HTML-file? Storing in properties file seems to be more
convenient since Spring has build-in mechanism to work with it, but I'm
not sure this is a good approach.
Thanks.
Formatted Printing of Lists in Haskell?
Formatted Printing of Lists in Haskell?
So I have a list of lists that is being returned from one of my
expressions. I'd like to print it out so that every list is being
outputted on one line instead of all on different lines. Is there anyway
to do good formatting in Haskell?
So I have a list of lists that is being returned from one of my
expressions. I'd like to print it out so that every list is being
outputted on one line instead of all on different lines. Is there anyway
to do good formatting in Haskell?
How to run iOS Core Location in background forever
How to run iOS Core Location in background forever
I am creating a custom application for our office. I want this app to get
the user's location every 5 minutes and send it to our server via json. I
have it working however it won't run in the background longer than 10
minutes.
I have added "App registers for location updates" in Required background
modes.
My code is in the AppDelegate, like this:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(@"Went to Background");
UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
NSLog(@"Became active");
if (!_lastSentUpdateAt) {
_lastSentUpdateAt = [[NSDate date] dateByAddingTimeInterval:-24*60*60];
// Start location services
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = 100.0f;
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation
*)oldLocation
{
if ([_lastSentUpdateAt timeIntervalSinceNow] < -5 * 60) {
// Get battery level
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
float batteryLevel = [[UIDevice currentDevice] batteryLevel];
// Send data to server
float lat = newLocation.coordinate.latitude;
float lng = newLocation.coordinate.longitude;
// My code to send data to the server is here
// ....
_lastSentUpdateAt = [NSDate date];
}
}
Is there something I'm missing?
I am creating a custom application for our office. I want this app to get
the user's location every 5 minutes and send it to our server via json. I
have it working however it won't run in the background longer than 10
minutes.
I have added "App registers for location updates" in Required background
modes.
My code is in the AppDelegate, like this:
- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(@"Went to Background");
UIApplication *app = [UIApplication sharedApplication];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
NSLog(@"Became active");
if (!_lastSentUpdateAt) {
_lastSentUpdateAt = [[NSDate date] dateByAddingTimeInterval:-24*60*60];
// Start location services
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.distanceFilter = 100.0f;
self.locationManager.delegate = self;
[self.locationManager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation
*)oldLocation
{
if ([_lastSentUpdateAt timeIntervalSinceNow] < -5 * 60) {
// Get battery level
[[UIDevice currentDevice] setBatteryMonitoringEnabled:YES];
float batteryLevel = [[UIDevice currentDevice] batteryLevel];
// Send data to server
float lat = newLocation.coordinate.latitude;
float lng = newLocation.coordinate.longitude;
// My code to send data to the server is here
// ....
_lastSentUpdateAt = [NSDate date];
}
}
Is there something I'm missing?
Sunday, 15 September 2013
Patch installation in GWT
Patch installation in GWT
I have a single module which contains series of java script files post
compilation(One module, one WAR file). The same has been deployed as
single module in production.
I have a scenario where I have modified only one Java file and compiled
the module. During deployment, Is it possible to update modified JS file
instead of replacing entire module? Trying to achieve modularity as much
as possible during patch installation.
Thank you.
I have a single module which contains series of java script files post
compilation(One module, one WAR file). The same has been deployed as
single module in production.
I have a scenario where I have modified only one Java file and compiled
the module. During deployment, Is it possible to update modified JS file
instead of replacing entire module? Trying to achieve modularity as much
as possible during patch installation.
Thank you.
Python 3: ImportError: No module named 'setuptools'
Python 3: ImportError: No module named 'setuptools'
I am working with python 3.3 on a Mac OS X laptop. I have been trying to
install the pysparse package, but to no avail.
When running 'python setup.py install', I always get the 'print
'setuptools module not found.'' error. I searched for fixes to this
problem and found the threads about the distribute package, which I
installed. But this does not change anything and I still get the same
error when trying to install the pysparse package.
Has anybody had the same problem or knows how to fix it? Thanks!
I am working with python 3.3 on a Mac OS X laptop. I have been trying to
install the pysparse package, but to no avail.
When running 'python setup.py install', I always get the 'print
'setuptools module not found.'' error. I searched for fixes to this
problem and found the threads about the distribute package, which I
installed. But this does not change anything and I still get the same
error when trying to install the pysparse package.
Has anybody had the same problem or knows how to fix it? Thanks!
Field boosting in elasticsearch with django-haystack
Field boosting in elasticsearch with django-haystack
We're trying to implement field boosting in Elasticsearch using Django
Haystack 2.1.0 and pyelasticsearch 0.6. If I curl -XGET
"http://localhost:9200/_mapping?pretty=true, I get a response (extraneous
parts removed) of
{
"haystack" : {
"modelresult" : {
"_boost" : {
"name" : "boost",
"null_value" : 1.0
},
"properties" : {
"headline" : {
"type" : "string",
"boost" : 1.5,
"analyzer" : "snowball",
"store" : "yes",
"term_vector" : "with_positions_offsets"
},
}
}
}
So far we're only trying to boost the "headline" field. Even using a boost
of something absurd like 5000 shows no effect on the output. Is there
something we're missing?
We're trying to implement field boosting in Elasticsearch using Django
Haystack 2.1.0 and pyelasticsearch 0.6. If I curl -XGET
"http://localhost:9200/_mapping?pretty=true, I get a response (extraneous
parts removed) of
{
"haystack" : {
"modelresult" : {
"_boost" : {
"name" : "boost",
"null_value" : 1.0
},
"properties" : {
"headline" : {
"type" : "string",
"boost" : 1.5,
"analyzer" : "snowball",
"store" : "yes",
"term_vector" : "with_positions_offsets"
},
}
}
}
So far we're only trying to boost the "headline" field. Even using a boost
of something absurd like 5000 shows no effect on the output. Is there
something we're missing?
Textarea not POSTing with form
Textarea not POSTing with form
I'm trying to input a textarea tag when I submit my form:
<textarea id="confirmationText" class="text" cols="86" rows ="20"
name="confirmationText" form="confirmationForm"></textarea>
<form action="sendConfirmation.php" name="confirmationForm" method="post">
<input type="submit" value="Email" class="submitButton">
</form>
As you can see I've set the form="confirmationForm" attribute in my
textarea tag. I've used Live HTTP Headers to catch the POST request and it
is empty (so I know the problem is not in sendConfirmation.php, the
problem is that the confirmationText is not being POSTed). I've searched
the net and as far as I can see I've set it correctly.
I'm trying to input a textarea tag when I submit my form:
<textarea id="confirmationText" class="text" cols="86" rows ="20"
name="confirmationText" form="confirmationForm"></textarea>
<form action="sendConfirmation.php" name="confirmationForm" method="post">
<input type="submit" value="Email" class="submitButton">
</form>
As you can see I've set the form="confirmationForm" attribute in my
textarea tag. I've used Live HTTP Headers to catch the POST request and it
is empty (so I know the problem is not in sendConfirmation.php, the
problem is that the confirmationText is not being POSTed). I've searched
the net and as far as I can see I've set it correctly.
Removing a node from HTML
Removing a node from HTML
From reading here and elsewhere I would expect the following to remove the
first div from the page.
<div class = "name">one</div>
<div class = "name">two</div>
<div class = "name">three</div>
<div class = "name">four</div>
<div class = "name">five</div>
<div class = "name">six</div>
var removeName = function(x,y) {
x.remove(y);
};
removeName(document.getElementsByClassName("name"),0);
I'm not sure what I have missed? Any help appreciated.
From reading here and elsewhere I would expect the following to remove the
first div from the page.
<div class = "name">one</div>
<div class = "name">two</div>
<div class = "name">three</div>
<div class = "name">four</div>
<div class = "name">five</div>
<div class = "name">six</div>
var removeName = function(x,y) {
x.remove(y);
};
removeName(document.getElementsByClassName("name"),0);
I'm not sure what I have missed? Any help appreciated.
Sending data through get in facebox
Sending data through get in facebox
I have an array,
ab = new Array();
I then populate the array with a list of values.
And I have this line,
$.facebox({ajax: "/process/abvals/" });
I would like to know if there is a way to pass the array ab to the url
/process/abvals/ and still have the page be displayed in a facebox?
I have an array,
ab = new Array();
I then populate the array with a list of values.
And I have this line,
$.facebox({ajax: "/process/abvals/" });
I would like to know if there is a way to pass the array ab to the url
/process/abvals/ and still have the page be displayed in a facebox?
Loading images in apk with as3
Loading images in apk with as3
I'm trying to create an app for Google's play store using Flash CS5 with
as3. I have the following code to load images:
function loadImage():void
{
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);
loader.load(new URLRequest('app:/images/'+ imagesArray[counter]));
}
It compiles and runs correctly when I 'Test Scene' but when I upload the
.apk file and download to my phone the app runs but the images do not
appear. The images in the apk are in a folder assets/Images but including
the assets folder produces a compiler error. How can I ensure the images
work in the app?
Thanks
I'm trying to create an app for Google's play store using Flash CS5 with
as3. I have the following code to load images:
function loadImage():void
{
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaded);
loader.load(new URLRequest('app:/images/'+ imagesArray[counter]));
}
It compiles and runs correctly when I 'Test Scene' but when I upload the
.apk file and download to my phone the app runs but the images do not
appear. The images in the apk are in a folder assets/Images but including
the assets folder produces a compiler error. How can I ensure the images
work in the app?
Thanks
jquery mobile for BlackBerry z10 image link zooms
jquery mobile for BlackBerry z10 image link zooms
I'm developing a mobile app for BlackBerry z10 with jquery mobile for
BlackBerry 10. I used an image as a button, but when I double tap the
image, the whole app zooms.
This is the code I used:
<a href="#frm_page1" onClick="show()"><img
src="images/buttons/page1.png"/></a>
but the other images are not zooming at all (image with no links).
What seems to be the problem while I'm having this code here:
<meta name="viewport" content="user-scalable=0, initial-scale=0.45,
maximum-scale=0.45, minimum-scale=0.45, width=device-width,
height=device-height" charset="UTF-8"/>
Can anyone help me to get rid of this. Thanks in advance.
I'm developing a mobile app for BlackBerry z10 with jquery mobile for
BlackBerry 10. I used an image as a button, but when I double tap the
image, the whole app zooms.
This is the code I used:
<a href="#frm_page1" onClick="show()"><img
src="images/buttons/page1.png"/></a>
but the other images are not zooming at all (image with no links).
What seems to be the problem while I'm having this code here:
<meta name="viewport" content="user-scalable=0, initial-scale=0.45,
maximum-scale=0.45, minimum-scale=0.45, width=device-width,
height=device-height" charset="UTF-8"/>
Can anyone help me to get rid of this. Thanks in advance.
Saturday, 14 September 2013
Making a CustomView with a static vertical size in Cocoa
Making a CustomView with a static vertical size in Cocoa
I'm making a document viewer in Objective-C, I want to have a bar at the
top of the page with a bunch of buttons in it which open up menus, change
pages, etc. At the moment I'm using a custom view which then just has all
of the buttons inside it, but my problem is that it isn't a static
vertical height, so when the window resizes it changes the size of the
custom view rather than my PDFView. Is there a way I can stop it from
resizing, or is there a better method I should be using to create a menu?
Thanks!
I'm making a document viewer in Objective-C, I want to have a bar at the
top of the page with a bunch of buttons in it which open up menus, change
pages, etc. At the moment I'm using a custom view which then just has all
of the buttons inside it, but my problem is that it isn't a static
vertical height, so when the window resizes it changes the size of the
custom view rather than my PDFView. Is there a way I can stop it from
resizing, or is there a better method I should be using to create a menu?
Thanks!
jquery play and pause buttons to start/stop image plugin
jquery play and pause buttons to start/stop image plugin
I have an image slider plugin that gets initialized onload with this:
$('#headerwrapper img').peTransitionHilight({
slideshow: true,
transition: "all",
duration: 1234,
delay: 8888,
boost: 0.6
});
Once started it runs forever.
I'm trying to figure out how to make it startable and stoppable, as in:
<button class="play">play</button>
<button class="pause">pause</button>
I've tried many approaches but nothing gives, e.g.,
var interval;
function slideBoxTimeout(){
var interval = setInterval(function(){
slideBoxTransition();
}, delay);
}
$(".play").click(function() {
slideBoxTimeout();
});
$(".pause").click(function() {
clearInterval(interval);
});
What's a good way to start and stop this thing?
I have an image slider plugin that gets initialized onload with this:
$('#headerwrapper img').peTransitionHilight({
slideshow: true,
transition: "all",
duration: 1234,
delay: 8888,
boost: 0.6
});
Once started it runs forever.
I'm trying to figure out how to make it startable and stoppable, as in:
<button class="play">play</button>
<button class="pause">pause</button>
I've tried many approaches but nothing gives, e.g.,
var interval;
function slideBoxTimeout(){
var interval = setInterval(function(){
slideBoxTransition();
}, delay);
}
$(".play").click(function() {
slideBoxTimeout();
});
$(".pause").click(function() {
clearInterval(interval);
});
What's a good way to start and stop this thing?
Deserialize cookies stored WebDriver
Deserialize cookies stored WebDriver
OK going round in circles, I need some help!
How do I deserialize this so I can re-load the cookies that I have stored
try
{
var cookies = driver.Manage().Cookies.AllCookies;
SiteCookieList siteCookies = new SiteCookieList();
siteCookies.Cookies = new List<SiteCookie>();
foreach (var cookie in cookies)
{
SiteCookie sc = new SiteCookie
{
Domain = cookie.Domain,
Name = cookie.Name,
Path = cookie.Path,
Expiry = cookie.Expiry,
Secure = cookie.Secure,
Value = cookie.Value
};
siteCookies.Cookies.Insert(0, sc);
}
lc.SharingCookie = SerializeAnObject(siteCookies);
rep.UpdateLoginCredential(lc);
}
catch (Exception)
{
throw;
}
My other classes
[Serializable]
public class SiteCookie
{
[XmlAttribute]
public string Domain { get; set; }
public string Name { get; set; }
public string Path { get; set; }
public DateTime? Expiry { get; set; }
public bool Secure { get; set; }
public string Value { get; set; }
}
[Serializable]
public class SiteCookieList
{
public List<SiteCookie> Cookies { get; set; }
}
Im trying
public static object DeSerializeAnObject(string Xml)
{
using (StringReader strreader = new StringReader(Xml))
{
using (XmlReader xmlreader = XmlReader.Create(strreader))
{
object result = new
XmlSerializer(typeof(SiteCookieList)).Deserialize(xmlreader);
return result as SiteCookieList;
}
}
}
public static string SerializeAnObject(object AnObject)
{
XmlSerializer Xml_Serializer = new XmlSerializer(AnObject.GetType());
StringWriter Writer = new StringWriter();
Xml_Serializer.Serialize(Writer, AnObject);
return Writer.ToString();
}
private static void loadStoredCookies(IWebDriver driver, string XML)
{
try
{
dynamic siteCookies = DeSerializeAnObject(XML);
foreach (var cookie in siteCookies)
{
driver.Manage().Cookies.AddCookie(cookie);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Its wrong, late at 5am here so I need to have fresh eyes on this!
OK going round in circles, I need some help!
How do I deserialize this so I can re-load the cookies that I have stored
try
{
var cookies = driver.Manage().Cookies.AllCookies;
SiteCookieList siteCookies = new SiteCookieList();
siteCookies.Cookies = new List<SiteCookie>();
foreach (var cookie in cookies)
{
SiteCookie sc = new SiteCookie
{
Domain = cookie.Domain,
Name = cookie.Name,
Path = cookie.Path,
Expiry = cookie.Expiry,
Secure = cookie.Secure,
Value = cookie.Value
};
siteCookies.Cookies.Insert(0, sc);
}
lc.SharingCookie = SerializeAnObject(siteCookies);
rep.UpdateLoginCredential(lc);
}
catch (Exception)
{
throw;
}
My other classes
[Serializable]
public class SiteCookie
{
[XmlAttribute]
public string Domain { get; set; }
public string Name { get; set; }
public string Path { get; set; }
public DateTime? Expiry { get; set; }
public bool Secure { get; set; }
public string Value { get; set; }
}
[Serializable]
public class SiteCookieList
{
public List<SiteCookie> Cookies { get; set; }
}
Im trying
public static object DeSerializeAnObject(string Xml)
{
using (StringReader strreader = new StringReader(Xml))
{
using (XmlReader xmlreader = XmlReader.Create(strreader))
{
object result = new
XmlSerializer(typeof(SiteCookieList)).Deserialize(xmlreader);
return result as SiteCookieList;
}
}
}
public static string SerializeAnObject(object AnObject)
{
XmlSerializer Xml_Serializer = new XmlSerializer(AnObject.GetType());
StringWriter Writer = new StringWriter();
Xml_Serializer.Serialize(Writer, AnObject);
return Writer.ToString();
}
private static void loadStoredCookies(IWebDriver driver, string XML)
{
try
{
dynamic siteCookies = DeSerializeAnObject(XML);
foreach (var cookie in siteCookies)
{
driver.Manage().Cookies.AddCookie(cookie);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Its wrong, late at 5am here so I need to have fresh eyes on this!
Notification of Message app opening
Notification of Message app opening
Is there a public API to listen for when apple apps open? For example if a
user opens up the message app can my app listen for that event? Thank you
Is there a public API to listen for when apple apps open? For example if a
user opens up the message app can my app listen for that event? Thank you
Record Audio in my App Errors
Record Audio in my App Errors
I am trying to let the users record their voice in my app and I am
following this tutorial. This is the code in viewDidLoad:
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:@"sound.caf"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSDictionary *recordSettings = [NSDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:AVAudioQualityMin],
AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16],
AVEncoderBitRateKey,
[NSNumber numberWithInt: 2],
AVNumberOfChannelsKey,
[NSNumber numberWithFloat:44100.0],
AVSampleRateKey,
nil];
NSError *error = nil;
self.recorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
if (error)
{
NSLog(@"error: %@", [error localizedDescription]);
} else {
[self.recorder prepareToRecord];
}
I am getting 6 errors:
I know the errors are coming from the the code in viewDidLoad because when
I comment out that code the errors go away. What do the errors mean and
how do I fix it?
I am trying to let the users record their voice in my app and I am
following this tutorial. This is the code in viewDidLoad:
NSArray *dirPaths;
NSString *docsDir;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
docsDir = dirPaths[0];
NSString *soundFilePath = [docsDir
stringByAppendingPathComponent:@"sound.caf"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
NSDictionary *recordSettings = [NSDictionary
dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:AVAudioQualityMin],
AVEncoderAudioQualityKey,
[NSNumber numberWithInt:16],
AVEncoderBitRateKey,
[NSNumber numberWithInt: 2],
AVNumberOfChannelsKey,
[NSNumber numberWithFloat:44100.0],
AVSampleRateKey,
nil];
NSError *error = nil;
self.recorder = [[AVAudioRecorder alloc]
initWithURL:soundFileURL
settings:recordSettings
error:&error];
if (error)
{
NSLog(@"error: %@", [error localizedDescription]);
} else {
[self.recorder prepareToRecord];
}
I am getting 6 errors:
I know the errors are coming from the the code in viewDidLoad because when
I comment out that code the errors go away. What do the errors mean and
how do I fix it?
Show more/Less similar to Windows xp Quick launch bar
Show more/Less similar to Windows xp Quick launch bar
I 'm new to jquery and scripts .
can anyone help me to get this, I have five (div)buttons in the
index.cshtml(asp.net MVC) , I have a showmore button similar to the
5buttons. This showmore button have to do the same function in the windows
xp Quicklaunch.
here are my 4 buttons:
>>
(A to E are my buttons)
I need some help in getting jquery plugin or atleast guidance to make this
similar to the windowx xp quick launch buttons , show in the image below
I 'm new to jquery and scripts .
can anyone help me to get this, I have five (div)buttons in the
index.cshtml(asp.net MVC) , I have a showmore button similar to the
5buttons. This showmore button have to do the same function in the windows
xp Quicklaunch.
here are my 4 buttons:
>>
(A to E are my buttons)
I need some help in getting jquery plugin or atleast guidance to make this
similar to the windowx xp quick launch buttons , show in the image below
file upload strange issue with size and extension
file upload strange issue with size and extension
I am currently working on a script that will allow users to upload images,
nothing too sophisticated just a few simple lines of code. Anyway, last
night everything was working like a charm and now surprise surprise,
strange things started happening out of the blue for who knows what
reason. That said, it's important to note that I am asynchronously passing
values using jQuery Form Plugin and that part has been working flawlessly
hence I will not post that part of the code.
here is the cfc component code:
<cfcomponent output="false">
<cffunction name="test" access="remote" output="false">
<cfparam name="form.title" type="string" default="">
<cfparam name="form.File" type="string" default="">
<cfset add.Msg = ArrayNew(1)>
<!---check if text is added and whether it contains more than 15
characters--->
<cfif len (trim(form.title)) is 0>
<cfset ArrayAppend(add.Msg,"plese enter some text")>
<cfelseif len (trim(form.title)) lt 15>
<cfset ArrayAppend(add.Msg,"text should be at least 15 characters
long")>
</cfif>
<!---check if text contains special characters--->
<!--additionally we can allow other characters-->
<cfif refind ("[^A-Z a-z 0-9\\+]+", form.title) and len
(trim(form.title)) gte 15>
<cfset ArrayAppend(add.Msg,"your post can not conatin special
characters")>
</cfif>
<!---check to see if file has been submited--->
<cfif len(form.File) is 0>
<cfset ArrayAppend(add.Msg,"you haven't selected a file")>
</cfif>
<!---if there are no errors try to upload file to temp--->
<cfif ArrayLen (add.Msg) is 0>
<cftry>
<cffile action="upload" nameconflict="makeunique"
destination="#GetTempDirectory()#" filefield="File">
<!---check file size--->
<cfif (CFFILE.FileSize GT (100 * 1024))>
<cfset ArrayAppend(add.Msg,"#CFFILE.FileSize#you can not
upload files bigger than 1MB")>
<!---try to delete the file--->
<cftry>
<cffile action="delete"
file="#CFFILE.ServerDirectory#\#CFFILE.ServerFile#">
<cfcatch>
<!--we dan catch an error , though it would crash the page-->
</cfcatch>
</cftry>
</cfif>
<!---check file extension with aditional layer of protection
for just in case--->
<cfif not ListFindnoCase("jpg,jpeg,png,gif",CFFILE.ServerFileExt)
or not isImageFile("#GetTempDirectory()##CFFILE.ServerFile#")>
<cfset ArrayAppend(add.Msg,"#CFFILE.ServerFileExt#you can
only upload jpg,png or gif images.")>
<!---try to delete the file--->
<cftry>
<cffile action="delete"
file="#CFFILE.ServerDirectory#\#CFFILE.ServerFile#">
<cfcatch>
<!--again we can catch an error, though it would crash the
page-->
</cfcatch>
</cftry>
</cfif>
<cfcatch>
<!--if there was an error we could log it, though that would crash
the page-->
</cfcatch>
</cftry>
</cfif>
<cfif ArrayLen (add.Msg) is 0>
<cfset ArrayAppend(add.Msg,"#CFFILE.ServerFile# - yay! success")>
</cfif>
<cfreturn serializeJSON(add.Msg)>
</cffunction>
as you can see it's a simple validation that should work and has worked as
I mentioned last night. Now I am having issues with file size and file
format validation. That said, whatever I try it returns that file is
bigger that 1M and that it's not a correct type, even though I select
300kb file, jpg or png. as you can see i added #CFFILE.FileSize# and
#CFFILE.ServerFileExt# to those to error msgs and file is there, it's less
than 1MB in size and its correct type. So, WTF is going on here? I would
really appreciate your help on this one, if you have any suggestions on
how to fix this or how to improve my code.
I am currently working on a script that will allow users to upload images,
nothing too sophisticated just a few simple lines of code. Anyway, last
night everything was working like a charm and now surprise surprise,
strange things started happening out of the blue for who knows what
reason. That said, it's important to note that I am asynchronously passing
values using jQuery Form Plugin and that part has been working flawlessly
hence I will not post that part of the code.
here is the cfc component code:
<cfcomponent output="false">
<cffunction name="test" access="remote" output="false">
<cfparam name="form.title" type="string" default="">
<cfparam name="form.File" type="string" default="">
<cfset add.Msg = ArrayNew(1)>
<!---check if text is added and whether it contains more than 15
characters--->
<cfif len (trim(form.title)) is 0>
<cfset ArrayAppend(add.Msg,"plese enter some text")>
<cfelseif len (trim(form.title)) lt 15>
<cfset ArrayAppend(add.Msg,"text should be at least 15 characters
long")>
</cfif>
<!---check if text contains special characters--->
<!--additionally we can allow other characters-->
<cfif refind ("[^A-Z a-z 0-9\\+]+", form.title) and len
(trim(form.title)) gte 15>
<cfset ArrayAppend(add.Msg,"your post can not conatin special
characters")>
</cfif>
<!---check to see if file has been submited--->
<cfif len(form.File) is 0>
<cfset ArrayAppend(add.Msg,"you haven't selected a file")>
</cfif>
<!---if there are no errors try to upload file to temp--->
<cfif ArrayLen (add.Msg) is 0>
<cftry>
<cffile action="upload" nameconflict="makeunique"
destination="#GetTempDirectory()#" filefield="File">
<!---check file size--->
<cfif (CFFILE.FileSize GT (100 * 1024))>
<cfset ArrayAppend(add.Msg,"#CFFILE.FileSize#you can not
upload files bigger than 1MB")>
<!---try to delete the file--->
<cftry>
<cffile action="delete"
file="#CFFILE.ServerDirectory#\#CFFILE.ServerFile#">
<cfcatch>
<!--we dan catch an error , though it would crash the page-->
</cfcatch>
</cftry>
</cfif>
<!---check file extension with aditional layer of protection
for just in case--->
<cfif not ListFindnoCase("jpg,jpeg,png,gif",CFFILE.ServerFileExt)
or not isImageFile("#GetTempDirectory()##CFFILE.ServerFile#")>
<cfset ArrayAppend(add.Msg,"#CFFILE.ServerFileExt#you can
only upload jpg,png or gif images.")>
<!---try to delete the file--->
<cftry>
<cffile action="delete"
file="#CFFILE.ServerDirectory#\#CFFILE.ServerFile#">
<cfcatch>
<!--again we can catch an error, though it would crash the
page-->
</cfcatch>
</cftry>
</cfif>
<cfcatch>
<!--if there was an error we could log it, though that would crash
the page-->
</cfcatch>
</cftry>
</cfif>
<cfif ArrayLen (add.Msg) is 0>
<cfset ArrayAppend(add.Msg,"#CFFILE.ServerFile# - yay! success")>
</cfif>
<cfreturn serializeJSON(add.Msg)>
</cffunction>
as you can see it's a simple validation that should work and has worked as
I mentioned last night. Now I am having issues with file size and file
format validation. That said, whatever I try it returns that file is
bigger that 1M and that it's not a correct type, even though I select
300kb file, jpg or png. as you can see i added #CFFILE.FileSize# and
#CFFILE.ServerFileExt# to those to error msgs and file is there, it's less
than 1MB in size and its correct type. So, WTF is going on here? I would
really appreciate your help on this one, if you have any suggestions on
how to fix this or how to improve my code.
Friday, 13 September 2013
Create File from base64 String for Upload
Create File from base64 String for Upload
I have a web application that is able to create or build a base64 data to
be uploaded to a web service that accepts
application/x-www-form-urlencoded via POST.
Is it necessary to create a File object for upload, a Blob object?
Programmatically, no UI for a user to manually select File to upload.
A method is invoked passing the base64 image to be uploaded to an enpoint
with URL /blob/upload (same domain)
I have a web application that is able to create or build a base64 data to
be uploaded to a web service that accepts
application/x-www-form-urlencoded via POST.
Is it necessary to create a File object for upload, a Blob object?
Programmatically, no UI for a user to manually select File to upload.
A method is invoked passing the base64 image to be uploaded to an enpoint
with URL /blob/upload (same domain)
How to search posts of specific custom post type by a custom field value and then "filter" the results by a custom field checkbox value?
How to search posts of specific custom post type by a custom field value
and then "filter" the results by a custom field checkbox value?
I have a custom post type (songs) and several custom fields associated
with it. One of the custom fields is a checkbox (sample_playlist), the
rest are text strings.
I have added a select element and I am using the checkbox value to filter
the results when on edit.php?post_type=songs
add_filter( 'parse_query', array( &$this, 'wpse45436_posts_filter' ) );
function wpse45436_posts_filter( $query ){
// current page and post type checks omitted
$query->query_vars['meta_key'] = 'sample_playlist';
$query->query_vars['meta_value'] = 'on'; //these are the queries that
get executed when filtering the posts that have the custom field
checkbox checked
}
This works fine when I only attempt to filter the results based on the
checkbox value.
Searching by other custom field values is also possible on that same page via
add_filter( 'posts_join', array( &$this, 'songs_search_join' ) );
add_filter( 'posts_where', array( &$this, 'songs_search_where' ) );
function songs_search_join ($join){
// current page, post type and $_GLOBAL['s'] checks omitted
$join .='LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = '
. $wpdb->postmeta . '.post_id ';
return $join;
}
function songs_search_where( $where ){
// current page, post type and $_GLOBAL['s'] checks omitted
$where = preg_replace(
"/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR
(".$wpdb->postmeta.".meta_value LIKE $1)", $where
);
return $where;
}
The search works fine when I only try to search terms by custom field values.
HOWEVER, when I try to use both of these sequentially (ie search then
filter, or vice versa), I run into a problem with the search join using
wp_postmeta as well as the filter by "custom field checkbox value" using
it as well. Is there a way around this, that would allow me to utilize
both of these sequentially?
the error I recieve: WordPress database error Not unique table/alias:
'wp_postmeta'
the resulting sql query output:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN
wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)LEFT JOIN wp_postmeta ON
wp_posts.ID = wp_postmeta.post_id WHERE 1=1 AND (((wp_posts.post_title
LIKE '%searchterm%') OR (wp_postmeta.meta_value LIKE '%searchterm%') OR
(wp_posts.post_content LIKE '%searchterm%'))) AND wp_posts.post_type =
'songs' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status =
'future' OR wp_posts.post_status = 'draft' OR wp_posts.post_status =
'pending' OR wp_posts.post_status = 'private') AND ( (wp_postmeta.meta_key
= 'sample_playlist' AND CAST(wp_postmeta.meta_value AS CHAR) = 'on') )
ORDER BY wp_posts.post_date DESC LIMIT 0, 20
and then "filter" the results by a custom field checkbox value?
I have a custom post type (songs) and several custom fields associated
with it. One of the custom fields is a checkbox (sample_playlist), the
rest are text strings.
I have added a select element and I am using the checkbox value to filter
the results when on edit.php?post_type=songs
add_filter( 'parse_query', array( &$this, 'wpse45436_posts_filter' ) );
function wpse45436_posts_filter( $query ){
// current page and post type checks omitted
$query->query_vars['meta_key'] = 'sample_playlist';
$query->query_vars['meta_value'] = 'on'; //these are the queries that
get executed when filtering the posts that have the custom field
checkbox checked
}
This works fine when I only attempt to filter the results based on the
checkbox value.
Searching by other custom field values is also possible on that same page via
add_filter( 'posts_join', array( &$this, 'songs_search_join' ) );
add_filter( 'posts_where', array( &$this, 'songs_search_where' ) );
function songs_search_join ($join){
// current page, post type and $_GLOBAL['s'] checks omitted
$join .='LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = '
. $wpdb->postmeta . '.post_id ';
return $join;
}
function songs_search_where( $where ){
// current page, post type and $_GLOBAL['s'] checks omitted
$where = preg_replace(
"/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
"(".$wpdb->posts.".post_title LIKE $1) OR
(".$wpdb->postmeta.".meta_value LIKE $1)", $where
);
return $where;
}
The search works fine when I only try to search terms by custom field values.
HOWEVER, when I try to use both of these sequentially (ie search then
filter, or vice versa), I run into a problem with the search join using
wp_postmeta as well as the filter by "custom field checkbox value" using
it as well. Is there a way around this, that would allow me to utilize
both of these sequentially?
the error I recieve: WordPress database error Not unique table/alias:
'wp_postmeta'
the resulting sql query output:
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN
wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)LEFT JOIN wp_postmeta ON
wp_posts.ID = wp_postmeta.post_id WHERE 1=1 AND (((wp_posts.post_title
LIKE '%searchterm%') OR (wp_postmeta.meta_value LIKE '%searchterm%') OR
(wp_posts.post_content LIKE '%searchterm%'))) AND wp_posts.post_type =
'songs' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status =
'future' OR wp_posts.post_status = 'draft' OR wp_posts.post_status =
'pending' OR wp_posts.post_status = 'private') AND ( (wp_postmeta.meta_key
= 'sample_playlist' AND CAST(wp_postmeta.meta_value AS CHAR) = 'on') )
ORDER BY wp_posts.post_date DESC LIMIT 0, 20
XCode 5 GM Validate Crash?
XCode 5 GM Validate Crash?
Please help me for this crash, i'm not possible for me, distribute my app.
Long rapport posted in pastebin:
http://pastebin.com/ezndQpuX
Thanks for advance.
Please help me for this crash, i'm not possible for me, distribute my app.
Long rapport posted in pastebin:
http://pastebin.com/ezndQpuX
Thanks for advance.
MySql dump restore from Run Dialog (not the cmd prompt)
MySql dump restore from Run Dialog (not the cmd prompt)
I need to restore a mysqldump on a windows machine, which i perfectly know
how. But I need to do it via the Run Dialog in one GO.
So we open the Run Dialog and type : "[PathToMysql]\mysql.exe" -u
[someUser] -p[SomePass] [DatabaseName] < "[PathToDumpFile]"
If I execute the command inside the command prompt (cmd.exe), it works
perfectly. But if I run it directly from the Run Dialog, I get the list of
all mysql.exe options...
If I skip the (< "[PathToDumpFile]") part and execute the rest in the Run
Dialog, I end up with the mysql shell. So there is something in the last
part that the run dialog does not like but works in the cmd window.
Anybody has any experience with this or has an alternate suggestion?
If you wonder why from the Run Dialog, it's because it reacts the same as
a command sent through WMI, it's just faster to test that way. Since I'll
build the command dynamically to run on a remote server that could change
whenever, I'd rather not play with a batch file but I'll have to if what
I'm looking for proves impossible.
Thank you.
I need to restore a mysqldump on a windows machine, which i perfectly know
how. But I need to do it via the Run Dialog in one GO.
So we open the Run Dialog and type : "[PathToMysql]\mysql.exe" -u
[someUser] -p[SomePass] [DatabaseName] < "[PathToDumpFile]"
If I execute the command inside the command prompt (cmd.exe), it works
perfectly. But if I run it directly from the Run Dialog, I get the list of
all mysql.exe options...
If I skip the (< "[PathToDumpFile]") part and execute the rest in the Run
Dialog, I end up with the mysql shell. So there is something in the last
part that the run dialog does not like but works in the cmd window.
Anybody has any experience with this or has an alternate suggestion?
If you wonder why from the Run Dialog, it's because it reacts the same as
a command sent through WMI, it's just faster to test that way. Since I'll
build the command dynamically to run on a remote server that could change
whenever, I'd rather not play with a batch file but I'll have to if what
I'm looking for proves impossible.
Thank you.
Can Goutte/Guzzle be forced into UTF-8 mode?
Can Goutte/Guzzle be forced into UTF-8 mode?
I'm scraping from a UTF-8 site, using Goutte, which internally uses
Guzzle. The site declares a meta tag of UTF-8, thus:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
However, the content type header is thus:
Content-Type: text/html
and not:
Content-Type: text/html; charset=utf-8
Thus, when I scrape, Goutte does not spot that it is UTF-8, and grabs data
incorrectly. The remote site is not under my control, so I can't fix the
problem there! Here's a set of scripts to replicate the problem. First,
the scraper:
<?php
require_once realpath(__DIR__ . '/..') . '/vendor/goutte/goutte.phar';
$url = 'http://crawler-tests.local/utf-8.php';
use Goutte\Client;
$client = new Client();
$crawler = $client->request('get', $url);
$text = $crawler->text();
echo 'Whole page: ' . $text . "\n";
Now a test page to be placed on a web server:
<?php
// Correct
#header('Content-Type: text/html; charset=utf-8');
// Incorrect
header('Content-Type: text/html');
?>
<!DOCTYPE html>
<html>
<head>
<title>UTF-8 test</title>
<meta charset="utf-8" />
</head>
<body>
<p>When the Content-Header header is incomplete, the pound sign
breaks:
£15,216</p>
</body>
</html>
As you can see from the comments in the last script, properly declaring
the character set in the header fixes things. I've hunted around in Goutte
to see if there is anything that looks like it would force the character
set, but to no avail. Any ideas?
I'm scraping from a UTF-8 site, using Goutte, which internally uses
Guzzle. The site declares a meta tag of UTF-8, thus:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
However, the content type header is thus:
Content-Type: text/html
and not:
Content-Type: text/html; charset=utf-8
Thus, when I scrape, Goutte does not spot that it is UTF-8, and grabs data
incorrectly. The remote site is not under my control, so I can't fix the
problem there! Here's a set of scripts to replicate the problem. First,
the scraper:
<?php
require_once realpath(__DIR__ . '/..') . '/vendor/goutte/goutte.phar';
$url = 'http://crawler-tests.local/utf-8.php';
use Goutte\Client;
$client = new Client();
$crawler = $client->request('get', $url);
$text = $crawler->text();
echo 'Whole page: ' . $text . "\n";
Now a test page to be placed on a web server:
<?php
// Correct
#header('Content-Type: text/html; charset=utf-8');
// Incorrect
header('Content-Type: text/html');
?>
<!DOCTYPE html>
<html>
<head>
<title>UTF-8 test</title>
<meta charset="utf-8" />
</head>
<body>
<p>When the Content-Header header is incomplete, the pound sign
breaks:
£15,216</p>
</body>
</html>
As you can see from the comments in the last script, properly declaring
the character set in the header fixes things. I've hunted around in Goutte
to see if there is anything that looks like it would force the character
set, but to no avail. Any ideas?
Thursday, 12 September 2013
Elastic Search with Mongoose - Embedded Schema
Elastic Search with Mongoose - Embedded Schema
I have the following mongoose schema:
var ReviewSchema = new Schema({
title: String,
details: String,
user: {type: ObjectId, ref:'User'},
});
var SubjectSchema = new Schema({
name: {type: String, required: true},
website: {type: String, index: { unique: true }},
review: {type: [ReviewSchema], es_indexed:true}
});
I have another User schema which is referenced in Review.
I tried mongoosastic plugin but I can't find ways to index the referenced
schema. I want to index the name of the user of a review. So I just used
elastic search client for this.
Every create/update/delete of review, I looked up in the database and
update elastic search index with the value retrived from database. Is
there better way for this on updating index when embedded schema is
updated? Thanks
I have the following mongoose schema:
var ReviewSchema = new Schema({
title: String,
details: String,
user: {type: ObjectId, ref:'User'},
});
var SubjectSchema = new Schema({
name: {type: String, required: true},
website: {type: String, index: { unique: true }},
review: {type: [ReviewSchema], es_indexed:true}
});
I have another User schema which is referenced in Review.
I tried mongoosastic plugin but I can't find ways to index the referenced
schema. I want to index the name of the user of a review. So I just used
elastic search client for this.
Every create/update/delete of review, I looked up in the database and
update elastic search index with the value retrived from database. Is
there better way for this on updating index when embedded schema is
updated? Thanks
Choose relation one to many or many to one for design
Choose relation one to many or many to one for design
I need help to define the relationship between the models.
I have 2 models :
User
Product
The user own many products and the product is owned by only one user.
My use case : The logged user can access to some information in his
personnal account : - Display all his products - Add a new product
Later i'd like to add use case like : any user can see any product in some
screen (and know product's owner).
So, i can define the models like that :
A) ONE TO MANY
class User{
private Set<Product> products;
..
}
class Product{
...
}
B) MANY TO ONE
class User{
..
}
class Product{
private User owner;
}
Which is the best ? one to many or many to one ?
Because my use case display the product of logged user Im thinking its
better to choose one to many
I need help to define the relationship between the models.
I have 2 models :
User
Product
The user own many products and the product is owned by only one user.
My use case : The logged user can access to some information in his
personnal account : - Display all his products - Add a new product
Later i'd like to add use case like : any user can see any product in some
screen (and know product's owner).
So, i can define the models like that :
A) ONE TO MANY
class User{
private Set<Product> products;
..
}
class Product{
...
}
B) MANY TO ONE
class User{
..
}
class Product{
private User owner;
}
Which is the best ? one to many or many to one ?
Because my use case display the product of logged user Im thinking its
better to choose one to many
Bootstrap Modal not working in partialview
Bootstrap Modal not working in partialview
i use bootstrap modal in partialview not working, but working in view dont
know what happen, anyone can help me, thanks! my code
@Html.Partial("_Header") (in layout)
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<a data-toggle="modal" href="#myModal" class="btn btn-primary
btn-lg">Launch demo modal</a>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save
changes</button>
</div>
</div>
</div>
</div>
<script>
$(function () {
$('#myModal').modal({
backdrop: true,
keyboard: false,
show: false
});
});
</script>
i use bootstrap modal in partialview not working, but working in view dont
know what happen, anyone can help me, thanks! my code
@Html.Partial("_Header") (in layout)
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<a data-toggle="modal" href="#myModal" class="btn btn-primary
btn-lg">Launch demo modal</a>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save
changes</button>
</div>
</div>
</div>
</div>
<script>
$(function () {
$('#myModal').modal({
backdrop: true,
keyboard: false,
show: false
});
});
</script>
How to compare strings of two files?
How to compare strings of two files?
I am a new c-language programmer.
I have got two files. One consists of lines like:
84:1b:5e:a8:bf:7f
00:8e:f2:c0:13:cc
Another consists of lines like:
00-22-39
8C-FD-F0
My question is how can I using C language compare first half of line in
the first file with a line in the second file? Like: is 84:1b:5e equals to
8C-FD-F0? I know the way to create an arrays to store those lines for the
further comparison. But do I really need to create arrays?
P.S: comparison is case-insensitive
I am a new c-language programmer.
I have got two files. One consists of lines like:
84:1b:5e:a8:bf:7f
00:8e:f2:c0:13:cc
Another consists of lines like:
00-22-39
8C-FD-F0
My question is how can I using C language compare first half of line in
the first file with a line in the second file? Like: is 84:1b:5e equals to
8C-FD-F0? I know the way to create an arrays to store those lines for the
further comparison. But do I really need to create arrays?
P.S: comparison is case-insensitive
SQL: Using two dates from other query to select data between date interval
SQL: Using two dates from other query to select data between date interval
I am new to SQL and I am facing a complicated problem.
My table T2 contains start_date and end_date, two time stamps. Table T1
contains a time-stamp ts and values v for that.
I would like to use the pairs of time-stamps in T2 to obtain values v from
T1 between those pair of dates. I tried something like below but it will
not work. I would appreciate your help with pointing me to the problem.
select v, circle_ts from t1 where circle_ts between start_ts and end_ts in
(select start_ts, end_ts from t2 where meter_id = 10)
I am new to SQL and I am facing a complicated problem.
My table T2 contains start_date and end_date, two time stamps. Table T1
contains a time-stamp ts and values v for that.
I would like to use the pairs of time-stamps in T2 to obtain values v from
T1 between those pair of dates. I tried something like below but it will
not work. I would appreciate your help with pointing me to the problem.
select v, circle_ts from t1 where circle_ts between start_ts and end_ts in
(select start_ts, end_ts from t2 where meter_id = 10)
Wednesday, 11 September 2013
Is there a way to include scrol bar in list?
Is there a way to include scrol bar in list?
this is my list code but i want when list drop down menu open , then it
must be open with scroll bar because may bi my list very long so please
help me.?
<li style="margin-top:0%;"><a id="sign"
href="index.php?main_page=shopping_cart" ><img
src="/includes/templates/pure_orange/images/cart_full.png" height=22px
width=40px;/><?php echo $count;?><span id="arrow1"
class="nav-down-arrow nav-sprite"></span></a>
<ul>
<div id="clr" style=" border-top:solid; padding-right:15px;
border-top-color:black; padding-bottom:10%; margin-top:1%;
background-color:#EDEDED; ">
<?php
// print_r($var);
for($i=0; $i<$count; $i++)
{
//$i=0;
$p_id=$var[$i]['id'];
$arr=explode(':', $p_id);
$pr_id= $arr[0];
$urii=$db->Execute("select uri from zen_ceon_uri_mappings where
associated_db_id=$pr_id");
$link=$urii->fields['uri'];
echo "<a style='margin-top:1px;' href= '$link'>"?><?php echo
$var[$i]['name'];"</a>";
}
?>
<a href="index.php?main_page=shopping_cart"
class="myButton">View Cart Item: <?php echo $count;?></a>
</ul>
</li>
this is my list code but i want when list drop down menu open , then it
must be open with scroll bar because may bi my list very long so please
help me.?
<li style="margin-top:0%;"><a id="sign"
href="index.php?main_page=shopping_cart" ><img
src="/includes/templates/pure_orange/images/cart_full.png" height=22px
width=40px;/><?php echo $count;?><span id="arrow1"
class="nav-down-arrow nav-sprite"></span></a>
<ul>
<div id="clr" style=" border-top:solid; padding-right:15px;
border-top-color:black; padding-bottom:10%; margin-top:1%;
background-color:#EDEDED; ">
<?php
// print_r($var);
for($i=0; $i<$count; $i++)
{
//$i=0;
$p_id=$var[$i]['id'];
$arr=explode(':', $p_id);
$pr_id= $arr[0];
$urii=$db->Execute("select uri from zen_ceon_uri_mappings where
associated_db_id=$pr_id");
$link=$urii->fields['uri'];
echo "<a style='margin-top:1px;' href= '$link'>"?><?php echo
$var[$i]['name'];"</a>";
}
?>
<a href="index.php?main_page=shopping_cart"
class="myButton">View Cart Item: <?php echo $count;?></a>
</ul>
</li>
Whats wrong with my AngularJS directive
Whats wrong with my AngularJS directive
To be able to watch the contents change for a contenteditable div or an
input element, I have created the following directive:
app.directive('contenteditable',function() { return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
// view -> model
element.bind('input', function() {
scope.$apply(function() {
ctrl.$setViewValue(element["0"].tagName=="INPUT" ?
element.val() : element.text());
scope.watchCallback(element.attr('data-ng-model'));
});
});
// model -> view
ctrl.$render = function() {
element.text(ctrl.$viewValue);
element.val(ctrl.$viewValue);
};
}};
});
My Test Controller looks like:
function TestController($scope) {
$scope.singleVal = "X";
$scope.multiVal = ["A"];
$scope.addRow = function() {
$scope.multiVal.push("");
};
$scope.watchCallback = function(modelName) {
console.log(modelName+" was changed");
};
}
When I test it against the following html, the singleVal (statically
created) behaves well, but my multiVal (dynamically created using
ng-repeat) doesnt. When I input a value, it just retains the original
value (i.e the model is not getting refreshed). Please help.
<div data-ng-controller="TestController">
<div contenteditable="true" data-ng-model="singleVal"></div>
<button data-ng-click="addRow()">Add Row</button>
<table data-ng-repeat="val in multiVal"><tr><td>
<div contenteditable="true" data-ng-model="val"></div>
</td></tr></table>
</div>
To be able to watch the contents change for a contenteditable div or an
input element, I have created the following directive:
app.directive('contenteditable',function() { return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
// view -> model
element.bind('input', function() {
scope.$apply(function() {
ctrl.$setViewValue(element["0"].tagName=="INPUT" ?
element.val() : element.text());
scope.watchCallback(element.attr('data-ng-model'));
});
});
// model -> view
ctrl.$render = function() {
element.text(ctrl.$viewValue);
element.val(ctrl.$viewValue);
};
}};
});
My Test Controller looks like:
function TestController($scope) {
$scope.singleVal = "X";
$scope.multiVal = ["A"];
$scope.addRow = function() {
$scope.multiVal.push("");
};
$scope.watchCallback = function(modelName) {
console.log(modelName+" was changed");
};
}
When I test it against the following html, the singleVal (statically
created) behaves well, but my multiVal (dynamically created using
ng-repeat) doesnt. When I input a value, it just retains the original
value (i.e the model is not getting refreshed). Please help.
<div data-ng-controller="TestController">
<div contenteditable="true" data-ng-model="singleVal"></div>
<button data-ng-click="addRow()">Add Row</button>
<table data-ng-repeat="val in multiVal"><tr><td>
<div contenteditable="true" data-ng-model="val"></div>
</td></tr></table>
</div>
JExcelAPI has deep copy feature using copyTo(col,row) method. Nothing find in Apache POI
JExcelAPI has deep copy feature using copyTo(col,row) method. Nothing find
in Apache POI
JExcelAPI (jxl) has a deep copy feature using WritableCell.copyTo(int col,
int row) method.
I couldn't find anything like this in Apache POI .
I need to copy the formula cells and formula should change relative way in
the new cell using Apache POI.
Your help would be appreciated greatly.
Thanks Siva
in Apache POI
JExcelAPI (jxl) has a deep copy feature using WritableCell.copyTo(int col,
int row) method.
I couldn't find anything like this in Apache POI .
I need to copy the formula cells and formula should change relative way in
the new cell using Apache POI.
Your help would be appreciated greatly.
Thanks Siva
more than 1 actions occuring at once onclick
more than 1 actions occuring at once onclick
i am using a click-open accordian-type script. the problem is that the
selectors on which it is applied are repeated, and due to this on clicking
a link, one only the child element of the clicked element should be
affected, whereas all other list items (which are repeated) arebeing
affected at the same time.
the jquery is like this:
$(document).ready(function(){
$("#odd-accordion ul.nextslide > li a").click(function(){
$("ul.nextslide-second a").slideToggle('300');
});
});
the html is like this:
<div class="adminmenuback">
<div class="commonlogo">
<img src="images/logo.png" alt="Wish2book">
</div>
<div class="searchh">
<input type="text" placeholder="search"><span
class="menutitle_rightimage"></span>
</div>
<h2 class="menutitle"><span class="dashboard-icon"></span>Dashboard</h2>
<ul class="adminmenu" id="odd-accordion">
<li>
<h3><a href="#">Flights</a></h3>
<ul class="nextslide">
<li><a href="#">abc</a>
<ul class="nextslide-second">
<li><a href="#">abc-child</a>
</li>
</ul>
</li>
</ul>
</li>
<li>
<h3><a href="#">Flights</a></h3>
<ul class="nextslide">
<li><a href="#">abc</a>
<ul class="nextslide-second">
<li><a href="#">abc-child</a>
</li>
</ul>
</li>
</ul>
</li>
<li>
<h3><a href="#">Flights</a></h3>
<ul class="nextslide">
<li><a href="#">abc</a>
<ul class="nextslide-second">
<li><a href="#">abc-child</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
pls help. the jsfiddle link is here: http://jsfiddle.net/BVz97/
in the jsfiddle, just click "abc" and all abc-child will be selected
i am using a click-open accordian-type script. the problem is that the
selectors on which it is applied are repeated, and due to this on clicking
a link, one only the child element of the clicked element should be
affected, whereas all other list items (which are repeated) arebeing
affected at the same time.
the jquery is like this:
$(document).ready(function(){
$("#odd-accordion ul.nextslide > li a").click(function(){
$("ul.nextslide-second a").slideToggle('300');
});
});
the html is like this:
<div class="adminmenuback">
<div class="commonlogo">
<img src="images/logo.png" alt="Wish2book">
</div>
<div class="searchh">
<input type="text" placeholder="search"><span
class="menutitle_rightimage"></span>
</div>
<h2 class="menutitle"><span class="dashboard-icon"></span>Dashboard</h2>
<ul class="adminmenu" id="odd-accordion">
<li>
<h3><a href="#">Flights</a></h3>
<ul class="nextslide">
<li><a href="#">abc</a>
<ul class="nextslide-second">
<li><a href="#">abc-child</a>
</li>
</ul>
</li>
</ul>
</li>
<li>
<h3><a href="#">Flights</a></h3>
<ul class="nextslide">
<li><a href="#">abc</a>
<ul class="nextslide-second">
<li><a href="#">abc-child</a>
</li>
</ul>
</li>
</ul>
</li>
<li>
<h3><a href="#">Flights</a></h3>
<ul class="nextslide">
<li><a href="#">abc</a>
<ul class="nextslide-second">
<li><a href="#">abc-child</a>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
pls help. the jsfiddle link is here: http://jsfiddle.net/BVz97/
in the jsfiddle, just click "abc" and all abc-child will be selected
change the value of parent scope
change the value of parent scope
please help to change the value "allNews" after clicking the button .all_news
http://plnkr.co/edit/xKVpczgVa9wKtIpS95ng?p=preview
as a result of the class .allNews should be added to the block
.slide_panel_inner and block height increase to 600px
please help to change the value "allNews" after clicking the button .all_news
http://plnkr.co/edit/xKVpczgVa9wKtIpS95ng?p=preview
as a result of the class .allNews should be added to the block
.slide_panel_inner and block height increase to 600px
Format a number based on a required number of decimal places *and* sig figs
Format a number based on a required number of decimal places *and* sig figs
Our scientific application allows the user to configure the number of
significant figures and decimal places to use when displaying numeric
values. The formatting is currently being done with this code:-
var sigFigFormatted = valueToConvert.ToString("G" + numberOfSigFigs);
var theFullyFormattedValue = Convert.ToDouble(sigFigFormatted)
.ToString("F" + numberOfDecimalPlaces);
I don't like all this conversion to/from strings, and can't help thinking
there must be a more efficient solution?
Our scientific application allows the user to configure the number of
significant figures and decimal places to use when displaying numeric
values. The formatting is currently being done with this code:-
var sigFigFormatted = valueToConvert.ToString("G" + numberOfSigFigs);
var theFullyFormattedValue = Convert.ToDouble(sigFigFormatted)
.ToString("F" + numberOfDecimalPlaces);
I don't like all this conversion to/from strings, and can't help thinking
there must be a more efficient solution?
c# Getting the text from PDF as copy paste will do
c# Getting the text from PDF as copy paste will do
I am trying to get the text from PDF file. I tried using itextsharp and
sautinsoft.pdffocus.
Is ok but i get, but i want to get the same text as i would select all
text from pdf , copy, and paste.
The text i get with pdffocus pastebin.com/Cfcyvne0
The text i get with itextsharp pastebin.com/hsw8Q22i
And the text i get from doing CTRL + A, CTRL + C, CTRL +V in Adobe Reader:
pastebin.com/Rr7WiTJ0
The PDF i want to read:
i.stack.imgur.com/6LKsr.png
If I use copy paste I will get the first big column and then the second,
just like i want to. If I use PDfFocus or itextsharp the text of the
columns are combining.
My code for PDFFocus
SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();
f.OpenPdf("50.pdf");
text = f.ToText();
My code for itextsharp:
PdfReader reader = new PdfReader("50.pdf");
for (int page = 1; page <= reader.NumberOfPages; page++)
{
ITextExtractionStrategy its = new
LocationTextExtractionStrategy();
string s = PdfTextExtractor.GetTextFromPage(reader, page,its);
richTextBox1.Text = s;
} }
What should I Do?
I am trying to get the text from PDF file. I tried using itextsharp and
sautinsoft.pdffocus.
Is ok but i get, but i want to get the same text as i would select all
text from pdf , copy, and paste.
The text i get with pdffocus pastebin.com/Cfcyvne0
The text i get with itextsharp pastebin.com/hsw8Q22i
And the text i get from doing CTRL + A, CTRL + C, CTRL +V in Adobe Reader:
pastebin.com/Rr7WiTJ0
The PDF i want to read:
i.stack.imgur.com/6LKsr.png
If I use copy paste I will get the first big column and then the second,
just like i want to. If I use PDfFocus or itextsharp the text of the
columns are combining.
My code for PDFFocus
SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();
f.OpenPdf("50.pdf");
text = f.ToText();
My code for itextsharp:
PdfReader reader = new PdfReader("50.pdf");
for (int page = 1; page <= reader.NumberOfPages; page++)
{
ITextExtractionStrategy its = new
LocationTextExtractionStrategy();
string s = PdfTextExtractor.GetTextFromPage(reader, page,its);
richTextBox1.Text = s;
} }
What should I Do?
Tuesday, 10 September 2013
Loading views from various modules upon pressing Ribbon buttons in PRISM
Loading views from various modules upon pressing Ribbon buttons in PRISM
I'm developing WPF application using PRISM. I have two regions :
Ribbon region (which has got buttons to launch views from different
modules) View Region (in which views from different modules will be loaded
but one view at a time)
I have separate module assemblies for Ribbon and views (i.e.
CustomerModule, OrderModule, etc.). My ribbon has got buttons which should
load view from modules i.e. pressing "Customer" button should load the
specific view from "CustomerModule", pressing "OrderModule" should load
the specific view from "OrderModule", etc.
Can someone provide code snippet on how I should implement the command for
my ribbon buttons to launch the view from different module assemblies? I'm
not sure on how I can access the view module information into my ribbon
module?
Regards,
Krunal
I'm developing WPF application using PRISM. I have two regions :
Ribbon region (which has got buttons to launch views from different
modules) View Region (in which views from different modules will be loaded
but one view at a time)
I have separate module assemblies for Ribbon and views (i.e.
CustomerModule, OrderModule, etc.). My ribbon has got buttons which should
load view from modules i.e. pressing "Customer" button should load the
specific view from "CustomerModule", pressing "OrderModule" should load
the specific view from "OrderModule", etc.
Can someone provide code snippet on how I should implement the command for
my ribbon buttons to launch the view from different module assemblies? I'm
not sure on how I can access the view module information into my ribbon
module?
Regards,
Krunal
Passing a structure through a FIFO
Passing a structure through a FIFO
I have written a simple code where one process is passing a structure to
another process, the parent process is writing the data, but child process
is not able to access it. I have used fork() system call to create two
processes. But i have problem here the parent process i called twice and
child process is also called twice when i run the program. Can any one let
me know what mistake i am doing.
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <errno.h>
#include <sys/errno.h>
#include <fcntl.h>
#include <string.h>
#define MAX_LINE_LEN 100
#define FIFO_NAME "my_fifo"
typedef struct student_info {
char *name;
int age;
char *sex;
}student;
int w_byte_parent = 0, r_byte_parent = 0;
int w_byte_child = 0, r_byte_child = 0;
void do_child() {
int fifo;
char buffer[MAX_LINE_LEN];
int i = 0;
student child;
printf("Child opening FIFO \n");
if( (fifo = open(FIFO_NAME, O_RDWR)) < 0 ) {
perror("open in child failed");
exit(EXIT_FAILURE);
}
printf("Child reading from FIFO \n");
r_byte_child = read(fifo, child, sizeof(student));
if(r_byte_child < 0)
printf("Read failed by child process\n");
printf("%d Bytes read by child process\n", r_byte_child);
}
int main(int argc, char **argv) {
int fifo;
char buffer[MAX_LINE_LEN];
int ch = 0, i = 0;
/*
** Create a FIFO
*/
/* Parent creating FIFO */
if( (mkfifo(FIFO_NAME, 0666)) < 0) {
if( errno != EEXIST ) {
perror( "mkfifo" );
exit( EXIT_FAILURE );
}
}
/*
** Create other process
*/
switch(fork()) {
case -1:
perror("fork()");
exit(EXIT_FAILURE);
case 0: /* Child Process */
do_child();
break;
default:/* Parent Process */
break;
}
/* Pass a structure to FIFO */
student *info;
info = (student *)malloc( sizeof (student)) ;
info->name = (char *)calloc(sizeof(char), 10);
strcpy(info->name, "jack");
info->age = 27;
info->sex = (char *)calloc(sizeof(char), 10);
strcpy(info->sex , "Male");
/* Parent Opening FIFO */
printf("parent opening FIFO \n");
if( (fifo = open(FIFO_NAME, O_RDWR)) < 0 ) {
perror("open in parent failed");
exit(EXIT_FAILURE);
}
/*
** Write some thing into FIFO so child can read it
*/
printf("parent writing to FIFO \n");
w_byte_parent = write( fifo, info, sizeof(struct student_info));
if(w_byte_parent < 0)
printf("Nothing was written to FIFO by parent\n");
printf("Wrote %d bytes to FIFO\n",w_byte_parent);
}
I have written a simple code where one process is passing a structure to
another process, the parent process is writing the data, but child process
is not able to access it. I have used fork() system call to create two
processes. But i have problem here the parent process i called twice and
child process is also called twice when i run the program. Can any one let
me know what mistake i am doing.
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <errno.h>
#include <sys/errno.h>
#include <fcntl.h>
#include <string.h>
#define MAX_LINE_LEN 100
#define FIFO_NAME "my_fifo"
typedef struct student_info {
char *name;
int age;
char *sex;
}student;
int w_byte_parent = 0, r_byte_parent = 0;
int w_byte_child = 0, r_byte_child = 0;
void do_child() {
int fifo;
char buffer[MAX_LINE_LEN];
int i = 0;
student child;
printf("Child opening FIFO \n");
if( (fifo = open(FIFO_NAME, O_RDWR)) < 0 ) {
perror("open in child failed");
exit(EXIT_FAILURE);
}
printf("Child reading from FIFO \n");
r_byte_child = read(fifo, child, sizeof(student));
if(r_byte_child < 0)
printf("Read failed by child process\n");
printf("%d Bytes read by child process\n", r_byte_child);
}
int main(int argc, char **argv) {
int fifo;
char buffer[MAX_LINE_LEN];
int ch = 0, i = 0;
/*
** Create a FIFO
*/
/* Parent creating FIFO */
if( (mkfifo(FIFO_NAME, 0666)) < 0) {
if( errno != EEXIST ) {
perror( "mkfifo" );
exit( EXIT_FAILURE );
}
}
/*
** Create other process
*/
switch(fork()) {
case -1:
perror("fork()");
exit(EXIT_FAILURE);
case 0: /* Child Process */
do_child();
break;
default:/* Parent Process */
break;
}
/* Pass a structure to FIFO */
student *info;
info = (student *)malloc( sizeof (student)) ;
info->name = (char *)calloc(sizeof(char), 10);
strcpy(info->name, "jack");
info->age = 27;
info->sex = (char *)calloc(sizeof(char), 10);
strcpy(info->sex , "Male");
/* Parent Opening FIFO */
printf("parent opening FIFO \n");
if( (fifo = open(FIFO_NAME, O_RDWR)) < 0 ) {
perror("open in parent failed");
exit(EXIT_FAILURE);
}
/*
** Write some thing into FIFO so child can read it
*/
printf("parent writing to FIFO \n");
w_byte_parent = write( fifo, info, sizeof(struct student_info));
if(w_byte_parent < 0)
printf("Nothing was written to FIFO by parent\n");
printf("Wrote %d bytes to FIFO\n",w_byte_parent);
}
Google Maps iframe not showing droppings centered
Google Maps iframe not showing droppings centered
I am trying to add two maps to my website, each with two drop pins. Users
can switch between the two maps by clicking on tabs. I built the two maps
using the Google Maps Engine. The first map appears great, zoomed in to
the right amount and showing the two pins. However, the second map is
totally off. I tried doing what was suggested in this previous question
Marker not centering in iframe for google map but 1) it was still off and
2) I was unable to add a second pin to the map (plus the map did not look
as nice as the iframe I embedded directly on to the site).
Here is the JsFiddle: http://jsfiddle.net/SbH3Y/5/
Google Maps iframes:
<iframe
src="http://mapsengine.google.com/map/embed?mid=zzFoZgN4yc_E.kT_V1HoEUMHs"
width="461" height="350" scrolling='no' marginheight='0'
marginwidth='0'></iframe>
Thanks
I am trying to add two maps to my website, each with two drop pins. Users
can switch between the two maps by clicking on tabs. I built the two maps
using the Google Maps Engine. The first map appears great, zoomed in to
the right amount and showing the two pins. However, the second map is
totally off. I tried doing what was suggested in this previous question
Marker not centering in iframe for google map but 1) it was still off and
2) I was unable to add a second pin to the map (plus the map did not look
as nice as the iframe I embedded directly on to the site).
Here is the JsFiddle: http://jsfiddle.net/SbH3Y/5/
Google Maps iframes:
<iframe
src="http://mapsengine.google.com/map/embed?mid=zzFoZgN4yc_E.kT_V1HoEUMHs"
width="461" height="350" scrolling='no' marginheight='0'
marginwidth='0'></iframe>
Thanks
Insert date in MySql
Insert date in MySql
I need to insert dates on MySql Data Base. I want to insert a image name
in a row that have a "Nick" I want. I don't know what sentence I should
use. Thanks for your answers.
I need to insert dates on MySql Data Base. I want to insert a image name
in a row that have a "Nick" I want. I don't know what sentence I should
use. Thanks for your answers.
Dealing with nested NSDictionary keys
Dealing with nested NSDictionary keys
I need to grab a set of latitude and longitude points and use them to plot
map markers, but for some reason I cannot store them as a double value and
pass them into my method. I have tried logging out the the values using
this:
// Make the URL connection
NSString *urlAsString = @"...........";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// Error and success message handling.
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError
*error) {
if([data length] > 0 &&
error == nil){
NSData *jsonData = [NSData dataWithContentsOfURL:url];
if (jsonData != nil){
NSError *error = nil;
self.result = [NSJSONSerialization
JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers error:&error];
if(error == nil)
NSLog(@"Longitude: %@",[_result
valueForKeyPath:@"merchants.branches.longitude"]);
NSLog(@"Name: %@", [_result
valueForKeyPath:@"merchants.branches.name"]);
}
}
else if ([data length] == 0 &&
error == nil){
NSLog(@"Nothing was downloaded");
}
else if (error != nil){
NSLog(@"Error happened = %@", error);
}
}];
}
and this is the data that is sent back:
2013-09-10 10:14:35.775 JoySync[597:5803] Longitude: (
(
"-115.118958"
),
(
"-114.985397"
),
(
"-115.285782"
),
(
"-115.114960"
),
(
"-115.108841"
),
(
"-115.280380"
),
(
"-115.120628"
),
(
"-115.166840"
),
(
"-115.224167",
"-115.172226"
)
)
2013-09-10 10:14:35.776 JoySync[597:5803] Name: (
(
"36.110806"
),
(
"36.033428"
),
(
"36.158482"
),
(
"36.029102"
),
(
"36.076591"
),
(
"36.143978"
),
(
"35.997353"
),
(
"36.106091"
),
(
"36.238758",
"36.067402"
)
)
Now I'm trying to create a for loop that takes each of these values and
stores them as a doublevalue in order to send it through a method. Here's
that for loop:
for(NSDictionary *location in _result) {
CLLocationCoordinate2D annotationCoordinate =
CLLocationCoordinate2DMake([location
valueForKey:@"merchants.branches.latitude"]
doubleValue]]),
([location
valueForKey:@"merchants.branches.longitude"]
doubleValue]]);
Annotation *annotation = [[Annotation alloc] init];
annotation.coordinate = annotationCoordinate;
annotation.title = location[@"name"];
annotation.subtitle = nil;
[self.mapView addAnnotation:annotation];
I'm not sure what's going on, but it keeps sending me back an error. Any
ideas? I know it has to do with the keys I'm trying to call.
I need to grab a set of latitude and longitude points and use them to plot
map markers, but for some reason I cannot store them as a double value and
pass them into my method. I have tried logging out the the values using
this:
// Make the URL connection
NSString *urlAsString = @"...........";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
// Error and success message handling.
[NSURLConnection
sendAsynchronousRequest:urlRequest
queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError
*error) {
if([data length] > 0 &&
error == nil){
NSData *jsonData = [NSData dataWithContentsOfURL:url];
if (jsonData != nil){
NSError *error = nil;
self.result = [NSJSONSerialization
JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers error:&error];
if(error == nil)
NSLog(@"Longitude: %@",[_result
valueForKeyPath:@"merchants.branches.longitude"]);
NSLog(@"Name: %@", [_result
valueForKeyPath:@"merchants.branches.name"]);
}
}
else if ([data length] == 0 &&
error == nil){
NSLog(@"Nothing was downloaded");
}
else if (error != nil){
NSLog(@"Error happened = %@", error);
}
}];
}
and this is the data that is sent back:
2013-09-10 10:14:35.775 JoySync[597:5803] Longitude: (
(
"-115.118958"
),
(
"-114.985397"
),
(
"-115.285782"
),
(
"-115.114960"
),
(
"-115.108841"
),
(
"-115.280380"
),
(
"-115.120628"
),
(
"-115.166840"
),
(
"-115.224167",
"-115.172226"
)
)
2013-09-10 10:14:35.776 JoySync[597:5803] Name: (
(
"36.110806"
),
(
"36.033428"
),
(
"36.158482"
),
(
"36.029102"
),
(
"36.076591"
),
(
"36.143978"
),
(
"35.997353"
),
(
"36.106091"
),
(
"36.238758",
"36.067402"
)
)
Now I'm trying to create a for loop that takes each of these values and
stores them as a doublevalue in order to send it through a method. Here's
that for loop:
for(NSDictionary *location in _result) {
CLLocationCoordinate2D annotationCoordinate =
CLLocationCoordinate2DMake([location
valueForKey:@"merchants.branches.latitude"]
doubleValue]]),
([location
valueForKey:@"merchants.branches.longitude"]
doubleValue]]);
Annotation *annotation = [[Annotation alloc] init];
annotation.coordinate = annotationCoordinate;
annotation.title = location[@"name"];
annotation.subtitle = nil;
[self.mapView addAnnotation:annotation];
I'm not sure what's going on, but it keeps sending me back an error. Any
ideas? I know it has to do with the keys I'm trying to call.
Cannot send response to TCP client
Cannot send response to TCP client
I have a TCP server with the following code:
// Start a TCP Server
require('net').createServer(function (socket) {
// Handle incoming messages from clients.
socket.on('data', function (data) {
console.log("received:" + data);
// Do something with the data
//...
// Send result to client
socket.write('OK'); // Code added which make the server crash
});
}).listen(10000);
Each time a client connects, the server retrieve the data from the socket
and process it. This runs well if I do not try to send a response to the
client.
If I add the 'socket.write("ok");' line of code I get the following error
(seems like the socket is already closed ?):
"memoryUsage":{"rss":22474752,"heapTotal":16571136,"heapUsed":7168552}},"os":{"loadavg":[1.25634765625,1.111328125,1.00341796875],"uptime":185009},"trace":[{"column":11,"file":"net.js","function":"errnoException","line":884,"method":null,"native":false},{"column":19,"file":"net.js","function":"TCP.onread","line":539,"method":"onread","native":false}],"stack":["Error:
read ECONNRESET"," at errnoException (net.js:884:11)"," at TCP.onread
(net.js:539:19)"],"level":"error","message":"uncaughtException: read
ECONNRESET","timestamp":"2013-09-10T14:11:29.354Z"}
Any idea of what is wrong ?
I have a TCP server with the following code:
// Start a TCP Server
require('net').createServer(function (socket) {
// Handle incoming messages from clients.
socket.on('data', function (data) {
console.log("received:" + data);
// Do something with the data
//...
// Send result to client
socket.write('OK'); // Code added which make the server crash
});
}).listen(10000);
Each time a client connects, the server retrieve the data from the socket
and process it. This runs well if I do not try to send a response to the
client.
If I add the 'socket.write("ok");' line of code I get the following error
(seems like the socket is already closed ?):
"memoryUsage":{"rss":22474752,"heapTotal":16571136,"heapUsed":7168552}},"os":{"loadavg":[1.25634765625,1.111328125,1.00341796875],"uptime":185009},"trace":[{"column":11,"file":"net.js","function":"errnoException","line":884,"method":null,"native":false},{"column":19,"file":"net.js","function":"TCP.onread","line":539,"method":"onread","native":false}],"stack":["Error:
read ECONNRESET"," at errnoException (net.js:884:11)"," at TCP.onread
(net.js:539:19)"],"level":"error","message":"uncaughtException: read
ECONNRESET","timestamp":"2013-09-10T14:11:29.354Z"}
Any idea of what is wrong ?
sending an svg string using jquery ajax to mvc controller?
sending an svg string using jquery ajax to mvc controller?
I am trying to send an SVG string to the controller but it is null when it
reaches the server.
$.ajax({
type: "GET",
url: "/chart/GetChartImage",
data: JSON.stringify({ svgString: svg }),
dataType: "text",
contentType: "application/text; charset=utf-8"
}).done(function (data) {
debugger
});
the data being sent:
"{"svgString":"<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\"
xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"800\"
height=\"400\"><desc>Created with Highcharts 3.0.1</desc><defs><clipPath
id=\"highcharts-17\"><rect rx=\"0\" ry=\"0\" fill=\"none\" x=\"0\" y=\"0\"
width=\"9999\" height=\"400\"></rect></clipPath><clipPath
id=\"highcharts-18\"><rect fill=\"none\" x=\"0\" y=\"0\" width=\"780\"
height=\"344\"></rect></clipPath></defs><rect rx=\"5\" ry=\"5\"
fill=\"#FFF\" x=\"0\" y=\"0\" width=\"800\" height=\"400\"></rect><g
class=\"highcharts-grid\" ></g><g class=\"highcharts-grid\" ><path
fill=\"none\" d=\"M 10 316.5 L 790 316.5\" stroke=\"#C0C0C0\"
stroke-width=\"1\" opacity=\"1\"></path><path fill=\"none\" d=\"M 10
247.5 L 790 247.5\" stroke=\"#C0C0C0\" stroke-width=\"1\"
opacity=\"1\"></path><path fill=\"none\" d=\"M 10 178.5 L 790 178.5\"
stroke=\"#C0C0C0\" stroke-width=\"1\" opacity=\"1\"></path><path
fill=\"none\" d=\"M 10 109.5 L 790 109.5\" stroke=\"#C0C0C0\"
stroke-width=\"1\" opacity=\"1\"></path><path fill=\"none\" d=\"M 10 40.5
L 790 40.5\" stroke=\"#C0C0C0\" stroke-width=\"1\"
opacity=\"1\"></path><path fill=\"none\" d=\"M 10 384.5 L 790 384.5\"
stroke=\"#C0C0C0\" stroke-width=\"1\" opacity=\"1\"></path></g><g
class=\"highcharts-axis\" ><path fill=\"none\" d=\"M 119.5 385 L 119.5
386\" stroke=\"#C0D0E0\" stroke-width=\"1\" opacity=\"1\"></path><path
fill=\"none\" d=\"M 194.5 385 L 194.5 386\" stroke=\"#C0D0E0\"
stroke-width=\"1\" opacity=\"1\"></path><path fill=\"none\" d=\"M 268.5
385 L 268.5 386\" stroke=\"#C0D0E0\" stroke-width=\"1\"
opacity=\"1\"></path><path fill=\"none\" d=\"M 343.5 385 L 343.5 386\"
stroke=\"#C0D0E0\" stroke-width=\"1\" opacity=\"1\"></path><path
fill=\"none\" d=\"M 418.5 385 L 418.5 386\" stroke=\"#C0D0E0\"
stroke-width=\"1\" opacity=\"1\"></path><path fill=\"none\" d=\"M 492.5
385 L 492.5 386\" stroke=\"#C0D0E0\" stroke-width=\"1\"
opacity=\"1\"></path><path fill=\"none\" d=\"M 567.5 385 L 567.5 386\"
stroke=\"#C0D0E0\" stroke-width=\"1\" opacity=\"1\"></path><path
fill=\"none\" d=\"M 642.5 385 L 642.5 386\" stroke=\"#C0D0E0\"
stroke-width=\"1\" opacity=\"1\"></path><path fill=\"none\" d=\"M 716.5
385 L 716.5 386\" stroke=\"#C0D0E0\" stroke-width=\"1\"
opacity=\"1\"></path><path fill=\"none\" d=\"M 44.5 385 L 44.5 386\"
stroke=\"#C0D0E0\" stroke-width=\"1\" opacity=\"1\"></path><path
fill=\"none\" d=\"M 10 384.5 L 790 384.5\" stroke=\"#C0D0E0\"
stroke-width=\"1\" visibility=\"visible\"></path></g><g
class=\"highcharts-axis\" ></g><g class=\"highcharts-series-group\" ><g
class=\"highcharts-series\" visibility=\"visible\"
transform=\"translate(10,40) scale(1 1)\"
clip-path=\"url(#highcharts-18)\"><path fill=\"none\" d=\"M
35.45454545454545 303.6 L 72.77511961722489 220.8 L 110.09569377990431
41.4 L 147.41626794258374 331.2 L 184.73684210526315 276 L
222.05741626794259 303.6 L 259.377990430622 262.2 L 296.69856459330146
317.4 L 334.01913875598086 289.8 L 371.3397129186603 303.6 L
408.66028708133973 289.8 L 445.98086124401914 303.6 L 483.3014354066986
276 L 520.622009569378 303.6 L 557.9425837320574 289.8 L 595.2631578947369
303.6 L 669.9043062200957 234.6 L 707.2248803827752 331.2 L
744.5454545454546 234.6\" stroke=\"#2f7ed8\" stroke-width=\"2\"
></path></g><g class=\"highcharts-markers\" visibility=\"visible\"
transform=\"translate(10,40) scale(1 1)\" clip-path=\"none\"><path
fill=\"#2f7ed8\" d=\"M 744.5454545454546 230.6 C 749.8734545454546 230.6
749.8734545454546 238.6 744.5454545454546 238.6 C 739.2174545454546 238.6
739.2174545454546 230.6 744.5454545454546 230.6 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 707.2248803827752 327.2 C 712.5528803827751 327.2
712.5528803827751 335.2 707.2248803827752 335.2 C 701.8968803827752 335.2
701.8968803827752 327.2 707.2248803827752 327.2 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 669.9043062200957 230.6 C 675.2323062200957 230.6
675.2323062200957 238.6 669.9043062200957 238.6 C 664.5763062200957 238.6
664.5763062200957 230.6 669.9043062200957 230.6 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 595.2631578947369 299.6 C 600.5911578947369 299.6
600.5911578947369 307.6 595.2631578947369 307.6 C 589.9351578947369 307.6
589.9351578947369 299.6 595.2631578947369 299.6 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 557.9425837320574 285.8 C 563.2705837320574 285.8
563.2705837320574 293.8 557.9425837320574 293.8 C 552.6145837320574 293.8
552.6145837320574 285.8 557.9425837320574 285.8 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 520.622009569378 299.6 C 525.9500095693779 299.6
525.9500095693779 307.6 520.622009569378 307.6 C 515.294009569378 307.6
515.294009569378 299.6 520.622009569378 299.6 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 483.3014354066986 272 C 488.6294354066986 272
488.6294354066986 280 483.3014354066986 280 C 477.9734354066986 280
477.9734354066986 272 483.3014354066986 272 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 445.98086124401914 299.6 C 451.3088612440191 299.6
451.3088612440191 307.6 445.98086124401914 307.6 C 440.65286124401916
307.6 440.65286124401916 299.6 445.98086124401914 299.6 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 408.66028708133973 285.8 C 413.9882870813397 285.8
413.9882870813397 293.8 408.66028708133973 293.8 C 403.33228708133976
293.8 403.33228708133976 285.8 408.66028708133973 285.8 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 371.3397129186603 299.6 C 376.6677129186603 299.6
376.6677129186603 307.6 371.3397129186603 307.6 C 366.01171291866035 307.6
366.01171291866035 299.6 371.3397129186603 299.6 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 334.01913875598086 285.8 C 339.34713875598084 285.8
339.34713875598084 293.8 334.01913875598086 293.8 C 328.6911387559809
293.8 328.6911387559809 285.8 334.01913875598086 285.8 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 296.69856459330146 313.4 C 302.02656459330143 313.4
302.02656459330143 321.4 296.69856459330146 321.4 C 291.3705645933015
321.4 291.3705645933015 313.4 296.69856459330146 313.4 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 259.377990430622 258.2 C 264.70599043062197 258.2
264.70599043062197 266.2 259.377990430622 266.2 C 254.049990430622 266.2
254.049990430622 258.2 259.377990430622 258.2 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 222.05741626794259 299.6 C 227.3854162679426 299.6
227.3854162679426 307.6 222.05741626794259 307.6 C 216.72941626794258
307.6 216.72941626794258 299.6 222.05741626794259 299.6 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 184.73684210526315 272 C 190.06484210526315 272
190.06484210526315 280 184.73684210526315 280 C 179.40884210526315 280
179.40884210526315 272 184.73684210526315 272 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 147.41626794258374 327.2 C 152.74426794258375 327.2
152.74426794258375 335.2 147.41626794258374 335.2 C 142.08826794258374
335.2 142.08826794258374 327.2 147.41626794258374 327.2 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 110.09569377990431 37.4 C 115.42369377990431 37.4
115.42369377990431 45.4 110.09569377990431 45.4 C 104.7676937799043 45.4
104.7676937799043 37.4 110.09569377990431 37.4 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 72.77511961722489 216.8 C 78.10311961722489 216.8
78.10311961722489 224.8 72.77511961722489 224.8 C 67.44711961722489 224.8
67.44711961722489 216.8 72.77511961722489 216.8 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 35.45454545454545 299.6 C 40.782545454545456 299.6
40.782545454545456 307.6 35.45454545454545 307.6 C 30.126545454545454
307.6 30.126545454545454 299.6 35.45454545454545 299.6 Z\"></path><path
fill=\"none\" d=\"M 25.454545454545453 303.6 L 35.45454545454545 303.6 L
72.77511961722489 220.8 L 110.09569377990431 41.4 L 147.41626794258374
331.2 L 184.73684210526315 276 L 222.05741626794259 303.6 L
259.377990430622 262.2 L 296.69856459330146 317.4 L 334.01913875598086
289.8 L 371.3397129186603 303.6 L 408.66028708133973 289.8 L
445.98086124401914 303.6 L 483.3014354066986 276 L 520.622009569378 303.6
L 557.9425837320574 289.8 L 595.2631578947369 303.6 L 669.9043062200957
234.6 L 707.2248803827752 331.2 L 744.5454545454546 234.6 L
754.5454545454546 234.6\" class=\"highcharts-tracker highcharts-tracker\"
stroke-linejoin=\"round\" visibility=\"visible\" stroke-opacity=\"0.0001\"
stroke=\"rgb(192,192,192)\" stroke-width=\"22\"
style=\"\"></path></g></g><text x=\"400\" y=\"25\"
style=\"font-family:'lucida grande', 'lucida sans unicode', verdana,
arial, helvetica, sans-serif;font-size:10px;color:#274b6d;fill:#274b6d;\"
text-anchor=\"middle\" class=\"highcharts-title\" ><tspan
x=\"400\">Competitor Trend</tspan></text><g class=\"highcharts-legend\"
transform=\"translate(296,30)\"><rect rx=\"5\" ry=\"5\" fill=\"none\"
x=\"0.5\" y=\"0.5\" width=\"208\" height=\"26\" stroke=\"#909090\"
stroke-width=\"1\" visibility=\"visible\"></rect><g
clip-path=\"url(#highcharts-17)\"><g><g class=\"highcharts-legend-item\"
transform=\"translate(8,3)\"><path fill=\"none\" d=\"M 0 11 L 16 11\"
stroke=\"#2f7ed8\" stroke-width=\"2\"></path><path fill=\"#2f7ed8\" d=\"M
8 7 C 13.328 7 13.328 15 8 15 C 2.6719999999999997 15 2.6719999999999997 7
8 7 Z\"></path><text x=\"21\" y=\"15\" style=\"font-family:'lucida
grande', 'lucida sans unicode', verdana, arial, helvetica,
sans-serif;font-size:12px;cursor:pointer;color:#274b6d;fill:#274b6d;\"
text-anchor=\"start\" ><tspan x=\"21\">European Commission
(2261)</tspan></text></g></g></g></g><g class=\"highcharts-axis-labels\"
></g><g class=\"highcharts-axis-labels\" ></g><g
class=\"highcharts-tooltip\"
style=\"cursor:default;padding:0;white-space:nowrap;\"
visibility=\"hidden\"><rect rx=\"3\" ry=\"3\" fill=\"none\" x=\"0.5\"
y=\"0.5\" width=\"16\" height=\"16\" fill-opacity=\"0.85\"
stroke=\"black\" stroke-opacity=\"0.049999999999999996\"
stroke-width=\"5\" transform=\"translate(1, 1)\"></rect><rect rx=\"3\"
ry=\"3\" fill=\"none\" x=\"0.5\" y=\"0.5\" width=\"16\" height=\"16\"
fill-opacity=\"0.85\" stroke=\"black\"
stroke-opacity=\"0.09999999999999999\" stroke-width=\"3\"
transform=\"translate(1, 1)\"></rect><rect rx=\"3\" ry=\"3\" fill=\"none\"
x=\"0.5\" y=\"0.5\" width=\"16\" height=\"16\" fill-opacity=\"0.85\"
stroke=\"black\" stroke-opacity=\"0.15\" stroke-width=\"1\"
transform=\"translate(1, 1)\"></rect><rect rx=\"3\" ry=\"3\"
fill=\"rgb(255,255,255)\" x=\"0.5\" y=\"0.5\" width=\"16\" height=\"16\"
fill-opacity=\"0.85\"></rect><text x=\"8\" y=\"21\"
style=\"font-family:'lucida grande', 'lucida sans unicode', verdana,
arial, helvetica, sans-serif;font-size:12px;color:#333333;fill:#333333;\"
></text></g></svg>"}"
the controller:
[HttpGet]
public ActionResult GetChartImage(string svgString)
{
byte[] imageBytes;
byte[] bytes = new byte[svgString.Length * sizeof(char)];
System.Buffer.BlockCopy(svgString.ToCharArray(), 0, bytes, 0,
bytes.Length);
//var byteArray = Encoding.ASCII.GetBytes(svg);
using (var stream = new MemoryStream(bytes))
{
var svgDocument = SvgDocument.Open(stream);
var bitmap = svgDocument.Draw();
bitmap.Save(stream, ImageFormat.Png);
imageBytes = stream.ToArray();
}
return new FileContentResult(imageBytes, "image/png");
}
I am trying to send an SVG string to the controller but it is null when it
reaches the server.
$.ajax({
type: "GET",
url: "/chart/GetChartImage",
data: JSON.stringify({ svgString: svg }),
dataType: "text",
contentType: "application/text; charset=utf-8"
}).done(function (data) {
debugger
});
the data being sent:
"{"svgString":"<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\"
xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"800\"
height=\"400\"><desc>Created with Highcharts 3.0.1</desc><defs><clipPath
id=\"highcharts-17\"><rect rx=\"0\" ry=\"0\" fill=\"none\" x=\"0\" y=\"0\"
width=\"9999\" height=\"400\"></rect></clipPath><clipPath
id=\"highcharts-18\"><rect fill=\"none\" x=\"0\" y=\"0\" width=\"780\"
height=\"344\"></rect></clipPath></defs><rect rx=\"5\" ry=\"5\"
fill=\"#FFF\" x=\"0\" y=\"0\" width=\"800\" height=\"400\"></rect><g
class=\"highcharts-grid\" ></g><g class=\"highcharts-grid\" ><path
fill=\"none\" d=\"M 10 316.5 L 790 316.5\" stroke=\"#C0C0C0\"
stroke-width=\"1\" opacity=\"1\"></path><path fill=\"none\" d=\"M 10
247.5 L 790 247.5\" stroke=\"#C0C0C0\" stroke-width=\"1\"
opacity=\"1\"></path><path fill=\"none\" d=\"M 10 178.5 L 790 178.5\"
stroke=\"#C0C0C0\" stroke-width=\"1\" opacity=\"1\"></path><path
fill=\"none\" d=\"M 10 109.5 L 790 109.5\" stroke=\"#C0C0C0\"
stroke-width=\"1\" opacity=\"1\"></path><path fill=\"none\" d=\"M 10 40.5
L 790 40.5\" stroke=\"#C0C0C0\" stroke-width=\"1\"
opacity=\"1\"></path><path fill=\"none\" d=\"M 10 384.5 L 790 384.5\"
stroke=\"#C0C0C0\" stroke-width=\"1\" opacity=\"1\"></path></g><g
class=\"highcharts-axis\" ><path fill=\"none\" d=\"M 119.5 385 L 119.5
386\" stroke=\"#C0D0E0\" stroke-width=\"1\" opacity=\"1\"></path><path
fill=\"none\" d=\"M 194.5 385 L 194.5 386\" stroke=\"#C0D0E0\"
stroke-width=\"1\" opacity=\"1\"></path><path fill=\"none\" d=\"M 268.5
385 L 268.5 386\" stroke=\"#C0D0E0\" stroke-width=\"1\"
opacity=\"1\"></path><path fill=\"none\" d=\"M 343.5 385 L 343.5 386\"
stroke=\"#C0D0E0\" stroke-width=\"1\" opacity=\"1\"></path><path
fill=\"none\" d=\"M 418.5 385 L 418.5 386\" stroke=\"#C0D0E0\"
stroke-width=\"1\" opacity=\"1\"></path><path fill=\"none\" d=\"M 492.5
385 L 492.5 386\" stroke=\"#C0D0E0\" stroke-width=\"1\"
opacity=\"1\"></path><path fill=\"none\" d=\"M 567.5 385 L 567.5 386\"
stroke=\"#C0D0E0\" stroke-width=\"1\" opacity=\"1\"></path><path
fill=\"none\" d=\"M 642.5 385 L 642.5 386\" stroke=\"#C0D0E0\"
stroke-width=\"1\" opacity=\"1\"></path><path fill=\"none\" d=\"M 716.5
385 L 716.5 386\" stroke=\"#C0D0E0\" stroke-width=\"1\"
opacity=\"1\"></path><path fill=\"none\" d=\"M 44.5 385 L 44.5 386\"
stroke=\"#C0D0E0\" stroke-width=\"1\" opacity=\"1\"></path><path
fill=\"none\" d=\"M 10 384.5 L 790 384.5\" stroke=\"#C0D0E0\"
stroke-width=\"1\" visibility=\"visible\"></path></g><g
class=\"highcharts-axis\" ></g><g class=\"highcharts-series-group\" ><g
class=\"highcharts-series\" visibility=\"visible\"
transform=\"translate(10,40) scale(1 1)\"
clip-path=\"url(#highcharts-18)\"><path fill=\"none\" d=\"M
35.45454545454545 303.6 L 72.77511961722489 220.8 L 110.09569377990431
41.4 L 147.41626794258374 331.2 L 184.73684210526315 276 L
222.05741626794259 303.6 L 259.377990430622 262.2 L 296.69856459330146
317.4 L 334.01913875598086 289.8 L 371.3397129186603 303.6 L
408.66028708133973 289.8 L 445.98086124401914 303.6 L 483.3014354066986
276 L 520.622009569378 303.6 L 557.9425837320574 289.8 L 595.2631578947369
303.6 L 669.9043062200957 234.6 L 707.2248803827752 331.2 L
744.5454545454546 234.6\" stroke=\"#2f7ed8\" stroke-width=\"2\"
></path></g><g class=\"highcharts-markers\" visibility=\"visible\"
transform=\"translate(10,40) scale(1 1)\" clip-path=\"none\"><path
fill=\"#2f7ed8\" d=\"M 744.5454545454546 230.6 C 749.8734545454546 230.6
749.8734545454546 238.6 744.5454545454546 238.6 C 739.2174545454546 238.6
739.2174545454546 230.6 744.5454545454546 230.6 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 707.2248803827752 327.2 C 712.5528803827751 327.2
712.5528803827751 335.2 707.2248803827752 335.2 C 701.8968803827752 335.2
701.8968803827752 327.2 707.2248803827752 327.2 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 669.9043062200957 230.6 C 675.2323062200957 230.6
675.2323062200957 238.6 669.9043062200957 238.6 C 664.5763062200957 238.6
664.5763062200957 230.6 669.9043062200957 230.6 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 595.2631578947369 299.6 C 600.5911578947369 299.6
600.5911578947369 307.6 595.2631578947369 307.6 C 589.9351578947369 307.6
589.9351578947369 299.6 595.2631578947369 299.6 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 557.9425837320574 285.8 C 563.2705837320574 285.8
563.2705837320574 293.8 557.9425837320574 293.8 C 552.6145837320574 293.8
552.6145837320574 285.8 557.9425837320574 285.8 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 520.622009569378 299.6 C 525.9500095693779 299.6
525.9500095693779 307.6 520.622009569378 307.6 C 515.294009569378 307.6
515.294009569378 299.6 520.622009569378 299.6 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 483.3014354066986 272 C 488.6294354066986 272
488.6294354066986 280 483.3014354066986 280 C 477.9734354066986 280
477.9734354066986 272 483.3014354066986 272 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 445.98086124401914 299.6 C 451.3088612440191 299.6
451.3088612440191 307.6 445.98086124401914 307.6 C 440.65286124401916
307.6 440.65286124401916 299.6 445.98086124401914 299.6 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 408.66028708133973 285.8 C 413.9882870813397 285.8
413.9882870813397 293.8 408.66028708133973 293.8 C 403.33228708133976
293.8 403.33228708133976 285.8 408.66028708133973 285.8 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 371.3397129186603 299.6 C 376.6677129186603 299.6
376.6677129186603 307.6 371.3397129186603 307.6 C 366.01171291866035 307.6
366.01171291866035 299.6 371.3397129186603 299.6 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 334.01913875598086 285.8 C 339.34713875598084 285.8
339.34713875598084 293.8 334.01913875598086 293.8 C 328.6911387559809
293.8 328.6911387559809 285.8 334.01913875598086 285.8 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 296.69856459330146 313.4 C 302.02656459330143 313.4
302.02656459330143 321.4 296.69856459330146 321.4 C 291.3705645933015
321.4 291.3705645933015 313.4 296.69856459330146 313.4 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 259.377990430622 258.2 C 264.70599043062197 258.2
264.70599043062197 266.2 259.377990430622 266.2 C 254.049990430622 266.2
254.049990430622 258.2 259.377990430622 258.2 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 222.05741626794259 299.6 C 227.3854162679426 299.6
227.3854162679426 307.6 222.05741626794259 307.6 C 216.72941626794258
307.6 216.72941626794258 299.6 222.05741626794259 299.6 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 184.73684210526315 272 C 190.06484210526315 272
190.06484210526315 280 184.73684210526315 280 C 179.40884210526315 280
179.40884210526315 272 184.73684210526315 272 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 147.41626794258374 327.2 C 152.74426794258375 327.2
152.74426794258375 335.2 147.41626794258374 335.2 C 142.08826794258374
335.2 142.08826794258374 327.2 147.41626794258374 327.2 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 110.09569377990431 37.4 C 115.42369377990431 37.4
115.42369377990431 45.4 110.09569377990431 45.4 C 104.7676937799043 45.4
104.7676937799043 37.4 110.09569377990431 37.4 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 72.77511961722489 216.8 C 78.10311961722489 216.8
78.10311961722489 224.8 72.77511961722489 224.8 C 67.44711961722489 224.8
67.44711961722489 216.8 72.77511961722489 216.8 Z\"></path><path
fill=\"#2f7ed8\" d=\"M 35.45454545454545 299.6 C 40.782545454545456 299.6
40.782545454545456 307.6 35.45454545454545 307.6 C 30.126545454545454
307.6 30.126545454545454 299.6 35.45454545454545 299.6 Z\"></path><path
fill=\"none\" d=\"M 25.454545454545453 303.6 L 35.45454545454545 303.6 L
72.77511961722489 220.8 L 110.09569377990431 41.4 L 147.41626794258374
331.2 L 184.73684210526315 276 L 222.05741626794259 303.6 L
259.377990430622 262.2 L 296.69856459330146 317.4 L 334.01913875598086
289.8 L 371.3397129186603 303.6 L 408.66028708133973 289.8 L
445.98086124401914 303.6 L 483.3014354066986 276 L 520.622009569378 303.6
L 557.9425837320574 289.8 L 595.2631578947369 303.6 L 669.9043062200957
234.6 L 707.2248803827752 331.2 L 744.5454545454546 234.6 L
754.5454545454546 234.6\" class=\"highcharts-tracker highcharts-tracker\"
stroke-linejoin=\"round\" visibility=\"visible\" stroke-opacity=\"0.0001\"
stroke=\"rgb(192,192,192)\" stroke-width=\"22\"
style=\"\"></path></g></g><text x=\"400\" y=\"25\"
style=\"font-family:'lucida grande', 'lucida sans unicode', verdana,
arial, helvetica, sans-serif;font-size:10px;color:#274b6d;fill:#274b6d;\"
text-anchor=\"middle\" class=\"highcharts-title\" ><tspan
x=\"400\">Competitor Trend</tspan></text><g class=\"highcharts-legend\"
transform=\"translate(296,30)\"><rect rx=\"5\" ry=\"5\" fill=\"none\"
x=\"0.5\" y=\"0.5\" width=\"208\" height=\"26\" stroke=\"#909090\"
stroke-width=\"1\" visibility=\"visible\"></rect><g
clip-path=\"url(#highcharts-17)\"><g><g class=\"highcharts-legend-item\"
transform=\"translate(8,3)\"><path fill=\"none\" d=\"M 0 11 L 16 11\"
stroke=\"#2f7ed8\" stroke-width=\"2\"></path><path fill=\"#2f7ed8\" d=\"M
8 7 C 13.328 7 13.328 15 8 15 C 2.6719999999999997 15 2.6719999999999997 7
8 7 Z\"></path><text x=\"21\" y=\"15\" style=\"font-family:'lucida
grande', 'lucida sans unicode', verdana, arial, helvetica,
sans-serif;font-size:12px;cursor:pointer;color:#274b6d;fill:#274b6d;\"
text-anchor=\"start\" ><tspan x=\"21\">European Commission
(2261)</tspan></text></g></g></g></g><g class=\"highcharts-axis-labels\"
></g><g class=\"highcharts-axis-labels\" ></g><g
class=\"highcharts-tooltip\"
style=\"cursor:default;padding:0;white-space:nowrap;\"
visibility=\"hidden\"><rect rx=\"3\" ry=\"3\" fill=\"none\" x=\"0.5\"
y=\"0.5\" width=\"16\" height=\"16\" fill-opacity=\"0.85\"
stroke=\"black\" stroke-opacity=\"0.049999999999999996\"
stroke-width=\"5\" transform=\"translate(1, 1)\"></rect><rect rx=\"3\"
ry=\"3\" fill=\"none\" x=\"0.5\" y=\"0.5\" width=\"16\" height=\"16\"
fill-opacity=\"0.85\" stroke=\"black\"
stroke-opacity=\"0.09999999999999999\" stroke-width=\"3\"
transform=\"translate(1, 1)\"></rect><rect rx=\"3\" ry=\"3\" fill=\"none\"
x=\"0.5\" y=\"0.5\" width=\"16\" height=\"16\" fill-opacity=\"0.85\"
stroke=\"black\" stroke-opacity=\"0.15\" stroke-width=\"1\"
transform=\"translate(1, 1)\"></rect><rect rx=\"3\" ry=\"3\"
fill=\"rgb(255,255,255)\" x=\"0.5\" y=\"0.5\" width=\"16\" height=\"16\"
fill-opacity=\"0.85\"></rect><text x=\"8\" y=\"21\"
style=\"font-family:'lucida grande', 'lucida sans unicode', verdana,
arial, helvetica, sans-serif;font-size:12px;color:#333333;fill:#333333;\"
></text></g></svg>"}"
the controller:
[HttpGet]
public ActionResult GetChartImage(string svgString)
{
byte[] imageBytes;
byte[] bytes = new byte[svgString.Length * sizeof(char)];
System.Buffer.BlockCopy(svgString.ToCharArray(), 0, bytes, 0,
bytes.Length);
//var byteArray = Encoding.ASCII.GetBytes(svg);
using (var stream = new MemoryStream(bytes))
{
var svgDocument = SvgDocument.Open(stream);
var bitmap = svgDocument.Draw();
bitmap.Save(stream, ImageFormat.Png);
imageBytes = stream.ToArray();
}
return new FileContentResult(imageBytes, "image/png");
}
Subscribe to:
Comments (Atom)