url rewrite with multiple param
I need to convert an URL, with some params like this:
/anytext/l1v5n3
to a normal URL with querystring:
/index.php?liv=1&id=5&lang=3
the params l, v, n could be in any order and the following value could be
numeric and can include special symbols (+,-, etc.)
Any help will be appreciated!
Thursday, 3 October 2013
Wednesday, 2 October 2013
Sorted String List Array Based- Add Method
Sorted String List Array Based- Add Method
public void add(String item) throws ListException
// Inserts item into its proper position in a sorted list
// Throws an exception if the item connot be placed on the list
{
try
{
}
catch(Exception e)
{
throw new ListException("Add to List failed: " + e.toString());
}
}
i need help with the add method, how would go about this?
public void add(String item) throws ListException
// Inserts item into its proper position in a sorted list
// Throws an exception if the item connot be placed on the list
{
try
{
}
catch(Exception e)
{
throw new ListException("Add to List failed: " + e.toString());
}
}
i need help with the add method, how would go about this?
jQuery plugin's syntax is too strange
jQuery plugin's syntax is too strange
I have a little trouble about the meaning of syntax "(function( $ )" and
"(jQuery)" in the below code.
(function( $ ){
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};})(jQuery);
Can you please explain what meaning of them ?
If I want to change phrase "(jQuery)" in the above code to "(abc)" then
how to do it and how to use it ?
Thanks for taking the time to answer my question.
I have a little trouble about the meaning of syntax "(function( $ )" and
"(jQuery)" in the below code.
(function( $ ){
$.fn.myPlugin = function() {
// Do your awesome plugin stuff here
};})(jQuery);
Can you please explain what meaning of them ?
If I want to change phrase "(jQuery)" in the above code to "(abc)" then
how to do it and how to use it ?
Thanks for taking the time to answer my question.
flag 0 or 1 on a foreach loop php
flag 0 or 1 on a foreach loop php
I have a query always results to two rows. How can i flag the first row
equal 1 and the second is 0?
here is the code
$rows = array(
array('number' => 1),
array('number' => 2)
);
$i=1;
foreach($rows as $r) {
if($i == 1) {
$i = 1;
} else {
$i = 0;
}
//Flag first row as 1
//Flag second row as 0;
}
Is this correct?
I have a query always results to two rows. How can i flag the first row
equal 1 and the second is 0?
here is the code
$rows = array(
array('number' => 1),
array('number' => 2)
);
$i=1;
foreach($rows as $r) {
if($i == 1) {
$i = 1;
} else {
$i = 0;
}
//Flag first row as 1
//Flag second row as 0;
}
Is this correct?
Tuesday, 1 October 2013
What is the difference between a frame got from a video device and image loaded after saving the frame
What is the difference between a frame got from a video device and image
loaded after saving the frame
In matlab I am not getting what should I get after working on a frame. But
I get if i write that frame in a file and read it back and it works fine.
I = step(vidDevice); % Acquire single frame
imwrite(I,'tmp.jpg');
im=imread('tmp.jpg');
out=skin_detect(im);
But I get only the black image if I work directly on the frame.
I = step(vidDevice); % Acquire single frame
out=skin_detect(im);
loaded after saving the frame
In matlab I am not getting what should I get after working on a frame. But
I get if i write that frame in a file and read it back and it works fine.
I = step(vidDevice); % Acquire single frame
imwrite(I,'tmp.jpg');
im=imread('tmp.jpg');
out=skin_detect(im);
But I get only the black image if I work directly on the frame.
I = step(vidDevice); % Acquire single frame
out=skin_detect(im);
Portable JNDI name for DataSource
Portable JNDI name for DataSource
I have a EJB with field
@Resource(lookup = "jdbc/sampleDS")
private DataSource ds;
and persistence.xml with entry
<jta-data-source>jdbc/sampleDS</jta-data-source>
I want to make the application easy portable across different Java EE
servers. But in JBoss JNDI name has to start with java:/ or java:jboss/.
At the same time Glassfish doesn't like symbol ':'. How to achieve
portability? I tried to set attribute use-java-context="false" for data
source instandalone.xml, but it didn't help me.
Thanks in advance.
I have a EJB with field
@Resource(lookup = "jdbc/sampleDS")
private DataSource ds;
and persistence.xml with entry
<jta-data-source>jdbc/sampleDS</jta-data-source>
I want to make the application easy portable across different Java EE
servers. But in JBoss JNDI name has to start with java:/ or java:jboss/.
At the same time Glassfish doesn't like symbol ':'. How to achieve
portability? I tried to set attribute use-java-context="false" for data
source instandalone.xml, but it didn't help me.
Thanks in advance.
cannot open reg backup file because in use (by who though)
cannot open reg backup file because in use (by who though)
I don't know if this is bad so please forgive me ahead of time.
Wasn't sure if this would be considered repost:
http://stackoverflow.com/q/19014447/139698
or if it wouldn't have gotten visibility here?
I don't know if this is bad so please forgive me ahead of time.
Wasn't sure if this would be considered repost:
http://stackoverflow.com/q/19014447/139698
or if it wouldn't have gotten visibility here?
Prove/disprove statements regarding continuous functions.
Prove/disprove statements regarding continuous functions.
I found some old math tests from my school years and thought it might be
fun to see what I still remember. The answer is simply, not as much as I
hoped for. I'm having trouble proving/disproving these statements, not
sure where to go with it.
If f is a continuous function on the closed interval [a,b] then f([a,b] =
[f(a),f(b)] or f([a,b]) = [f(b),f(a)].
There exists a function f that maps ]0,1[ to R/Z+
Is there a continuous function that maps ]0,10] to R?
I'm pretty sure that when I get 2, 3 will follow closely, hopefully at least.
I found some old math tests from my school years and thought it might be
fun to see what I still remember. The answer is simply, not as much as I
hoped for. I'm having trouble proving/disproving these statements, not
sure where to go with it.
If f is a continuous function on the closed interval [a,b] then f([a,b] =
[f(a),f(b)] or f([a,b]) = [f(b),f(a)].
There exists a function f that maps ]0,1[ to R/Z+
Is there a continuous function that maps ]0,10] to R?
I'm pretty sure that when I get 2, 3 will follow closely, hopefully at least.
Monday, 30 September 2013
Software which opens PSD files correctly on Ubuntu?
Software which opens PSD files correctly on Ubuntu?
I am stuck in trying to find a software which can render PSD files
properly under Ubuntu. I have tried GIMP and Krita but they both have
problems with that - especially the clipping mask functionality.
Is there a working solution for Ubuntu?
I am stuck in trying to find a software which can render PSD files
properly under Ubuntu. I have tried GIMP and Krita but they both have
problems with that - especially the clipping mask functionality.
Is there a working solution for Ubuntu?
Why does $\frac{d}{d\theta} \theta\prod_{i=1}^nx_i = \sum_{i=1}^nx_i$
Why does $\frac{d}{d\theta} \theta\prod_{i=1}^nx_i = \sum_{i=1}^nx_i$
Is this just the product rule? I have this in my notes but I didn't think
anything of it and now I'm wondering how this happens?
Edit: Im working with maximum likelihood estimation and in my notes I have
that the likelihood funciton $=L(x;\theta)=\prod_{i=1}^nf(x;\theta)$ where
$x$ is the variable and $\theta$ is the parameter of a probability
distribution. To estimate I was told that we take the log of the
likelihood function e.i. $ln(L)$, then take it's derivative to estimate
the parameter. The function I'm working with is $f(x;\theta)=(\theta
+1)x^{\theta}$. So $$L(x;\theta)=\prod_{i=1}^n(\theta
+1)x_i^{\theta}=(\theta+1)^n\prod_{i=1}^nx_i^{\theta}$$ Now
$$ln(L(x;\theta))=n*ln(\theta+1)+\theta
ln\left(\prod_{i=1}^nx_i\right)$$Here's where I'm confused, I have in my
notes that $$\frac{dL}{d\theta}=\frac{n}{\theta+1}+\sum_{i=1}^nln(x_i)$$
Why does the product of $x_i$ become the summation of $x_i$?
Is this just the product rule? I have this in my notes but I didn't think
anything of it and now I'm wondering how this happens?
Edit: Im working with maximum likelihood estimation and in my notes I have
that the likelihood funciton $=L(x;\theta)=\prod_{i=1}^nf(x;\theta)$ where
$x$ is the variable and $\theta$ is the parameter of a probability
distribution. To estimate I was told that we take the log of the
likelihood function e.i. $ln(L)$, then take it's derivative to estimate
the parameter. The function I'm working with is $f(x;\theta)=(\theta
+1)x^{\theta}$. So $$L(x;\theta)=\prod_{i=1}^n(\theta
+1)x_i^{\theta}=(\theta+1)^n\prod_{i=1}^nx_i^{\theta}$$ Now
$$ln(L(x;\theta))=n*ln(\theta+1)+\theta
ln\left(\prod_{i=1}^nx_i\right)$$Here's where I'm confused, I have in my
notes that $$\frac{dL}{d\theta}=\frac{n}{\theta+1}+\sum_{i=1}^nln(x_i)$$
Why does the product of $x_i$ become the summation of $x_i$?
How to test your client server program
How to test your client server program
I'm making a multiplayer game and often i want to test out if it perfectly
works on global network, because sometime it's just works locally, so how
could i do that without sending my client to friend to test it out.
I'm making a multiplayer game and often i want to test out if it perfectly
works on global network, because sometime it's just works locally, so how
could i do that without sending my client to friend to test it out.
Authenticate API-access against URL parameter instead of Authorization-header
Authenticate API-access against URL parameter instead of Authorization-header
I'm are using WSO2 API Manager for managing our public API's. I now have
the case where an external party wants to consume an API but only has the
ability to specificy a URL, no Authorization/OAuth headers can be added.
Is there a way to let the API Gateway authenticate against a URL-parameter
instead of the Authorization header?
I'm are using WSO2 API Manager for managing our public API's. I now have
the case where an external party wants to consume an API but only has the
ability to specificy a URL, no Authorization/OAuth headers can be added.
Is there a way to let the API Gateway authenticate against a URL-parameter
instead of the Authorization header?
Sunday, 29 September 2013
VirtualBox Open Virtual Disk dialog on Mac is Hidden behind Storage Dialog
VirtualBox Open Virtual Disk dialog on Mac is Hidden behind Storage Dialog
I am trying to load an existing VMDK for VBox running on Mac Mountain Lion.
In the screenshot below we can see three relevant dialog boxes open:
The "parent" Storage dialog
The child "Please choose a virtual hard drive" dialog
Mostly hidden! The directory navigation/ Finder dialog In the screenshot
it is 90% obscured by the Storage dialog. We can barely see a bit of its
right side peeking through. That is a serious bug/problem.
The number 3 took me quite a while to realize what was happening: the
other dialogs naturally are not responding since the 3rd mostly hidden is
a modal dialog.
Anyone encountered this / determined a workaround?
I intended to put this on superuser. How can this be migrated to that sit?
I am trying to load an existing VMDK for VBox running on Mac Mountain Lion.
In the screenshot below we can see three relevant dialog boxes open:
The "parent" Storage dialog
The child "Please choose a virtual hard drive" dialog
Mostly hidden! The directory navigation/ Finder dialog In the screenshot
it is 90% obscured by the Storage dialog. We can barely see a bit of its
right side peeking through. That is a serious bug/problem.
The number 3 took me quite a while to realize what was happening: the
other dialogs naturally are not responding since the 3rd mostly hidden is
a modal dialog.
Anyone encountered this / determined a workaround?
I intended to put this on superuser. How can this be migrated to that sit?
Two elements with the same id, want to select one contained in a specific div
Two elements with the same id, want to select one contained in a specific div
I have something like this
<div id='container0'>
<input id='item0'>
</div>
<div id='container1'>
<input id='item0'>
</div>
I want to select the second item0 (the one in div container1) and change
it's id to item1. Best way to do this? Is there a way I can select all
item0's on a page and then check their container div and make sure it
matches to 'container1'?
Thank you for your time.
I have something like this
<div id='container0'>
<input id='item0'>
</div>
<div id='container1'>
<input id='item0'>
</div>
I want to select the second item0 (the one in div container1) and change
it's id to item1. Best way to do this? Is there a way I can select all
item0's on a page and then check their container div and make sure it
matches to 'container1'?
Thank you for your time.
I can't create apache derby DB in worklight 6.0
I can't create apache derby DB in worklight 6.0
I upgraded to worklight 6.0. I added both derby_core_plugin_10_8_2,
derby_iu_doc_plugin_1.1.3, into eclipse-->plugins I restarted Eclipse and
right click my project to add Apache Derby nature...nothing seems to
happened, then I tried to go directly to server/java-->apache derby--> run
SQL Script using "ij"...I get (the selected project does not have Apache
derby nature please add it and try again)
I upgraded to worklight 6.0. I added both derby_core_plugin_10_8_2,
derby_iu_doc_plugin_1.1.3, into eclipse-->plugins I restarted Eclipse and
right click my project to add Apache Derby nature...nothing seems to
happened, then I tried to go directly to server/java-->apache derby--> run
SQL Script using "ij"...I get (the selected project does not have Apache
derby nature please add it and try again)
Passing array to mysql stored procedure
Passing array to mysql stored procedure
want to be able to pass an "array" of values to my stored procedure,
instead of calling "Add value" procedure serially.
Can anyone suggest a way to do it using mysql database ?
want to be able to pass an "array" of values to my stored procedure,
instead of calling "Add value" procedure serially.
Can anyone suggest a way to do it using mysql database ?
Saturday, 28 September 2013
Get the `category_title` using javascript or from the category table using the same MySql query?
Get the `category_title` using javascript or from the category table using
the same MySql query?
In the items table I only save the category_id.
Is it better to get the category_title using javascript or from the
category table using the same MySql query?
All the categories are downloaded as a json file to the client when the
page is loaded. So the client has them all. (9KB)
Categories are around 700 items.
...
{id:1, title:"fruits"}
...
Using JS I would loop through categories until category.id ==
item.category_id and then return category.title.
the same MySql query?
In the items table I only save the category_id.
Is it better to get the category_title using javascript or from the
category table using the same MySql query?
All the categories are downloaded as a json file to the client when the
page is loaded. So the client has them all. (9KB)
Categories are around 700 items.
...
{id:1, title:"fruits"}
...
Using JS I would loop through categories until category.id ==
item.category_id and then return category.title.
JPanelMenu does not create the JPanelMenu-Menu class
JPanelMenu does not create the JPanelMenu-Menu class
The JpanelMenu will not create the additional class and I can't figure out
why.
I placed linked to the site with this HEAD
<script type="text/javascript"
src="http://jpanelmenu.com/js/lib/jquery.jpanelmenu.min.js"></script>
I then placed the script to enable the sidebar directly underneath it in
the HEAD
<script type="text/javascript">
$(document).ready(function () {
var jPM = $.jPanelMenu();
jPM.on();
});
</script>
I then placed the code for the nav within the HEADER
<a class="menu-trigger" href="#menu">Click Me</a>
<ul id="menu" style="display: none;">
<li><a href="/">Overview</a></li>
<li><a href="#usage">Usage</a></li>
<li><a href="#about">About</a></li>
</ul>
But then when I run the page inspector, the "click me" works and opens but
the sidebar is empty. It will NOT create the following class:
<ul id="jPanelMenu-menu" style="width: 250px; display: block; z-index:
1;">...</ul>
I think there may be something wrong within my CSS but I do not have any
elements created for JPanel Menu but I do have a left and right panel
within the body like so:
body {
height: 100%;
max-width: 100%;
min-width: 960px;
min-height: 600px;}
right-panel, .left-panel {
height: 100%;
min-height: 600px;}
.left-panel {
background: url('Images/side-bar-parchment.png') no-repeat fixed center;
background-size: cover;
position: absolute;
width: 170px;
z-index: 1;}
.right-panel {
margin-left: 170px;
max-width: 100%;
z-index: 1;}
The JpanelMenu will not create the additional class and I can't figure out
why.
I placed linked to the site with this HEAD
<script type="text/javascript"
src="http://jpanelmenu.com/js/lib/jquery.jpanelmenu.min.js"></script>
I then placed the script to enable the sidebar directly underneath it in
the HEAD
<script type="text/javascript">
$(document).ready(function () {
var jPM = $.jPanelMenu();
jPM.on();
});
</script>
I then placed the code for the nav within the HEADER
<a class="menu-trigger" href="#menu">Click Me</a>
<ul id="menu" style="display: none;">
<li><a href="/">Overview</a></li>
<li><a href="#usage">Usage</a></li>
<li><a href="#about">About</a></li>
</ul>
But then when I run the page inspector, the "click me" works and opens but
the sidebar is empty. It will NOT create the following class:
<ul id="jPanelMenu-menu" style="width: 250px; display: block; z-index:
1;">...</ul>
I think there may be something wrong within my CSS but I do not have any
elements created for JPanel Menu but I do have a left and right panel
within the body like so:
body {
height: 100%;
max-width: 100%;
min-width: 960px;
min-height: 600px;}
right-panel, .left-panel {
height: 100%;
min-height: 600px;}
.left-panel {
background: url('Images/side-bar-parchment.png') no-repeat fixed center;
background-size: cover;
position: absolute;
width: 170px;
z-index: 1;}
.right-panel {
margin-left: 170px;
max-width: 100%;
z-index: 1;}
Why does inherting from object in Python, change they type of the __dict__ when not specifying a parent does not?
Why does inherting from object in Python, change they type of the __dict__
when not specifying a parent does not?
I have a simple piece of code that tries to give a convenience to file in
Python.
class File:
def __init__(this, *args):
this._file = file(*args)
def __del__(this):
this._file.close()
def createCallForwarder(method):
return lambda obj,*args: method(obj._file, *args)
_dict = file.__dict__
for (k,v) in zip(_dict.keys(), _dict.values()):
if not (k.startswith('__') and k.endswith('__')):
if v.__class__.__name__ == 'method_descriptor':
File.__dict__[k] = createCallForwarder(v)
# get the repr method
File.__repr__ = createCallForwarder(dict_proxy['__repr__'])
If i change File to inherit from object, it does not let me assign the
methods.
Why is it different?
when not specifying a parent does not?
I have a simple piece of code that tries to give a convenience to file in
Python.
class File:
def __init__(this, *args):
this._file = file(*args)
def __del__(this):
this._file.close()
def createCallForwarder(method):
return lambda obj,*args: method(obj._file, *args)
_dict = file.__dict__
for (k,v) in zip(_dict.keys(), _dict.values()):
if not (k.startswith('__') and k.endswith('__')):
if v.__class__.__name__ == 'method_descriptor':
File.__dict__[k] = createCallForwarder(v)
# get the repr method
File.__repr__ = createCallForwarder(dict_proxy['__repr__'])
If i change File to inherit from object, it does not let me assign the
methods.
Why is it different?
How send to email using codeignater
How send to email using codeignater
$config['protocol'] = "smtp";
$config['smtp_host'] = "ssl://smtp.tch-pnt.in"; //
$config['smtp_port'] = 587;
$config['smtp_user'] = "bnft@tch-pnt.in";
$config['smtp_pass'] = "********";
$config['charset'] = "utf-8";
$config['mailtype'] = "html";
$config['newline'] = "\r\n";
$config['wordwrap'] = TRUE;
Error... I am using above configuration setup for sending email...
No error but i am not getting mails in my inbox.I tried 3 times.
I used default port as 25 still no mails
Advanced thanks.....
$config['protocol'] = "smtp";
$config['smtp_host'] = "ssl://smtp.tch-pnt.in"; //
$config['smtp_port'] = 587;
$config['smtp_user'] = "bnft@tch-pnt.in";
$config['smtp_pass'] = "********";
$config['charset'] = "utf-8";
$config['mailtype'] = "html";
$config['newline'] = "\r\n";
$config['wordwrap'] = TRUE;
Error... I am using above configuration setup for sending email...
No error but i am not getting mails in my inbox.I tried 3 times.
I used default port as 25 still no mails
Advanced thanks.....
Friday, 27 September 2013
Why Xcode 5.0 (5A1413) crash only when I build & run on an iPhone 5S?
Why Xcode 5.0 (5A1413) crash only when I build & run on an iPhone 5S?
I am running Mountain Lion with the latest version of Xcode 5. It is
extremely unstable and crashes when I try to build & run on an iPhone 5S.
It does not crash when I build & run on older devices.
It looks like a crash related to "DBGLLDBLauncher Serial Queue", the
debugger maybe?
Process: Xcode [1706]
Path: /Applications/Xcode.app/Contents/MacOS/Xcode
Identifier: com.apple.dt.Xcode
Version: 5.0 (3332.25)
Build Info: IDEApplication-3332025000000000~2
Code Type: X86-64 (Native)
Parent Process: launchd [125]
User ID: 501
Date/Time: 2013-09-28 01:29:23.661 +0200
OS Version: Mac OS X 10.8.5 (12F37)
Report Version: 10
Interval Since Last Report: 1061 sec
Crashes Since Last Report: 3
Per-App Interval Since Last Report: 876 sec
Per-App Crashes Since Last Report: 3
Anonymous UUID: 52DE9388-C7D9-F332-DBDD-9024E9D2ED05
Crashed Thread: 8 Dispatch queue: DBGLLDBLauncher Serial Queue
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Application Specific Information:
ProductBuildVersion: 5A1413
Assertion failed: (pointer_byte_size == m_host_arch.GetAddressByteSize()),
function GetHostInfo, file
/SourceCache/lldb/lldb-300.2.47/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp,
line 1266.
Thread 0:: Dispatch queue: com.apple.main-thread
0 libsystem_kernel.dylib 0x00007fff86ad9686 mach_msg_trap + 10
1 libsystem_kernel.dylib 0x00007fff86ad8c42 mach_msg + 70
2 com.apple.CoreFoundation 0x00007fff844c1233
__CFRunLoopServiceMachPort + 195
3 com.apple.CoreFoundation 0x00007fff844c6916 __CFRunLoopRun + 1078
4 com.apple.CoreFoundation 0x00007fff844c60e2
CFRunLoopRunSpecific + 290
5 com.apple.HIToolbox 0x00007fff8ce3eeb4
RunCurrentEventLoopInMode + 209
6 com.apple.HIToolbox 0x00007fff8ce3ec52
ReceiveNextEventCommon + 356
7 com.apple.HIToolbox 0x00007fff8ce3eae3
BlockUntilNextEventMatchingListInMode + 62
8 com.apple.AppKit 0x00007fff88df0533 _DPSNextEvent + 685
9 com.apple.AppKit 0x00007fff88defdf2 -[NSApplication
nextEventMatchingMask:untilDate:inMode:dequeue:] + 128
10 com.apple.AppKit 0x00007fff88de71a3 -[NSApplication
run] + 517
11 com.apple.AppKit 0x00007fff88d8bbd6 NSApplicationMain +
869
12 libdyld.dylib 0x00007fff8ca4a7e1 start + 1
Is this related to the new 64 bit architecture of the iPhone 5S? Do I need
to upgrade to OS X Mavericks? Has anyone managed to get an iPhone 5S work
with Xcode 5?
I am running Mountain Lion with the latest version of Xcode 5. It is
extremely unstable and crashes when I try to build & run on an iPhone 5S.
It does not crash when I build & run on older devices.
It looks like a crash related to "DBGLLDBLauncher Serial Queue", the
debugger maybe?
Process: Xcode [1706]
Path: /Applications/Xcode.app/Contents/MacOS/Xcode
Identifier: com.apple.dt.Xcode
Version: 5.0 (3332.25)
Build Info: IDEApplication-3332025000000000~2
Code Type: X86-64 (Native)
Parent Process: launchd [125]
User ID: 501
Date/Time: 2013-09-28 01:29:23.661 +0200
OS Version: Mac OS X 10.8.5 (12F37)
Report Version: 10
Interval Since Last Report: 1061 sec
Crashes Since Last Report: 3
Per-App Interval Since Last Report: 876 sec
Per-App Crashes Since Last Report: 3
Anonymous UUID: 52DE9388-C7D9-F332-DBDD-9024E9D2ED05
Crashed Thread: 8 Dispatch queue: DBGLLDBLauncher Serial Queue
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Application Specific Information:
ProductBuildVersion: 5A1413
Assertion failed: (pointer_byte_size == m_host_arch.GetAddressByteSize()),
function GetHostInfo, file
/SourceCache/lldb/lldb-300.2.47/source/Plugins/Process/gdb-remote/GDBRemoteCommunicationClient.cpp,
line 1266.
Thread 0:: Dispatch queue: com.apple.main-thread
0 libsystem_kernel.dylib 0x00007fff86ad9686 mach_msg_trap + 10
1 libsystem_kernel.dylib 0x00007fff86ad8c42 mach_msg + 70
2 com.apple.CoreFoundation 0x00007fff844c1233
__CFRunLoopServiceMachPort + 195
3 com.apple.CoreFoundation 0x00007fff844c6916 __CFRunLoopRun + 1078
4 com.apple.CoreFoundation 0x00007fff844c60e2
CFRunLoopRunSpecific + 290
5 com.apple.HIToolbox 0x00007fff8ce3eeb4
RunCurrentEventLoopInMode + 209
6 com.apple.HIToolbox 0x00007fff8ce3ec52
ReceiveNextEventCommon + 356
7 com.apple.HIToolbox 0x00007fff8ce3eae3
BlockUntilNextEventMatchingListInMode + 62
8 com.apple.AppKit 0x00007fff88df0533 _DPSNextEvent + 685
9 com.apple.AppKit 0x00007fff88defdf2 -[NSApplication
nextEventMatchingMask:untilDate:inMode:dequeue:] + 128
10 com.apple.AppKit 0x00007fff88de71a3 -[NSApplication
run] + 517
11 com.apple.AppKit 0x00007fff88d8bbd6 NSApplicationMain +
869
12 libdyld.dylib 0x00007fff8ca4a7e1 start + 1
Is this related to the new 64 bit architecture of the iPhone 5S? Do I need
to upgrade to OS X Mavericks? Has anyone managed to get an iPhone 5S work
with Xcode 5?
Sending file-path to already opened program
Sending file-path to already opened program
Can a C# program send a file to an already open program?
For example, if I have Photoshop running, a click would send a image path
to it as when I would drag an image from Windows Explorer to it... or
think about dragging txt file to notepad window.
Can a C# program send a file to an already open program?
For example, if I have Photoshop running, a click would send a image path
to it as when I would drag an image from Windows Explorer to it... or
think about dragging txt file to notepad window.
Uncaught Error: Error calling method on NPObject.
Uncaught Error: Error calling method on NPObject.
am a newbie to JSON and i just cant's access to the object data.
this is the code :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ajax </title>
</head>
<body>
<p id="p"></p>
<script type="text/javascript" >
var r = new XMLHttpRequest()
r.open("GET", "d.json");
if(r.readyState ===4 && r.status ===200){
var data = JSON.parse(r.responseText);
var p = document.getElementById("p");
p.innerHTML = data.user;
}
r.send();
</script>
</body>
</html>
and this is the d.json file
{"user":"khaled","age":"20"};
i got that error : "Uncaught Error: Error calling method on NPObject. "
thanks.
am a newbie to JSON and i just cant's access to the object data.
this is the code :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>ajax </title>
</head>
<body>
<p id="p"></p>
<script type="text/javascript" >
var r = new XMLHttpRequest()
r.open("GET", "d.json");
if(r.readyState ===4 && r.status ===200){
var data = JSON.parse(r.responseText);
var p = document.getElementById("p");
p.innerHTML = data.user;
}
r.send();
</script>
</body>
</html>
and this is the d.json file
{"user":"khaled","age":"20"};
i got that error : "Uncaught Error: Error calling method on NPObject. "
thanks.
WPF numeric format
WPF numeric format
I have this XAML for acolumn into DataGrid
<DataGridTemplateColumn Header="% Deduccion Anticipo">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding NumPorcentajeAnticipo, Mode=TwoWay,
StringFormat={}{0:00.}%}" Visibility="{Binding
Merlin_ConceptosFacturacion.BitOtrosItms_Anticipos,Converter={StaticResource
boolToVisibility}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding NumPorcentajeAnticipo,
Mode=TwoWay,StringFormat={}{0:00.}%}" Visibility="{Binding
Merlin_ConceptosFacturacion.BitOtrosItms_Anticipos,Converter={StaticResource
boolToVisibility}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
The Stringformat applys as i expect, but muy problem is the user can fill
it with any char alpha, number symbol, how can i do to prevent it, it is
posible set an inputmask ?
I'm was trying with another StringFormats but any one of them work as I
expect.
I have this XAML for acolumn into DataGrid
<DataGridTemplateColumn Header="% Deduccion Anticipo">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding NumPorcentajeAnticipo, Mode=TwoWay,
StringFormat={}{0:00.}%}" Visibility="{Binding
Merlin_ConceptosFacturacion.BitOtrosItms_Anticipos,Converter={StaticResource
boolToVisibility}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding NumPorcentajeAnticipo,
Mode=TwoWay,StringFormat={}{0:00.}%}" Visibility="{Binding
Merlin_ConceptosFacturacion.BitOtrosItms_Anticipos,Converter={StaticResource
boolToVisibility}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
The Stringformat applys as i expect, but muy problem is the user can fill
it with any char alpha, number symbol, how can i do to prevent it, it is
posible set an inputmask ?
I'm was trying with another StringFormats but any one of them work as I
expect.
Getting failed expectations from GMock
Getting failed expectations from GMock
Currently, I am using GMock without GTest ( specifically, I'm using it
with mstest ). Is there any way to get a string of the failed expectations
?
IE:
EXPECT_CALL( mockObject, MethodWith3Params( 1, 2, 3 ) ).Times(1);
// Do does not call MethodWith3Params at all.
stuffDoer.Do( mockObject);
Assert::IsTrue( Mock::VerifyAndClearExpectations( &mockObject ), " "/*What
can I do here to say what expectation/s failed ?*/ );
I assume GMock is storing these strings ( or at least raw data that can be
used to deduce a message ) somewhere, since GTest is able to tell you when
an expectation isn't met.
Currently, I am using GMock without GTest ( specifically, I'm using it
with mstest ). Is there any way to get a string of the failed expectations
?
IE:
EXPECT_CALL( mockObject, MethodWith3Params( 1, 2, 3 ) ).Times(1);
// Do does not call MethodWith3Params at all.
stuffDoer.Do( mockObject);
Assert::IsTrue( Mock::VerifyAndClearExpectations( &mockObject ), " "/*What
can I do here to say what expectation/s failed ?*/ );
I assume GMock is storing these strings ( or at least raw data that can be
used to deduce a message ) somewhere, since GTest is able to tell you when
an expectation isn't met.
Visual Studio Recovery Backup Location and Freezing
Visual Studio Recovery Backup Location and Freezing
We find that Visual Studio hangs frequently if our code is stored on a
network drive. Moving to to the local drive fixed this.
However, now we are using the Modeller, it saves recover information to
H:\Visual Studio 2012\Backup Files
and there seems no option to change that.
As a result, it frequently hangs with "Saving auto recovery information".
It does eventually complete, but it takes minutes to do so.
Our network drives work fine for other programs etc.
Has anyone else seen this and found a solution? Is the location a registry
setting?
We find that Visual Studio hangs frequently if our code is stored on a
network drive. Moving to to the local drive fixed this.
However, now we are using the Modeller, it saves recover information to
H:\Visual Studio 2012\Backup Files
and there seems no option to change that.
As a result, it frequently hangs with "Saving auto recovery information".
It does eventually complete, but it takes minutes to do so.
Our network drives work fine for other programs etc.
Has anyone else seen this and found a solution? Is the location a registry
setting?
Using Negative Range for Bessel Function Results in 2 Values
Using Negative Range for Bessel Function Results in 2 Values
I am using the inbuilt function of matlab to calculate the bessel function
of second order, following is the code
format long
z = (-5:1:5)';
y = bessely(1,z)
plot (y)
The output is as follows
y =
-0.147863143391227 + 0.655158275182930i
-0.397925710557100 + 0.132086656047098i
-0.324674424791800 - 0.678117917051873i
0.107032431540937 - 1.153449615513747i
0.781212821300289 - 0.880101171489867i
-Inf
-0.781212821300289
-0.107032431540937
0.324674424791800
0.397925710557100
0.147863143391227
What i don't understand is why am i getting two values when the value of z
is negative ?
I am using the inbuilt function of matlab to calculate the bessel function
of second order, following is the code
format long
z = (-5:1:5)';
y = bessely(1,z)
plot (y)
The output is as follows
y =
-0.147863143391227 + 0.655158275182930i
-0.397925710557100 + 0.132086656047098i
-0.324674424791800 - 0.678117917051873i
0.107032431540937 - 1.153449615513747i
0.781212821300289 - 0.880101171489867i
-Inf
-0.781212821300289
-0.107032431540937
0.324674424791800
0.397925710557100
0.147863143391227
What i don't understand is why am i getting two values when the value of z
is negative ?
Thursday, 26 September 2013
I am able to call a method w/o passing the required arguments in c++. How come?
I am able to call a method w/o passing the required arguments in c++. How
come?
Here is the code...
#include "stdafx.h"
#include<iostream>
using namespace std;
class Base
{
public:
virtual void Display(bool b = false)
{
cout<<"Base"<<"\t"<<b<<endl;
}
};
class Derived : public Base
{
public:
virtual void Display(bool b) override
{
cout<<"Derived"<<"\t"<<b<<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Base* bp = new Base();
Derived* dp = new Derived();
bp->Display();
dp->Display(true);
bp = new Derived();
bp->Display();
cout<<"Done"<<endl;
return 0;
}
When the Display() method called second time, surprisingly it hit the
method in Derived class. in Derived class I didn't specify default
argument. But it took the default base class argument. How?
come?
Here is the code...
#include "stdafx.h"
#include<iostream>
using namespace std;
class Base
{
public:
virtual void Display(bool b = false)
{
cout<<"Base"<<"\t"<<b<<endl;
}
};
class Derived : public Base
{
public:
virtual void Display(bool b) override
{
cout<<"Derived"<<"\t"<<b<<endl;
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Base* bp = new Base();
Derived* dp = new Derived();
bp->Display();
dp->Display(true);
bp = new Derived();
bp->Display();
cout<<"Done"<<endl;
return 0;
}
When the Display() method called second time, surprisingly it hit the
method in Derived class. in Derived class I didn't specify default
argument. But it took the default base class argument. How?
Wednesday, 25 September 2013
Testing restfull controllers with profiler - Laravel 3
Testing restfull controllers with profiler - Laravel 3
I am using laravel 3. I enabled the profiler. It's working fine when I am
viewing views but when I try to test the Restfull controllers, all of the
html of profiler also comes in response. How to get rid of this?
I am using laravel 3. I enabled the profiler. It's working fine when I am
viewing views but when I try to test the Restfull controllers, all of the
html of profiler also comes in response. How to get rid of this?
Thursday, 19 September 2013
IllegalStateException occurs when using Jackson @JsonDeserialize annotation
IllegalStateException occurs when using Jackson @JsonDeserialize annotation
I'm trying to use a custom deserializer in Jackson to deserialize some
json objects. However, when I try to have the ObjectMapper read the json,
the following exception occurs:
java.lang.IllegalStateException: AnnotationIntrospector returned Class
com.Geometry.GeometryDeserializer; expected Class<JsonDeserializer>
I'm somewhat at a loss of what to do here, since it seems like the
AnnotationIntrospector is complaining that my GeometryDeserializer is not
a subclass of JsonDeserializer, when it clearly is.
Here's where I create the Object Mapper:
public void deserializeJson(String json) {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(Feature.class, MixIn.class);
Feature feature = mapper.readValue(json, Feature.class);
}
...my Mix In class:
abstract class MixIn {
@JsonDeserialize(using=GeometryDeserializer.class)
abstract void setGeometry(Geometry geometry);
}
...and my deserializer:
public class GeometryDeserializer extends JsonDeserializer<Geometry> {
@Override
public Geometry deserialize(JsonParser jp, DeserializationContext dc)
throws IOException, JsonProcessingException {
//stuff happens
}
}
Any feedback/assistance would be greatly appriciated.
Thanks.
I'm trying to use a custom deserializer in Jackson to deserialize some
json objects. However, when I try to have the ObjectMapper read the json,
the following exception occurs:
java.lang.IllegalStateException: AnnotationIntrospector returned Class
com.Geometry.GeometryDeserializer; expected Class<JsonDeserializer>
I'm somewhat at a loss of what to do here, since it seems like the
AnnotationIntrospector is complaining that my GeometryDeserializer is not
a subclass of JsonDeserializer, when it clearly is.
Here's where I create the Object Mapper:
public void deserializeJson(String json) {
ObjectMapper mapper = new ObjectMapper();
mapper.addMixInAnnotations(Feature.class, MixIn.class);
Feature feature = mapper.readValue(json, Feature.class);
}
...my Mix In class:
abstract class MixIn {
@JsonDeserialize(using=GeometryDeserializer.class)
abstract void setGeometry(Geometry geometry);
}
...and my deserializer:
public class GeometryDeserializer extends JsonDeserializer<Geometry> {
@Override
public Geometry deserialize(JsonParser jp, DeserializationContext dc)
throws IOException, JsonProcessingException {
//stuff happens
}
}
Any feedback/assistance would be greatly appriciated.
Thanks.
Bootstrap 3.0.0 nav vertical collapse responsive
Bootstrap 3.0.0 nav vertical collapse responsive
After many search without results, I try to send a post.
I'm looking for a way for the nav-stacked (vertical menu) from bootstrap
3.0.0 (http://getbootstrap.com/components/#nav-pills) or my sidebare
becomes collapsed when tablet or smartphone is used (such as navbar).
I'm agree to use other component that nav-stacked if the result is a
vertical responsive menu.
My code
<div class="col-md-2">
<div class="panel panel-default" id="sidebar" >
<div class="panel-heading"
style="background-color:#888;color:#fff;"
data-target="#test">Sidebar</div>
<div class="panel-body" id="test">
<ul class="nav nav-stacked nav-collapse">
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
<hr>
<div class="col col-span-12">
<i class="icon-2x icon-facebook"></i>
<i class="icon-2x icon-twitter"></i>
<i class="icon-2x icon-linkedin"></i>
<i class="icon-2x icon-pinterest"></i>
</div>
</div><!--/panel body-->
</div><!--/panel-->
</div><!--/end left column-->
Thank you in advance for your help :-)
After many search without results, I try to send a post.
I'm looking for a way for the nav-stacked (vertical menu) from bootstrap
3.0.0 (http://getbootstrap.com/components/#nav-pills) or my sidebare
becomes collapsed when tablet or smartphone is used (such as navbar).
I'm agree to use other component that nav-stacked if the result is a
vertical responsive menu.
My code
<div class="col-md-2">
<div class="panel panel-default" id="sidebar" >
<div class="panel-heading"
style="background-color:#888;color:#fff;"
data-target="#test">Sidebar</div>
<div class="panel-body" id="test">
<ul class="nav nav-stacked nav-collapse">
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
<li><a href="#">Link</a></li>
</ul>
<hr>
<div class="col col-span-12">
<i class="icon-2x icon-facebook"></i>
<i class="icon-2x icon-twitter"></i>
<i class="icon-2x icon-linkedin"></i>
<i class="icon-2x icon-pinterest"></i>
</div>
</div><!--/panel body-->
</div><!--/panel-->
</div><!--/end left column-->
Thank you in advance for your help :-)
Development tool to structure the code?
Development tool to structure the code?
I've been searching for a development tool, which allows me to have a
diagram with all classes, public & private methods, attributes and
everything else which is relevant to them.
I could imagine something like this being pretty useful for planning out
your project + keeping track of it while developing, as I've had to
restart a project quite a few times in the past days because it just
turned into a mess of methods & attributes (perfectionist right here).
Are you aware of such a tool or do I have to spend time on making one?
I've been searching for a development tool, which allows me to have a
diagram with all classes, public & private methods, attributes and
everything else which is relevant to them.
I could imagine something like this being pretty useful for planning out
your project + keeping track of it while developing, as I've had to
restart a project quite a few times in the past days because it just
turned into a mess of methods & attributes (perfectionist right here).
Are you aware of such a tool or do I have to spend time on making one?
Cancel handler.postdelayed from another activity in which it was not created
Cancel handler.postdelayed from another activity in which it was not created
Mind the typos, just a mock up.
class myActivity1 extends Activity
{
oncreate()
{
Handler myHandler = new Handler();
myHandler.postDelayed(myRunnable,1000)
}
onPause()
{
}
}
The handler does its job, and after 1 second the myRunnable runs. Assuming
I call another postDelayed inside my myRunnable, that restarts the
postDelayed for repetition.
In myActivity1 I am not using the removeCallbacks() function, thus the
myHandler will be running even if I leave the activity.
However, my question is, HOW CAN I CANCEL the myHandler from inside
another activity that I moved to ? (Assume my app has 15 activites, and I
do not know inside which one I am.)
Mind the typos, just a mock up.
class myActivity1 extends Activity
{
oncreate()
{
Handler myHandler = new Handler();
myHandler.postDelayed(myRunnable,1000)
}
onPause()
{
}
}
The handler does its job, and after 1 second the myRunnable runs. Assuming
I call another postDelayed inside my myRunnable, that restarts the
postDelayed for repetition.
In myActivity1 I am not using the removeCallbacks() function, thus the
myHandler will be running even if I leave the activity.
However, my question is, HOW CAN I CANCEL the myHandler from inside
another activity that I moved to ? (Assume my app has 15 activites, and I
do not know inside which one I am.)
Ruby 1.9.3 nil? undefined local variable or method. Is nil? broken?
Ruby 1.9.3 nil? undefined local variable or method. Is nil? broken?
I've been using var.nil? for a while, it's all over my code. Suddenly, I'm
getting undefined local variable or method for the variable with .nil?
after it.
What's going on? is .nil? broken? I even tried it on an IRB online to make
sure it wasn't something in my environment. I should be able to type:
me.nil?
and that should come back as true if the variable hasn't been defined,
that's the whole point, but I get undefined local variable or method me
for main:Object
Maybe I got nil? wrong and have to use something like:
defined?(me) == nil
and .nil? can only be used with an existing object? This was not the way I
understood it. The ruby docs even say this:
nil.nil? -> true
<anything_else>.nil? -> false
Going crazy here.
I've been using var.nil? for a while, it's all over my code. Suddenly, I'm
getting undefined local variable or method for the variable with .nil?
after it.
What's going on? is .nil? broken? I even tried it on an IRB online to make
sure it wasn't something in my environment. I should be able to type:
me.nil?
and that should come back as true if the variable hasn't been defined,
that's the whole point, but I get undefined local variable or method me
for main:Object
Maybe I got nil? wrong and have to use something like:
defined?(me) == nil
and .nil? can only be used with an existing object? This was not the way I
understood it. The ruby docs even say this:
nil.nil? -> true
<anything_else>.nil? -> false
Going crazy here.
jquery range slider values which follows the handles?
jquery range slider values which follows the handles?
I'm playing with jquery range slider, I've managed to split two values in
different inputs. Now don't get mad at me, I'm still nooby about jquery
and I was wondering how to set up that each input follow its handle on
slider?
Like in this examples: http://egorkhmelev.github.io/jslider/
My code till now looks like this:
script:
$(function() {
$( ".slider-assets" ).slider({
range: true,
min: 100,
max: 500,
values: [ 200, 300 ],
slide: function( event, ui ) {
$( ".amount-assets1" ).val( ui.values[ 0 ] + "k ");
$( ".amount-assets2" ).val( ui.values[ 1 ] + "k " );
}
});
$( ".amount-assets1" ).val($( ".slider-assets" ).slider( "values",
0 ) + "k " );
$( ".amount-assets2" ).val($( ".slider-assets" ).slider( "values",
1 ) + "k " );
});
html:
<input type="text" class="amount-assets1" />
<input type="text" class="amount-assets2" />
<div class="slider-assets"></div>
css:
.amount-assets1,.amount-assets2{
width: 48px;
}
and you can see and play with my jsfiddle here:
http://jsfiddle.net/dzorz/sJBLh/
The problem is that I don't know from where to start. Do I need another
one plugin that puts tooltip above handles or something else?
Any suggestion and solutions are welcome.
Thanks.
I'm playing with jquery range slider, I've managed to split two values in
different inputs. Now don't get mad at me, I'm still nooby about jquery
and I was wondering how to set up that each input follow its handle on
slider?
Like in this examples: http://egorkhmelev.github.io/jslider/
My code till now looks like this:
script:
$(function() {
$( ".slider-assets" ).slider({
range: true,
min: 100,
max: 500,
values: [ 200, 300 ],
slide: function( event, ui ) {
$( ".amount-assets1" ).val( ui.values[ 0 ] + "k ");
$( ".amount-assets2" ).val( ui.values[ 1 ] + "k " );
}
});
$( ".amount-assets1" ).val($( ".slider-assets" ).slider( "values",
0 ) + "k " );
$( ".amount-assets2" ).val($( ".slider-assets" ).slider( "values",
1 ) + "k " );
});
html:
<input type="text" class="amount-assets1" />
<input type="text" class="amount-assets2" />
<div class="slider-assets"></div>
css:
.amount-assets1,.amount-assets2{
width: 48px;
}
and you can see and play with my jsfiddle here:
http://jsfiddle.net/dzorz/sJBLh/
The problem is that I don't know from where to start. Do I need another
one plugin that puts tooltip above handles or something else?
Any suggestion and solutions are welcome.
Thanks.
Wednesday, 18 September 2013
SublimeText 3, how to navigate between files in project
SublimeText 3, how to navigate between files in project
I'm new to SublimeText (migrated from TextMate) and it's awesome. But I'm
familiar with JetBrains IDE and I need functionality to quickly open a
file/class in a project. SublimeText provides cool features, like open
symbol anywhere, goto anything and so on, but I can't find anything to
open just files in a project. When I'm working on a big project – goto
anything and similar are not suit for me.
For example, I have a class named Data. When I'm trying to open that class
with 'goto anything/symbol in project' – I got a lot of variables and
methods in the list, because 'data' is pretty common word in programming.
So, I'm trying to achieve functionality to open only classes/files,
without searching inside of them (like JetBrains Navigate -> Class). Is
there any built-in functionality, or I need to write a custom plugin for
my needs?
I'm new to SublimeText (migrated from TextMate) and it's awesome. But I'm
familiar with JetBrains IDE and I need functionality to quickly open a
file/class in a project. SublimeText provides cool features, like open
symbol anywhere, goto anything and so on, but I can't find anything to
open just files in a project. When I'm working on a big project – goto
anything and similar are not suit for me.
For example, I have a class named Data. When I'm trying to open that class
with 'goto anything/symbol in project' – I got a lot of variables and
methods in the list, because 'data' is pretty common word in programming.
So, I'm trying to achieve functionality to open only classes/files,
without searching inside of them (like JetBrains Navigate -> Class). Is
there any built-in functionality, or I need to write a custom plugin for
my needs?
How do boolean operators work in 'if' conditions?
How do boolean operators work in 'if' conditions?
I am currently new to Python and am trying to run a few simple lines of
code. I cannot understand how Python is evaluating this syntax after the
if statement. Any explanations will be appreciated.
number = int(raw_input("Enter number : "))
if number == (1 or 2 or 3):
print "Match"
else:
print "No match"
Only the integer 1 yield a positive result and any other numbers including
2 and 3 go through the else branch. Can the conditions be stated as the
following only?:
if number == 1 or number == 2 or number == 3:
Thank you.
I am currently new to Python and am trying to run a few simple lines of
code. I cannot understand how Python is evaluating this syntax after the
if statement. Any explanations will be appreciated.
number = int(raw_input("Enter number : "))
if number == (1 or 2 or 3):
print "Match"
else:
print "No match"
Only the integer 1 yield a positive result and any other numbers including
2 and 3 go through the else branch. Can the conditions be stated as the
following only?:
if number == 1 or number == 2 or number == 3:
Thank you.
Way to short-circut propigation of checked exception in Junit
Way to short-circut propigation of checked exception in Junit
I just thought of something minor I would like to do and was curious if it
the ability to do it existed. It's purely a convenience syntactic-sugar
sort of thing, hardly mandatory to have, but a slight convenience I
thought may have been implemented at some point.
I have a method nestled 2-3 layers down in helper methods of a Junit test
case which throws a checked exception. I know for a fact that I want to
fail if this exception is ever thrown. However, if I just call Fail() I
lose the stack trace of the exception and the other conveniences that come
with allowing the exception to propagate
I know the 'standard' approach is to have the method throw the exception.
However, as I said, I'm buried a few methods deep already, and I suspect
this method will be called by many future helper methods. If I throw an
exception in this method I will have to constantly adding a throw clause
to all the methods that use this one method, directly or indirectly, which
could be quite a few methods. This is obviously doable, just a little
annoying; and, in theory at least, I could mask a situation where the
exception is thrown and I actually wanted to catch it if all my methods
already throw it.
Is there a way I can tell Junit to act as if the exception had propagated
up to the top level and fail, without having to have all my methods throw
it? So Junit reports a failure due to exception, with the stack trace and
all, immediately. Essentially I want a fail method that takes an
exception.
Does anything like this exist, or do I have to simply throw it?
ps. I know I could wrap it in a runtime exception and re-throw it, but I
don't really like that option either.
I just thought of something minor I would like to do and was curious if it
the ability to do it existed. It's purely a convenience syntactic-sugar
sort of thing, hardly mandatory to have, but a slight convenience I
thought may have been implemented at some point.
I have a method nestled 2-3 layers down in helper methods of a Junit test
case which throws a checked exception. I know for a fact that I want to
fail if this exception is ever thrown. However, if I just call Fail() I
lose the stack trace of the exception and the other conveniences that come
with allowing the exception to propagate
I know the 'standard' approach is to have the method throw the exception.
However, as I said, I'm buried a few methods deep already, and I suspect
this method will be called by many future helper methods. If I throw an
exception in this method I will have to constantly adding a throw clause
to all the methods that use this one method, directly or indirectly, which
could be quite a few methods. This is obviously doable, just a little
annoying; and, in theory at least, I could mask a situation where the
exception is thrown and I actually wanted to catch it if all my methods
already throw it.
Is there a way I can tell Junit to act as if the exception had propagated
up to the top level and fail, without having to have all my methods throw
it? So Junit reports a failure due to exception, with the stack trace and
all, immediately. Essentially I want a fail method that takes an
exception.
Does anything like this exist, or do I have to simply throw it?
ps. I know I could wrap it in a runtime exception and re-throw it, but I
don't really like that option either.
Boolean with loops to check an array
Boolean with loops to check an array
Write Java code for a loop that sets boolean variable isOrdered to true if
the elements of a
given array of ints called a are in non-decreasing order, otherwise it
sets isOrdered to false.
int i[] = { 1, 2, 3, 4, 5 };
int b = 0;
boolean isOrdered = false;
while (b < i.length) {
if (i[0] <= i[b]) {
isOrdered = true;
}
b++;
}
out.println(isOrdered);
Am I doing this correctly?
Write Java code for a loop that sets boolean variable isOrdered to true if
the elements of a
given array of ints called a are in non-decreasing order, otherwise it
sets isOrdered to false.
int i[] = { 1, 2, 3, 4, 5 };
int b = 0;
boolean isOrdered = false;
while (b < i.length) {
if (i[0] <= i[b]) {
isOrdered = true;
}
b++;
}
out.println(isOrdered);
Am I doing this correctly?
OpenGL with SDL, what am I doing wrong?
OpenGL with SDL, what am I doing wrong?
I'm trying to display simple white cube in OpenGL with SDL. I've setup my
VBO and IBO like this:
GLfloat vertexData[] =
{
-0.5f, -0.5f, -0.5f, // bot, left, back
-0.5f, 0.5f, -0.5f, // top, left, back
-0.5f, -0.5f, 0.5f, // bot, left, front
-0.5f, 0.5f, 0.5f, // top, left, front
0.5f, -0.5f, -0.5f, // bot, right, back
0.5f, -0.5f, 0.5f, // bot, right, front
0.5f, 0.5f, -0.5f, // top, right, back
0.5f, 0.5f, 0.5f // top, right, front
};
GLint indexData[] =
{
//back
0, 1, 6,
0, 5, 6,
//left
0, 2, 3,
0, 1, 3,
//right
4, 5, 7,
4, 6, 7,
//bot
0, 4, 5,
0, 2, 5,
//top
1, 3, 7,
1, 6, 7,
//front
2, 3, 7,
2, 5, 7
};
However, it looks like this:
What am I doing wrong? Thanks for your answers.
I'm trying to display simple white cube in OpenGL with SDL. I've setup my
VBO and IBO like this:
GLfloat vertexData[] =
{
-0.5f, -0.5f, -0.5f, // bot, left, back
-0.5f, 0.5f, -0.5f, // top, left, back
-0.5f, -0.5f, 0.5f, // bot, left, front
-0.5f, 0.5f, 0.5f, // top, left, front
0.5f, -0.5f, -0.5f, // bot, right, back
0.5f, -0.5f, 0.5f, // bot, right, front
0.5f, 0.5f, -0.5f, // top, right, back
0.5f, 0.5f, 0.5f // top, right, front
};
GLint indexData[] =
{
//back
0, 1, 6,
0, 5, 6,
//left
0, 2, 3,
0, 1, 3,
//right
4, 5, 7,
4, 6, 7,
//bot
0, 4, 5,
0, 2, 5,
//top
1, 3, 7,
1, 6, 7,
//front
2, 3, 7,
2, 5, 7
};
However, it looks like this:
What am I doing wrong? Thanks for your answers.
Making sure Checkboxes are checked on page reload jQuery
Making sure Checkboxes are checked on page reload jQuery
So I am having some strange functionality with this snippet of jQuery:
$(document).ready(function()
{
$('.pinToggles').attr('checked','checked');
})
This is the html:
<input type="checkbox" id="redCheck" name="pinSet" value="Red"
class="pinToggles" onclick="pinSetCheck(redSet)">Red
<input type="checkbox" id="yellowCheck" name="pinSet" value="Yellow"
class="pinToggles" onclick="pinSetCheck(yellowSet)">Yellow<br>
<input type="checkbox" id="greenCheck" name="pinSet" value="Green"
class="pinToggles" onclick="pinSetCheck(greenSet)">Green
<input type="checkbox" id="blueCheck" name="pinSet" value="Blue"
class="pinToggles"onclick="pinSetCheck(blueSet)">Blue<br>
What ends up happening is if I would uncheck some of the boxes and then
reload, it will only check the first unchecked box and then each refresh
after that it checks the following unchecked box. The functionality that I
want is on refresh is all of the checkboxes to be checked.
I was able to achieve this with javascript by using this:
document.getElementById('redCheck').checked = true;
document.getElementById('yellowCheck').checked = true;
document.getElementById('greenCheck').checked = true;
document.getElementById('blueCheck').checked = true;
But I think jQuery is the better way about doing this but unsure why it is
reacting the way it is right now.
So I am having some strange functionality with this snippet of jQuery:
$(document).ready(function()
{
$('.pinToggles').attr('checked','checked');
})
This is the html:
<input type="checkbox" id="redCheck" name="pinSet" value="Red"
class="pinToggles" onclick="pinSetCheck(redSet)">Red
<input type="checkbox" id="yellowCheck" name="pinSet" value="Yellow"
class="pinToggles" onclick="pinSetCheck(yellowSet)">Yellow<br>
<input type="checkbox" id="greenCheck" name="pinSet" value="Green"
class="pinToggles" onclick="pinSetCheck(greenSet)">Green
<input type="checkbox" id="blueCheck" name="pinSet" value="Blue"
class="pinToggles"onclick="pinSetCheck(blueSet)">Blue<br>
What ends up happening is if I would uncheck some of the boxes and then
reload, it will only check the first unchecked box and then each refresh
after that it checks the following unchecked box. The functionality that I
want is on refresh is all of the checkboxes to be checked.
I was able to achieve this with javascript by using this:
document.getElementById('redCheck').checked = true;
document.getElementById('yellowCheck').checked = true;
document.getElementById('greenCheck').checked = true;
document.getElementById('blueCheck').checked = true;
But I think jQuery is the better way about doing this but unsure why it is
reacting the way it is right now.
Edit virtual host file using php
Edit virtual host file using php
I have a php application and somethings related to the application need
changes to vhost.conf file.
Presently i'm making the changes manually. But i would like to automate it
using a php script.
Is this advisable? I want to know the security complications involved.
I have a php application and somethings related to the application need
changes to vhost.conf file.
Presently i'm making the changes manually. But i would like to automate it
using a php script.
Is this advisable? I want to know the security complications involved.
populate combobox with items on single line of text file
populate combobox with items on single line of text file
I have a line of text A;B;C;D; in a text file. what I'm wanting to achive
is to populate a combobox so that it reads as follows A B C D
Using the ; char as a way to define a new combobox entry.
its supose to work in combination with the following code...
For Each line As String In IO.File.ReadAllLines("C:\TEST.txt")
If line.StartsWith("<dep>") Then
ComboBox1.Text = line.Substring(5)
End If
which selects a tag from a file with alsorts of stored data (in this case
the tag and usses this to populate the combobox...
dose anyboy know how?
I'm ussing vb.net
I have a line of text A;B;C;D; in a text file. what I'm wanting to achive
is to populate a combobox so that it reads as follows A B C D
Using the ; char as a way to define a new combobox entry.
its supose to work in combination with the following code...
For Each line As String In IO.File.ReadAllLines("C:\TEST.txt")
If line.StartsWith("<dep>") Then
ComboBox1.Text = line.Substring(5)
End If
which selects a tag from a file with alsorts of stored data (in this case
the tag and usses this to populate the combobox...
dose anyboy know how?
I'm ussing vb.net
Tuesday, 17 September 2013
Get data by Return vs passing pointer
Get data by Return vs passing pointer
int get1(void) { return test; }
void get2(int* arg) { *arg = test;}
static test = 5;
int main()
{
int result = 0;
result = get1();
get2(&result);
}
get1 vs get2 which one is best performance for embedded system
int get1(void) { return test; }
void get2(int* arg) { *arg = test;}
static test = 5;
int main()
{
int result = 0;
result = get1();
get2(&result);
}
get1 vs get2 which one is best performance for embedded system
AJAX async set to false block the page, otherwise can not get the value
AJAX async set to false block the page, otherwise can not get the value
I'm using an ajax request inside im.js so it will call my PHP server from
the js and get the feedback. However, I need to update an variable based
on the callback of the .ajax function like this:
var picture = "<img src='https://www.123.com/pictures/unknown.jpg'
width='30' />";
$.ajax({'type':'GET',
'async':false,'url':'https://www.123.com/site/getpic?username=' +
username,
'success':function(callback){
picture = "<img src='" + callback + "' width='30' />";
} //ajax success
}); //ajax
See that if i delete "async: false", the variable picture will not be
updated since ajax is async, and if I disable it like this, it blocks the
whole page from going on even I load the whole im.js async.
Please help: How can I update the variable, in the meantime, do not block
the page?
Thanks
I'm using an ajax request inside im.js so it will call my PHP server from
the js and get the feedback. However, I need to update an variable based
on the callback of the .ajax function like this:
var picture = "<img src='https://www.123.com/pictures/unknown.jpg'
width='30' />";
$.ajax({'type':'GET',
'async':false,'url':'https://www.123.com/site/getpic?username=' +
username,
'success':function(callback){
picture = "<img src='" + callback + "' width='30' />";
} //ajax success
}); //ajax
See that if i delete "async: false", the variable picture will not be
updated since ajax is async, and if I disable it like this, it blocks the
whole page from going on even I load the whole im.js async.
Please help: How can I update the variable, in the meantime, do not block
the page?
Thanks
Using image maps with text somehow (jquery?)
Using image maps with text somehow (jquery?)
First of all, I know image maps are kind of outdated, but they're not
deprecated yet, and neat enough! I'm upgrading an existing and really
cluttered image map, which is being used to show the work of different
labs around the world in an area of chemistry research, and really just
trying to tackle a coding/design problem for myself.
I'm wondering how I might go about coupling a rollover image fade (e.g.
for individual countries) with text (i.e. captions rather than a URL with
text tip). The map is rendered and setting coordinates is a simple enough
matter, but I need some way to produce links on rollover, such as for
[Researcher 1 | lab website],[Researcher 2 | lab website], etc. in
particular for when they reside in the same place on the map.
All I can seem to see being done to make these interactive from other
examples is alerts and single links for a region of an image map, but I'm
sure it could be more versatile and I'm wondering if anyone knows how I
could present text in this way?
Something that acts like this (shown all expanded) would be great source
I'm sorry I can't be more constructive but the code is too dense for me to
work out how that's done, and I get the feeling I might be missing some
basic solution...?
Thanks
First of all, I know image maps are kind of outdated, but they're not
deprecated yet, and neat enough! I'm upgrading an existing and really
cluttered image map, which is being used to show the work of different
labs around the world in an area of chemistry research, and really just
trying to tackle a coding/design problem for myself.
I'm wondering how I might go about coupling a rollover image fade (e.g.
for individual countries) with text (i.e. captions rather than a URL with
text tip). The map is rendered and setting coordinates is a simple enough
matter, but I need some way to produce links on rollover, such as for
[Researcher 1 | lab website],[Researcher 2 | lab website], etc. in
particular for when they reside in the same place on the map.
All I can seem to see being done to make these interactive from other
examples is alerts and single links for a region of an image map, but I'm
sure it could be more versatile and I'm wondering if anyone knows how I
could present text in this way?
Something that acts like this (shown all expanded) would be great source
I'm sorry I can't be more constructive but the code is too dense for me to
work out how that's done, and I get the feeling I might be missing some
basic solution...?
Thanks
i need a text input area for a form to appear only if 'other' is selected on drop down select list?
i need a text input area for a form to appear only if 'other' is selected
on drop down select list?
Well my question is pretty simple and straight forward. The html for the
drop down list is easy enough here is the script and html that i found to
use
<select id='combo'>
<option>Yes</option>
<option>No</option>
<option>other</option>
</select>
<input id='text1' style='display: none'/>
<input id='text2' style='display: none'/>
<script>
document.getElementById('combo').onchange = function() {
var display = this.selectedIndex == 2 ? "inline" : "none";
document.getElementById('text1').style.display = display;
document.getElementById('text2').style.display = display;
}
</script>
how do i go about applying this? if of course, this even works...
thanks
on drop down select list?
Well my question is pretty simple and straight forward. The html for the
drop down list is easy enough here is the script and html that i found to
use
<select id='combo'>
<option>Yes</option>
<option>No</option>
<option>other</option>
</select>
<input id='text1' style='display: none'/>
<input id='text2' style='display: none'/>
<script>
document.getElementById('combo').onchange = function() {
var display = this.selectedIndex == 2 ? "inline" : "none";
document.getElementById('text1').style.display = display;
document.getElementById('text2').style.display = display;
}
</script>
how do i go about applying this? if of course, this even works...
thanks
Delphi XE5 Android : how to make each listview item have its own template?
Delphi XE5 Android : how to make each listview item have its own template?
Is there a way to make the TListView of Delphi to behave like actual
ListView in android? for example each item of the list has its own "View"
and in that view can be multiple other views(components) like multiple
text boxes and check boxes and ...?
Is there a way to make the TListView of Delphi to behave like actual
ListView in android? for example each item of the list has its own "View"
and in that view can be multiple other views(components) like multiple
text boxes and check boxes and ...?
Sunday, 15 September 2013
Android Activity Hangs or Screen freeze When Reading Tags From NFC
Android Activity Hangs or Screen freeze When Reading Tags From NFC
I am developing an Android App which is functionality of Reading NFC-Tag
ID from NFC Card. I am using following code for reading NFC Tag from Card.
@Override
protected void onNewIntent(Intent intent) {
ReadNFCTagFromIntent(intent);
}
private void ReadNFCTagFromIntent(Intent intent) {
byte[] inarray = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
int i, j, in;
String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"A", "B", "C", "D", "E", "F" };
String nfc_card_tag = "";
for (j = 0; j < inarray.length; ++j) {
in = (int) inarray[j] & 0xff;
i = (in >> 4) & 0x0f;
nfc_card_tag += hex[i];
i = in & 0x0f;
nfc_card_tag += hex[i];
}
ShowDialog(nfc_card_tag); // This function Will Display a Dialog With
Tag Value....
}
I have also configured Foreground Dispatch System in activity OnPause &
OnResume method of activity
@Override
protected void onResume() {
super.onResume();
try {
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, getClass())
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter filter = new IntentFilter();
filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.enableForegroundDispatch(this, pendingIntent,
new IntentFilter[] { filter }, this.techList);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
super.onPause();
try {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.disableForegroundDispatch(this);
} catch (Exception e) {
}
}
Here is My Activity Declaration in Manifest File
<activity android:name="ActHome"
android:launchMode="singleTask"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfctechlist" />
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
</intent-filter>
This the xml in resource file that i am using for "TECH_DISCOVERED"
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech-list>
<tech>android.nfc.tech.IsoDep</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcA</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcB</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcF</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcV</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.Ndef</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NdefFormatable</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.MifareClassic</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.MifareUltralight</tech>
</tech-list>
</resources>
This code is working fine, but the problem is when i try to attach
nfc-card to my device, my activity hangs/freeze for at least 10/15 seconds
and then Dialog is shown as per my code. If i try to attach 5 to 6 cards
continuously one by one then its showing me all dialog after 10-15 seconds
at the same time. I don't know why my Activity is Hanging while reading
Tag from NFC Card.
Thanks in Advance
I am developing an Android App which is functionality of Reading NFC-Tag
ID from NFC Card. I am using following code for reading NFC Tag from Card.
@Override
protected void onNewIntent(Intent intent) {
ReadNFCTagFromIntent(intent);
}
private void ReadNFCTagFromIntent(Intent intent) {
byte[] inarray = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
int i, j, in;
String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
"A", "B", "C", "D", "E", "F" };
String nfc_card_tag = "";
for (j = 0; j < inarray.length; ++j) {
in = (int) inarray[j] & 0xff;
i = (in >> 4) & 0x0f;
nfc_card_tag += hex[i];
i = in & 0x0f;
nfc_card_tag += hex[i];
}
ShowDialog(nfc_card_tag); // This function Will Display a Dialog With
Tag Value....
}
I have also configured Foreground Dispatch System in activity OnPause &
OnResume method of activity
@Override
protected void onResume() {
super.onResume();
try {
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, getClass())
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter filter = new IntentFilter();
filter.addAction(NfcAdapter.ACTION_TAG_DISCOVERED);
filter.addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
filter.addAction(NfcAdapter.ACTION_TECH_DISCOVERED);
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.enableForegroundDispatch(this, pendingIntent,
new IntentFilter[] { filter }, this.techList);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onPause() {
super.onPause();
try {
NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
nfcAdapter.disableForegroundDispatch(this);
} catch (Exception e) {
}
}
Here is My Activity Declaration in Manifest File
<activity android:name="ActHome"
android:launchMode="singleTask"
android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
<intent-filter>
<action android:name="android.nfc.action.TAG_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<intent-filter>
<action android:name="android.nfc.action.TECH_DISCOVERED" />
</intent-filter>
<meta-data android:name="android.nfc.action.TECH_DISCOVERED"
android:resource="@xml/nfctechlist" />
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
</intent-filter>
This the xml in resource file that i am using for "TECH_DISCOVERED"
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
<tech-list>
<tech>android.nfc.tech.IsoDep</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcA</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcB</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcF</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NfcV</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.Ndef</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.NdefFormatable</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.MifareClassic</tech>
</tech-list>
<tech-list>
<tech>android.nfc.tech.MifareUltralight</tech>
</tech-list>
</resources>
This code is working fine, but the problem is when i try to attach
nfc-card to my device, my activity hangs/freeze for at least 10/15 seconds
and then Dialog is shown as per my code. If i try to attach 5 to 6 cards
continuously one by one then its showing me all dialog after 10-15 seconds
at the same time. I don't know why my Activity is Hanging while reading
Tag from NFC Card.
Thanks in Advance
strace Darwin Streaming Server
strace Darwin Streaming Server
I am trying to find out how Darwin Streaming Server (DSS) cooperate with
the OS, and what are the most common system calls made by the DSS. I used
the following commands to attach strace to DSS processes:
ps auxw | grep /usr/local/sbin/DarwinStreaming | awk '{print"-p " $2}' |
xargs strace
However, as shown below, the output of strace is not informative:
I am just wondering if there is any way to figure out what I want.
Thank you in advance,
I am trying to find out how Darwin Streaming Server (DSS) cooperate with
the OS, and what are the most common system calls made by the DSS. I used
the following commands to attach strace to DSS processes:
ps auxw | grep /usr/local/sbin/DarwinStreaming | awk '{print"-p " $2}' |
xargs strace
However, as shown below, the output of strace is not informative:
I am just wondering if there is any way to figure out what I want.
Thank you in advance,
How to redirect to another xaml page windows phone c#
How to redirect to another xaml page windows phone c#
I have the following code that finds out if the status of the posted
request (to an external api) was successful, and if so, it should navigate
to the Interface.xaml page I have created in the windows phone app.
public bool UsernameAndPassword(string username, string password)
{
data = "grant_type=" + GRANTTYPE + "&username=" + username +
"&password=" + password + "&client_id=" + CLIENTID + "&redirect_uri="
+ REDIRECTURI + "&client_secret=" + CLIENTSECRET;
return true;
}
public bool Authenticate()
{
// form the URI
UriBuilder fullUri = new UriBuilder(urlPath);
fullUri.Query = data;
// initialize a new WebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUri.Uri);
request.Method = "POST";
// set up the state object for the async request
DataUpdateState dataState = new DataUpdateState();
dataState.AsyncRequest = request;
// start the asynchronous request
request.BeginGetResponse(new AsyncCallback(HandleResponse),
dataState);
return true;
}
private void HandleResponse(IAsyncResult asyncResult)
{
// get the state information
DataUpdateState dataState = (DataUpdateState)asyncResult.AsyncState;
HttpWebRequest dataRequest = (HttpWebRequest)dataState.AsyncRequest;
// end the async request
dataState.AsyncResponse =
(HttpWebResponse)dataRequest.EndGetResponse(asyncResult);
if (dataState.AsyncResponse.StatusCode.ToString() == "OK")
{
// Navigatge to Interface.xaml not working?
NavigationService.Navigate(new Uri("Interface.xaml",
UriKind.Relative));
}
}
The problem can be found within the HandleResponse method in the if
statement.
public class DataUpdateState
{
public HttpWebRequest AsyncRequest { get; set; }
public HttpWebResponse AsyncResponse { get; set; }
}
I have the following code that finds out if the status of the posted
request (to an external api) was successful, and if so, it should navigate
to the Interface.xaml page I have created in the windows phone app.
public bool UsernameAndPassword(string username, string password)
{
data = "grant_type=" + GRANTTYPE + "&username=" + username +
"&password=" + password + "&client_id=" + CLIENTID + "&redirect_uri="
+ REDIRECTURI + "&client_secret=" + CLIENTSECRET;
return true;
}
public bool Authenticate()
{
// form the URI
UriBuilder fullUri = new UriBuilder(urlPath);
fullUri.Query = data;
// initialize a new WebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUri.Uri);
request.Method = "POST";
// set up the state object for the async request
DataUpdateState dataState = new DataUpdateState();
dataState.AsyncRequest = request;
// start the asynchronous request
request.BeginGetResponse(new AsyncCallback(HandleResponse),
dataState);
return true;
}
private void HandleResponse(IAsyncResult asyncResult)
{
// get the state information
DataUpdateState dataState = (DataUpdateState)asyncResult.AsyncState;
HttpWebRequest dataRequest = (HttpWebRequest)dataState.AsyncRequest;
// end the async request
dataState.AsyncResponse =
(HttpWebResponse)dataRequest.EndGetResponse(asyncResult);
if (dataState.AsyncResponse.StatusCode.ToString() == "OK")
{
// Navigatge to Interface.xaml not working?
NavigationService.Navigate(new Uri("Interface.xaml",
UriKind.Relative));
}
}
The problem can be found within the HandleResponse method in the if
statement.
public class DataUpdateState
{
public HttpWebRequest AsyncRequest { get; set; }
public HttpWebResponse AsyncResponse { get; set; }
}
Limited number of products displayed on portfolio page
Limited number of products displayed on portfolio page
On the portfolio page I want to a limited number of products. I have 300
products and that's too much to be all on one page.
I put this code for limited number of products (10 products per page)
'posts_per_page' => 10
And I put this code for insert page switching (in this case 30 page)
<!-- Pagination -->
<?php if(function_exists('pagination')){ pagination(); }else{
paginate_links(); } ?>
<!-- Pagination End -->
And in fact both codes work. Number of shown products is limited to 10
products. At the bottom of the page I got the option to switch to one of
the 30 pages.
But whatever number page I click, I always opened the first 10 the
products of.
Portfolio page - PHP Code
<?php
/*
Template Name: Portfolio 4 Column
*/
?>
<?php get_header(); ?>
<?php
if ( function_exists( 'get_option_tree') ) {
$tune_portfoliolock = get_option_tree(
'value_portfolio4columnlock' );
if($tune_portfoliolock != 0 && $tune_portfoliolock != ""){
$tune_pih = $tune_portfoliolock; }else{ $tune_pih = null; }
}
$templateurl = get_template_directory_uri();
$pagecustoms = getOptions();
if (isset($pagecustoms["header_title"])){$tune_htitle =
$pagecustoms['header_title'];}else{$tune_htitle = "";}
if (isset($pagecustoms["sidebar_orientation"])){$tune_sideo =
$pagecustoms['sidebar_orientation'];}else{$tune_sideo = 1;}
if ($tune_sideo == 0){$conorient = "right"; $sideoffset = "";
$conoffset = "offset-by-one";}else{$conorient = "left"; $sideoffset =
"offset-by-one"; $conoffset = "";}
if (isset($pagecustoms["sidebar"])){$tune_sidebar =
$pagecustoms["sidebar"];}else{$tune_sidebar = "Page Sidebar";}
if (isset($pagecustoms["portfolio_category"])){
$ptype = $pagecustoms['portfolio_category'];
$pcat = "category_".$ptype;
}
if (isset($pagecustoms["portfolio_alpha"])){
if($pagecustoms['portfolio_alpha']!=""){$tune_folioalpha =
$pagecustoms['portfolio_alpha'];}else{$tune_folioalpha = 0;}}else{
$tune_folioalpha = 0;}
?>
<!-- Text Block
================================================== -->
<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
<?php if( get_the_content() != ""){ ?>
<div class="sixteen columns row textblock">
<?php } else { ?>
<div class="sixteen columns row textblock" style="margin-top: -26px;">
<?php } the_content(); endwhile; endif; ?><div class="clear"></div>
</div>
<?php
$args=array(
'post_type' => $ptype,
'posts_per_page' => 10
);
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query($args);
$terms = get_terms($pcat);
?>
<!-- Portfolio Filters
================================================== -->
<div class="sixteen columns row noheadline"></div>
<div class="sixteen columns row portfolio_filter">
<ul>
<?php
echo '<li><a class="portfolio_selector" data-group="all-group"
href="#">'.__('All Projects',
'tune').'</a><span>·</span></li>';
foreach ( $terms as $term ) {
$filter_last_item = end($terms);
if($term!=$filter_last_item){
echo '<li><a class="portfolio_selector"
data-group="'.strtolower(str_replace(" ", "-",
$term->name)).'"
href="#">'.$term->name.'</a><span>·</span></li>';
}else{
echo '<li><a class="portfolio_selector"
data-group="'.strtolower(str_replace(" ", "-",
$term->name)).'" href="#">'.$term->name.'</a></li>';
}
}
?>
</ul>
</div><div class="clear"></div>
<!-- Portfolio
================================================== -->
<div class="sixteen columns row teasers portfolio nopadding">
<?php if ($wp_query->have_posts()) : ?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
<?php
$custom = get_post_custom($post->ID);
$foliocatlist = get_the_term_list( $post->ID, $pcat, '', ', ', '' );
$entrycategory = get_the_term_list( $post->ID, $pcat, '', '_', '' );
$entrycategory = strip_tags($entrycategory);
$entrycategory = strtolower($entrycategory);
$entrycategory = str_replace(' ', '-', $entrycategory);
$entrycategory = str_replace('_', ' ', $entrycategory);
$entrytitle = get_the_title();
$blogimageurl = wp_get_attachment_url(
get_post_thumbnail_id($post->ID) );
if($blogimageurl==""){
$theblogimage = $templateurl.'/images/demo/460x259.jpg';
}else{
$theblogimage = aq_resize( $blogimageurl, 420,
$tune_portfoliolock, true );
}
$foliocustoms = getOptions($post->ID);
if (isset($foliocustoms["postformat_detail"])){$tune_postdetail =
$foliocustoms['postformat_detail'];}else{$tune_postdetail = 0;}
if (isset($foliocustoms["postformat_type"])){$tune_postformat =
$foliocustoms['postformat_type'];}else{$tune_postformat = 0;}
if (isset($foliocustoms["postformat_video"])){$tune_postvideo =
$foliocustoms['postformat_video'];}else{$tune_postvideo = "";}
if (isset($foliocustoms["postformat_lightbox"])){$tune_lightbox =
$foliocustoms['postformat_lightbox'];}else{$tune_lightbox = 0;}
if($tune_lightbox==1){ $lblink = $blogimageurl; } else
if($tune_lightbox==2){ $lblink =
'http://www.youtube.com/watch?v='.$tune_postvideo.'&width=720&height=435';
} else if($tune_lightbox==3){ $lblink =
'http://vimeo.com/'.$tune_postvideo.'&width=720&height=405';
}
if($tune_lightbox!=0 && $tune_postdetail==0){ $notalonemod =
"notalone"; } else { $notalonemod = ""; }
?>
<div class="four columns teaser all-group <?php echo $entrycategory ?>">
<div class="mediaholder">
<?php echo '<img src="'.$theblogimage.'" alt="" />'; ?>
<div class="cover"></div>
<?php if($tune_postdetail==0){ ?>
<a href="<?php the_permalink(); ?>"><div class="link <?php
echo $notalonemod ?>"></div></a>
<?php } ?>
<?php if($tune_lightbox!=0){ ?>
<a title="<?php echo $entrytitle ?>" href="<?php echo
$lblink ?>" data-rel="prettyPhoto[folio]"><div class="show
<?php echo $notalonemod ?>"></div></a>
<?php } ?>
</div>
<div class="topline">
<?php if($tune_postdetail==0){ ?><a href="<?php the_permalink();
?>"><?php echo $entrytitle ?></a><?php } else { ?><?php echo
$entrytitle ?><?php } ?>
</div>
<div class="subline"><?php echo $foliocatlist ?></div>
</div>
<?php endwhile; ?>
<!-- Pagination -->
<?php if(function_exists('pagination')){ pagination(); }else{
paginate_links(); } ?>
<!-- Pagination End -->
<?php else : ?>
<div class="eleven columns row alpha">
<p><?php _e('Oops, we could not find what you were looking
for...', 'tune'); ?></p>
</div>
<?php endif; ?>
<?php
$wp_query = null;
$wp_query = $temp;
wp_reset_query();
?>
<div class="clear"></div>
</div><div class="clear"></div>
<!-- Space Adjuster
================================================== -->
<div class="sixteen columns bottomadjust"></div><div class="clear"></div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.portfolio4column').tpportfolio({
row:4,
portfolioContainer:'.portfolio'
});
});
</script>
<?php get_footer(); ?>
If anyone has any suggestions on how to solve this problem. Thanks!
On the portfolio page I want to a limited number of products. I have 300
products and that's too much to be all on one page.
I put this code for limited number of products (10 products per page)
'posts_per_page' => 10
And I put this code for insert page switching (in this case 30 page)
<!-- Pagination -->
<?php if(function_exists('pagination')){ pagination(); }else{
paginate_links(); } ?>
<!-- Pagination End -->
And in fact both codes work. Number of shown products is limited to 10
products. At the bottom of the page I got the option to switch to one of
the 30 pages.
But whatever number page I click, I always opened the first 10 the
products of.
Portfolio page - PHP Code
<?php
/*
Template Name: Portfolio 4 Column
*/
?>
<?php get_header(); ?>
<?php
if ( function_exists( 'get_option_tree') ) {
$tune_portfoliolock = get_option_tree(
'value_portfolio4columnlock' );
if($tune_portfoliolock != 0 && $tune_portfoliolock != ""){
$tune_pih = $tune_portfoliolock; }else{ $tune_pih = null; }
}
$templateurl = get_template_directory_uri();
$pagecustoms = getOptions();
if (isset($pagecustoms["header_title"])){$tune_htitle =
$pagecustoms['header_title'];}else{$tune_htitle = "";}
if (isset($pagecustoms["sidebar_orientation"])){$tune_sideo =
$pagecustoms['sidebar_orientation'];}else{$tune_sideo = 1;}
if ($tune_sideo == 0){$conorient = "right"; $sideoffset = "";
$conoffset = "offset-by-one";}else{$conorient = "left"; $sideoffset =
"offset-by-one"; $conoffset = "";}
if (isset($pagecustoms["sidebar"])){$tune_sidebar =
$pagecustoms["sidebar"];}else{$tune_sidebar = "Page Sidebar";}
if (isset($pagecustoms["portfolio_category"])){
$ptype = $pagecustoms['portfolio_category'];
$pcat = "category_".$ptype;
}
if (isset($pagecustoms["portfolio_alpha"])){
if($pagecustoms['portfolio_alpha']!=""){$tune_folioalpha =
$pagecustoms['portfolio_alpha'];}else{$tune_folioalpha = 0;}}else{
$tune_folioalpha = 0;}
?>
<!-- Text Block
================================================== -->
<?php if(have_posts()) : while(have_posts()) : the_post(); ?>
<?php if( get_the_content() != ""){ ?>
<div class="sixteen columns row textblock">
<?php } else { ?>
<div class="sixteen columns row textblock" style="margin-top: -26px;">
<?php } the_content(); endwhile; endif; ?><div class="clear"></div>
</div>
<?php
$args=array(
'post_type' => $ptype,
'posts_per_page' => 10
);
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query($args);
$terms = get_terms($pcat);
?>
<!-- Portfolio Filters
================================================== -->
<div class="sixteen columns row noheadline"></div>
<div class="sixteen columns row portfolio_filter">
<ul>
<?php
echo '<li><a class="portfolio_selector" data-group="all-group"
href="#">'.__('All Projects',
'tune').'</a><span>·</span></li>';
foreach ( $terms as $term ) {
$filter_last_item = end($terms);
if($term!=$filter_last_item){
echo '<li><a class="portfolio_selector"
data-group="'.strtolower(str_replace(" ", "-",
$term->name)).'"
href="#">'.$term->name.'</a><span>·</span></li>';
}else{
echo '<li><a class="portfolio_selector"
data-group="'.strtolower(str_replace(" ", "-",
$term->name)).'" href="#">'.$term->name.'</a></li>';
}
}
?>
</ul>
</div><div class="clear"></div>
<!-- Portfolio
================================================== -->
<div class="sixteen columns row teasers portfolio nopadding">
<?php if ($wp_query->have_posts()) : ?>
<?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?>
<?php
$custom = get_post_custom($post->ID);
$foliocatlist = get_the_term_list( $post->ID, $pcat, '', ', ', '' );
$entrycategory = get_the_term_list( $post->ID, $pcat, '', '_', '' );
$entrycategory = strip_tags($entrycategory);
$entrycategory = strtolower($entrycategory);
$entrycategory = str_replace(' ', '-', $entrycategory);
$entrycategory = str_replace('_', ' ', $entrycategory);
$entrytitle = get_the_title();
$blogimageurl = wp_get_attachment_url(
get_post_thumbnail_id($post->ID) );
if($blogimageurl==""){
$theblogimage = $templateurl.'/images/demo/460x259.jpg';
}else{
$theblogimage = aq_resize( $blogimageurl, 420,
$tune_portfoliolock, true );
}
$foliocustoms = getOptions($post->ID);
if (isset($foliocustoms["postformat_detail"])){$tune_postdetail =
$foliocustoms['postformat_detail'];}else{$tune_postdetail = 0;}
if (isset($foliocustoms["postformat_type"])){$tune_postformat =
$foliocustoms['postformat_type'];}else{$tune_postformat = 0;}
if (isset($foliocustoms["postformat_video"])){$tune_postvideo =
$foliocustoms['postformat_video'];}else{$tune_postvideo = "";}
if (isset($foliocustoms["postformat_lightbox"])){$tune_lightbox =
$foliocustoms['postformat_lightbox'];}else{$tune_lightbox = 0;}
if($tune_lightbox==1){ $lblink = $blogimageurl; } else
if($tune_lightbox==2){ $lblink =
'http://www.youtube.com/watch?v='.$tune_postvideo.'&width=720&height=435';
} else if($tune_lightbox==3){ $lblink =
'http://vimeo.com/'.$tune_postvideo.'&width=720&height=405';
}
if($tune_lightbox!=0 && $tune_postdetail==0){ $notalonemod =
"notalone"; } else { $notalonemod = ""; }
?>
<div class="four columns teaser all-group <?php echo $entrycategory ?>">
<div class="mediaholder">
<?php echo '<img src="'.$theblogimage.'" alt="" />'; ?>
<div class="cover"></div>
<?php if($tune_postdetail==0){ ?>
<a href="<?php the_permalink(); ?>"><div class="link <?php
echo $notalonemod ?>"></div></a>
<?php } ?>
<?php if($tune_lightbox!=0){ ?>
<a title="<?php echo $entrytitle ?>" href="<?php echo
$lblink ?>" data-rel="prettyPhoto[folio]"><div class="show
<?php echo $notalonemod ?>"></div></a>
<?php } ?>
</div>
<div class="topline">
<?php if($tune_postdetail==0){ ?><a href="<?php the_permalink();
?>"><?php echo $entrytitle ?></a><?php } else { ?><?php echo
$entrytitle ?><?php } ?>
</div>
<div class="subline"><?php echo $foliocatlist ?></div>
</div>
<?php endwhile; ?>
<!-- Pagination -->
<?php if(function_exists('pagination')){ pagination(); }else{
paginate_links(); } ?>
<!-- Pagination End -->
<?php else : ?>
<div class="eleven columns row alpha">
<p><?php _e('Oops, we could not find what you were looking
for...', 'tune'); ?></p>
</div>
<?php endif; ?>
<?php
$wp_query = null;
$wp_query = $temp;
wp_reset_query();
?>
<div class="clear"></div>
</div><div class="clear"></div>
<!-- Space Adjuster
================================================== -->
<div class="sixteen columns bottomadjust"></div><div class="clear"></div>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('.portfolio4column').tpportfolio({
row:4,
portfolioContainer:'.portfolio'
});
});
</script>
<?php get_footer(); ?>
If anyone has any suggestions on how to solve this problem. Thanks!
UIPanGestureRecognizer prevent 2 views to overlap
UIPanGestureRecognizer prevent 2 views to overlap
I have 2 UIViews. When I move one view, I need it not to overlap the
second how do I do it?
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x +
translation.x,
recognizer.view.center.y +
translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
// Figure out where the user is trying to drag the view.
CGPoint centerOfMovingObject = CGPointMake(self.view.bounds.size.width
/ 2,
recognizer.view.center.y +
translation.y);
UIButton* otherButton = nil;
if (recognizer.view.tag == 1) {
otherButton = (UIButton*)[self.view viewWithTag:2];
}else{
otherButton = (UIButton*)[self.view viewWithTag:1];
}
// Figure out where the user is trying to drag the view.
CGPoint centerOfTheOtherObject =
CGPointMake(self.view.bounds.size.width / 2,
recognizer.view.center.y +
translation.y);
// **Prevent from overlaping**???
}
I have 2 UIViews. When I move one view, I need it not to overlap the
second how do I do it?
- (IBAction)handlePan:(UIPanGestureRecognizer *)recognizer {
CGPoint translation = [recognizer translationInView:self.view];
recognizer.view.center = CGPointMake(recognizer.view.center.x +
translation.x,
recognizer.view.center.y +
translation.y);
[recognizer setTranslation:CGPointMake(0, 0) inView:self.view];
// Figure out where the user is trying to drag the view.
CGPoint centerOfMovingObject = CGPointMake(self.view.bounds.size.width
/ 2,
recognizer.view.center.y +
translation.y);
UIButton* otherButton = nil;
if (recognizer.view.tag == 1) {
otherButton = (UIButton*)[self.view viewWithTag:2];
}else{
otherButton = (UIButton*)[self.view viewWithTag:1];
}
// Figure out where the user is trying to drag the view.
CGPoint centerOfTheOtherObject =
CGPointMake(self.view.bounds.size.width / 2,
recognizer.view.center.y +
translation.y);
// **Prevent from overlaping**???
}
Get elements that are not inside of an element that has a known class
Get elements that are not inside of an element that has a known class
Suppose you have the following HTML code:
<div class="test">
<div class="class1">
<input type="text" data-required="true"/>
</div>
<input type="text" data-required="true"/>
</div>
I want to get all elements that have data-required attribute from .test
that are not inside of the .class1 div. So, in the example above only the
second input would be returned.
I tried:
$(".test [data-required]:not('.class1')")
but it returns the both input because :not doesn't select the parent
elements.
Is this possible with one jQuery selector?
JSFIDDLE
Suppose you have the following HTML code:
<div class="test">
<div class="class1">
<input type="text" data-required="true"/>
</div>
<input type="text" data-required="true"/>
</div>
I want to get all elements that have data-required attribute from .test
that are not inside of the .class1 div. So, in the example above only the
second input would be returned.
I tried:
$(".test [data-required]:not('.class1')")
but it returns the both input because :not doesn't select the parent
elements.
Is this possible with one jQuery selector?
JSFIDDLE
How can I send emails from my custom UIActivity class?
How can I send emails from my custom UIActivity class?
I made a costume UIActivity class. I like to send emails with attachments
with the class, but I can't send emails, or present any ViewControllers
from the class. I am trying to present the Mail ViewController with this:
- (void)prepareWithActivityItems:(NSArray *)activityItems
{
NSString *subject = [NSString stringWithFormat:@"%@", [self.filePath
lastPathComponent]];
NSString *messageBody = [NSString stringWithFormat:@"%@ was extracted
with @FilyForiOS, visit", [self.filePath lastPathComponent]];
NSData *attachment = [NSData dataWithContentsOfFile:self.filePath];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc]
init];
mc.mailComposeDelegate = self;
[mc setSubject:subject];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:nil];
[mc addAttachmentData:attachment mimeType:[[self.filePath
lastPathComponent] pathExtension] fileName:[self.filePath
lastPathComponent]];
[self presentViewController:mc animated:YES completion:nil]; // Here
is the error: No visible @interface for 'MailTo' declares the selector
'presentViewController:animated:completion:'
}
Can anyone tell me how I can present a ViewController from this class?
I made a costume UIActivity class. I like to send emails with attachments
with the class, but I can't send emails, or present any ViewControllers
from the class. I am trying to present the Mail ViewController with this:
- (void)prepareWithActivityItems:(NSArray *)activityItems
{
NSString *subject = [NSString stringWithFormat:@"%@", [self.filePath
lastPathComponent]];
NSString *messageBody = [NSString stringWithFormat:@"%@ was extracted
with @FilyForiOS, visit", [self.filePath lastPathComponent]];
NSData *attachment = [NSData dataWithContentsOfFile:self.filePath];
MFMailComposeViewController *mc = [[MFMailComposeViewController alloc]
init];
mc.mailComposeDelegate = self;
[mc setSubject:subject];
[mc setMessageBody:messageBody isHTML:NO];
[mc setToRecipients:nil];
[mc addAttachmentData:attachment mimeType:[[self.filePath
lastPathComponent] pathExtension] fileName:[self.filePath
lastPathComponent]];
[self presentViewController:mc animated:YES completion:nil]; // Here
is the error: No visible @interface for 'MailTo' declares the selector
'presentViewController:animated:completion:'
}
Can anyone tell me how I can present a ViewController from this class?
Saturday, 14 September 2013
Fixing a class to ensure that it adds objects to its list, only if it implements a certain interface - Java
Fixing a class to ensure that it adds objects to its list, only if it
implements a certain interface - Java
I've been given a class - GoodPetStoreClient - that makes use of another
class - NoisyPetStore - in order to create a list of objects - Cat, Dog
and Cow - which implement an interface - MakesSound - and have been asked
to modify NoisyPetStore to ensure that GoodPetStoreClient will compile
properly. I've been trying to work out what I'm missing, but without luck
so far, and would appreciate some more experienced insight.
Thanks!
Here's the code public class GoodPetStoreClient {
public static void main(String[] args) {
NoisyPetStore petStore = new NoisyPetStore();
petStore.addPet(new Cat());
petStore.addPet(new Cow());
System.out.println("I bought an animal, and it goes: " +
petStore.buyNewestPet().makeNoise()); //moo...
System.out.println("The rest of the pet store goes: " +
petStore.makeHugeNoise()); //meow
System.out.println("I bought another animal, and it goes: " +
petStore.buyNewestPet().makeNoise()); //meow
petStore.addPet(new Dog());
System.out.println("The pet store now goes: " +
petStore.buyNewestPet().makeNoise());
}
private static class CollisionInSpace {
// makes no sound at all
}
}
import java.util.ArrayList; import java.util.List;
public class NoisyPetStore
{
//Stores pets
private List list;
public NoisyPetStore()
{
list = new ArrayList();
}
/* add a pet to the pet store after checking
* whether or not the object implements
* <MakesSound>
* @param o takes in a object of an unspecified
* class
**/
public void addPet(Object o )
{
//check if the instance implements the MakesSound interface
if(o instanceof MakesSound)
{
list.add(o);
}
}
/* get the last pet from the store by accessing
* the last item in the list, and hence the one
* which has been added most recently
**/
public Object buyNewestPet()
{
Object ans = null;
if (list.size() > 0)
{
ans = list.remove(list.size() - 1);
}
return ((MakesSound)ans);
}
/* creates a string representation of all of the noises
* made by pets which have been added to the list using
* a <StringBuilder>
* @return returns a String representation of all the noises
* made by the pets in the list
**/
public String makeHugeNoise() {
StringBuilder ans = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
ans.append(((MakesSound) list.get(i)).makeNoise());
}
return ans.toString();
}
}
public class Cat implements MakesSound
{
String sound;
/* Constructor for Cat object
* takes in no parameters and instantiates
* the instance variable sound
**/
public Cat()
{
sound = "Meeow";
}
/* Overrides the <makeNoise> method defined by the
* <MakeSounds> interface
* takes in no parameters and returns the sound made
* by a cat, represented as a <String> {@link String}
**/
@Override
public String makeNoise()
{
String s = sound;
return s;
}
}
//dog and cow have identical codes to cat, with the exception that they
produce the sounds "Woof!" and "Moo!" respectively.
implements a certain interface - Java
I've been given a class - GoodPetStoreClient - that makes use of another
class - NoisyPetStore - in order to create a list of objects - Cat, Dog
and Cow - which implement an interface - MakesSound - and have been asked
to modify NoisyPetStore to ensure that GoodPetStoreClient will compile
properly. I've been trying to work out what I'm missing, but without luck
so far, and would appreciate some more experienced insight.
Thanks!
Here's the code public class GoodPetStoreClient {
public static void main(String[] args) {
NoisyPetStore petStore = new NoisyPetStore();
petStore.addPet(new Cat());
petStore.addPet(new Cow());
System.out.println("I bought an animal, and it goes: " +
petStore.buyNewestPet().makeNoise()); //moo...
System.out.println("The rest of the pet store goes: " +
petStore.makeHugeNoise()); //meow
System.out.println("I bought another animal, and it goes: " +
petStore.buyNewestPet().makeNoise()); //meow
petStore.addPet(new Dog());
System.out.println("The pet store now goes: " +
petStore.buyNewestPet().makeNoise());
}
private static class CollisionInSpace {
// makes no sound at all
}
}
import java.util.ArrayList; import java.util.List;
public class NoisyPetStore
{
//Stores pets
private List list;
public NoisyPetStore()
{
list = new ArrayList();
}
/* add a pet to the pet store after checking
* whether or not the object implements
* <MakesSound>
* @param o takes in a object of an unspecified
* class
**/
public void addPet(Object o )
{
//check if the instance implements the MakesSound interface
if(o instanceof MakesSound)
{
list.add(o);
}
}
/* get the last pet from the store by accessing
* the last item in the list, and hence the one
* which has been added most recently
**/
public Object buyNewestPet()
{
Object ans = null;
if (list.size() > 0)
{
ans = list.remove(list.size() - 1);
}
return ((MakesSound)ans);
}
/* creates a string representation of all of the noises
* made by pets which have been added to the list using
* a <StringBuilder>
* @return returns a String representation of all the noises
* made by the pets in the list
**/
public String makeHugeNoise() {
StringBuilder ans = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
ans.append(((MakesSound) list.get(i)).makeNoise());
}
return ans.toString();
}
}
public class Cat implements MakesSound
{
String sound;
/* Constructor for Cat object
* takes in no parameters and instantiates
* the instance variable sound
**/
public Cat()
{
sound = "Meeow";
}
/* Overrides the <makeNoise> method defined by the
* <MakeSounds> interface
* takes in no parameters and returns the sound made
* by a cat, represented as a <String> {@link String}
**/
@Override
public String makeNoise()
{
String s = sound;
return s;
}
}
//dog and cow have identical codes to cat, with the exception that they
produce the sounds "Woof!" and "Moo!" respectively.
WP8 WebClient Not Found Error
WP8 WebClient Not Found Error
I am trying to POST JSON data to my WCF service but I get a Not Found error.
Code:
public void ReportSighting()
{
Sighting.Instance.TypeId = "SightingTypes/2";
Sighting.Instance.BrandId = "brands/1";
string jsonData = JsonConvert.SerializeObject(Sighting.Instance);
WebClient webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] =
"application/json";
var uri = new Uri("myUrl", UriKind.Absolute);
webClient.Headers[HttpRequestHeader.ContentLength] =
jsonData.Length.ToString();
webClient.AllowWriteStreamBuffering = true;
webClient.Encoding = System.Text.Encoding.UTF8;
webClient.UploadStringAsync(uri, "POST", jsonData.ToString());
webClient.UploadStringCompleted += new
UploadStringCompletedEventHandler(postComplete);
System.Threading.Thread.Sleep(200);
}
private void postComplete(object sender,
UploadStringCompletedEventArgs e)
{
//Response result =
JsonConvert.DeserializeObject<Response>(e.Result);
try
{
MessageBox.Show(e.Result);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Error: InnerException = {System.Net.WebException: The remote server
returned an error: NotFound. ---> System.Net.WebException: The remote
server returned an error: NotFound. at
System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult
asyncResult) at Syst...
I am trying to POST JSON data to my WCF service but I get a Not Found error.
Code:
public void ReportSighting()
{
Sighting.Instance.TypeId = "SightingTypes/2";
Sighting.Instance.BrandId = "brands/1";
string jsonData = JsonConvert.SerializeObject(Sighting.Instance);
WebClient webClient = new WebClient();
webClient.Headers[HttpRequestHeader.ContentType] =
"application/json";
var uri = new Uri("myUrl", UriKind.Absolute);
webClient.Headers[HttpRequestHeader.ContentLength] =
jsonData.Length.ToString();
webClient.AllowWriteStreamBuffering = true;
webClient.Encoding = System.Text.Encoding.UTF8;
webClient.UploadStringAsync(uri, "POST", jsonData.ToString());
webClient.UploadStringCompleted += new
UploadStringCompletedEventHandler(postComplete);
System.Threading.Thread.Sleep(200);
}
private void postComplete(object sender,
UploadStringCompletedEventArgs e)
{
//Response result =
JsonConvert.DeserializeObject<Response>(e.Result);
try
{
MessageBox.Show(e.Result);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
Error: InnerException = {System.Net.WebException: The remote server
returned an error: NotFound. ---> System.Net.WebException: The remote
server returned an error: NotFound. at
System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult
asyncResult) at Syst...
All entries in registry are gone
All entries in registry are gone
I am working on wine to install some windows software in my linux.
Following some guidelines on the web, I made some changes in registry. I
suppose it will save the changes on its own, since there is no a "save"
button. But surprisingly, after I closed the registry and reopened it, I
found everything was gone! What might be the reason for this? Can I
download and import a new registry?
I am working on wine to install some windows software in my linux.
Following some guidelines on the web, I made some changes in registry. I
suppose it will save the changes on its own, since there is no a "save"
button. But surprisingly, after I closed the registry and reopened it, I
found everything was gone! What might be the reason for this? Can I
download and import a new registry?
Find and replace relative url with url from database - PHP
Find and replace relative url with url from database - PHP
I'm trying to to find internal links in html e.g.
<p>This is first <a href="/old-link-first">old link</a> and this is second
<a href="/old-link-second">old link</a></p>
I have to match relative links make query on database in order to get
links from database, I have problem with matching :/ and executing.
I tried with this but it seems to work only with first link:
$out='<p>This is first <a href="/old-link-first">old link</a> and this is
second <a href="/old-link-second">old link</a></p>';
$pattern = '/href="\/(.*)?"/';
function ch($match){
$oldurl = 'href="'.$match[1].'"';
// query to database
return $newurl;
}
$out = preg_replace_callback($pattern, 'ch', $out);
print $out;
Probably I have lots of mistakes Thanks in advance
I'm trying to to find internal links in html e.g.
<p>This is first <a href="/old-link-first">old link</a> and this is second
<a href="/old-link-second">old link</a></p>
I have to match relative links make query on database in order to get
links from database, I have problem with matching :/ and executing.
I tried with this but it seems to work only with first link:
$out='<p>This is first <a href="/old-link-first">old link</a> and this is
second <a href="/old-link-second">old link</a></p>';
$pattern = '/href="\/(.*)?"/';
function ch($match){
$oldurl = 'href="'.$match[1].'"';
// query to database
return $newurl;
}
$out = preg_replace_callback($pattern, 'ch', $out);
print $out;
Probably I have lots of mistakes Thanks in advance
Rails Engines, mountable apps etc, effect of failure of one
Rails Engines, mountable apps etc, effect of failure of one
I assume that if you mount an app in a main rails or use a rails engine.
If any of the sub-apps fail/crash than that means the main app and all the
sub-app fail/crash.
Does anyone know this for sure? I am wondering if I am building a system
if I should separate my architecture into multiple standalone application
and instances or build Engine/mountable apps instead of a larger app. The
worry is what would happen if part of the app ecosystem goes don't how
does it effect the rest of the applications.
Thanks
I assume that if you mount an app in a main rails or use a rails engine.
If any of the sub-apps fail/crash than that means the main app and all the
sub-app fail/crash.
Does anyone know this for sure? I am wondering if I am building a system
if I should separate my architecture into multiple standalone application
and instances or build Engine/mountable apps instead of a larger app. The
worry is what would happen if part of the app ecosystem goes don't how
does it effect the rest of the applications.
Thanks
Avoiding full postback when using OnClientDateSelectionChanged on a control
Avoiding full postback when using OnClientDateSelectionChanged on a control
I am using ASP.NET c# 4.0
I am using AJAX.
I am using ajax calendar extender which after selecting a date fills a
text box with a chosen date. I wanted to execute some server side code
when the date changes so I put this in :
OnClientDateSelectionChanged="function
ddd(){__doPostBack('DateTextBox','') ;}" into the extender control.
Unfortunately, the whole page gets posted back. If i put this control in
an Update control it tells me that it is already in an update control. If
I include the textbox within the update panel i get 2 of these text boxes
on my web page after selecting a date. Does anyone know how to inform the
server that the date selected from this ajax control has changed without a
full post back please?
thanks
I am using ASP.NET c# 4.0
I am using AJAX.
I am using ajax calendar extender which after selecting a date fills a
text box with a chosen date. I wanted to execute some server side code
when the date changes so I put this in :
OnClientDateSelectionChanged="function
ddd(){__doPostBack('DateTextBox','') ;}" into the extender control.
Unfortunately, the whole page gets posted back. If i put this control in
an Update control it tells me that it is already in an update control. If
I include the textbox within the update panel i get 2 of these text boxes
on my web page after selecting a date. Does anyone know how to inform the
server that the date selected from this ajax control has changed without a
full post back please?
thanks
Terrible run time with Parallel computin
Terrible run time with Parallel computin
I have use this code for running two function simultaneously. but run time
is Terrible.my CPU is dual core and function g and g1 do not interact.in
normal run xc1 is matrix with 4950 row and 4 column and same for xc2.
matlabpool ('open',2);
parfor i = 1:2
if i == 1
xc1=gh(0.10001,0.8,12,0.2,68,1.2);
else
xc2=gh1(3,0.40001,9,0.7,50,3.25);
end
end
matlabpool close;
I have use this code for running two function simultaneously. but run time
is Terrible.my CPU is dual core and function g and g1 do not interact.in
normal run xc1 is matrix with 4950 row and 4 column and same for xc2.
matlabpool ('open',2);
parfor i = 1:2
if i == 1
xc1=gh(0.10001,0.8,12,0.2,68,1.2);
else
xc2=gh1(3,0.40001,9,0.7,50,3.25);
end
end
matlabpool close;
FBgraphapiurl values cant be able access
FBgraphapiurl values cant be able access
I have used facebook login in my application,i have used FBgraphapiurl to
get the details ,But i cant able to get the BIRTHDAY,COUNTRY, STATE, CITY,
Whereas the firstname,Lastname,email id coming properly,Here my code.
var url5 =
FBgraphapiurl+'me?fields=id,first_name,last_name,email,gender&access_token='
+ fbcodessss + '&redirect_uri=http://www.fastabuy.com/index.php';
Ext.Ajax.request({
url: url5,
success: function (data, status) {
var jsondata = eval("(" + data.responseText + ")");
var data = jsondata;
var id = data.id;
var email = data.email;
var name = data.first_name;
if (data.id != null) {
App.gvars.BuyFBID = data.id;
}
if (data.first_name != null) {
Ext.getCmp('firstname').setValue(data.first_name);
Ext.getCmp('lastname').setValue(data.last_name);
}
if (data.email != null) {
Ext.getCmp('emailId').setValue(data.email);
Ext.getCmp('Gender').setValue(data.gender);
}
}
})}});
When i try with the following
var url5 =
FBgraphapiurl+'me?fields=id,first_name,last_name,email,gender,birthdate,country,state&access_token='
+ fbcodessss + '&redirect_uri=http://www.fastabuy.com/index.php';
its not showing?whats wrong with my code
I have used facebook login in my application,i have used FBgraphapiurl to
get the details ,But i cant able to get the BIRTHDAY,COUNTRY, STATE, CITY,
Whereas the firstname,Lastname,email id coming properly,Here my code.
var url5 =
FBgraphapiurl+'me?fields=id,first_name,last_name,email,gender&access_token='
+ fbcodessss + '&redirect_uri=http://www.fastabuy.com/index.php';
Ext.Ajax.request({
url: url5,
success: function (data, status) {
var jsondata = eval("(" + data.responseText + ")");
var data = jsondata;
var id = data.id;
var email = data.email;
var name = data.first_name;
if (data.id != null) {
App.gvars.BuyFBID = data.id;
}
if (data.first_name != null) {
Ext.getCmp('firstname').setValue(data.first_name);
Ext.getCmp('lastname').setValue(data.last_name);
}
if (data.email != null) {
Ext.getCmp('emailId').setValue(data.email);
Ext.getCmp('Gender').setValue(data.gender);
}
}
})}});
When i try with the following
var url5 =
FBgraphapiurl+'me?fields=id,first_name,last_name,email,gender,birthdate,country,state&access_token='
+ fbcodessss + '&redirect_uri=http://www.fastabuy.com/index.php';
its not showing?whats wrong with my code
Friday, 13 September 2013
Is {1, 2} a value? If yes, what is its type? If no, why can it be assigned to an initializer list?
Is {1, 2} a value? If yes, what is its type? If no, why can it be assigned
to an initializer list?
#include <initializer_list>
using namespace std;
template<class T>
void f(initializer_list<T>)
{}
int main()
{
typeid(1); // OK
typeid(int); // OK
typeid(decltype(1)); // OK
f({1, 2}); // OK
typeid({1, 2}); // error
decltype({1, 2}) v; // error
typeid(decltype({1, 2})); // error
}
Is {1, 2} a value?
If yes, why is typeid({1, 2}); not legal?
If no, why can it be assigned to an initializer_list object?
to an initializer list?
#include <initializer_list>
using namespace std;
template<class T>
void f(initializer_list<T>)
{}
int main()
{
typeid(1); // OK
typeid(int); // OK
typeid(decltype(1)); // OK
f({1, 2}); // OK
typeid({1, 2}); // error
decltype({1, 2}) v; // error
typeid(decltype({1, 2})); // error
}
Is {1, 2} a value?
If yes, why is typeid({1, 2}); not legal?
If no, why can it be assigned to an initializer_list object?
Design Pattern to track partial results of a complex process
Design Pattern to track partial results of a complex process
I'm facing a programming problem that I don't know how to solve in a
object oriented and flexible way. I have in mind some bad solutions, but
I'm searching for a good one. I develop in Java, so I prefer Java ideas,
but any object oriented idea is welcome.
I've been searching for ideas, design patterns, or some algorithm that can
help me, but I don't know which terminology or name give to my problem, so
I couldn't find any clue.
Problem:
Summary:
I need to track partial results of a process that makes different changes
to a collection of entities. I need this to report to the user, the detail
of each calculation "step" in a table report. And also I need to persist
this collection in a database.
Detail:
The software I maintain has an entity similar to this one: public class
Salary { private Date date; private BigDecimal amount; }
That is grouped in a Collection, like this:
List<Salary> teamSalaries;
This set of entities can be modified by a set of "tasks" depending on some
rules:
Apply a certain tax (from a set of differents taxes)
Calculate a Future value for the money amount (More Info)
Discount an amount of money to keep below a maximum
etc...
For example:
public void processTeamSalaries(List<Salary> teamSalaries) {
applyTax(teamSalaries, Taxes.TAX_TYPE_1);
(...)
getFutureValue(teamSalaries, someFutureDate);
(...)
restrictToAMaximum(teamSalaries, Maximum.MARRIED_MAXIMUM);
(...)
applyTax(teamSalaries, TAXES.TAX_TYPE_3);
(...)
}
public void applyTax(List<Salary> teamSalaries, Tax taxToApply) {
for(Salary aSalary : teamSalaries) {
aSalary.setAmount(calculateAmountWithTax(aSalary.getAmount(),
taxToApply);
}
}
(...)
What I need is to process this collection of salaries, making changes to
the amount of money but preserving all the intermediate "states" of the
money amount, to show it to the user in a table with columns like these:
Date | Original Amount | Amount after tax 1 | Future Amount | Amount after
restriction | Amount after tax 2
My Ideas:
Add an attribute for each "partial result" on the class Salary
public class Salary {
(...)
private BigDecimal originalAmount;
private BigDecimal amountAfterFirstTax;
private BigDecimal amountAfterMaximumRestriction;
(...)
}
Problems:
The "steps" aren't rigid, maybe tomorrow one "step" changes, a new one
appears, or the "meaning" of some step changes. In that case I will need
to refactor the code too much.
Some "steps" can be repeated, so, how can I tell to the "method" in which
attribute have to "set" the result of the calculation?
Add a HashMap to the Salary class where I can put the partial results, and
pass to the "step" method the "key" where it have to put the partial
result
public class Salary {
(...)
HashMap<String, BigDecimal> partialResults;
(...)
}
Problems:
In some place I need to populate the HashMap to a JPA entity to save it on
my Database
If another developer changes the name of the key (for whatever reason)
maybe the "populating" of the attributes gets broken
Final Note: There are other similar situations with other "similar"
entities in my application, so it would be great if we can find a general
solution for this :D
I'm facing a programming problem that I don't know how to solve in a
object oriented and flexible way. I have in mind some bad solutions, but
I'm searching for a good one. I develop in Java, so I prefer Java ideas,
but any object oriented idea is welcome.
I've been searching for ideas, design patterns, or some algorithm that can
help me, but I don't know which terminology or name give to my problem, so
I couldn't find any clue.
Problem:
Summary:
I need to track partial results of a process that makes different changes
to a collection of entities. I need this to report to the user, the detail
of each calculation "step" in a table report. And also I need to persist
this collection in a database.
Detail:
The software I maintain has an entity similar to this one: public class
Salary { private Date date; private BigDecimal amount; }
That is grouped in a Collection, like this:
List<Salary> teamSalaries;
This set of entities can be modified by a set of "tasks" depending on some
rules:
Apply a certain tax (from a set of differents taxes)
Calculate a Future value for the money amount (More Info)
Discount an amount of money to keep below a maximum
etc...
For example:
public void processTeamSalaries(List<Salary> teamSalaries) {
applyTax(teamSalaries, Taxes.TAX_TYPE_1);
(...)
getFutureValue(teamSalaries, someFutureDate);
(...)
restrictToAMaximum(teamSalaries, Maximum.MARRIED_MAXIMUM);
(...)
applyTax(teamSalaries, TAXES.TAX_TYPE_3);
(...)
}
public void applyTax(List<Salary> teamSalaries, Tax taxToApply) {
for(Salary aSalary : teamSalaries) {
aSalary.setAmount(calculateAmountWithTax(aSalary.getAmount(),
taxToApply);
}
}
(...)
What I need is to process this collection of salaries, making changes to
the amount of money but preserving all the intermediate "states" of the
money amount, to show it to the user in a table with columns like these:
Date | Original Amount | Amount after tax 1 | Future Amount | Amount after
restriction | Amount after tax 2
My Ideas:
Add an attribute for each "partial result" on the class Salary
public class Salary {
(...)
private BigDecimal originalAmount;
private BigDecimal amountAfterFirstTax;
private BigDecimal amountAfterMaximumRestriction;
(...)
}
Problems:
The "steps" aren't rigid, maybe tomorrow one "step" changes, a new one
appears, or the "meaning" of some step changes. In that case I will need
to refactor the code too much.
Some "steps" can be repeated, so, how can I tell to the "method" in which
attribute have to "set" the result of the calculation?
Add a HashMap to the Salary class where I can put the partial results, and
pass to the "step" method the "key" where it have to put the partial
result
public class Salary {
(...)
HashMap<String, BigDecimal> partialResults;
(...)
}
Problems:
In some place I need to populate the HashMap to a JPA entity to save it on
my Database
If another developer changes the name of the key (for whatever reason)
maybe the "populating" of the attributes gets broken
Final Note: There are other similar situations with other "similar"
entities in my application, so it would be great if we can find a general
solution for this :D
Fetch data from all classes having same name using javascript
Fetch data from all classes having same name using javascript
I am new with javascript and the problem I have is that while building a
chrome extension I need to extract data from a website let's say
"www.abc.com". The data that I need is all present in all divs with the
class="className" (say). How can I get the data from that particular
class.
Thanks in advance.
I am new with javascript and the problem I have is that while building a
chrome extension I need to extract data from a website let's say
"www.abc.com". The data that I need is all present in all divs with the
class="className" (say). How can I get the data from that particular
class.
Thanks in advance.
Android Navigation Drawer BaseActivity sample
Android Navigation Drawer BaseActivity sample
Can someone suggest me a tutorial how to create a BaseActivity for the
Android Navigation Drawer ?
Or can anyone post a sample BaseActivity for the Navigation Drawer
including the layout ?
Thanks for help!
Can someone suggest me a tutorial how to create a BaseActivity for the
Android Navigation Drawer ?
Or can anyone post a sample BaseActivity for the Navigation Drawer
including the layout ?
Thanks for help!
Thursday, 12 September 2013
Change my client to enable the program to return the respond from the server
Change my client to enable the program to return the respond from the server
Client
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class Program
{
public static ManualResetEvent connectDone = new ManualResetEvent(false);
public static ManualResetEvent sendDone = new ManualResetEvent(false);
public static ManualResetEvent receiveDone = new ManualResetEvent(false);
public static void Connect(EndPoint remoteEP, Socket client)
{
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Send(Socket client, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, SocketFlags.None,
new AsyncCallback(SendCallback), client);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);
// Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so
far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0,
bytesRead));
// Get the rest of the data.
client.BeginReceive(state.buffer, 0,
StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
// All the data has arrived; put it in response.
if (state.sb.Length > 1)
{
string response = state.sb.ToString();
Console.WriteLine(response);
}
// Signal that all bytes have been received.
receiveDone.Set();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void Main(string[] args)
{
//IPAddress ipAddress = System.Net.IPAddress.Loopback;
IPAddress ipAddress = IPAddress.Parse("192.168.0.100");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 1515);
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
Connect(localEndPoint, sock);
string packet;
//while (true)
//{
packet = Console.ReadLine();
packet += "<EOF>";
Send(sock, packet);
Receive(sock);
connectDone.WaitOne();
//}
}
}
This is my client and this client i am going to execute via another
program via its exe file and all i want to change is that this mail to
return a string from the server respond and close after the server
respond. what i need to change in this code ?
Client
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class Program
{
public static ManualResetEvent connectDone = new ManualResetEvent(false);
public static ManualResetEvent sendDone = new ManualResetEvent(false);
public static ManualResetEvent receiveDone = new ManualResetEvent(false);
public static void Connect(EndPoint remoteEP, Socket client)
{
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Send(Socket client, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, SocketFlags.None,
new AsyncCallback(SendCallback), client);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);
// Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Receive(Socket client)
{
try
{
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so
far.
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0,
bytesRead));
// Get the rest of the data.
client.BeginReceive(state.buffer, 0,
StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
else
{
// All the data has arrived; put it in response.
if (state.sb.Length > 1)
{
string response = state.sb.ToString();
Console.WriteLine(response);
}
// Signal that all bytes have been received.
receiveDone.Set();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
static void Main(string[] args)
{
//IPAddress ipAddress = System.Net.IPAddress.Loopback;
IPAddress ipAddress = IPAddress.Parse("192.168.0.100");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 1515);
Socket sock = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
Connect(localEndPoint, sock);
string packet;
//while (true)
//{
packet = Console.ReadLine();
packet += "<EOF>";
Send(sock, packet);
Receive(sock);
connectDone.WaitOne();
//}
}
}
This is my client and this client i am going to execute via another
program via its exe file and all i want to change is that this mail to
return a string from the server respond and close after the server
respond. what i need to change in this code ?
Thread.sleep() skips to last method in Java/Android
Thread.sleep() skips to last method in Java/Android
While there must be a better tactic of completing a countdown I have set
up in my app, it seemed clear to me that using Thread.sleep(1000) between
every digit would work. It did not and I still do not have any other
solution. When I run the app, the countdown goes from 5, straight to 1 in
1 second.
This is my code:
bBegin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bBegin.setText("5");
try{
Thread.sleep(1000);
}catch(InterruptedException ie){
}
bBegin.setText("4");
try{
Thread.sleep(1000);
}catch(InterruptedException ie){
}
bBegin.setText("3");
try{
Thread.sleep(1000);
}catch(InterruptedException ie){
}
bBegin.setText("2");
try{
Thread.sleep(1000);
}catch(InterruptedException ie){
}
bBegin.setText("1");
try{
Thread.sleep(1000);
}catch(InterruptedException ie){
}
Thanks, I hope this problems helps other noobs like me (and no worries, I
did check the site for a previous solution)
While there must be a better tactic of completing a countdown I have set
up in my app, it seemed clear to me that using Thread.sleep(1000) between
every digit would work. It did not and I still do not have any other
solution. When I run the app, the countdown goes from 5, straight to 1 in
1 second.
This is my code:
bBegin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
bBegin.setText("5");
try{
Thread.sleep(1000);
}catch(InterruptedException ie){
}
bBegin.setText("4");
try{
Thread.sleep(1000);
}catch(InterruptedException ie){
}
bBegin.setText("3");
try{
Thread.sleep(1000);
}catch(InterruptedException ie){
}
bBegin.setText("2");
try{
Thread.sleep(1000);
}catch(InterruptedException ie){
}
bBegin.setText("1");
try{
Thread.sleep(1000);
}catch(InterruptedException ie){
}
Thanks, I hope this problems helps other noobs like me (and no worries, I
did check the site for a previous solution)
runAction not excuted when invoked from CCNode (not onEnter )
runAction not excuted when invoked from CCNode (not onEnter )
I have Class that is CCNode extended from one of its methods i want to
excute actions but none of then are running : from this class :
class GameController : public CCNode
where i have also this:
void GameController::onEnter()
{
CCNode::onEnter();
}
this is the code i have :
bool GameController::removeFinalGems(CCArray* gemsToRemove)
{
onGemScaleInAnim = CCCallFuncND::create(this,
callfuncND_selector(GameController::OnGemScaleInAnim),gemsToRemove);
onRemoveGemScaleInAnim = CCCallFuncND::create(this,
callfuncND_selector(GameController::OnRemoveGemScaleInAnim),gemsToRemove);
CCSequence* selectedGemScaleInAndRemove =
CCSequence::create(onGemScaleInAnim,
onRemoveGemScaleInAnim,
NULL);
bool b = this->isRunning();
CCAction *action = this->runAction(selectedGemScaleInAndRemove);
return true;
}
void GameController::OnGemScaleInAnim(CCNode* sender,void* data)
{
CCArray *gemsToRemove = (CCArray*) data;
}
void GameController::OnRemoveGemScaleInAnim(CCNode* sender,void* data)
{
CCArray *gemsToRemove = (CCArray*) data;
}
it never gets to the OnRemoveGemScaleInAnim and OnGemScaleInAnim methods
I have Class that is CCNode extended from one of its methods i want to
excute actions but none of then are running : from this class :
class GameController : public CCNode
where i have also this:
void GameController::onEnter()
{
CCNode::onEnter();
}
this is the code i have :
bool GameController::removeFinalGems(CCArray* gemsToRemove)
{
onGemScaleInAnim = CCCallFuncND::create(this,
callfuncND_selector(GameController::OnGemScaleInAnim),gemsToRemove);
onRemoveGemScaleInAnim = CCCallFuncND::create(this,
callfuncND_selector(GameController::OnRemoveGemScaleInAnim),gemsToRemove);
CCSequence* selectedGemScaleInAndRemove =
CCSequence::create(onGemScaleInAnim,
onRemoveGemScaleInAnim,
NULL);
bool b = this->isRunning();
CCAction *action = this->runAction(selectedGemScaleInAndRemove);
return true;
}
void GameController::OnGemScaleInAnim(CCNode* sender,void* data)
{
CCArray *gemsToRemove = (CCArray*) data;
}
void GameController::OnRemoveGemScaleInAnim(CCNode* sender,void* data)
{
CCArray *gemsToRemove = (CCArray*) data;
}
it never gets to the OnRemoveGemScaleInAnim and OnGemScaleInAnim methods
Return just the results from %SYS.ProcessQuery using $SYSTEM.SQL.Shell() in Intersystems Caché on a Unix server
Return just the results from %SYS.ProcessQuery using $SYSTEM.SQL.Shell()
in Intersystems Caché on a Unix server
Background
Hi,
I work with a Unix-based application that uses an Intersystems Caché
database. Since I'm not that familiar with Caché, it wasn't until recently
that I found out I could type...
$ cache
...to enter the database. From here, I found out I could access a number
of things like the %FREECNT report, the ^DATABASE routine (to view/modify
the size and other properties of the database), and $SYSTEM.SQL.Shell().
Since I found the $SYSTEM.SQL.Shell(), I've found a number of things I can
use it for to obtain info about the database, specifically running
processes using the %SYS.ProcessQuery table.
I'm able to run queries successfully - for example:
USER>ZN "%SYS"
%SYS>D $SYSTEM.SQL.Shell()
SQL Command Line Shell #Comment - Sql Shell Intro text
--------------------------------
Enter q to quit, ? for help.
%SYS>Select PID As Process_ID, State As Process_Status From %SYS.ProcessQuery
The above query will return results in this format:
Process_ID Process_State
--------------------------------
528352 READ
2943582 HANG
707023 RUN
3 Rows(s) Affected
--------------------------------
Question
Considering the background identified above, I'm looking for a way to
return just the results without the "SQL Command Line Shell" intro text,
the column names, or the row count footer. When I write a .ksh script in
Unix to connect to Caché and run a query, like above, I return the
results, along with the following text that I don't want included:
SQL Command Line Shell
--------------------------------
Enter q to quit, ? for help.
Process_ID Process_State
--------------------------------
3 Rows(s) Affected
--------------------------------
Additional Info
I realize I could use Unix commands to filter out some of the text using
awk and sed, but I'm looking for something a little easier/cleaner way
that might be built-in. Maybe something that has a silent or
no_column_names flag, like the example in this LINK.
My end game is to have a script run that will obtain info from a query,
then use that info to make changes to the database when certain thresholds
are met. Ultimately, I want to schedule the script to run at regular
intervals, so I need all the processing to occur on the server instead of
creating a separate Client app that binds to the database.
in Intersystems Caché on a Unix server
Background
Hi,
I work with a Unix-based application that uses an Intersystems Caché
database. Since I'm not that familiar with Caché, it wasn't until recently
that I found out I could type...
$ cache
...to enter the database. From here, I found out I could access a number
of things like the %FREECNT report, the ^DATABASE routine (to view/modify
the size and other properties of the database), and $SYSTEM.SQL.Shell().
Since I found the $SYSTEM.SQL.Shell(), I've found a number of things I can
use it for to obtain info about the database, specifically running
processes using the %SYS.ProcessQuery table.
I'm able to run queries successfully - for example:
USER>ZN "%SYS"
%SYS>D $SYSTEM.SQL.Shell()
SQL Command Line Shell #Comment - Sql Shell Intro text
--------------------------------
Enter q to quit, ? for help.
%SYS>Select PID As Process_ID, State As Process_Status From %SYS.ProcessQuery
The above query will return results in this format:
Process_ID Process_State
--------------------------------
528352 READ
2943582 HANG
707023 RUN
3 Rows(s) Affected
--------------------------------
Question
Considering the background identified above, I'm looking for a way to
return just the results without the "SQL Command Line Shell" intro text,
the column names, or the row count footer. When I write a .ksh script in
Unix to connect to Caché and run a query, like above, I return the
results, along with the following text that I don't want included:
SQL Command Line Shell
--------------------------------
Enter q to quit, ? for help.
Process_ID Process_State
--------------------------------
3 Rows(s) Affected
--------------------------------
Additional Info
I realize I could use Unix commands to filter out some of the text using
awk and sed, but I'm looking for something a little easier/cleaner way
that might be built-in. Maybe something that has a silent or
no_column_names flag, like the example in this LINK.
My end game is to have a script run that will obtain info from a query,
then use that info to make changes to the database when certain thresholds
are met. Ultimately, I want to schedule the script to run at regular
intervals, so I need all the processing to occur on the server instead of
creating a separate Client app that binds to the database.
Accessing json value where attribute has ":"
Accessing json value where attribute has ":"
I am using a REST service and it returns json formatted like this:
{
ea:productionId: "123",
....
}
How can I create a class at server side corresponding to this type of json
for parsing? I am using c#.
EDIT
This is the code I am using
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonClass result= serializer.Deserialize<JsonClass>(jsonresult);
JsonClass is the class I have created with the fields corresponding to the
attributes in the jsonresult. And the problem is, I can't create a
property with name ea:productionId as it contains :.
I am using a REST service and it returns json formatted like this:
{
ea:productionId: "123",
....
}
How can I create a class at server side corresponding to this type of json
for parsing? I am using c#.
EDIT
This is the code I am using
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonClass result= serializer.Deserialize<JsonClass>(jsonresult);
JsonClass is the class I have created with the fields corresponding to the
attributes in the jsonresult. And the problem is, I can't create a
property with name ea:productionId as it contains :.
Best way to open phonegap project created with CLI in eclipse
Best way to open phonegap project created with CLI in eclipse
When I create a phonegap folder structure via the CLI (3.0), how do I open
this in Eclipse?
When I choose project [New] - [Android project from existing code], the
assets are taken from the platforms/android folder. But I need to change
the html and js of the top folder (www). These are the files that are
being used when I build the project to other platforms (via CLI or
build.phonegap). Now I change the assets in the editor of the eclipse
environment and then manually copy paste the content to the files under
www.
When I create a phonegap folder structure via the CLI (3.0), how do I open
this in Eclipse?
When I choose project [New] - [Android project from existing code], the
assets are taken from the platforms/android folder. But I need to change
the html and js of the top folder (www). These are the files that are
being used when I build the project to other platforms (via CLI or
build.phonegap). Now I change the assets in the editor of the eclipse
environment and then manually copy paste the content to the files under
www.
WKHTMLTOPDF Installation error on Ubuntu
WKHTMLTOPDF Installation error on Ubuntu
We require features like header, footer, table of contents and cover page
of pdf, which we want to generate from html/css. We tried WKHTML on
windows and it worked like a charm, when moving to our server, we
installed WKHTML on our ubuntu server, installation process was successful
but it had only limited features, it was able to generate pdf from HTML
but all features mentioned (i-e header, footer , table of content and
cover page) wasn't working. Following is the error which it was producing.
"The switch -t, is not support using unpatched qt, and will be ignored.
Error: This version of wkhtmltopdf is build against an unpatched version
of QT, and does not support more then one input document."
We followed many tutorials and installed it with QT patched, one of the
tutorial is here (https://code.google.com/p/wkhtmltopdf/wiki/compilation)
. We are not sure if we skipped something or did something wrong, it is
installed and few of features has started to work but not all. we are able
to generate header and footer but cover page and table of content are
still not working. which we really need.
We require features like header, footer, table of contents and cover page
of pdf, which we want to generate from html/css. We tried WKHTML on
windows and it worked like a charm, when moving to our server, we
installed WKHTML on our ubuntu server, installation process was successful
but it had only limited features, it was able to generate pdf from HTML
but all features mentioned (i-e header, footer , table of content and
cover page) wasn't working. Following is the error which it was producing.
"The switch -t, is not support using unpatched qt, and will be ignored.
Error: This version of wkhtmltopdf is build against an unpatched version
of QT, and does not support more then one input document."
We followed many tutorials and installed it with QT patched, one of the
tutorial is here (https://code.google.com/p/wkhtmltopdf/wiki/compilation)
. We are not sure if we skipped something or did something wrong, it is
installed and few of features has started to work but not all. we are able
to generate header and footer but cover page and table of content are
still not working. which we really need.
Wednesday, 11 September 2013
Python equivalent R code - numeric seconds from epoch to POSIXlt
Python equivalent R code - numeric seconds from epoch to POSIXlt
I have number of seconds elapsed since an epoch and can convert it to
localtime in python, like so
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(1378182603));
## yields '2013-09-03 10:00:03'
How can I achieve the same in R?
I have number of seconds elapsed since an epoch and can convert it to
localtime in python, like so
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(1378182603));
## yields '2013-09-03 10:00:03'
How can I achieve the same in R?
Intelligently Detect Duplicate Content Using PHP
Intelligently Detect Duplicate Content Using PHP
I have built a web scraper that takes a website or RSS feed, parses said
contents of the feed and or website, extracts all of the appropriate
information and then saves it into a database. This is a personal
experiment to see if I can build an intelligent and anonymous web scraper
with no real purpose just to see how advanced I can go and then I will be
open sourcing the code for others to learn from.
The problem is I am scraping at present 3 news websites. When it comes to
breaking news, there is a high chance all 3 websites (especially if it's a
big story) will all be writing their own interpretations of the news, but
ultimately it's the same news.
I have been trying to come up with a solution that can detect as best as
it can when an article being pulled in has already been spoken about and
imported from another news website and perhaps the link is associated with
the story (other sites also wrote about this: link1, link2).
Is there a tried and tested way of detecting if one or more pieces of
content are effectively the same? I've written some pseudo-code, but
unfortunately I'm not a very smart developer to take it and make it
something that works.
Here is my thinking:
A link to a website is parsed
Generic words are stripped out and keywords left in (company names,
countries, etc)
The remaining words are then counted and a score is calculated
That's where my thinking hits a roadblock. How do I efficiently create a
snapshot of a page and then compare it to pre-existing content in my
database I've already imported? This is how I think it needs to be done.
Perhaps I am over-thinking this and I merely need to check if articles
have similar titles?
I have built a web scraper that takes a website or RSS feed, parses said
contents of the feed and or website, extracts all of the appropriate
information and then saves it into a database. This is a personal
experiment to see if I can build an intelligent and anonymous web scraper
with no real purpose just to see how advanced I can go and then I will be
open sourcing the code for others to learn from.
The problem is I am scraping at present 3 news websites. When it comes to
breaking news, there is a high chance all 3 websites (especially if it's a
big story) will all be writing their own interpretations of the news, but
ultimately it's the same news.
I have been trying to come up with a solution that can detect as best as
it can when an article being pulled in has already been spoken about and
imported from another news website and perhaps the link is associated with
the story (other sites also wrote about this: link1, link2).
Is there a tried and tested way of detecting if one or more pieces of
content are effectively the same? I've written some pseudo-code, but
unfortunately I'm not a very smart developer to take it and make it
something that works.
Here is my thinking:
A link to a website is parsed
Generic words are stripped out and keywords left in (company names,
countries, etc)
The remaining words are then counted and a score is calculated
That's where my thinking hits a roadblock. How do I efficiently create a
snapshot of a page and then compare it to pre-existing content in my
database I've already imported? This is how I think it needs to be done.
Perhaps I am over-thinking this and I merely need to check if articles
have similar titles?
How to send form on gumtree?
How to send form on gumtree?
How to send form on Gumtree? I'm trying, cuz i need to use curl/php (or
perl/Java) to do it. I dont care about email activation after of it or
account authorization before sending.
Right now im using this:
<php
(...)
// Setting POST data
// Type of announcement
// HTML code of this form radio button:
// <input type="radio" name="AdType" value="2" checked>
$postData["AdType"] = "value=\"2\"";
(...)
// Sending form using cUrl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.gumtree.pl/c-ConfirmAd"); //or
c-PostAd
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT
6.1; en-GB; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_REFERER, 'http//www.gumtree.pl');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$response = curl_exec ($ch);
print_r($response);
exit();
What i get back is:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>417 - Expectation Failed</title>
</head>
<body>
<h1>417 - Expectation Failed</h1>
</body>
</html>
How to send form on Gumtree? I'm trying, cuz i need to use curl/php (or
perl/Java) to do it. I dont care about email activation after of it or
account authorization before sending.
Right now im using this:
<php
(...)
// Setting POST data
// Type of announcement
// HTML code of this form radio button:
// <input type="radio" name="AdType" value="2" checked>
$postData["AdType"] = "value=\"2\"";
(...)
// Sending form using cUrl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://www.gumtree.pl/c-ConfirmAd"); //or
c-PostAd
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT
6.1; en-GB; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_COOKIESESSION, true);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file_path);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file_path);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_REFERER, 'http//www.gumtree.pl');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$response = curl_exec ($ch);
print_r($response);
exit();
What i get back is:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>417 - Expectation Failed</title>
</head>
<body>
<h1>417 - Expectation Failed</h1>
</body>
</html>
Get the continent/country or location of user in php?
Get the continent/country or location of user in php?
Is possible to get the continent from where the user it is accessing a
site? I do know i can get the language of the browser like this:::
<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
switch ($lang){
case "fr":
//echo "PAGE FR";
include("index_fr.php");//include check session FR
break;
case "it":
//echo "PAGE IT";
include("index_it.php");
break;
case "en":
//echo "PAGE EN";
include("index_en.php");
break;
default:
//echo "PAGE EN - Setting Default";
include("index_en.php");//include EN in all other cases of
different lang detection
break;
}
?>
REF
Also i do know there is something php function call ->
geoip_continent_code_by_name which if a pass a string with the host name
it will return me:
Code Continent name
AF Africa
AN Antarctica
AS Asia
EU Europe
NA North america
OC Oceania
SA South america
But this only returns me the host name, so is there any way to get the
same result but for the user who is accessing the site? or is even
possible to do?
Is possible to get the continent from where the user it is accessing a
site? I do know i can get the language of the browser like this:::
<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
switch ($lang){
case "fr":
//echo "PAGE FR";
include("index_fr.php");//include check session FR
break;
case "it":
//echo "PAGE IT";
include("index_it.php");
break;
case "en":
//echo "PAGE EN";
include("index_en.php");
break;
default:
//echo "PAGE EN - Setting Default";
include("index_en.php");//include EN in all other cases of
different lang detection
break;
}
?>
REF
Also i do know there is something php function call ->
geoip_continent_code_by_name which if a pass a string with the host name
it will return me:
Code Continent name
AF Africa
AN Antarctica
AS Asia
EU Europe
NA North america
OC Oceania
SA South america
But this only returns me the host name, so is there any way to get the
same result but for the user who is accessing the site? or is even
possible to do?
Subscribe to:
Comments (Atom)