text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Facebook - Detect if user has liked your page? Is there any way to detect if a user has liked X page outside of facebook?
So say my URL is:
http://www.site.com/page.html
My facebook page is:
http://www.facebook.com/myfacebookpage
Is there any way to detect if the user visiting my web page has liked my facebook page? and show text if they have or haven't liked it?
A: The only way to do this is if the user has authenticated with your application and has granted user_likes extended permission. Then you could call /me/likes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is monodoc.ashx and why does googlebot request it? I am getting TONS of request. They all start with
/1.1/handlers/monodoc.ashx?link=
then follows what look like .NET classes. What are these and why is googlebot requesting them?
I need to turn it off so my access and error log isnt polluted.
A: Googlebot will request any URL that it knows of, which includes URLs that you may not have generated yourself.
For instance, if there's a forum out there that links to your site with that URI, Googlebot will attempt to crawl it to see if there's any information worth indexing.
Based on IP provided, I verified that it was indeed Googlebot since the reverse DNS lookup resolves to 'crawl-66-249-68-184.googlebot.com' and the forward DNS lookup for 'crawl-66-249-68-184.googlebot.com' resolves back to the IP address provided.
The best thing you can do it respond with a 404 or 410 response if that page shouldn't exist. If you have an idea of what content used to be there, you should 301 redirect it to a relevant page on your site just in case other people had linked to those pages ... you not only want to retain the link credit for those links, but also it's just a better user experience for users who have followed that link. If there isn't a relevant place to 301 redirect the users to, you can redirect them to your homepage, but just know that from an SEO perspective, the link value will decay since the relevancy of the links probably won't match exactly to the content of your homepage.
Definitely make sure that you're not responding with a 500 or 503 response code. If you have a large number of 5xx type of responses, Googlebot will think that it's hitting your site too hard and will throttle back their crawl.
Lastly, even if you 301, 404, or send a 410 response ... expect to see Googlebot to hit these URLs for sometime (e.g. even years from now). I've got sites that receive a burst of Googlebot traffic for long dead legacy URIs every few weeks. There are some old crusty URLs out there, and Googlebot will run across them from time to time and then attempt to recrawl them. They even keep a historic list which they'll attempt to crawl when they feel they have additional bandwidth to allocate to your site.
TL;DR: Don't sweat it. Googlebot will hit these URLs for no good reason. Just send the response that would be the best User Experience, and you'll be fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to run my app offline iphone sdk I'm creating an iphone web app, in this one I'm getting some string values from a web service, and its loaded into an array. And I have created another array with some sample values (strings). My app should run offline, I mean it should work in background, that is the values i'm getting from web service may vary. So if the values from the web service is equal to the content in the second array, I need to get an alert. I mean a notification. Note that, it should happen even if the app is not open in the phone.
Thank you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Posting, Login in and redirecting for user Here is the scenario: when the user is clicking on a link on my webpage i want to perform a login to another site, and use the cookies to login the user to the second site.
I'm using PEAR Request2 and i'm able to get the login cookies but when i use:
setcookie($cookies['1']['name'], $cookies['1']['value'], time()+3600, '/');
header("Location: http://www.example.com");
the cookie host is my site and i suspect that is why i get a login error.
Is there anyway to issue a cookie as the secondary site - or do you have any suggestion how can i simulate login (i have all the relevant information) and redirect the user to home page?
A: You can use the setcookie like normal, but with just adding the domain of the cookie.
setcookie('cookiename','value',time()+3600,'/','.example.com');
However this is not suggested at all because it can open security risks.
http://php.net/manual/en/function.setcookie.php
A: Your script can pass some key to other site in private channel. after that you redirect to:
http://your.other.site.com/login.php?auth_key=$auth_key
And other site can auth_user. But be carefull, you need every time generate random key and make sure that user can use this key only one time.
A: Figured it out! you can only set the cookie on the client side for your domain.
I was fetching the cookies from a 3rd party website and tried to set those cookies, this can only b done using javascript :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Something like Apache Zookeeper with no java? Is there some library or project out there that works like Zookeeper but has no java dependency? I'm looking at putting this on an embedded linux system, and need minimal footprint... something like a megabyte or less. I have Lua, C and C++ runtimes, and could put something like NewLISP on there if I had to. Most or all of the clients will be C or C++, a nice command line utility for the benefit of shell scripts would also be useful. http://zookeeper.apache.org/
A: There is Doozerd
written in Go!
A: There is accord,
Accord is a high-performance coordination service like Apache
ZooKeeper
It looks like accord is written in c.
A: Maybe check out etcd:
etcd
A highly-available key value store for shared configuration and service discovery. etcd is inspired by zookeeper and doozer, with a focus on:
*
*Simple: curl'able user facing API (HTTP+JSON)
*Secure: optional SSL client cert authentication
*Fast: benchmarked 1000s of writes/s per instance
*Reliable: Properly distributed using Raft
Etcd is written in go and uses the raft consensus algorithm to manage a highly availably replicated log.
See go-etcd for a native go client. Or feel free to just use curl, as in the examples below.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Store jquery result into a array (or something like that) to be used by another javascript Appreciate some insight given the following code:
<script type="text/javascript">
$(document).ready(function() {
var soapEnv =
"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
<soapenv:Body> \
<GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
<listName>video_player</listName> \
<viewFields> \
<ViewFields> \
<FieldRef Name='Title' /> \
</ViewFields> \
</viewFields> \
</GetListItems> \
</soapenv:Body> \
</soapenv:Envelope>";
$.ajax({
url: "_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: soapEnv,
complete: processResult,
contentType: "text/xml; charset=\"utf-8\""
});
});
function processResult(xData, status) {
$(xData.responseXML).find("z\\:row").each(function() {
var liHtml = "<a href='" + $(this).attr("ows_Title") + "'><img src='" + $(this).attr("ows_snapshot_file_location") + "' width=120 height=90><strong>" + $(this).attr("ows_video_description") + "</strong><br /><br />" + $(this).attr("ows_video_description") + "<em>" + $(this).attr("ows_video_length") + "</em></a><br />";
//{missing code}//
});
}
</script>
What code should I enter inside the //{missing code}// such that I can store the variable 'lihtml' into a array that can be used in any javascript? (I wish to use document.write() to display the "lihtml" variable.
UPDATE 1:
After taking minus4 consideration, the code is as follows:
<script type="text/javascript">
var glob;
$(document).ready(function() {
var soapEnv =
"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'> \
<soapenv:Body> \
<GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
<listName>video_player</listName> \
<viewFields> \
<ViewFields> \
<FieldRef Name='Title' /> \
</ViewFields> \
</viewFields> \
</GetListItems> \
</soapenv:Body> \
</soapenv:Envelope>";
$.ajax({
url: "_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: soapEnv,
complete: processResult,
contentType: "text/xml; charset=\"utf-8\""
});
});
function processResult(xData, status) {
$(xData.responseXML).find("z\\:row").each(function() {
var liHtml = "<a href='" + $(this).attr("ows_Title") + "'><img src='" + $(this).attr("ows_snapshot_file_location") + "' width=120 height=90><strong>" + $(this).attr("ows_video_description") + "</strong><br /><br />" + $(this).attr("ows_video_description") + "<em>" + $(this).attr("ows_video_length") + "</em></a><br />";
glob.append(liHtml);
});
}
</script>
and at the other part of the same document, I used
<script type="text/javascript">
document.write(glob);
</script>
and now, I receive the 'undefined' error. Any insight?
A: I think you should directly call any other javascript fonction from processResult function so you don't have to store data anymore. So missing code could be something like
printMe(liHtml,'SomePlace');
Or directly add the document.write function there?
document.write(liHtml);
Or maybe can you give more details about the kind of js you want to call?
A: you could create a global variable.
or if you wan to caryy this around multiple pages then try http://blog.reybango.com/2010/04/08/alternative-client-side-storage-using-sessvars-js/ it will store the data for you wihin the browser, across pages etc
then using jquery you can say $('#idofdivorspan').html('');
A: Try -
var glob = [];
then -
function processResult(xData, status) {
$(xData.responseXML).find("z\\:row").each(function() {
var liHtml = "<a href='" + $(this).attr("ows_Title") + "'><img src='" + $(this).attr("ows_snapshot_file_location") + "' width=120 height=90><strong>" + $(this).attr("ows_video_description") + "</strong><br /><br />" + $(this).attr("ows_video_description") + "<em>" + $(this).attr("ows_video_length") + "</em></a><br />";
glob.push(liHtml);
});
}
and for output -
document.write(glob.join(""));
That should build up a dynamic array of your html strings, that can be output via the array.join method. I think the problem with you original code is you're using `append' on a normal JavaScript variable when it is a jQuery specific function. Adding the content to a dynamic array should have the same effect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can i make not allow column to allow null and Allow Null column to not allow null Could any one help me to perform below task.
How can i make not allow column to allow null and Allow Null column to not allow null.
A: Use ALTER TABLE table_name ALTER COLUMN column_name datatype [NOT] NULL
Example:
CREATE TABLE #Foo
(
X INT NULL,
Y INT NOT NULL
)
/*This is metadata only change and very quick*/
ALTER TABLE #Foo ALTER COLUMN Y INT NULL
/*This requires all rows to be scanned to validate the data*/
ALTER TABLE #Foo ALTER COLUMN X INT NOT NULL
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: ExtJS Textarea - autosave contents on user input I'm an ExtJS newbie and need to send the contents of a ExtJS Textarea to the backend server for saving (autosave facility) as the user types in. Is there a way to do it. I've currently registered a keyup listener to collect the input value as shown below:
items: [{
xtype: 'textarea',
id: 'notes',
anchor: '100%',
height: 270,
msgTarget: 'under',
fieldLabel: 'Note',
enableKeyEvents: true,
listeners: {
'keyup': function(textarea, event) {
var v= textarea.getValue();
Ext.Ajax.request({
url: 'buffernote.action',
params: {value: v}
})
}
}
}
}]
Am I in the right direction?
A: If you need a buffer, put some ref to the textarea, then call
this.mon(myTextarea, 'keyup', this.onMyTextareaKeyup, this, {buffer: 1000});
where onMyTextareaKeyup contains the code that you provided to do the request. More info on buffer can be found on API.
A: You should use two events: one key event and one blur event (blur, change or valid)
Then fill a 'key hit' buffer and write the whole field back if full and reset the buffer. Also write the whole field back if the blur event get executed.
Personally I am using stores that do the write & updates actions for me. So I just need to modify a record in the store.
For that way you just need to play with record.beginEdit() & record.endEdit()
In ExtJS 4.x they are now using the term Ext.data.Model but it behaves much the same as in ExtJS 3.x
The store will need the option autoSave: true otherwise you have to call save() on the store to submit any changes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: percentage in jquery css Positioning Why the JQuery syntax below is not correct:
$('#Footer').css({ right: 6%, bottom: 0 });
And this one is:
$('#Footer').css('right', '6%');
$('#Footer').css('bottom', '0');
What is incorrect in the first code ?
Thanks in advance
A: 6% is not a number, so it must be specified as a string.
$('#Footer').css({ right: '6%', bottom: 0 });
A: you are missing ''
$('#Footer').css({ right: '6%', bottom: '0' });
for reference http://api.jquery.com/Types/#jQuery
A: because of your missing quotes
it should be
$('#Footer').css({ 'right': '6%', 'bottom': 0 });
A:
$('#Footer').css({ 'right': '6%', 'bottom': 0 });
Is the right answer as Kimtho6 stated.
Kapa is universally mistaken in this instance. As the quotes are only optional when using single word properties; if you used his reasoning then your code would fail when getting the padding-right property.
It's the same reason JSON requires quotes. Because quotes make property names universal. And because that's how JS and many other coding languages do not allow the - character as standalone property names; because it was a math symbol before there was any computer coding languages.
Fail:
$('#Footer').css({ padding-top: '6%', padding-bottom: 0 });
Success:
$('#Footer').css({ 'padding-top': '6%', 'padding-bottom': 0 });
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Stackoverflow when trying to run the Text example in the AndEngineExampleLauncher Hey Game Engine Folks,
This is a question for those who worked with AndEngine for Android.
I've a problem getting the Text example of the AndEngineExampleLauncher working!
It throws the following exception:
09-30 10:11:19.940: ERROR/AndroidRuntime(466): FATAL EXCEPTION: main
09-30 10:11:19.940: ERROR/AndroidRuntime(466): java.lang.StackOverflowError
09-30 10:11:19.940: ERROR/AndroidRuntime(466): at org.anddev.andengine.ui.activity.BaseGameActivity.getFontManager(BaseGameActivity.java:137)
09-30 10:11:19.940: ERROR/AndroidRuntime(466): at org.anddev.andengine.ui.activity.BaseGameActivity.getFontManager(BaseGameActivity.java:137)
09-30 10:11:19.940: ERROR/AndroidRuntime(466): at org.anddev.andengine.ui.activity.BaseGameActivity.getFontManager(BaseGameActivity.java:137)
I've googled that error and it seems that some other guys having the same problem, but I couldn't find a solution posted anywhere!
Have anybody been able to get this example working without getting this 80's & 90's StackOverflowError!.
Really appreciate your help.
Thanks,
Mohamed A.Karim
A: This is very odd, but I took the time to debug the AndEngine BaseGameActivity.java class from the AndEngine src and I've found the cause of the problem:
Here is the shipped with getFontManger() method:
public FontManager getFontManager() {
return this.getFontManager();
}
This is the typical StackOverFlow cause... The very classic one.
I've changed that method to be:
public FontManager getFontManager() {
return this.mEngine.getFontManager();
}
And the AndEngine Text example is working like charm now.
So, here are the steps I've done to get the AndEngine Text example working:
1- Go to the AndEngine Project (Source code you import to your game)
2- Go to class org.anddev.andengine.ui.activity.BaseGameActivity.java
3- Go to method: getFontManager()
4- Change the return value
From: return this.getFontManager();
To: return this.mEngine.getFontManager();
I hope this can be a help for anybody who has the same problem
Really appreciate the great effort from @Nicolas Gramlich for creating such an incredible game engine.
Thanks,
Mohamed.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: 'git grep' and word boundaries on Mac OS X and BSD I run git grep "\<blah\>" regularly on my linux development server, but I just discovered that I am not able to use \< and \> on Mac (Mac OS X 10.6.8) (not able to use = it does not find anything). Is the regular expressions syntax different in Mac?
I tried using git grep -E "\<blah\>" but to no avail! :-(
A: After struggling with this, too, I found this very helpful post on a BSD mailing list. So here's the (albeit rather ugly) solution:
git grep "[[:<:]]blah[[:>:]]"
The -w flag of git-grep also works but sometimes you want to only match the beginning or end of a word.
Update: This has changed in OS X 10.9 "Mavericks". Now you can use \<, \>, and \b. [[:<:]] and [[:>:]] are no longer supported.
A: I guess it's caused by the BSD vs Linux grep library.
See if the -w (match pattern only at word boundary) option to git grep does it for you:
$ git grep -w blah
A: You can compile git with PCRE support and use git grep -P "\bblah\b" for word boundaries.
Here's a guide on how to compile git using OSX Homebrew:
http://realultimateprogramming.blogspot.com/2012/01/how-to-enable-git-grep-p-on-os-x-using.html
A: If you do use -P, make sure to use Git 2.40 (Q1 2023): "grep -P" learned to use Unicode Character Property to grok character classes when processing \b and \w etc.
See commit acabd20 (08 Jan 2023) by Carlo Marcelo Arenas Belón (carenas).
(Merged by Junio C Hamano -- gitster -- in commit 557d93a, 27 Jan 2023)
grep: correctly identify utf-8 characters with \{b,w} in -P
Signed-off-by: Carlo Marcelo Arenas Belón
Acked-by: Ævar Arnfjörð Bjarmason
When UTF is enabled for a PCRE match, the corresponding flags are added to the pcre2_compile() call, but PCRE2_UCP wasn't included.
This prevents extending the meaning of the character classes to include those new valid characters and therefore result in failed matches for expressions that rely on that extention, for ex:
$ git grep -P '\bÆvar'
Add PCRE2_UCP so that \w will include Æ and therefore \b could correctly match the beginning of that word.
This has an impact on performance that has been estimated to be between 20% to 40% and that is shown through the added performance test.
That means those patterns will work, with any character:
'\bhow'
'\bÆvar'
'\d+ \bÆvar'
'\bBelón\b'
'\w{12}\b'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Blackberry JDE or Eclipse Plugin for developing Blackberry applications I use for now the Blackberry JDE for developing blackberry applications. And I am so familiar with it. I spent six months developing on this software.
I installed Blackberry plugin for ecplise last week to try it and see if it is better. Well Eclipse helps you more in writing the code, much easier. But some difference exist espacially in locating the images.
I am afraid that when starting projects on eclipse, I wouldn't be able to move them to JDE.
So what are your recommendations? Which is best to use? Blackberry plugin for eclipse or JDE? If you recommend me moving to eclipse than why? Is there some benefits that are worth this?
A: Eclipse is standard for developers, at least for Java, including app engine and Android. You can do all your projects from it, with helpful plugins and regular updates for the BB plugin from RIM and Eclipse itself is also regularly updated. The JDE is a monster from the past with an at least 10-year-old UI that is still dragging along; only time I used it was for an alpha release of BlackBerry 7 (that was called 6.1 at the time).
A: Coding in JDE is a nightmare. Six months!.. :)
I still use Eclipse just for coding + JDE just for building/debugging. This tandem works just nice for me. Approximately a year ago I gave a try to BB plugin for Eclipse, however there was some issue with the plugin (unfortunatelly now I don't remember what exactly) so I dropped the idea of using BB plugin. Probably by now the plugin became better, however I don't know any substantial reason of why I should give it a try again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: moving "logic" out of dataaccess layer would lead to lots of database connections I have a method in my dataaccess layer that processes a file import. Such a file can have many records in it that need to be inserted into the database.
This method already contains certain "logic or business rules" and more need to be added.
Problem is if I move this out of the dataaccess layer each record would have to be inserted separately with a new connection. Obviously that is not very good when inserting thousands of records. (there is no guarantee that connections are pooled).
So I'm kind of lost on how to solve this. The dataaccess layer class is getting bigger and bigger and in term of good design os probably violating several rules already.
Only thing that comes to my mind is producer-consumer -> business logic imports file and performs validation and puts validated records into a queue. A separate thread (the dataaccess layer) reads from that queue.
Any other ideas? is there a pattern for such problems?
A: You have a design problem. The business logic layer should be the one demarcating transactions, and the data access layer should always use the same connection for a given transaction.
You could be using Spring, for example, which would let you use declarative transactions and a connection pool, and would make sure the same connection is used for the whole transaction.
A: *
*Have a separte business layer separate from dataaccess layer - here deal with your business rules , and when you are ready to call into data-access , create collection of business objects - pass then into the DA layer - the DA layer will process the objects - either as individual rows or as a single bulk operation -
*Use Design patterns in your business layer that will keep the evolution simple.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to prevent ActiveMQ CPP send method from blocking forever? I am developing a software that uses ActiveMQ C++ library. The problem that I have is, when I try to send a message and the network is down, the send method (method of cms::MessageProducer class) blocks forever and I need to recover the control in this case.
I am using persistent deliver mode (It is compulsory, I can't avoid it).
A: Do you set the sendTimeout when you create ActiveMQConnectionFactory? It is set to 0 by default, which means "infinite".
auto_ptr<ActiveMQConnectionFactory> connectionFactory(
new ActiveMQConnectionFactory( brokerURI ) );
connectionFactory->setSendTimeout( 1000 ); // number of milliseconds
// ...
// creating Session and MessageProducer as usually
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: cancel button php form jquery These are the buttons on my form:
<input type="submit" id="form-submit" class="btn" name="save" value="verzenden" />
<input type="submit" name="cancel" class="btn" value="annuleren" />
I catch the cancel click with php like this:
if($_POST['cancel'])
{
Helper::redirect('page.php');
}
But before I submit my form, I use some jQuery to validate the form, now I can't click cancel because it will validate first.
This is my jQuery code:
<script type="text/javascript">
$(document).ready(function(){
$('#cancel').delegate('','click change',function(){
console.log('test');
});
$('form').submit(function(){
var proceed = true;
$('.required').each(function(){
if ($(this).val() == '' || $(this).val() == 0 || $(this).val() == '0') {
$(this).css('border-color', '#F00');
proceed = false;
}
else {
$(this).css('border-color', '#999');
}
});
return proceed;
});
// Check on typing if a required field is empty
$('.required').keyup(function(){
if ($(this).val() == '' || $(this).val() == 0 || $(this).val() == '0' )
$(this).css('border-color', '#F00');
else
$(this).css('border-color', '#999');
});
});
</script>
How can I ignore the jQuery and redirect to page.php when I hit cancel?
Thanks
A: $('#cancel').delegate('','click change',function(){
console.log('test');
});
This will not work, while you don't have any element in your form with id cancel
Change that button
<input type="submit" name="cancel" class="btn" value="annuleren" />
to
<input type="submit" id="cancel" name="cancel" class="btn" value="annuleren" />
A: This is what I got now:
Thanks ThiefMaster
//javascript
$('#cancel').delegate('','click change',function(){
window.location = "testimonials.php";
return false;
});
//php
if($_POST['cancel'])
{
Helper::redirect('testimonials.php');
}
//html
<input name="cancel" type="submit" id="cancel" class="btn" value="annuleren" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: arraylist with custom objects I have a very basic question. I am trying to read values of three EditText fields and save them as one item in an arraylist using an arrayadapter. My question is how can I group the three variables I read from the EditTexts and add them as a single item in the arraylist?
A: You can create a custom object that holds the strings from 3 edittexts
And the array list can be
public class CustomObj{
String str1;
String str2;
String str3;
public CustomObj(String s1,String s2,String s3){
this.str1 = s1;
this.str2 = s2;
this.str3 = s3;
}
}
ArrayList<CustomObj> customObjList = new ArrayList<CustomObj>();
A: class editTextString{
private String str1
private String str2
private String str3
public editTextString(String data1,String data2,String data3){
str1 = data1;
str2 = data2;
str3 = data3;
}
}
now add this class to ArrayList..
just like below,
ArrayList<editTextString> list = new ArrayList<editTextString>();
editTextString data = new editTextString("edit1","edit2","edit3")
list.add(data)
A: public class MyObject {
private String string1;
private String string2;
private String string3;
public MyObject(String s1,String s2,String s3) {
string1 = s1;
string2 = s2;
string3 = s3;
}
public toString() {
return string1 + " " + string 2 + " " +string3;// your string representation
}
}
MyObject[] adapterList = new MyObect[1];
A: adapter.add(edtxt1.getText()+edtxt2.getText()+edtxt3.getText())
this will stored in the adapter
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Generate additional artifact while creating reports or in another phase? I understand that you can create only one artifact from one pom in maven.
I wrote a javadoc doclet that creates an html report of my artifact (my-rest-api). This doclet can also create stub requests and models for writing integration tests. My problem is now, that I have to manually copy the generated classes into a third maven project (my-test-models) in order to create an artifact from it. Is there any other way? The generated classes are created from source so I cannot just depend on the my-rest-api artifact. I could hard-code paths between both project but I don't like that neither. Any ideas?
A: From what I understand of your question, you can install/deploy the source of my-rest-api artifact and in your my-test-models, specify this as a dependency.
You can use maven source plugin to do this.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>2.1.2</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C/C++ Preprocessing Error I stumble on a compiling error:
Invoking: GCC C Compiler
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/3dsloader.d"-MT"src/3dsloader.d" -o "src/3dsloader.o" "../src/3dsloader.c"
In file included from ../src/3dsloader.c:42:
../src/3dsloader.h:8:9: error: macro names must be identifiers
make: *** [src/3dsloader.o] Error 1
it points to:
#ifndef 3DSLOADER_H_
#define 3DSLOADER_H_
With the following message:
Multiple markers at this line
macro names must be identifiers
macro definition not found: #ifndef 3DSLOADER_H_
I am running the C/C++ OpenGL Program on Ubuntu with Eclipse IDE. All other programs so far are working fine. But this one to load a 3DS file is mocking around with me already for two days with no fix on it.
Any suggestion? All comments are highly appreciated!
A: C identifiers may not start with a number. Try _H_3DSLOADER instead.
To be exact: They may only start with letters or an underscore.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Text scrolls outside of the UITextView box boundary I have a UITextView that has some text in it. The problem is that the text scrolls outside of the boundaries of the UITextView box. (The UITextView is uneditable.)
here's the code and what I have tried to resolve this issue:
- (void)viewDidLoad {
textBG.contentInset = UIEdgeInsetsZero;
// textBG.layer.masksToBounds = NO;
textBG.layer.cornerRadius = 10.0;
textBG.layer.borderWidth = 0.0;
[textBG setClipsToBounds:YES];
[super viewDidLoad];
}
- (void)textViewDidBeginEditing:(UITextView*)textView
{
textBG.contentInset = UIEdgeInsetsZero;
[textBG setClipsToBounds:YES];
}
- (void) shouldChangeTextInRange:(UITextView*)textView {
textBG.contentInset = UIEdgeInsetsZero;
[textBG setClipsToBounds:YES];
}
thanks for any help
A: write this in textView delegate methods like textViewDidBeginEditing
textBG.contentInset = UIEdgeInsetsZero;
in viewDidload
[textBG setClipsToBounds:YES];
A: Try to change in XIB for your TextView like below:
A: I faced this same problem, so I track down the source ... this is because of while adding shadow somehow you disturbed it's masksToBounds property. Therefore, while adding more text it got overflowed. Simple solution which I found is to write this simple line after adding shadow.
[self.myTextView setClipsToBounds:YES];
usually should be in viewDidLoad method, but remember to write this line only after applying shadow.
Thanks for reading this.
A: Just put this one line code to solve problem.
yourTextView.clipsToBounds = true
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: lightbox disappears of view from window resize in Android the lightbox is shown in the right position (top/left centered), but when users zoom; the lightobx stays in the same position (without considering the window/view has been resized/cropped),
You can test this here clicking in the blue button of the header
I am checking at the code of lightbox, and, i can see
$(window).bind('resize', $.proxy(function() {
if (this.visible)
{
this.overlay.resize();
if (!this.maximized) {
this.movebox();
}
}
}, this));
WHERE MOVEBOX() IS:
function(w, h) {
var size = { x: $(window).width(), y: $(window).height() };
var scroll = { x: $(window).scrollLeft(), y: $(window).scrollTop() };
var height = h!=null ? h : this.esqueleto.lightbox.outerHeight();
var width = w!=null ? w : this.esqueleto.lightbox.outerWidth();
var y = 0;
var x = 0;
//vertically center
x = scroll.x + ((size.x - width) / 2);
if (this.visible) {
y = scroll.y + (size.y - height) / 2;
} else if (this.options.emergefrom == "bottom") {
y = (scroll.y + size.y + 14);
} else {// top
y = (scroll.y - height) - 14;
}
if (this.visible) {
if (!this.animations.move) {
this.morph(this.esqueleto.move, {
'left' : x
}, 'move');
}
this.morph(this.esqueleto.move, {
'top' : y
}, 'move');
} else {
this.esqueleto.move.css({
'left' : x,
'top' : y
});
}
}
question is: how can I properly calculate new height and new with so the lightbox follows srcoll/zoom in android (and also in iphone it moves a bit)
A: My answer at move() element on window.resize() function not working on Android might shed some light on the subject for you. I'm guessing you're running into some sort of problem with scrollLeft().
Sad times :(
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: perl Win32::OLE ExportAsFixedFormat syntax for powerpoint I have trouble using perl (strawberry) and win32::ole using powerpoint (from office2010)
to convert ppt(x) to pdf.
I can export to jpgs fine with Export function but the function ExportAsFixedFormat has a quite obscure syntax and alwawys gives me
Win32::OLE(0.1709) error 0x80020011: "Does not support a collection".
this is a sample of what I am trying
my $ppoint = Win32::OLE->new('PowerPoint.Application', 'Quit');
my $Presentation = $ppoint->Presentations->Open("$infile") || die("Una +ble to open document ", Win32::OLE->LastError()) ;
$Presentation->ExportAsFixedFormat("$outfile", 2, 2, "msoCTrue", "ppPrintHandoutHorizontalFir +st", "ppPrintOutputFourSlideHandouts", "msoFalse", "", "" , "", "Fals +e", "False", "False", "False", "False");
second parameter ppFixedFormatTypePDF should be 2
third param 'ppFixedFormatIntentPrint' should be 2
Can anyone suggest a working example?
A: Just to complete the answer from golemwashere:
use Win32::OLE::Const 'Microsoft PowerPoint';
...
$Presentation->SaveAs("$outfile",ppSaveAsPDF, 1);
This works using powerpoint 2007 on windows 7, but the return value has to be ignored.
A: I solved using
$Presentation->SaveAs("$outfile", 32);
it was tricky finding that 32 = pdf format
and also $outfile needed foward slashes : /
in path (with \ I got confusing errors).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Weblogic ALSBConfigurationMBean initialization I'm trying to make an OSB (ESB) automated build process using Java. For that purpose I need to do the following things:
*
*Connect to weblogic - this is working //The weblogic version is 10.3.0.0
*Make a DomainRuntimeServiceMBean object using the connection - this is also working
*Make a ALSBConfigurationMBean object using the previously created DomainRuntimeServiceMBean object - here is my problem.
I use the following code for making the ALSBConfigurationMBean object:
DomainRuntimeServiceMBean domainService = ConnectionUtil
.createDomainService(mHost, mPort, mUsername, mPassword,
connector);
ALSBConfigurationMBean alsbSession = (ALSBConfigurationMBean) domainService
.findService(ALSBConfigurationMBean.NAME,
ALSBConfigurationMBean.TYPE, null);
The error that I get is:
Exception in thread "main" java.lang.ClassCastException: $Proxy1 cannot be cast to weblogic.management.mbeanservers.Service
at $Proxy0.findService(Unknown Source)
A: I am working on something similar, and the solution that @Rich gave worked for me. However, I have ended up with a slightly different approach that doesn't require using the weblogic.management.jmx.MBeanServerInvocationHandler (directly at least).
Here is some code that should do what you are looking for:
package scratch;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Hashtable;
import javax.management.JMX;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;
import weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean;
import com.bea.wli.sb.management.configuration.ALSBConfigurationMBean;
import com.bea.wli.sb.management.configuration.SessionManagementMBean;
public class TestOSB_JMX {
public static void main(String[] args) throws Throwable {
// Provide connection information for OSB WebLogic AdminServer on command line
String host = args[0];
int port = Integer.parseInt(args[1]);
String user = args[2];
String password = args[3];
JMXConnector conn = initJmxConnection(host, port, user, password);
try {
System.out.println("Opened JMX connection to " + host + ":" + port + " as " + user);
// get mbean connection
MBeanServerConnection mbconn = conn.getMBeanServerConnection();
// Get SessionmanagementMBean
SessionManagementMBean sm =
JMX.newMBeanProxy(mbconn, ObjectName.getInstance(SessionManagementMBean.OBJECT_NAME), SessionManagementMBean.class);
// Create a session
String sessionName = "MySession";
sm.createSession(sessionName);
// Get the configuration MBean for the session, do stuff, and then discard the session.
try
{
System.out.println("Session exists? : " + sm.sessionExists(sessionName));
ALSBConfigurationMBean configMBean =
JMX.newMBeanProxy(
mbconn,
ObjectName.getInstance("com.bea:Name=" +ALSBConfigurationMBean.NAME + "." + sessionName +",Type=" + ALSBConfigurationMBean.TYPE),
ALSBConfigurationMBean.class
);
System.out.println("Got the config MBean for session: " + configMBean.getSession());
// Do stuff in the session here....
}
finally
{
// use activateSession to commit session changes instead
sm.discardSession(sessionName);
}
} finally {
conn.close();
System.out.println("Closed JMX connection");
}
}
public static JMXConnector initJmxConnection(String hostname, int port,String username, String password)
throws IOException, MalformedURLException
{
JMXServiceURL serviceURL = new JMXServiceURL("t3", hostname, port, "/jndi/" + DomainRuntimeServiceMBean.MBEANSERVER_JNDI_NAME);
Hashtable<String, String> h = new Hashtable<String, String>();
h.put(Context.SECURITY_PRINCIPAL, username);
h.put(Context.SECURITY_CREDENTIALS, password);
h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
return JMXConnectorFactory.connect(serviceURL, h);
}
}
Here are some things to note about my solution:
*
*My classpath directly references the following WebLogic and OSB JAR files: alsb.jar, osb-server-modules-ref.jar, wlfullclient.jar
*These JARs will reference (many) other JARs through the Class-Path entries in the Manifest files.
*You may need to generate the wlfullclient.jar file as described here: http://docs.oracle.com/cd/E17904_01/web.1111/e13717/jarbuilder.htm
*It is better to use wlfullclient.jar instead of weblogic.jar for this type of client application. I was using weblogic.jar first and it caused many class loading headaches for me.
*I am using Oracle Service Bus Version: 11.1.1.4 WebLogic version: 10.3.4, and Java 1.6.0_29.
A: In case that anyone gets the same error then use
weblogic.management.jmx.MBeanServerInvocationHandler instead of javax.management.MBeanServerInvocationHandler:
https://forums.oracle.com/forums/thread.jspa?threadID=817973&tstart=420
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Backbone.js Collection.create and overridden Model.set I have a backbone model where I have changed the set method to calculate extra attributes on every set of the model.
According to the docs this should be the way to call super in order to make sure the model is actually saved.
Backbone.Model.prototype.set.call(this, attributes, options);
And it works just as expected, unless I use Collection.create.
My custom set method gets run, but I think the original does not since the collection remains empty.
The server receives the correct data and sends the right data back. On both occasions my method gets executed, but the collection is still empty.
Can I change the super call to make it work with Collection.create or is there another way to do the same thing?
A: Just as I thought, I missed something.
When overriding Model.set() one must put return this; at the end.
So a model should look like this:
var MyModel = Backbone.Model.extend({
set: function(attributes, options) {
// Custom code...
return Backbone.Model.prototype.set.call(this, attributes, options);
}
});
A: I'd recommend cracking open a debugger and following it through. Take a look at the Collection.create function and the Model.save function. Note that the create function calls Model.save with a success callback. Model.save sends the data to the server and also chains to the success callback at which Model.set is called.
I'd put breakpoints in the success callbacks for both of these functions as they are very straight forward and will likely point out your issue.
Finally, if you are able to reproduce the problem with a jsFiddle, it would be really useful in helping us understand the full context of the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: jQuery Mobile: explicitly override the rounding of all corners jQuery Mobile automatically rounds all corners of input elements, by adding a class ui-corner-all. I noticed that if I change this class manually to ui-corner-left in Chrome inspector, then I correctly get only rounded corners on the left (top and bottom). This could of course easily be done with one line of jQuery, such as
$('#myid').removeClass('ui-corner-all').addClass('ui-corner-left');
My question is, is there a way I can instruct jQuery Mobile to apply this class straight away, without having to execute this extra bit of code after JQM has done it's work?
A: Basically following can be apply, but your concern is to run without extra code execution, lets see wheter we get chance to get it, even I'm looking same question, but following is my solution.
$('div').live('pageshow',function(event){
$('#myid').removeClass('ui-corner-all').addClass('ui-corner-left');
});
A: You can override the default value by specifying in your index.html file the jquery mobile class you want. A good example would be, instead of:
<ul id='myid' data-inset='true' data-theme='a' data-role='listview' class='ui-listview ui-listview-inset ui-shadow'>
which would automatically insert this
class ui-corner-all
you would then add your own class:
<ul id='myid' data-inset='true' data-theme='a' data-role='listview' class='ui-listview ui-corner-left ui-listview-inset ui-shadow'>
In firefox, the ui-corner-all class does not get automatically added for me, maybe you are using an older version of jquery mobile and need to upgrade.
If you want to do it dynamically in a javascript file:
$("#my_page_id").live("pagecreate",function(){
var ul = $("<ul id='myid' data-inset='true' data-theme='a' data-role='listview' class='ui-listview ui-listview-inset ui-corner-left ui-shadow'>");
ul.append($('<li class="ui-li ui-li-static ui-body-a ui-corner-left">').append("Code Slayer!!!"));
$('mydiv_in_mypage').html(ul);
});
as in re-write the contents of the div all over again, automatically erasing the old contents. If you will display a lot of information in your list you might want to use the
$.mobile.showPageLoadingMsg('a','Page Loading', true);
and then hide the message when your page has been fully displayed.
A: hey Simply you can do like this
<a href="#panel" data-corners="false"></a>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unit Test Outcome in Silverlight Unit Test for WP7 I m executing some unit tests for my application. I would like to know what is the outcome of my testmethod. Testoutcome always gives "error" as output. I have given the code snippet
below. Please let me know how to get the result of [TestMethod] - CheckUploadPageLoaded.
public TestContext TestContext
{
get { return testContextInstance; }
set { testContextInstance = value; }
}
public TestOutcome _testoutcome { get; set; }
[TestMethod]
public void AlwaysTrue()
{
Assert.IsTrue(true, "this method always pass");
TestContext.WriteLine(TestContext.TestName);
}
[TestMethod]
public void CheckUploadPageLoaded()
{
FlickrShare.Upload upload = new FlickrShare.Upload();
Assert.IsNotNull(upload);
Console.WriteLine(_testoutcome);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: "for each" loop in reverse Is it possible to have "for each" loop in reverse?
Or the only way to do it is like
for(var i:int = maxnumber; i>0; i--)
{
//something
}
A: No, you'll need to use an ordinary for loop.
A: You can reverse array:
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#reverse()
And have "for each" loop. After loop you can reverse again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Zend Ldap allow only if user has a certain Group What I want to achieve:
*
*there are two different group
*administration
*readonly
I want to be able to authenticate a user and assign a role depending on which group he belongs to.
What I've tried:
Given the official docs I've set up two "servers" with different group options to authenticate:
ldap.admin.host = myhost
ldap.admin.port = myport
ldap.admin.useStartTls = true
ldap.admin.useSsl = true
ldap.admin.username = "cn=ama,ou=LDAPAuth,dc=mydc,dc=de"
ldap.admin.password = "mypass"
ldap.admin.accountFilterFormat = "cn=%s"
ldap.admin.baseDn = "dc=mydc,dc=de"
ldap.admin.bindRequiresDn = true
ldap.admin.group = "ama"
ldap.admin.groupDn = "cn=ama,ou=groups,dc=mydc,dc=de"
ldap.admin.groupAttr = "cn"
ldap.admin.groupFilter = "objectClass=groupOfNames"
ldap.admin.memberAttr = "member"
ldap.readonly.host = myhost
ldap.readonly.port = myport
ldap.readonly.useStartTls = true
ldap.readonly.useSsl = true
ldap.readonly.username = "cn=ama,ou=LDAPAuth,dc=mydc,dc=de"
ldap.readonly.password = "mypass"
ldap.readonly.accountFilterFormat = "cn=%s"
ldap.readonly.baseDn = "dc=mydc,dc=de"
ldap.readonly.bindRequiresDn = true
ldap.readonly.group = "ama_ro"
ldap.readonly.groupDn = "cn=ama_ro,ou=groups,dc=mydc,dc=de"
ldap.readonly.groupAttr = "cn"
ldap.readonly.groupFilter = "objectClass=groupOfNames"
ldap.readonly.memberAttr = "member"
Now the official docs say, that if the authentication against the first server fails, it will try to do so against the second one. However, That doesn't seem to be the case with my authentication script.
I got three test accounts, one without group, two with each one of them. If I use only one of the options, it works for the user it should, all others get access denied, just as I want.
But I just can't seem to be able to implement the "fluid check".
Furthermore: even if the 'fluid check' would work, I don't really understand how I would find out, against which group the user was able to authenticate.
To my understanding I would need to manually query against the server after I get a positive authentication to read the groups of the user - is this correct? If so, I have found the following question here on this site: Query all groups of a user using Zend_Ldap
That however doesn't seem to work for me, because I only get empty arrays or errors, depending on what I try :(
A:
Now the official docs say, that if the authentication against the
first server fails, it will try to do so against the second one.
However, That doesn't seem to be the case with my authentication
script.
The behaviour you describe was introduced as a solution to bug ZF-409. In order to get it to work as you want just set different accountDomainName (or accountDomainNameShort) in your 2 LDAP server options:
ldap.admin.accountDomainName = admin.domain
ldap.admin.accountDomainNameShort = admin
ldap.readonly.accountDomainName = readonly.domain
ldap.readonly.accountDomainNameShort = readonly
If you login using a "readonly" valid user, it will fail to login in as admin but it will login in as readonly. The Zend_Auth_Result will be something like:
object(Zend_Auth_Result)#159 (3) {
["_code":protected] => int(1)
["_identity":protected] => string(26) "readonly\username"
["_messages":protected] => array(6) {
[0] => string(0) ""
[1] => string(0) ""
[2] => string(312) "host=host,useSsl=1,accountDomainName=admin.domain,accountDomainNameShort=admin,accountCanonicalForm=3,baseDn=dc=mydc,dc=de,bindRequiresDn=1,useStartTls=1,group=ama_ro,groupDn=cn=ama_ro,ou=groups,dc=mydc,dc=de,groupAttr=cn,groupFilter=objectClass=groupOfNames,memberAttr=member"
[3] => string(142) "Failed to verify group membership with (&(&(cn=admin)(member=youruserDN))(yourfilter))"
[4] => string(310) "host=host,useSsl=1,accountDomainName=readonly.domain,accountDomainNameShort=readonly,accountCanonicalForm=3,baseDn=dc=mydc,dc=de,bindRequiresDn=1,useStartTls=1,group=ama_ro,groupDn=cn=ama_ro,ou=groups,dc=mydc,dc=de,groupAttr=cn,groupFilter=objectClass=groupOfNames,memberAttr=member"
[5] => string(52) "readonly\username authentication successful"
}
}
After you get a $login->isValid() just perform $login->getIdentity() and you'll get the accountDomainNameShort value along with username provided.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is there attribute for proxing instead of serialzing for remote objects properties in .NET Remoting? I have a class for remoting (name it RemoteClass). It has property Other of class OtherClass. By default, client has a proxy of RemoteClass object and a serialized copy of OtherClass after calling property Other. I want that client recieve a proxy for OtherClass too after calling property Other. Do not suggest me to separate RemoteClass and OtherClass, because this solution is unacceptable. My question is: May I to do what I want with .NET Remoting or It is better to use WCF instead (Can WCF help me at all?). Thanks for advice and any help.
A: Instead of using Serializable attribute, make your OtherClass inherit from MarshalByRefObject.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Query to show rows that only have one value in table I have problem in writing SQL in SQL Server. Here is the case, I have three tables named User, Client, and UserClient. Below are the sample of the table content
CLIENT
idClient | client
____________________________
1 | Client A
2 | Client B
3 | Client C
USER
idUser | User
____________________________
1 | User A
2 | User B
3 | User C
USERCLIENT
idUserClient | idUser | idClient
____________________________________
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
4 | 2 | 3
5 | 3 | 1
I need a query to show user with idClient = 1 AND only have one client from USERCLIENT table. As shown in the sample above, the result of the query should be
idUserClient | idUser | idClient
_________________________________________
5 | 3 | 1
A: BINGO!
SELECT * FROM USERCLIENT WHERE iduser IN
(SELECT iduser FROM USERCLIENT GROUP BY iduser HAVING COUNT(iduser)=1)
A: This worked for me...
with cte AS
(
SELECT 1 AS idUserClient, 1 AS idUser, 1 AS idClient
UNION
SELECT 2 AS idUserClient, 1 AS idUser, 2 AS idClient
UNION
SELECT 3 AS idUserClient, 2 AS idUser, 1 AS idClient
UNION
SELECT 4 AS idUserClient, 2 AS idUser, 3 AS idClient
UNION
SELECT 5 AS idUserClient, 3 AS idUser, 1 AS idClient
)
SELECT * FROM cte c1
WHERE
idUserClient IN
(
SELECT MIN(c2.idUserClient) FROM cte c2 GROUP BY c2.idUser HAVING COUNT(c2.idUser) = 1
)
A: Assuming that (idUser, idClient) is an unique index:
SELECT USERCLIENT.idUser
FROM USER
INNER JOIN USERCLIENT
ON USER.idUser = USERCLIENT.idUser
WHERE USERCLIENT.idClient = 1
GROUP BY USERCLIENT.idUser
HAVING COUNT(*) = 1
A: Given the data you mention, you can get the result you are looking for in two ways.
select * from userclient where idUser = 3
or
select * form userClient where idUser = 3 and idClient = 1
I'm not sure what you really want, but these two cases produces the result.
What do you got to query with?
A: This will show users that are associated with the client idClient = 1 and only that client:
SELECT
MAX(idUserClient) AS idUserClient,
idUser,
MAX(idClient) AS idClient
FROM USERCLIENT
GROUP BY idUser
HAVING COUNT(*) = 1
AND COUNT(CASE idClient WHEN 1 THEN 1 END) = 1
The HAVING clause checks that a group of rows for a user contains exactly one row and among 'them' there's exactly one row where idClient = 1.
Alternatively, SQL Server 2008 would allow you to do something like this:
WITH ranked AS (
SELECT
*,
rnk = ROW_NUMBER() OVER (
PARTITION BY idUser
ORDER BY CASE idClient WHEN 1 THEN 1 ELSE 0 END, idClient
)
FROM USERCLIENT
)
SELECT
idUserClient,
idUser,
idClient
FROM ranked
WHERE rnk = 1
AND idClient = 1
The CTE ranks the rows in USERCLIENT in such a way that if a user is associated with idClient = 1 and no other client, the corresponding row is ranked as 1, otherwise the row with idClient = 1 (if such one is present) gets a different rank. Therefore, when selecting from the CTE, you simply need to filter on rnk = 1 AND idClient = 1.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to pass data to a PartialView in my layout? I have a _layout.cshtml containing this row:
@{Html.RenderPartial("Menu");}
Now I want to pass in a model into this RenderPartial-function. This model can be read from my repository.
How and where(in code) can this be done?
Thanks!
A: RenderPartial has an overload that can take an object to send it to the partial view.
Don't forget to define your @model at the top of your partialview to work with the right object type.
@Html.RenderPartial("ViewName",object)
Extra info: MSDN
Edit after comment:
I think it would be easier to create a MenuController that takes in the repository. Then let it create a view which takes in the required repository as it's model, then with a foreach render every menu-item as actionlinks, passing the menu info to it.
So you would have this in your _layout.cshtml:
<div id="Menu">
@{Html.RenderAction("Menu", "Menu");}
</div>
This in your MenuController:
public class MenuController : Controller
{
private IMenuRepository _repository;
public MenuController(IMenuRepository repo)
{
_repository = repo;
}
//
// GET: /Menu/
public PartialViewResult Menu(string menu = null)
{
ViewBag.SelectedMenu = menu;
IEnumerable<MenuInfoObject> menus= _repository.Menus;
return PartialView(menus);
}
}
And your MenuView:
@model IEnumerable<MenuInfoObject>
@{
Layout = null;
}
@foreach (var item in Model)
{
@Html.RouteLink(item.MenuName, new
{
controller = item.ControllerInfo,
action = item.ActionInfo,
}, new
{
@class = item.Menu == ViewBag.SelectedMenu ? "selected" : null
})
}
Would that be any closer to a solution?
A: There is another solution as well to pass data to a partial view in Layout. You can simply add this in your _Layout.cshtml file
@Html.Action("ActionName","ControllerName")
And in your Controller :
[ChildActionOnly]
public ActionResult ActionName()
{
var model = new YourModel();
return PartialView(model);
}
The ChildActionOnly attribute ensures that an action method can be called only as a child method. This action will render the corresponding partial view with model in Layout.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I use the mobileweb facebook connect API with phonegap? I'm trying to integrate Facebook into my Phonegap application that is going to be deployed for both Android and Blackberry devices. As there is only a plugin available for Android I need to go down the standard Facebook connect mobileweb route. However I cannot redirect back to file:// (Phonegap) so I'm wondering if anybody has come up with an alternative solution?
I was wondering if it was possible to redirect to a separate hosted site I setup that would store the access code and then get the Phonegap application to subsequently interrogate for the access code to then use with Facebook API calls?
A: Yes, you can.
Use the JavaScript API, enable "Website" and "Mobile Web" under your app settings at https://www.facebook.com/developers
You will need some sort of publicly accessible page available that you can put in your settings, but because you are using this app in a standalone manner, the site doesn't ever need to be used.
Also, have a "Login" button when using the JavaScript API. You might run into popup blocker issues if you programmatically try to open Facebook's login window.
A: Can't you use the InAppBrowser of PhoneGap to call the Mobile Web auth stuff? See http://docs.phonegap.com/en/3.0.0/cordova_inappbrowser_inappbrowser.md.html#InAppBrowser
To get started with Facebook Login, have a look here: https://developers.facebook.com/docs/facebook-login/getting-started-web/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: CakePhp: Don't display ONE warning I've one place in my code where I free some ingres resources, and I've no way to know if the parameter is valid ingres resource.
So I would like to do it anyway(except if empty() ).
I'm try-catching it, but when this isnt a valid resource, I got the exception catched by cakePhp and then it display the debug message, and it mess with the encoding the whole site.
I know that I can't deactivate the debugging for the whole site, but the website is under development and it's not what I want.
So, how to manage cakePhp to DON'T display this warning for this exception on this line(I also don't want to ignore all errors of this type).
Is it possible?
Thank you very much
A: You can suppress errors/warnings with the error control operator but without seeing some code can't advise more specifically.
@mysql_connect('localhost', 'root, 'pass');
@file('file.txt');
etc.
Or you could try ~
Configure::write('debug', 0); // turn off debugging
/* your code here where you don't want any errors */
Configure::write('debug',2); // turn on debugging
I'm sure there's a proper way to check for valid data however. some code in your original post would help
A: If it's not a persistent connection, PHP will free it automatically: http://www.php.net/manual/en/language.types.resource.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I read configuration settings from Symfony2 config.yml in twig template? In controller i can read like this
$this->container->getParameter('test');
But how get this var "test" in my twig template?
A: Yes, you can create your own Twig extension, in this class you can override getGlobals() and return an array with your global variables.
Or you can create a Twig method in this extension param($value) to return the right parameter.
A: Depends what you need to get, my way of getting data from parameters.ini is:
config.yml
twig:
globals:
google_maps_api_key: %google_maps_api_key%
parameters.ini
[parameters]
google_maps_api_key="authkey"
in template:
{{ google_maps_api_key }}
Hope it helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: DB2: GRANT statement & access rights What rights should I give to DB user to execute REFRESH TABLE SOME_MQT; statement? Is it enough GRANT ALL ON SOME_MQT TO USER %USER_NAME ?
DB2 version: 9.5.3
A: The documentation for the REFRESH TABLE Statement seems pretty clear on that.
The privileges held by the authorization ID of the statement must
include at least one of the following:
*
*CONTROL privilege on the table
*SYSADM or DBADM authority
I'm not sure whether GRANT ALL is enough. It's not unusual for a dbms to grant a subset of all possible privileges using GRANT ALL. But it's easy enough to test. Just GRANT ALL on a materialized view (not necessarily the view in question; use a scratch view) and let the user try to refresh it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: (MySQLNonTransientConnectionException) Hibernate3.6 + MySQL5 + c3p0 I am using JPA + hibernate 3.6.6 + MySQL5 (mysql-connector-java-5.1.6-bin.jar) with c3p0-0.9.1.jar pool implementation. My persistence.xml
<properties>
<property name="hibernate.connection.username" value="xxx"/>
<property name="hibernate.connection.driver_class" value="xxx"/>
<property name="hibernate.connection.password" value="xxx"/>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/xxx"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.c3p0.min_size" value="5" />
<property name="hibernate.c3p0.max_size" value="100" />
<property name="hibernate.c3p0.timeout" value="1800" />
<property name="hibernate.c3p0.max_statements" value="50" />
</properties>
Probably 1 out 30 request I make, I would get the following exception. Then if I make the same request again after the exception, it works fine. I know MySQL5 has a 8 hr time-out but I get the exception way before that. Thanks.
Sep 30, 2011 3:56:50 PM com.mchange.v2.c3p0.stmt.GooGooStatementCache checkinStatement
INFO: Problem with checked-in Statement, discarding.
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after statement closed.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
at com.mysql.jdbc.Util.getInstance(Util.java:381)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:984)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:926)
at com.mysql.jdbc.StatementImpl.checkClosed(StatementImpl.java:380)
at com.mysql.jdbc.PreparedStatement.clearParameters(PreparedStatement.java:784)
at com.mchange.v2.c3p0.stmt.GooGooStatementCache.refreshStatement(GooGooStatementCache.java:604)
at com.mchange.v2.c3p0.stmt.GooGooStatementCache.checkinStatement(GooGooStatementCache.java:236)
at com.mchange.v2.c3p0.impl.NewPooledConnection.checkinStatement(NewPooledConnection.java:239)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.close(NewProxyPreparedStatement.java:1807)
at org.hibernate.jdbc.AbstractBatcher.closePreparedStatement(AbstractBatcher.java:563)
at org.hibernate.jdbc.AbstractBatcher.closeStatement(AbstractBatcher.java:291)
at org.hibernate.jdbc.AbstractBatcher.closeQueryStatement(AbstractBatcher.java:307)
at org.hibernate.jdbc.AbstractBatcher.closeQueryStatement(AbstractBatcher.java:234)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1967)
at org.hibernate.loader.Loader.doQuery(Loader.java:802)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274)
at org.hibernate.loader.Loader.doList(Loader.java:2533)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
at org.hibernate.loader.Loader.list(Loader.java:2271)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:452)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:363)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1268)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:246)
...
A: It might happen after a long time of inactivity. Add validationQuery to your dataSource bean:
<property name="validationQuery">
<value>Select 1</value>
</property>
Hope it helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can a Wakelock be released automatically? I inicialize a wakelock in the onStartCommand of a service:
wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
wl.acquire();
I want the wakelock active because I need to recognize a shake event at any time, even with the screen locked.
When the service is up for a long time and I destroy it, it gives an error when acessing the wakelock on the destroy method:
@Override
public void onDestroy() {
mSensorManager.unregisterListener(mSensorListener);
if(wl.isHeld())
wl.release();
super.onDestroy();
}
Am I doing anything wrong? Is the wakelock released at some point automatically?
Is there a more correct way to do this?
A: What error do you get?
Assuming your Service isn't strictly "one-shot" you should be getting several calls to onStartCommand on the same service instance - thus creating a lot of wakelocks. Don't do that.
Start by moving the creation of the WakeLock to your Service#onCreate() - you only really ever need one. If you want to keep the device awake until you kill your service "manually" I'd recommend that you WakeLock#aquire() in Service#onCreate(), no point in calling it more than once.
If you insist on keeping the WakeLock#aquire() in Service#onStartCommand() you need to keep track of the number of times you've called it (since it is reference counted by default) - or turn of reference counting on the WakeLock when you create it by calling WakeLock#setReferenceCounted(false).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Git clone fails with out of memory error - "fatal: out of memory, malloc failed (tried to allocate 905574791 bytes) / fatal: index-pack failed" I'm attempting to clone a large (1.4GB) Git repository to a 32-bit Debian VM with 384MB of RAM. I'm using Git 1.7.2.5, and using the SSH protocol to clone ('git clone user@host.com:/my/repo')
The clone fails with this message:
remote: Counting objects: 18797, done.
remote: warning: subobtimal pack - out of memory
remote: Compressing objects: 100% (10363/10363), done.
fatal: out of memory, malloc failed (tried to allocate 905574791 bytes)
fatal: index-pack failed
I've tried reducing the amount of memory Git uses to repack on the host repository end, and repacking:
git config pack.windowMemory 10m
git config pack.packSizeLimit 20m
git repack -a -d
My questions are as follows:
*
*Is this a client-size (clone-side) problem or should it be resolved in the repo that I'm cloning from?
*In either case, is there anything I can do to make the clone succeed? A lot of the potential solutions online involve some/all of the following things, none of which are acceptable in this instance:
*
*changing the contents of the repository substantively (i.e. deleting large files)
*giving the VM which is doing the clone more RAM
*giving the VM which is doing the clone a 64-bit virtual CPU
*transferring out-of-band (e.g. using Rsync or SFTP to transfer the .git directory)
Thanks in advance.
A: git clone will not look at your pack.packSizeLimit setting, it'll anyway transfer everything in a single pack - unless it changed since the last time I looked.
Using SCP or Rsync might be a way to work around your issue indeed. Removing the "useless" large files, then repacking the repository you try to clone could also help.
Giving more RAM to the VM might also help - I don't think you'll need a 64-bits address space to allocate 900MB... You could also give it enough SWAP space to handle the 900MB package instead of increasing the RAM.
A: I got a similar issue on Windows using MSysGit 32 bits.
The git 64 bits from Cygwin did the job.
Maybe you should use a 64 bits Debian VM (instead of 32 bits one).
My original answer is available on question Git on Windows, “Out of memory - malloc failed”.
A: Today I had the same issue. Git server ran out of memory, but gitlab reported that there is still memory available. We checked memory with htop (reported none available), restarted gitlab and everything went back to normal.
A: sudo git pull
I faced the same error message every time I pull and sudo git pull actually helped me to overcome this error message and pull was successful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: Azure tutorial - How to use local blob storage I am new to Windows Azure world. I do not have live Azure account. Can I still do the development work using local blob storage, SQL Azure, Fabric etc?
Can anybody share any link for Azure videos for begineer? I am looking for step by step guide.
Atul Sureka
A: To answer your first question. Yes you can. Just download the SDK from here and get started without an account.
You can find a video of how to use blob storage here as well as other video tutorials.
If you want a text version of how to use Azure Blob Storage you can find it here.
A: There's a free trial for Azure: http://www.microsoft.com/windowsazure/free-trial/
You'll find the Azure SDK includes an emulator for table and Blob storage. It doesn't include an emulator for SQL Azure, however, as it's close enough to full SQL Server that almost all applications will work without drastic changes.
The link above also includes a vast range of documentation and tutorials.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Are there any performance test results for usage of likely/unlikely hints? gcc features likely/unlikely hints that help the compiler to generate machine code with better branch prediction.
Is there any data on how proper usage or failure to use those hints affects performance of real code on some real systems?
A: The question differs, but Peter Cordes's answer on this question gives a clear hint ;) . Modern CPU's ignore static hints and use dynamic branch prediction.
A: I don't know of any thorough analysis of such particular hints. In any case, it would be extremely CPU-specific. In general, if you are sure about the likelyhood (e.g., > 90%) then it is probably worthwhile to add such annotations, although improvements will vary a lot with the specific use case.
Modern Desktop CPUs tend to have very good branch prediction. If your code is on a hot path anyway, the dynamic branch predictor will quickly figure out that the branch is biased on its own. Such hints are mainly useful to help the static predictor which kicks in if no dynamic branch information is available.
On x86, the static predictor predicts forward branches not to be taken and backward branches to be taken (since they usually indicate loops). The compiler will therefore adjust static code layout to match the predictions. (This may also help putting the hot path on adjacent cache lines, which may help further.)
On PPC, some jump instructions have a bit to predict their likelyhood. I don't know if the compiler will rearrange code, too.
I don't know how ARM CPUs predict branches. As a low-power device it may have less sophisticated branch prediction and static prediction could have more impact.
A: Likely/Unlikely hints work by preloading the ICache with the branch code that is perceived as being generally correct by the programmer. Branch predictors are, by nature of relying upon limited historical data, effective in loops (or small codebases) only, and loops are not always the issue, with regards to branching performance -- for example, in a real-time simulation, or game, where large amounts of sim/game logic need to be processed for large numbers of objects, at a very high rate. Branch predictors cannot operate effectively in this context, and this is a serious performance concern for sim developers. This logic can consist of literally thousands of different, non-repeating conditionals each frame, completely disabling the ability of a branch predictor to operate effectively.
In answer to the original question, compilers tend to assume a conditional will be false, when generating the code to preload the Icache. You should check the assembly output in your code to verify that, and then you might be able to author a macro for conditionals you want to preload in a performant way, if you don't want to structure your code to fit a particular processor architecture.
Some studies have estimated that modern game engines, on modern processors, spend 60-80% of their time on cache misses, and that branch mis-predictions are approximately 15% of those misses. In order to accommodate a modern game engine, a branch predictor would need historical data for the entire game logic frame -- probably involving several MB of data for each pipeline.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: your thoughts on implementing a 3D globe with javascript can you guys look at this screenshot - http://d.pr/IlEl
that's the intended design. Our user can rotate the globe left/right and on the globe they'd see which people are traveling to which place.
Someone suggested to use this library:
http://mrdoob.github.com/three.js/examples/canvas_geometry_earth.html
Unofortunately it runs in less than 2 fps... I was wondering if you guys can have any other suggestion or if its possible at all to do something like that in Javascript/HTML5 with an acceptable performance.
A: Have your looked at http://www.chromeexperiments.com/globe?
While it's not exactly what you need, the source is available, and you could easily modify it to provide the features you're looking for, with the great 3D performance that you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHP Call to a member function prepare() on a non-object error Hi i need some help with this error I keep getting. It works fine everywhere else in the script except when I try to call it within this one function.
The function I am calling is: getTotalServers
Error:
Fatal error: Call to a member function prepare() on a non-object in C:\xampp2\htdocs\runeloft\ss_sources\util.php on line 208
Calling in this function:
function display_table($online, $where, $num_servers = null){
global $aaaa, $bbbb;
$num_per_page = 30;
$page = 1;
// how many records per page
$size = 10;
// we get the current page from $_GET
if (isset($_GET['page'])){
$page = (int) $_GET['page'];
}
$aaaa = getTotalServers(1, $num_servers);;
$bbbb = $page;
// create the pagination class
$pagination = new Pagination();
$pagination->setLink("?action=status&page=%s");
$pagination->setPage($page);
$pagination->setSize($size);
$pagination->setTotalRecords($num_servers);
global $g_headers;
$g_headers = array(
'name' => 'Server Name',
'ip' => 'IP',
'port' => 'Port',
'uptime' => 'Uptime',
'online' => 'Status',
);
$start = isset($_GET['start']) ? $_GET['start'] : 0;
mysql_con();
global $g_mysqli;
$start = $g_mysqli->real_escape_string($start);
if(isset($_GET['sort']) && isset($g_headers[$_GET['sort']])){
$order_by = 'ORDER BY `'.$g_mysqli->real_escape_string($_GET['sort']).'` '.(isset($_GET['desc']) ? 'DESC' : 'ASC');
}else{
//default sort
$order_by = 'ORDER BY `uptime` DESC, `time` ASC';
}
//$order_by .= " LIMIT $start, $num_per_page";
$order_by .= " " . $pagination->getLimitSql();
if($start == 0 && $online == 1 && !isset($_GET['sort']))
echoTable('Spons', "`sponsored` != '0'", "ORDER BY `sponsored` DESC, RAND() LIMIT 10");
echoTable('Other', $where, $order_by, $online, $start, $num_per_page, $num_servers);
close_mysql();
}
Called Function:
function getTotalServers($online, $where, $num_servers = null){
$where = "`online` = '$online' AND `sponsored` = '0'";
if($num_servers == null){
global $g_mysqli;
$stmt = $g_mysqli->prepare("SELECT COUNT(*) FROM `servers` WHERE ".$where) or debug($g_mysqli->error);
$stmt->execute();
// bind result variables
$stmt->bind_result($num_servers);
$stmt->fetch();
$stmt->close();
}
return $num_servers;
}
Thanks for any help.
A: My guess is that as mysql_con has not been called at that point, the $g_mysql variable does not exist.
If you try to call a method on a non-object, PHP will trigger the error you are seeing. Basically since the variable doesn't exist, it's defaulting to null.
$a = null;
$a->prepare()
Makes no sense, so that's why PHP is throwing that error.
On a different note, you really shouldn't use global variables. You can google or search stackoverflow for a more detailed list, but in short, they break portability of code, and make errors like this one harder to spot. It's a pain to pass an extra parameter to each function call that needs it, but it's much better from a design point of view (and really not much extra effort :p).
A: The object $g_mysqli should be initialized BEFORE it is called in your code.
In your case you are creating global variable $g_mysqli at many places but every time it is a NULL object before you initialize it.
So you can't call any function within null object.
A: The problem is with header() function.
The all you need to do is to add a ob_start() at the top of your codes in any page which uses header() function.
Just a confusing error!!!
If anyone knows the reason please explain..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Changing column width in a combobox associated with a dataset in .net I have a ComboBox with its datasource being a dataset from a SQL Server database.
The width of its columns are relative to the width of the name of the columns. I would like to increase that width in order to see the content properly and not cuted.
Here is a screenshot of what I'm talking about:
As you can see the values in the second column do not appear completly.
Here is the method I use to load a ComboBox:
Public Sub CargarComboAlternativo(ByVal Combo As ComboBox, ByVal query As String)
Dim connectionString As String = "Data Source=" & Servidor & ";Database=" & Bdatos & ";Trusted_Connection=Yes;UID=" & UID & ";"
Dim adapter As SqlDataAdapter
Dim dataSet As DataSet = New DataSet()
Try
Using conn As SqlConnection = New SqlConnection(connectionString)
Using command As New SqlCommand(query, conn)
command.CommandType = CommandType.Text
conn.Open()
adapter = New SqlDataAdapter(command)
dataSet.Clear()
adapter.Fill(dataSet)
Combo.DataSource = dataSet
End Using
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Any suggestions?
I don't mind at all a suggestion in C#, I won't have problems to translate it to vb.net
A: what about somehting like at the end:
Dim total As Integer = 0
Dim maxLen As Integer = 0
For Each row As DataRow In ds.Tables(0).Rows
total = 0
For Each Str As String In row.ItemArray
total = Str.Length + total
Next
If maxLen < total Then maxLen = total
Next
Combo.Width = maxLen + 5
I know its brute force but you'll find the longest item and set the width to that. the +5 is for padding you may need to change that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Connect the Accessory to my JailBreak iPhone Device I am using serial programming for get connected serial cable to my iPhone
my code is as under
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
static struct termios gOriginalTTYAttrs;
static int OpenSerialPort()
{
int fileDescriptor = -1;
int handshake;
struct termios options;
// Open the serial port read/write, with no controlling terminal, and don't wait for a connection.
// The O_NONBLOCK flag also causes subsequent I/O on the device to be non-blocking.
// See open(2) ("man 2 open") for details.
fileDescriptor = open("/dev/tty.iap", O_RDWR | O_NOCTTY | O_NONBLOCK);
if (fileDescriptor == -1)
{
printf("Error opening serial port %s - %s(%d).\n",
"/dev/tty.iap", strerror(errno), errno);
goto error;
}
// Note that open() follows POSIX semantics: multiple open() calls to the same file will succeed
// unless the TIOCEXCL ioctl is issued. This will prevent additional opens except by root-owned
// processes.
// See tty(4) ("man 4 tty") and ioctl(2) ("man 2 ioctl") for details.
if (ioctl(fileDescriptor, TIOCEXCL) == -1)
{
printf("Error setting TIOCEXCL on %s - %s(%d).\n",
"/dev/tty.iap", strerror(errno), errno);
goto error;
}
// Now that the device is open, clear the O_NONBLOCK flag so subsequent I/O will block.
// See fcntl(2) ("man 2 fcntl") for details.
if (fcntl(fileDescriptor, F_SETFL, 0) == -1)
{
printf("Error clearing O_NONBLOCK %s - %s(%d).\n",
"/dev/tty.iap", strerror(errno), errno);
goto error;
}
// Get the current options and save them so we can restore the default settings later.
if (tcgetattr(fileDescriptor, &gOriginalTTYAttrs) == -1)
{
printf("Error getting tty attributes %s - %s(%d).\n",
"/dev/tty.iap", strerror(errno), errno);
goto error;
}
// The serial port attributes such as timeouts and baud rate are set by modifying the termios
// structure and then calling tcsetattr() to cause the changes to take effect. Note that the
// changes will not become effective without the tcsetattr() call.
// See tcsetattr(4) ("man 4 tcsetattr") for details.
options = gOriginalTTYAttrs;
// Print the current input and output baud rates.
// See tcsetattr(4) ("man 4 tcsetattr") for details.
printf("Current input baud rate is %d\n", (int) cfgetispeed(&options));
printf("Current output baud rate is %d\n", (int) cfgetospeed(&options));
// Set raw input (non-canonical) mode, with reads blocking until either a single character
// has been received or a one second timeout expires.
// See tcsetattr(4) ("man 4 tcsetattr") and termios(4) ("man 4 termios") for details.
cfmakeraw(&options);
options.c_cc[VMIN] = 1;
options.c_cc[VTIME] = 10;
// The baud rate, word length, and handshake options can be set as follows:
cfsetspeed(&options, B19200); // Set 19200 baud
options.c_cflag |= (CS8); // RTS flow control of input
printf("Input baud rate changed to %d\n", (int) cfgetispeed(&options));
printf("Output baud rate changed to %d\n", (int) cfgetospeed(&options));
// Cause the new options to take effect immediately.
if (tcsetattr(fileDescriptor, TCSANOW, &options) == -1)
{
printf("Error setting tty attributes %s - %s(%d).\n",
"/dev/tty.iap", strerror(errno), errno);
goto error;
}
// Success
return fileDescriptor;
// Failure "/dev/tty.iap"
error:
if (fileDescriptor != -1)
{
close(fileDescriptor);
}
return -1;
}
int main(int args, char *argv[])
{
int fd;
char somechar[8];
fd=OpenSerialPort(); // Open tty.iap with no hardware control, 8 bit, BLOCKING and at 19200 baud
if(fd>-1)
{
write(fd,"*",1); // Write handshaking message over serial
///////////////////////////////////////////////////////////////////////////////////////////////////
// After this, our device or our PC program should be strobing serial ground to gain access to the Iphone Serial Line
//////////////////////////////////////////////////////////////////////////////////////////////////
read(fd,&somechar[0],1); // Read 1 byte over serial. This will block (wait) untill the byte has been received
if(somechar[0]=='*') // Check if this byte is a "handshaking" message
{
printf("Serial connection established!\n"); // If it is, we have established a connection to the device and can freely read/write over serial!
while(1) // Do this forever or untill someone presses CTRL+C
{
read(fd,&somechar[0],1); // Read a character over serial!
putchar(somechar[0]); // Write the character to the Terminal!!
}
}
}
return 0;
}
but when i am going to check the cable is connected or not i got one Error like this
Error opening serial port /dev/tty.iap - Operation not permitted(1).
is there any one know the solution and please give me suggestion if i am going in wrong way
actually i am a new in iOS development so more confused.
Thanks
A: Perhaps the following articles iPhone Serial Communication may help?
iPhone/iPod Touch Serial Port Tutorial By Collin Meyer
and
iPhone Serial Communication
A: I got the same error when trying to open the serial port on a jailbroken iPod Touch running iOS 5.0 using a binary created with Xcode. However when I used gcc (for the iPhone with appropriate flags set) on the command line on my Mac instead of Xcode and created a command line app for iOS, the binary that was generated was able to open the serial port and read commands from my external accessory. This should be possible to create a library and link it with Xcode and have the same result (though I haven't tried it yet).
Update: Unfortunately creating a library in gcc and linking it in an Xcode project came up with the same error as before. Possible solutions:
*
*call the command line app from the iOS Xcode GUI app
*compile the app itself with gcc instead of Xcode
Actually, it's even simpler than this, found it while going through the second link in Fulvio's answer: You just need to move the app to a different directory than where Xcode normally puts them. As suggested in the blog entry, I put my app in a directory for Cydia apps (/private/var/stash/Applications), and was able to open the serial port--no gcc compiling necessary.
So my gcc-compiled command-line app was able to read from the serial port because I was executing it in the root's home directory, which also doesn't have the restrictions of the normal apps directory (/private/var/mobile/Applications)--whatever those restrictions might be.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Nullpointer exception in Splashscreen when it access drawable I builded a splashscreen which is showen for 5 sec afterwards it goes to my main activity. In this splashscreen I have a boolen which checks if the app is opened up the first time, if yes, it puts some stuff into my database. But exactly at this point I get a NullPointerException.
I don't get why its not working. In my eyes it should. It also really strange 'cause I tested the code in a demoapp with no errors.
So here is the Code of my SplashScreenActivity.java
package de.retowaelchli.filterit;
import org.apache.http.util.ByteArrayBuffer;
import android.app.Activity;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.ImageView;
import de.retowaelchli.filterit.database.DBAdapter;
import de.retowaelchli.filterit.database.SmileyDBAdapter;
public class SplashScreenActivity extends Activity {
//Variablen definieren
public static final String KEY_APP_IS_INITIALIZED = "APP_INITIALIZED";
public SmileyDBAdapter mDbHelper;
private DBAdapter db;
ImageView iv;
ContextWrapper context;
ByteArrayBuffer baf;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
//Datenbank filling
db = new DBAdapter(this);
db.open();
db.close();
mDbHelper = new SmileyDBAdapter(this);
startupcheck();
//Splash-Screen Animation
Thread splashThread = new Thread() {
@Override
public void run() {
try {
int waited = 0;
while (waited < 5000) {
sleep(100);
waited += 100;
}
}
catch (InterruptedException e) {
// do nothing
}
finally {
finish();
Intent i = new Intent();
i.setClassName("de.retowaelchli.filterit",
"de.retowaelchli.filterit.StartseiteActivity");
startActivity(i);
}
}
};
splashThread.start();
}
//Hier wird getestet ob das App bereits die Datenbankeinträge besitzt
private void startupcheck(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(SplashScreenActivity.this);
boolean appIsInitialized = prefs.getBoolean(KEY_APP_IS_INITIALIZED, false);
if (appIsInitialized == false){
//Hier werden die Smiley gefüllt
devil(); <--THIS IS GIVING ME A NULLPOINTEREXCEPTION
//Hier wird eingetragen das die Datenbank gefüllt wurde
Editor editor = prefs.edit();
editor.putBoolean(KEY_APP_IS_INITIALIZED, true);
editor.commit();
}
}
/** Hier sind alle Datenbank Einträge definiert**/
private void devil(){
int drawableID = context.getResources().getIdentifier("devil", "drawable", getPackageName());
iv.setImageResource(drawableID);
String info = String.valueOf(drawableID);
mDbHelper.open();
mDbHelper.createSmiley("You received a satanic message", info);
mDbHelper.close();
}
}
Probably it has something to do that drawable isn't loaded but I can't image why its not loaded....
So and here is my LogCat:
09-30 10:44:04.808: INFO/ActivityManager(1760): Starting activity: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=de.retowaelchli.filterit/.SplashScreenActivity } from pid 3193
09-30 10:44:04.838: VERBOSE/HtcAppUsageStats(1760): (launch app, package): (Filter It, de.retowaelchli.filterit)
09-30 10:44:04.858: INFO/ActivityManager(1760): Start proc de.retowaelchli.filterit for activity de.retowaelchli.filterit/.SplashScreenActivity: pid=9074 uid=10150 gids={}
09-30 10:44:04.868: INFO/SuperPowerSvc(16326): [SuperPowerSvc] App launched: [de.retowaelchli.filterit]
09-30 10:44:04.918: ERROR/jdwp(9074): Failed sending reply to debugger: Broken pipe
09-30 10:44:04.918: DEBUG/dalvikvm(9074): Debugger has detached; object registry had 1 entries
09-30 10:44:05.038: VERBOSE/levels(6925): ::Bundle[{icon-small=17302166, present=true, scale=100, level=75, technology=Li-ion, status=3, voltage=3965, plugged=2, health=2, temperature=270}]
09-30 10:44:05.548: DEBUG/Database(9074): dbopen(): path = /data/data/de.retowaelchli.filterit/databases/filterit, flag = 6
09-30 10:44:05.548: DEBUG/Database(9074): dbopen(): path = /data/data/de.retowaelchli.filterit/databases/filterit, free size = 689
09-30 10:44:05.578: DEBUG/AndroidRuntime(9074): Shutting down VM
09-30 10:44:05.578: WARN/dalvikvm(9074): threadid=1: thread exiting with uncaught exception (group=0x4001d5a0)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): FATAL EXCEPTION: main
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): java.lang.RuntimeException: Unable to start activity ComponentInfo{de.retowaelchli.filterit/de.retowaelchli.filterit.SplashScreenActivity}: java.lang.NullPointerException
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1816)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1837)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at android.app.ActivityThread.access$1500(ActivityThread.java:132)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1033)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at android.os.Handler.dispatchMessage(Handler.java:99)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at android.os.Looper.loop(Looper.java:143)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at android.app.ActivityThread.main(ActivityThread.java:4196)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at java.lang.reflect.Method.invokeNative(Native Method)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at java.lang.reflect.Method.invoke(Method.java:507)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at dalvik.system.NativeStart.main(Native Method)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): Caused by: java.lang.NullPointerException
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at de.retowaelchli.filterit.SplashScreenActivity.devil(SplashScreenActivity.java:109)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at de.retowaelchli.filterit.SplashScreenActivity.startupcheck(SplashScreenActivity.java:76)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at de.retowaelchli.filterit.SplashScreenActivity.onCreate(SplashScreenActivity.java:40)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1780)
09-30 10:44:05.628: ERROR/AndroidRuntime(9074): ... 11 more
09-30 10:44:05.628: WARN/ActivityManager(1760): Force finishing activity de.retowaelchli.filterit/.SplashScreenActivity
09-30 10:44:06.128: WARN/ActivityManager(1760): Activity pause timeout for HistoryRecord{40a95900 de.retowaelchli.filterit/.SplashScreenActivity}
09-30 10:44:06.228: WARN/ResourceType(1760): Skipping entry 0x7f040005 in package table 0 because it is not complex!
Thx for you help in advance!
A: I dont see anywhere you init your ImageView iv from onCreate().
A: ImageView iv;
because you did't initialise this and said iv.setImageResource(drawableID); whic is like null.setImageResource(drawableID);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: T-SQL Syntax error: Column 'dbo.Policy.CompanyId' is invalid in the select list Could someone help me figure out what's wrong with the following T-SQL syntax?
SELECT
p.CompanyId, COUNT(*) as PolicyCount, c.CompanyId, c.CompanyName
FROM
dbo.Policy p
INNER JOIN dbo.Company c ON p.CompanyId = c.CompanyId
WHERE
p.PolicyIssuingDate BETWEEN @StartDate AND @EndDate
GROUP BY
p.PolicyId
I keep getting the following syntax error:
Column 'dbo.Policy.CompanyId' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Any suggestions?
UPDATE:
Ok thanks to your input guys, I figured it out... Here's the solution:
SELECT
p.CompanyId, COUNT(p.PolicyId) as PolicyCount, c.CompanyName
FROM
dbo.Policy p
INNER JOIN dbo.Company c ON p.CompanyId = c.CompanyId
WHERE
p.PolicyIssuingDate BETWEEN @StartDate AND @EndDate
GROUP BY
p.CompanyId, c.CompanyName
A: According to your query u are trying to count records which have same policyID and whose issue date is between @startdate and @enddate
But the problem is u select companyid which is not in group by clause
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Xstream Implicit Map As Attributes to Root Element I am trying to find a solution to convert a map into root element attributes using XStream.
I do not think this is possible but here is what I have tried to far.
I created a custom converter and attached it to the root object, in the converter I then get access to the map that I am trying to convert into attributes, I iterate through the map and write the attirbute to the node, using writer.addAttribute(entry.getKey(), entry.getValue()); this does actually write the attributes to the root node e.g.
The problem with this approach is that it does not process the rest of the document, it just stops after processing the map, in order to get this to work I need some method of letting the default converter back in control and finish off the model.
The second solution I have been trying to use is to create a custom converter just for the map its self, the problem with this approach is that I can not get a handle to the root element so I can not write to it, is it possible to access the root element this way?
Thanks,
Jon
A: Create a converter that writes out the map and falls back on marshalling the object using a reflection converter:
static class MyConverter implements Converter {
private final Map<String, String> attributes;
private final Class<?> clazz;
private final Mapper mapper;
private final ReflectionProvider reflectionProvider;
public MyConverter(Mapper mapper,
ReflectionProvider reflectionProvider, Class<?> clazz,
Map<String, String> attributes) {
super();
this.mapper = mapper;
this.reflectionProvider = reflectionProvider;
this.attributes = attributes;
this.clazz = clazz;
}
@Override
public boolean canConvert(Class cls) {
return cls == clazz;
}
@Override
public void marshal(Object value, HierarchicalStreamWriter writer,
MarshallingContext context) {
for (String key : attributes.keySet()) {
writer.addAttribute(key, attributes.get(key));
}
Converter converter = new ReflectionConverter(mapper,
reflectionProvider);
context.convertAnother(p, converter);
}
@Override
public Object unmarshal(HierarchicalStreamReader arg0,
UnmarshallingContext arg1) {
// TODO Auto-generated method stub
return null;
}
}
Retrieve the Mapper and ReflectionProvider instances from your XStream instance, and register a converter with all necessary setup:
XStream xs = new XStream(new DomDriver());
Mapper mapper = xs.getMapper();
ReflectionProvider reflectionProvider = xs.getReflectionProvider();
xs.alias("youralias", YourRoot.class);
xs.registerConverter(new MyConverter(mapper, reflectionProvider,
YourRoot.class, map));
System.out.println(xs.toXML(yourRoot));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to change the font properties(size, color,style) of the pdf document in UIWebView CGPDFDocumentRef i am doing one eBook reader app for iphone in objective c ,i have tried 2 methods of loading pdf document using UIWebView and CGPDFDocumentRef but i am not getting how to change the font properties(size, color,style) of the pdf document in either of the methods(UIWebView and CGPDFDocumentRef ), can any one help me out,how to change font property in UIWebView as well as in CGPDFDocumentRef, thanx in advance
A: You can't. This function only give you a way to open it and others aspects. But, PDF is unable to edit in any operate system. So I don't think you can do this things.
What you can do is create a new PDF. And it isn't very easy... You can start with this: Writing text to a PDF via from an NSString
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is my if-else statement not executing correctly? I got a question why my if-else statement is not working.
I got a form with a text input, and when a user types in the size they want it should live edit the picture. I'm using the addclass and removeclass methods from jQuery. This is my script:
function slide() {
var n = Number(document.getElementById('Getal1').value)
if (n >= 101 && n < 201)
$(openDiv1());
else if(n > 200)
$(openDiv2());
else if(n >= 0 && n < 101)
$(closeDiv());
else {
alert("You did not enter a number!")
}
}
$(function openDiv1() {
$( "#ombouw_wrap" ).addClass( "Addclass_ombouw_wrap_2block", 1, callback );
return false;
});
function callback() {
setTimeout(function() {
$( "#midden" ).removeClass( "Addclass_ombouw_wrap_1block Addclass_ombouw_wrap_3block" );
}, 0 );
}
$(function openDiv2() {
$( "#ombouw_wrap" ).addClass( "Addclass_ombouw_wrap_3block", 1, callback );
return false;
});
function callback() {
setTimeout(function() {
$( "#midden" ).removeClass( "Addclass_ombouw_wrap_1block Addclass_ombouw_wrap_2block" );
}, 0 );
}
$(function closeDiv() {
$( "#ombouw_wrap" ).addClass( "Addclass_ombouw_wrap_1block", 1, callback );
return false;
});
function callback() {
setTimeout(function() {
$( "#midden" ).removeClass( "Addclass_ombouw_wrap_2block Addclass_ombouw_wrap_3block" );
}, 0 );
}
window.onload = closeDiv;
And this is my HTML code:
Lengte: <INPUT TYPE="text" NAME="numeric" onKeyup="slide()" id="Getal1" onKeyPress="return checkIt(evt)">
x Hoogte: <input type="text" ID="Getal2" onKeyPress="return checkIt(evt)">
x Diepte: <input type="text" ID="Getal3" onKeyPress="return checkIt(evt)">
</form>
When you reload the page, you see it is not starting with closedivs, but it starts straight with adding classes without executing the if-else statement.
What am I doing wrong here?
A:
When you reload the page, you see it is not starting with closedivs, but it starts straight with adding classes without executing the if-else statement.
This is because jQuery treats $(function) as a handy form of $.ready(function): the function-object passed is executed on page load.
That is, $(function openDiv1() {...}) defines a function-object which is then passed to jQuery to execute automatically when the page loads. Instead, remove the functions from $(...). For instance, function openDiv1() {...} will suffice. (This will also fix the errors with not being able to call openDiv1 -- since it is a function-expression it will not be assigned to a variable/property in scope.)
The following describes an issue with the slide function.
JavaScript does some coercions; the following show why the else branch will never be reached:
Number("") // same as Number(0)
Number("") >= 0 // true
But really, please don't use Number (it's a wrapper-object for number), consider parseInt(str, 10) as a replacement. As an added bonus, parseInt("", 10) evaluates to NaN (not 0) and since NaN >= 0 is false, this will fix the initial problem.
function slide(){
var n = parseInt(document.getElementById('Getal1').value, 10)
if (n >= 0 && n <= 100) {
$(closeDiv())
} else if (n > 100 && n <= 200) {
$(openDiv1())
} else if (n > 200) {
$(openDiv2())
} else {
alert("You did not enter a number!")
}
}
Also pay attention to the consistency changes I added. The brackets are not necessary, but I find it aides in writing in a consistent well-formatted/well-indented style. Other things to pay attention to are ordering of if/else statements as well as the comparissons (keep it "flowing").
Happy coding.
A: You are wrapping your functions in $() which will execute them when you are trying to define them...
// alerts 1
$(function myFunc(){ alert(1) })
You need to define your functions before your if/else statements, and just like this...
// does not execute until called
function myFunc(){ ... }
A: I'm not a Javascript programmer, but I believe you are missing some braces on your IF/ELSE statements. The correct syntax should be, according to W3:
if (condition1){
Handle condition1
}
else if (condition2){
Handle condition2
}
else{
Handle the rest
}
Of course if this isn't the case, and braces aren't needed, then I hope someone else can help you :).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ForeignKey and form submission I have a model that is many-to-one with users. But when I submit a form based on that model, I am not correctly providing the user.
class Thing(models.Model):
"""Things."""
user = models.ForeignKey(User)
salt = models.IntegerField()
# [...]
class GenerateThingForm(ModelForm):
"""A form for registering a new Thing."""
class Meta:
model = Thing
fields = (...) # There are some, but it would distract here
The view says this:
@login_required()
def register_thing(request):
"""Register Thing."""
if request.method == 'POST': # If the form has been submitted...
form = GenerateThingForm(request.POST)
if form.is_valid():
form.salt = random.getrandbits(32)
# Apparently I need to specify form.user.
# Same result if just request.user
form.user = User.objects.get(request.user)
form.save() # Oh, no! 'user_id' is null!
Thanks for any tips.
A: Don't set the user or salt on the form instance, it has no idea what to do with it. Set it on the Thing that is generated from form.save.
thing = form.save(commit=False)
thing.salt = whatever
thing.user = myuser
thing.save()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Appending %20 to space in BlackBerry without URLEncodedPostData
Possible Duplicate:
Country name with space not accepted in BlackBerry ObjectChoiceField
I have been researching a lot on how to append % 20 to a space. I used code from a couple of StackOverflow questions but none seem to work.
There is no way I am using POST. How can I use URLEncodedPostData and remove spaces in the url?
I am fetching response from my local server using the following code.
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection("http://www.XXXXXX.com/XXXXX/?
InputStream isText = httpConn.openInputStream();
byte[] bytes=new byte[isText.available()];
isText.read(bytes);
final String s = new String(bytes);
System.out.println(" SERVER RETURNS = "+s);
if(s.equals("successfull"))//&& loginid.indexOf("@"))
{
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert(("Registration success"));
}
}
}
A: Go to this below link and use the Utility.java code to append %20 for space;
Country name with space not accepted in BlackBerry ObjectChoiceField
If you have any doubt come on StackOverFlow chat room name "Life for Blackberry" to clarify Your and our doubts.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: good commercial memory debugging tools for C on Linux I have tried using electric fence to debug large C application on linux. It runs as a daemon and probably because of it (or some other issue that I cannot troubleshoot) electric fence is not working. Is there a good commerical tool that will help me debug memory issues?
A: Have you look at the intel tools for linux as it contains a debugger and vtune which are all very good indeed. These will work on AMD tools but clearly do not have a in-depth knowledge of the chip set.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I allow users to enter commas in a value that will be stored in an sql server 2005 numeric field? I have a table field whose Datatype is numeric(10, 1). This field stores the AmountPaid and the user prefers to enter the Amount Value with commas in between like 78,234,673 because that's what they're used to, otherwise they will making a lot of errors.
Is there a way I can allow commas in the value but remove them when saving, or is there a way I can go ahead and store them in SQL-SERVER without changing the DATATYPE?
A: It's not clear how you're parsing the values from the UI, or what type you're parsing them as, but you may find that NumberStyles.AllowThousands is what you're after. I assume you are parsing the user input as a number and passing that to SQL Server as a parameter value, rather than just including it in the SQL verbatim... if not, that's the first change to make.
A: I'm not sure either what your after but if you want to basically pass into SQL an array of ints have you thought about passing in the string you have (which seems to be in Comma Seperated Values) and then splitting them into the values you need inside SQL. Then placing them in the desired table.
I had to do something similar a couple of days ago but it was to a Oracle database which doesn't have a split function so had to create one. The code is bellow, you should have no trouble translating it into SQL Server.
CREATE OR REPLACE PACKAGE SPLIT_FNC IS
-- Create a Type to be used as a temp table
TYPE strArray IS TABLE OF VARCHAR2(30) INDEX BY BINARY_INTEGER;
FUNCTION SPLIT_STR(word IN VARCHAR2) RETURN strArray;
END;
CREATE OR REPLACE PACKAGE BODY SPLIT_FNC IS
FUNCTION SPLIT_STR(word IN VARCHAR2) RETURN strArray IS items strArray;
temp NUMBER;
delim CHAR := ',';
start_index NUMBER := 1;
end_index NUMBER := -1;
BEGIN
temp := 1;
-- If INSTR can not find a match it will return 0
WHILE end_index != 0 LOOP
-- Find location of next comma
end_index := INSTR(word, delim, start_index, 1);
CASE
WHEN
end_index = 0
THEN
-- Catch the last value
items(temp) := SUBSTR(word, start_index);
ELSE
-- Get substring of start to next comma
items(temp) := SUBSTR(word, start_index, end_index - start_index);
END CASE;
start_index := end_index + 1;
temp := temp + 1;
END LOOP;
RETURN items;
END SPLIT_STR;
END SPLIT_FNC;
Hopefully this is helpful - Ankou
A: Double.Parse(TextBox1.Text) is what i was looking for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How do I safely hook into the message pump from a DLL? I'm trying to get messages from the process that loaded my DLL.
I've tried:
SetWindowsHookEx(WH_CALLWNDPROC, (HOOKPROC)WndProc, hInstance, 0);
Which gives me error popups about how "Program X could not be started because Y.dll is missing from your system". This is the reason I put "safely" in the title.
I've also tried:
SetWindowsHookEx(WH_CALLWNDPROC, (HOOKPROC)WndProc, hInstance, threadId);
Where threadId is the result of GetCurrentThreadId() in my DLLMain.
This one works, but I don't get any messages for the window (just a bunch of 512 and 1025).
A: Messages are related to threads and windows, your DLL might be loaded by processes. So there is no direct correspondence.
Hooks on the other hand are either global or per-thread.
All together this means that you have to choose whether you want messages just from specific threads, or global (all threads in all processes in specific desktop) where you will filter out the process of your interest yourself.
Your second code snippet is a thread hook. The first one is the global hook where you definitely do something wrong as successful hook itself does not cause error messages you mentioned.
A: I'm guessing that you are calling these functions directly from inside DLLMain. There are serious limitations on which functions you can safely call from DLLMain, see the MSDN documentation on DLLMain about this.
There is no explicit list of safe and unsafe functions, but it seems likely that the call to SetWindowsHookEx in your first code fragment is doing something that is forbidden in a DLLMain function, hence the failure for the DLL to load properly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Hidden field in spring MVC I wanted to use Spring MVC hidden tag in below code. Is this possible in below code, what I have to write in my controller to do that or what I am doing is correct.
<c:forEach var="record" items="${records}">
<tr>
<td>
<form:form id="myForm" action="list.html" method="post">
<input type="hidden" name="record" value="${record}" />
<a href="#" onclick="document.getElementById('myForm').submit();">Submit</a>
</form:form>
</td>
</tr>
</c:forEach>
Any help will be highly appriciated.
A: In the rest of this answer, substitute "delete" and "deteted" with the operation you are attempting to implement. for example "exploded", "bitten", or "edited"
The JSP code you posted has several issues.
*
*no close tag for the <td> element.
*your form is posting to "items.html". This seems to be an html page. If so, your form action is 0% correct.
*every form has the same id, so the getElementById() call can never work.
*href="#" will cause your page to scroll to the top when the user clicks the link.
*You do not identify, to the user, the record to be deleted.
Here is what I think you want:
<c:forEach var="record" items="${records}">
<tr>
<td>
<form:form method="post">
<input type="hidden" name="activity" value="delete"/>
<input type="hidden" name="record" value="${record}"/>
<a href="javascript:this.form.submit()">Delete ${record}</a>
</form:form>
<td>
</tr>
</c:forEach>
The snippet will post to the current spring controller. Two fields are included in the post: "activity" which identifies this as a delete and "record" which identifies the record to be deleted. Based on your needs, add action="some url" to the form:form tag.
A: I think I solved the problem. If I write input tag like this
<form:hidden path="id" value="${record}" />
in this way I can reassign the value of hidden variable but when I look into the rendered html code its like this
<input type="hidden" value="0" name="record" value="10"/>
generate the value attribute twice and takes the value I wanted which is 10.But it solves my problem. If anyone has further comments on this then that will be appreciated.
A: You are on the right track [depending on what your backing bean is], but in order to bind an ID as a hidden field on submission automatically to a "Person" bean (in this example), you would do something like:
<c:forEach var="person" items="${persons}" varStatus="status">
<tr>
<c:set var="personFormId" value="person${status.index}"/>
....
<form id="${personFormId}" action="${deleteUrl}" method="POST">
<input id="id" name="id" type="hidden" value="${person.id}"/>
</form>
<td>${person.firstName}</td>
<td>${person.lastName}</td>
....
</tr>
</c:forEach>
In case you'd like to render a hidden field, you would use a form:hidden tag:
<form:hidden path="id" />
Take a look at Hidden Input Tag section of the Spring docs.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: PHP/MySQL Multidemensional/Associative Arrays I have this code that fetches data from mySQL and outputs it as an array(multidimensional) like so:
$res = @mysqli_query($dbc, "SELECT id, subject, exam, marks, remarks FROM log WHERE student = '2222' AND term = 'Term2'");
$studentMarks = array();
while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC))
{
$studentMarks[$row['subject']][$row['exam']] = $row['marks'];
}
//So far the code displays $studentMarks like this:
//$studentMarks = array(
// Maths => array('CAT1' => 50, 'CAT2' => 35)
// , English => array('CAT1' => 20, 'MIDTERM' => 40)
//);
//I wish it to add remarks thus displaying $studentMarks like:(Not sure whether I am right)
//$studentMarks = array(
// Maths => array('CAT1' => array(50,
// "Good"
// ),
// array('CAT2' => array(35,
// "Can do better"
// )
//)
// , English => array('CAT1' => array(20,
// "Good"
// ),
// array('MIDTERM' => array(40,
// "Much better"
// )
//);
echo '<table><thead><tr>';
echo '<td>Student</td><td>CAT1</td><td>CAT2</td><td>MIDTERM</td>';
echo '</tr></thead><tbody>';
foreach($studentMarks as $studentSub => $marks)
{
echo '<tr>';
echo '<td>', $studentSub, '</td>';
echo '<td>', (isset($marks['CAT1']) ? $marks['CAT1'] : ' '), '</td>';
echo '<td>', (isset($marks['CAT2']) ? $marks['CAT2'] : ' '), '</td>';
echo '<td>', (isset($marks['MIDTERM']) ? $marks['MIDTERM'] : ' '), '</td>';
echo '</tr>';
}
echo '</tbody></table>';
//END CODE
I am trying to achieve this:
SUBJECT CAT 1 | CAT 2 | MIDTERM | ENDTERM
MATH 50 35
Good Can do better
ENGLISH 20 40
Can do better Do better
QUESTION:
How can I display remarks under/against each marks displayed?
Your Help is Much Appreciated...
A: $res = @mysqli_query($dbc, "SELECT id, subject, exam, marks, remarks FROM log WHERE student = '2222' AND term = 'Term2'");
$studentMarks = array();
while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC))
{
$studentMarks[$row['subject']][$row['exam']]['mark'] = $row['marks'];
//This will get the remarks from the database
$studentMarks[$row['subject']][$row['exam']]['remark'] = $row['remarks'];
//This should be used when you chose to compare marks and display appropriate remarks
//$studentMarks[$row['subject']][$row['exam']]['remark'] = ( $row['marks'] < 40)?'can do better':( $row['marks'] < 50)?'do better':'good';
}
echo '<table><thead><tr>';
echo '<td>Student</td><td>CAT1</td><td>CAT2</td><td>MIDTERM</td>';
echo '</tr></thead><tbody>';
foreach($studentMarks as $studentSub => $marks)
{
echo '<tr>';
echo '<td>', $studentSub, '</td>';
echo '<td>', (isset($marks['CAT1']) ? $marks['CAT1']['mark'] : ' '), '</td>';
echo '<td>', (isset($marks['CAT2']) ? $marks['CAT2']['mark'] : ' '), '</td>';
echo '<td>', (isset($marks['MIDTERM']) ? $marks['MIDTERM']['mark'] : ' '), '</td>';
echo '</tr>';
echo '<tr>';
echo '<td> </td>';
echo '<td>', (isset($marks['CAT1']) ? $marks['CAT1']['remark'] : ' '), '</td>';
echo '<td>', (isset($marks['CAT2']) ? $marks['CAT2']['remark'] : ' '), '</td>';
echo '<td>', (isset($marks['MIDTERM']) ? $marks['MIDTERM']['remark'] : ' '), '</td>';
echo '</tr>';
}
echo '</tbody></table>';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mark select fields with same value In my form I have multiple select fields.
See here http://jsfiddle.net/ZNShh/
Now I want to mark all select fields that have the same value with the color red. Can somebody help me?
Thank you very much!
A: Try - http://jsfiddle.net/ZNShh/13/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Boost Subgraph and Bundled properties I'm using bundled properties and adjacency_list and would like to use the subgraph class.
struct Vertex
{
int index;
int seed;
};
struct Edge
{
bool visted;
double weight;
};
typedef adjacency_list<listS, listS, undirectedS, Vertex, property<edge_index_t,int,Edge> > Graph;
typedef subgraph<Graph> testSubgraph;
The property<edge_index_t,int,Edge> part is needed, as subgraph needs edge_index_t to compare two edges.
Now my question is how do I add an Edge using bundled properties in a Subgraph?
In the normal graph without property<edge_index_t,int,Edge> I add an edge as following:
Edge e;
vertex_descriptor u,v;
// fill in u and v;
e.weight = 1.0;
e.visted=false;
add_edge(u,v,e,graph);
But this doesn't work for Subgraph.
Hope someone knows a solution for this.
Thanks
Ben
A: I just ran into the a similar issue when trying to add a vertex with the add_vertex() function and found that there is a (very old) unresolved issue on the boost bugtracker:
Ticket #380: Support for bundled properties in graph adaptors:
The graph adaptors (such as subgraph) do not support bundled
properties, but they should.
Further searching lead to the following 2 patches, which are not yet merged but appear to finally bring the support for bundled properties in subgraphs:
*
*Ticket #10708: Property support in add_vertex() method for subgraph
*Ticket #10709: Graph bundled property support in subgraph
So I guess the answer is: For now, don't use bundled properties. But in the future, the issue should disappear.
A: An adjacency list do not have edge_index:es. You need to assign an index yourself, but that is as simple as adding a size_t index to the Edge, and assigning an index as you create the edges.
You probably do not need to create edges for the subgraph, since the boost subgraphs are induced subgraphs. Therefore, all edges in the graph of which both endpoints are in the subgraph will be included in your subgraphs.
A: I am also just learning BGL and the following code works for adding the bundled edge property within the add_edge call.
boost::add_edge(vd1, vd2, testSubgraph::edge_property_type{0, Edge{/* ... */}}, graph);
0 is a dummy edge index and, according to my experience, it is overwritten with the proper edge index by BGL. I don't know whether that's always true (any comment welcome).
You can also just add the edge to the subgraph without using the bundle and use the edge descriptor returned by add_edge to add the properties later.
auto pair = boost::add_edge(vd1, vd2, graph);
boost::put(boost::get(&Edge::member_name1, graph), pair.first, member_value1);
/* ... */
Don't know whether it is possible to put a complete property bundle using the second method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: find_by_slug(params[:id]) always return null I'm just using Ruby on Rails 3.1, and I want use mongoid and mongoid_slug gem to make my url readable. There is my problem:
In my photo mode iput this code: "include Mongoid::Document", "include Mongoid::Slug" and
"slug :title" ( title is one of photo's attributes)
And in my controller, I call thí one in my action:
"@photo = Photo.find_by_slug(params[:id])" but this code always return a null value!!
Please, help me!
A: I found my own answer but thanks you anyway! it always return null value because the model doesn't load the slug (that means every object of the model doesn't have "slug:title"). Therefore, I have to init slug to my model. I write in my db.rake file the following code and run rake db:init_slug. This my init_slug task: "photo.all.each do |p| p.send(:generate_slug!) p.save!" Then restart the server one more time and the code doesn't return null value anymore
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: RSpec 2.6, "Expected response to be a redirect to but was a redirect to ." I wonder why all my redirection tests suddenly fail. All failures are of the sort mentioned in the subject. Normally this is an issue of mixing foo_urland foo_path in controllers and/or tests, but this isn't the case here.
The controller actions all look like
redirect_to :action => :foo
and the tests all look like
response.should redirect_to(:action => :foo)
and still I get errors like
Expected response to be a redirect to </bar/foo>
but was a redirect to <http://test.host/bar/foo>.
Even when I replace :action => :foo with foo_path (or the equivalent named route) the error occurs.
Any ideas what might cause this to happen?
A: Solution:
Buried deep inside another test was this:
BasicSocket.do_not_reverse_lookup = true
Socket.do_not_reverse_lookup = true
to prevent (slow) reverse DNS lookups for tests which queried online databases. This, however, was a global setting and this caused the above error. Removing the Socket.do... made all redirection tests pass again. (BasicSocket had no such problem.)
I'm documenting this here so that others can find a solution faster.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Eclipse: Error initializing endpoint java.net.BindException: Permission denied:443 I'm on Mac OS X Lion and am currently using eclipse to deploy a project with the help of JBoss.
I get the following error:
Error initializing endpoint java.net.BindException: Permission
denied:443
I understand this is a permissions issue, how do I allow eclipse to bind to port 443 in Mac OS X?
A: On *-nix platforms, you generally can't bind to privileged ports (< 1024) if you aren't the root user.
If you are working in a development environment, you could configure JBoss to use a different port for SSL (8081, for instance) and point your testers/browser there.
If you absolutely need to use port 443 and can't run as root (which isn't recommended anyhow), you can:
*
*configure JBoss to use a different port
*configure a proxy
(Polipo, for
instance) to re-direct port 443
If you don't want separate proxy software, you could also configure iptables. See http://wiki.apache.org/tomcat/HowTo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to submit asp.net form data using jquery ajax feature dear all i want to know how to submit asp.net form data using jquery ajax functionality and how im get that json data in the server side
?
A: <script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#<%=btnSubmit.ClientID %>").click(
function()
{
$.ajax
({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/AcceptFormData",
data: "{'funcParam':'"+$('#formName').serialize()+"'}",
dataType: "json",
success: function(msg)
{
var msgFromASPXFunction = msg.d
}
});
}
);
});
[System.Web.Services.WebMethod]
public static string AcceptFormData(string funcParam)
{
// this is your server side function
//the data you will get will be in format e.g. a=1&b=2&c=3&d=4&e=5 inside funcParam variable
return "Data Submitted";
}
Just note the server-side function name should match the parameter you specified in the url property of $.ajax function of jQuery. (In above case it is "AcceptFormData"
Also the parameter name should be same as of the server side function parameter. In this case it is "funcParam".
Just compare the $.ajax and server-side function in this code.
Regards,
Amin Sayed
(Note: Please mark if it is helpful)
A: <form action="#" id="example-form">
...
</form>
<script type="text/javascript">
$('#example-form').submit(function(){
// block form
$.post('putUrlHere', $('#example-form').serialize(), function(data) {
//call back happens here. Unblock form/show result
});
return false; // this prevents regular post, forcing ajax post.
});
</script>
REFERENCE : http://forums.asp.net/t/1611677.aspx/1?Jquery+with+ASP+NET+Form+submit
Otherwise Check : jquery + ajax combine.....
http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can we directly run place the jar file under the local maven repository without specyfing the dependency under pom.xml file I have imported an existing Maven Project into Eclipse , this has got a lot of dependency with other jars
Please tell me can i directly run mvn install path to My jar file command , without specifying dependency tag on to the POM.xml file ??
In simple terms my question was , can we simple run this command without specifying any dependency inside the POm.xml file .
mvn install:install-file -DgroupId=<MVN_GROUPID> -DartifactId=<MVN_ARTIFACTID> -Dversion=<MVN_VERSION> -Dpackaging=jar -Dfile=<JAR_FILE_TO_INSTALL>
Thank you .
A: You can certainly run this command without modifying or adding dependencies to the pom.xml file. Note that the artifact will be installed in your local repository without the pom.xml. So the information about the project dependencies will be lost to any artifacts dependant on this project.
A much easier way to install the artifact in your local repository, with the pom.xml, is by executing the following command:
mvn install
Do you have reason to avoid this command?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery Resizable: Border jumps on resize when position absolute (jsFiddle) I've got a little niggle with a project I'm working on at the moment - when I make an anchor .resizable() which is also positioned : absolute and resize from left or top handles, the elements shifts a couple of pixels.
I thought the borders were the culprit, but when taken off, it still nudges 1 pixel along on each resize.
jsFiddle example
A: It appears that the bug only occurs if you use a helper. My updated jsFiddle doesn't have the buggy behavior. This would suggest that it is a bug in jQueryUI and it might be worthwhile filing a bug report with them and posting the ticket here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In Matplotlib, is there a way to know the list of available output format According to Matplotlib documentation, matplotlib.figure.save_figtakes an optional argument format (see matplotlib.figure documentation).
This parameters takes 'one of the file extensions supported by the active backend' (as said by the official documentation).
My point is: how to know, for a specific backend, the list of supported extensions?
The list of available backends is accessible thru matplotlib.rcsetup.all_backends. These backends are available in matplotlib.backends but, I do not find a way to retrieve supported extensions.
A: If you create a figure, you can get the available supported file format with the canvas object :
import matplotlib.pyplot as plt
fig = plt.figure()
print fig.canvas.get_supported_filetypes()
>>> {
'svgz': 'Scalable Vector Graphics',
'ps': 'Postscript',
'emf': 'Enhanced Metafile',
'rgba': 'Raw RGBA bitmap',
'raw': 'Raw RGBA bitmap',
'pdf': 'Portable Document Format',
'svg': 'Scalable Vector Graphics',
'eps': 'Encapsulated Postscript',
'png': 'Portable Network Graphics'
}
and it will list all the formats in which you can output your current object.
A: The FigureCanvasBase class, located in each backends has a get_supported_filetypes method.
For backend_agg:
figure = matplotlib.figure.Figure()
fcb = matplotlib.backends.backend_agg.FigureCanvasBase(figure)
supported_file_types = fcb.get_supported_filetypes()
supported_file_types contains:
{'emf': 'Enhanced Metafile',
'eps': 'Encapsulated Postscript',
'pdf': 'Portable Document Format',
'png': 'Portable Network Graphics',
'ps': 'Postscript',
'raw': 'Raw RGBA bitmap',
'rgba': 'Raw RGBA bitmap',
'svg': 'Scalable Vector Graphics',
'svgz': 'Scalable Vector Graphics'}
One remaining question .... matplotlib.get_backend() returns "agg". Is there an easier way to directly point to the correct backend module?
A: Here is a list of renderers and file types: http://matplotlib.sourceforge.net/faq/installing_faq.html#what-is-a-backend
Beyond that, individual backends have get_supported_filetypes method in their respective FigureCanvas{backend-name} class that gives a list of supported file formats.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
}
|
Q: Analyzing algorithms for time complexity I am analyzing an algorithm and I just want to know if I am on the right track.
For this algorithm, I am only counting the multiplications on the line which have *** in them.
Here's the algorithm:
*
*So I am starting from the inner most line, I can see there are 2 operations there (the two multiplications).
*Now I am looking at the 2 inner most loops, so I can tell that the p=p*20*z gets executed exactly (j) + (j-1)+(j-2)+(j-3)...1 times. This happens to be equal to j(j+1)/2.
*So in total, since there are two multiplication, it happens 2 * (j(j+1)/2).
*Then finally, the "i" loop happens exactly n times, so, in total, it's n(2 * (n(n+1)/2)).
That's my thought process behind this. Am I correct? Thanks.
A: Your thought process is correct. You need to replace the j term with an n (n being the largest value j can assume), but that is probably a typo.
Furthermore, you can simplify further from where you are:
n(2*(n(n+1)/2))
2*n*(n^2+n)/2
n^3+n^2
=> O(n^3)
The last step is because the n cubed term will grow at a much larger rate than the n squared term we can say it will dominate the runtime for large n. Only other point I would mention is that you should perhaps consider the store to p as an operation as well as the two multiplication, although obviously this will not change the simplified big-o runtime.
A: Computation in this particular example could be simplified if you can find out that all three loops has the same exit condition up to n:
*
*i <= n
*j <= n
*k <= j
Basically third loop would run n iterations as well because j <= n so k <= n,
this mean that complexity would be n * n * n = O(n ^ 3)
A: This is how you can obtain the order of growth of your algorithm methodically:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Remove the last Comma from a string (PHP / Wordpress) I am generating a list of the terms on a custom post type in Wordpress, in this code i add a comma to the end of each item to separate it in a list format, how would i either eliminate the last the comma from propagating on addition or remove the last comma on the list.
$terms = get_the_terms( $post->ID, 'clients' );
if ( $terms && ! is_wp_error( $terms ) ) :
$clients_list = array();
foreach ( $terms as $term ) {
$clients_list[] = $term->name;
}
$clients = join( ", ", $clients_list );
$catTags .= "$clients, ";
endif;
I have tried the following to no success;
<em><?php $string = $catTags;
echo preg_replace("/\,$/","",$catTags); ?></em>
A: You can do simply:
rtrim($catTags, ', ');
A: What I usually do, is to add a comma at the begin of a loop, by checking if there is already data in the variable.
So in this case something like this:
if (strlen($catTags) > 0)
$catTags .= ',';
A: This should work:
return substr($string, 0, -strlen(','));
will remove the last comma at the end of the string.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Request failed: Context parameter '$HIDDEN1.__EVENTVALIDATION' not found in test context I'am looking for a solution to this problem :
While running my automatic web test I received a request failed and here you are the response I found :
Request failed: Context parameter '$HIDDEN1.__EVENTVALIDATION' not found in test context
I figured out which request the hidden field was suppose to be extracted from (In the request before), where the (Hidden1) I found it in the extraction rule of the before request and the extraction rule’s value for Context Parameter Name is 1.
Note: I am using a statics parameters for this time, and the HTTP state is 200.
After searching on the internet i found : http://blogs.msdn.com/b/slumley/archive/2007/04/10/how-to-debug-a-web-test.aspx where I failed to find my solution in it.
This question seems to be complicated cause i kept it since 2 days without having any answer ! If anybody wants to know more information, I am online 24/24 :) Thanks alot...
A: I had a similar problem to what you were experiencing (I see that this question is very old, but I thought I would post a solution as this is the first result in google for this issue).
The problem is that the __EventValidation tag is one of the last things rendered by the browser and that VisualStudio 2008 web tests truncate the response object when it is over a certain length (I think the limit is 1.5MB).
You have three options:
*
*Ask yourself why your page is over 1.5MB in size and is it necessary, particularly if this is a public website?
*Set the variable ResponseBodyCaptureLimit in the web test to a massive value, the units are in bytes, so something like 9,000,000 (9MB) would big enough to get any response object. Just be aware that this will have an impact on the memory usage of your web test and if you are using this for any load/performance testing then that will mean your agents will need more memory.
*Override the OnPreRender method to move __EventValidation tag from the bottom of the page to the top of the page.
Hope that helps anyone facing similar issues.
~Dan
A: I'm running into similar issues and still working through them. In the meantime, this link may be of help as well:
http://blogs.msdn.com/b/slumley/archive/2007/04/10/how-to-debug-a-web-test.aspx
A: The solution is to change all the EnableEventValidation attribute to true (which is the default value).
But the best solution in my openion is to use the VSTS of visualstudio 2010 , it is better than the that of 2008, really a big evolution happened between both of them.
A: In case if someone would face this problem and choose to override Render method, here is a sample code.
var stringWriter = new System.IO.StringWriter();
var htmlWriter = new HtmlTextWriter(stringWriter);
base.Render(htmlWriter);
var html = stringWriter.ToString();
const string validationELement = "<input type=\"hidden\" name=\"__EVENTVALIDATION\"";
const string hiddenDivName = "<div class=\"aspNetHidden\">";
// Find event validation element.
var startIndex = html.IndexOf(validationELement);
if (startIndex >= 0)
{
var endIndex = html.IndexOf("/>", startIndex) + 2;
// Cut event validation element.
var input = html.Substring(startIndex, endIndex - startIndex);
html = html.Remove(startIndex, endIndex - startIndex);
// Paste element into hidden div.
var hiddenDivStartIndex = html.IndexOf(hiddenDivName);
html = html.Insert(hiddenDivStartIndex + hiddenDivName.Length, input);
}
writer.Write(html);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Should I seed a SecureRandom? Found the following code in our code base:
public static final int DEFAULT_LENGTH = 16;
private static SecureRandom SR;
static
{
try
{
SecureRandom sd0 = new SecureRandom();
SR = new SecureRandom(sd0.generateSeed(DEFAULT_LENGTH * 2));
}
catch (Exception e){}
}
Here a default SecureRandom is created, and then that is used to create a seed for another one which is the one that will be used later in the class. Is this really necessary? Is the second somehow better than the first because this is done?
When the seed is generated for the second, the number of bytes is given, is this important? Could a SecureRandom seeded with a different amount of bytes than another potentially be better or worse? Should the number of bytes used to seed it somehow correspond to what it will be used for?
If setSeed is not called, the first call to nextBytes will force the SecureRandom object to seed itself. This self-seeding will not occur if setSeed was previously called. - javadoc
Is the self-seeding not good enough? Does it depend on what it's going to be used for?
Note: For some context, it is used in class that creates random ids for stuff stored in a database.
A: Avoid using the default algorithm which is the case when doing new SecureRandom();
Instead do:
SecureRandom.getInstance("SHA1PRNG", "SUN");
If someone changes the default algorithm (as stated by @Jules) you won't be impacted.
Edited for Android:
For android, take a look at :
*
*https://android-developers.googleblog.com/2016/06/security-crypto-provider-deprecated-in.html
*http://www.infosecisland.com/blogview/24773-Android-N-Deprecating-Crypto-Provider-and-SHA1PRNG-Algorithm.html
*https://security.stackexchange.com/questions/128144/android-n-security-crypto-provider-is-deprecated
*Security "Crypto" provider deprecated in Android N
On Android, we don’t recommend specifying the provider. In general,
any call to the Java Cryptography Extension (JCE) APIs specifying a
provider should only be done if the provider is included in the
application or if the application is able to deal with a possible
ProviderNotFoundException.
...
in Android N we are deprecating the implementation of the SHA1PRNG
algorithm and the Crypto provider altogether
A: This is not only completely unnecessary, it may actually increase the predictability of the numbers generated by the SecureRandom object.
A SecureRandom that does not have an explicit seed set will self-seed. It uses a highly random data source to perform this operation, and is quite secure. The first SecureRandom in your code sample will use such a seed.
The second is seeded from the first by producing 256 random bits. Assuming the system-default SHA1PRNG is used, this is good enough. It uses 160 bits of state, so 256 random bits will completely satisfy it's requirements. But assume now somebody decides this isn't enough, and switches the default to a SHA512PRNG (they can do this without even looking at your code by changing java's security properties). Now you're providing too few seed bits to it: only half as many as it needs.
Get rid of it, and just use the self-seeded object, unless you have a better source of seed data than the system has available.
A: I think this is completely unneccessary, because as the Javadoc you quote clearly states: Default-constructed SecureRandom instances seed themselves. The person who wrote this probably didn't know that.
They might also actually decrease security by forcing a fixed seed length that could be less-than-ideal for the RNG implementation.
Finally, assuming the snippet is posted unaltered, the silent exception swallowing isn't very good coding style either.
A: Just an addendum to this answer. According to Google, if you are using this code in android you should definitely seed the SecureRandom using a high entropy source like /dev/urandom or /dev/random.
Even the post below is an year old now, perhaps this has already been corrected but I couldn't confirm if it was.
https://plus.google.com/+AndroidDevelopers/posts/YxWzeNQMJS2
EDIT:
It seems that the default behavior of the class is now the one specified in the post so seeding is again deemed unnecessary:
http://developer.android.com/reference/java/security/SecureRandom.html
A: Sad, that javadoc does not say, what the minimum seed size "DEFAULT_LENGTH" is to reach the intended security level of algorithm design, not even for some default implementation. :(
Essentially security depends on true random; there is nothing like "an algorithm seeding itself without exterior data". Unless the inputs of a seed generator are revealed, it is not possible to certify any security level.
Providers of true random are
1.) https://www.random.org/
2.) Tools as VeraCrypt derive white noise from mouse motion.
If your goal is real security, you will combine numbers from anonymous random generators with self-cerified white noise.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
}
|
Q: Need To Configure TFS Build With Custom Build Script I use the below script to queue build in TFS 2010 build server. This TFSBuil.proj runs successfully if I use locally with command: MSBUILD.exe TFSBuild.proj
and get my staging folder. I am trying hard to get this to build in build server. Lastly the build ran to success (in 8 secs !) but did nothing at the end. Logs indicate all targets called with success but dont see the result. Any help is very much appreciated and I am ready to work hand in hand for this. Thank you.
A: Just a guess (until hopefully the log file can be retrieved).. have you tried to verify the work folder mappings using tf workfold from the command line? I would do that "locally" and then on the build machine. You can do this from your workstation with sufficient permissions, but going to the build machine might help you see unexpected differences - this happened to me more than once :-).
Also, perhaps the definition of <SolutionRoot>..\</SolutionRoot> isn't appropriate for the existing mapping, i.e. it's going one level higher than what's mapped.
Hope this helps,
Jonno
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Displaying button inside componentsJoinedByString i have a question that i want to put a button instead of @"/n" ie,@"uibutton"
BibleIphoneAppDelegate *appDelegate = (BibleIphoneAppDelegate *)[[UIApplication sharedApplication] delegate];
NSArray *allVerses = [appDelegate.biblearray valueForKey:@"verseNumber"];
_bibleDesciption.text = [allVerses componentsJoinedByString:@"/n"];
verseNumber contains verses of the bible ,my need is to put a button in between verses.I hope u understand my question.plase help me to do this.
Thanks in advance.
A: I haven't tested this, so it probably contains some bugs, but should help you get started.
// set these as members of your class
NSMutableArray *_versesLabels; // used for easier access when a button is pressed
NSMutableArray *_versesButtons;
/*IBOutlet */UIScrollView *_scrollView;
// your initialization/loading method
// <..set up _scrollView as you wish>
int labelWidth = 300; // change this as you wish
int buttonWidth = 100, buttonHeight=30;
int padding = 5; // space between labels/buttons from the scrollView
BibleIphoneAppDelegate *appDelegate = (BibleIphoneAppDelegate *)[[UIApplication sharedApplication] delegate];
NSArray *allVerses = [appDelegate.biblearray valueForKey:@"verseNumber"];
int currentY = padding;
for(int i=0; i<[allVerses count]; i++){
// create and place the label
UILabel *lbl = [[UILabel alloc] init];
lbl.text = [allVerses objectAtIndex:i];
// <..customize the label - fonts, colors etc>
lbl.numberOfLines = 0; // in case you have verses that don't fit in a single line
CGSize size = [lbl.text sizeWithFont:lbl.font constrainedToSize:CGSizeMake(labelWidth, 500)];
lbl.frame = CGRectMake(0, currentY, labelWidth, size.height);
[_scrollView addSubView:lbl];
[_versesLabels addObject:lbl];
[lbl release];
currentY=currentY + lbl.frame.size.height + padding;
// create and place the button
UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, currentY, buttonWidth, buttonHeight)];
btn.tag = i;
// <..customize the button - fonts, colors etc>
[btn addTarget:self action:@selector(pressVerse:) event:UIEventTouchUpInside];
[_scrollView addSubView:btn];
[_versesButtons addObject:btn];
[btn release];
currentY=currentY + btn.frame.size.height + padding;
}
[_scrollView setContentSize:CGSizeMake(_scrollView.frame.size.width, currentY)];
-(void)pressVerse:(UIButton *)b{
verseIndex = b.tag;
UILabel *verseLabel = [_verseLabels objectAtIndex:verseIndex];
// <..do whatever you want when a button is pressed>
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Make pyplot faster than gnuplot I recently decided to give matplotlib.pyplot a try, while having used gnuplot for scientific data plotting for years. I started out with simply reading a data file and plot two columns, like gnuplot would do with plot 'datafile' u 1:2.
The requirements for my comfort are:
*
*Skip lines beginning with a # and skip empty lines.
*Allow arbitrary numbers of spaces between and before the actual numbers
*allow arbitrary numbers of columns
*be fast
Now, the following code is my solution for the problem. However, compared to gnuplot, it really is not as fast. This is a bit odd, since I read that one big advantage of py(plot/thon) over gnuplot is it's speed.
import numpy as np
import matplotlib.pyplot as plt
import sys
datafile = sys.argv[1]
data = []
for line in open(datafile,'r'):
if line and line[0] != '#':
cols = filter(lambda x: x!='',line.split(' '))
for index,col in enumerate(cols):
if len(data) <= index:
data.append([])
data[index].append(float(col))
plt.plot(data[0],data[1])
plt.show()
What would I do to make the data reading faster? I had a quick look at the csv module, but it didn't seem to be very flexible with comments in files and one still needs to iterate over all lines in the file.
A: Since you have matplotlib installed, you must also have numpy installed. numpy.genfromtxt meets all your requirements and should be much faster than parsing the file yourself in a Python loop:
import numpy as np
import matplotlib.pyplot as plt
import textwrap
fname='/tmp/tmp.dat'
with open(fname,'w') as f:
f.write(textwrap.dedent('''\
id col1 col2 col3
2010 1 2 3 4
# Foo
2011 5 6 7 8
# Bar
# Baz
2012 8 7 6 5
'''))
data = np.genfromtxt(fname,
comments='#', # skip comment lines
dtype = None, # guess dtype of each column
names=True) # use first line as column names
print(data)
plt.plot(data['id'],data['col2'])
plt.show()
A: You really need to profile your code to find out what the bottleneck is.
Here are some micro-optimizations:
import numpy as np
import matplotlib.pyplot as plt
import sys
datafile = sys.argv[1]
data = []
# use with to auto-close the file
for line in open(datafile,'r'):
# line will never be False because it will always have at least a newline
# maybe you mean line.rstrip()?
# you can also try line.startswith('#') instead of line[0] != '#'
if line and line[0] != '#':
# not sure of the point of this
# just line.split() will allow any number of spaces
# if you do need it, use a list comprehension
# cols = [col for col in line.split(' ') if col]
# filter on a user-defined function is slow
cols = filter(lambda x: x!='',line.split(' '))
for index,col in enumerate(cols):
# just made data a collections.defaultdict
# initialized as data = defaultdict(list)
# and you can skip this 'if' statement entirely
if len(data) <= index:
data.append([])
data[index].append(float(col))
plt.plot(data[0],data[1])
plt.show()
You may be able to do something like:
with open(datafile) as f:
lines = (line.split() for line in f
if line.rstrip() and not line.startswith('#'))
data = zip(*[float(col) for col in line for line in lines])
Which will give you a list of tuples instead of an int-keyed dict of lists, but otherwise appears identical. It can be done as a one-liner but I split it up to make it a little easier to read.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How could I log user-specific information (IP address etc) into a table?
Possible Duplicate:
How can I get the client's IP address in a PHP webservice?
I've a small site that lets anonymous users to upload images. However, this obviously has the potential to be abused. How could I track/log relevant information (IP address etc) for each image that is uploaded? I'm using PHP and MySQL.
Thanks.
A: to getting the IP address of the user who upload the image,
you just add the $_SERVER['REMOTE_ADDR'] to the image upload script,
and you will get the IP address of the user.
A:
$_SERVER
'REMOTE_ADDR' The IP address from which the user is viewing the
current page.
$_SERVER['REMOTE_ADDR'];
You can find how to get relevant data for each user.
http://php.net/manual/en/reserved.variables.server.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JTable Focus Movement Query? I am trying to highlight the focus movement in the JTable through this code:
if(e.getKeyCode() == (KeyEvent.VK_TAB)){
int prevRow;
int row = table.getSelectedRow();
int col = table.getSelectedColumn();
if(col == 0) {
System.out.println(row);
MinMax val = null;
TableCellRenderer currRend = table.getCellRenderer(row,col);
val = (MinMax) table.getValueAt(row, col);
JComponent comp = (JComponent) currRend.getTableCellRendererComponent(table, val, false, false, row,col);
comp.setBorder(BorderFactory.createLineBorder(Color.RED));
table.requestFocus(true);
}
The scenario is this, when I press TAB for the first time the second row is selected, initially the focus is set on row[0], the border is not painted, when I press the second time the third row is selected highlighting both 2 and 3rd row.
After that whenever tab is pressed, the highlighting of the border becomes relevant to the row selection.
I am facing issue when I am running the application under normal mode and not under de-bugger mode with break points.
A: There no reason for bothering with KeyEvents from KeyListener, if not generated some extra special Events, implements prepareRenderer, and there you have to test if is isSelected() or hasFocus(), I think that everything and nothing better around as @camickr's Table Row Rendering,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to hide an element in jsp file using javascript <li><label>Email:</label> <input type='text' name='username'
id="forgot_username" /></li>
<li><label> </label> <input type="submit"
id="forgot_btn" value="Send Reminder" class="btn"></li>
I have above text box and button in my jsp. and the below condition, what i want is when this condition occur , above text box and button should hide how can i do it.
<c:if test="${param.message == 3}">
<span class="error"><font color="red"> Email does not match</font></span>
</c:if>
A: You should put div tags around the first code like this:
<div id="hide">
<ol>
<li>
<label>Email:</label>
<input type='text' name='username' id="forgot_username" />
</li>
<li>
<label> </label>
<input type="submit" id="forgot_btn" value="Send Reminder" class="btn">
</li>
</ol>
</div>
And then you can hide like this:
<c:if test="${param.message == 3}">
<script>
$('#hide').hide();
</script>
<span class="error"><font color="red"> Email does not match</font></span>
</c:if>
A: Why can't you put those <li> elements inside an identical construct?
If you can't put those elements together and don't want to repeat the condition, you can always define a new variable:
<c:set var="condition" value="0">
<c:if test="${param.message == 3}">
<c:set var="condition" value="1">
</c:if>
<c:if test="${condition == 1}">
<span class="error"><font color="red"> Email does not match</font></span>
</c:if>
....
<c:if test="${condition == 1}">
<li><label>Email:</label> <input type='text' name='username'
id="forgot_username" /></li>
<li><label> </label> <input type="submit"
id="forgot_btn" value="Send Reminder" class="btn"></li>
</c:if>
This way those <li> will be hidden even if the client has JS disabled, or any kind of JS problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iOS resize and move image mask with fingers I am trying to resize and move mask on image with fingers. For moving the mask I need touch to move gesture and for resize I need to implement pinch-to-zoom gesture.
Generally I want to manipulate image mask with my fingers, not programatically.
How can I achieve this?
Thanks to you all!
A: I have found the answer at the Apple's Developer page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to print a dynamic div html element using jquery i was trying to print dynamic div html element using printElement() function but when i got problem...my code as follows
$("#btnPrint").click(function () {
if (ImgPath != '') {
sHtml = "<div id='dvPrint'><table>";
sHtml += "<tr><td>" + "<img src='" + ImgPath + "' border='0'/>" + "</td></tr>";
sHtml += "<tr><td>" + $('#lblTxt').html() + "</td></tr>";
sHtml += "</table></div>";
alert($('#dvPrint').html());
$("#element").printElement('#dvPrint');
}
else {
alert("Image not found for print");
}
return false;
});
when i just alert alert($('#dvPrint').html()); it show nothing. then how printElement() can work. i can append my dynamic div into body....i just need to generate div and print the content inside it by jquery.......i need help. thanks
A: You just formatted html string and didn't append it to the DOM. You cant find it using $('#dvPrint'). Use $(sHtml).html() to get the formatted html.
And as a result print will be: $(sHtml).printElement();
$("#btnPrint").click(function () {
if (ImgPath != '') {
sHtml = "<div id='dvPrint'><table>";
sHtml += "<tr><td>" + "<img src='" + ImgPath + "' border='0'/>" + "</td></tr>";
sHtml += "<tr><td>" + $('#lblTxt').html() + "</td></tr>";
sHtml += "</table></div>";
var $dvPrint = $(sHtml);
alert($dvPrint.html());
$dvPrint.printElement();
}
else {
alert("Image not found for print");
}
return false;
});
A: The alert($('#dvPrint').html()); won't work until you print the sHtml like this: $('#dvPrint').html(sHtml) - this will put all the content from the sHtml to the dvPrint.
A: I prefer to create a div using dom
var newdiv = document.createElement('div');
and then using it with jQuery
$(newdiv).html("<table>.....</table>");
or with DOM's interface (.addNode())
Regards
M.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: coredata sort by number of relationship In Core Data when entities have one to many or many to many relationship, how do we sort based on number of relationship?
For example
I want to know mothers with the most children
How would I do so in objective-c
A: This sort:
NSSortDescriptor *sort = [NSSortDescriptor
sortDescriptorWithKey:@"children.count"];
would work, but (assuming children is faulted) would use key-value coding methods on the children property, which in turn would fire the fault, so you'd lose the performance benefits of batching and faulting.
Another (debatable) approach is to keep the count as an attribute to the mother entity. You could then do a direct court without having to query the relationship at all.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: WCF web service not performing serialization properly i have the WCF web service within my solution. service has interface which implemeted in service class. i added few new methods in interface as well as implemented in service class. i can access if i use the sevice dll reference to my asp.net mvc 3 application. but after deployment and adding the service reference of service i am unable to get the newly added methods. by creating the client object . why should this happening? I deployed service at remote server.
I checked in wsdl also, but could not found metadata about the newly added methods.
Edited:
Well well well... I don't know what happened and somehow i got the serialized objects what i expected now. but when i am performing any operation with these objects I am getting problem that unable to connect to service.
"An error occurred while receiving the HTTP response to http://MyServer/MyAdminService.svc.
This could be due to the service endpoint binding not using the HTTP protocol.
This could also be due to an HTTP request context being aborted by the server
(possibly due to the service shutting down). See server logs for more details."
Inner Exception:
"The underlying connection was closed: An unexpected error occurred on a receive"
why should this? what are the necessary attributes int he web.config need to establish the connection between clent and server objects ?
Resolved:
http://lalitcdhake.blogspot.com/2011/10/serialization-with-entity-framework-4.html
Cheers
A: http://lalitcdhake.blogspot.com/2011/10/serialization-with-entity-framework-4.html
A: Have you marked new methods with OperationContract attribute? Sample from msdn:
[ServiceContract(Namespace="Microsoft.WCF.Documentation")]
public interface ISampleService{
// This operation specifies an explicit protection level requirement.
[OperationContract]
string SampleMethod(string msg);
}
class SampleService : ISampleService
{
#region ISampleService Members
public string SampleMethod(string msg)
{
Console.WriteLine("Called with: {0}", msg);
return "The service greets you: " + msg;
}
#endregion
}
A: I think you have a deployment issue. Some things to try.
*
*Confirm your methods are available in your local wsdl. If the methods are available locally your problem has nothing to do with serialization.
*Confirm the remote server you deployed to is in fact what you are looking at when you check the remote wsdl. There are many ways to do this but a simple one would be to introduce an error into web config and confirm the app goes down (if this is a dev server and taking down the app is not harmful).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL creating structural relationship between tables I have 2 tables, one is containing items and their properties, which are integers:
items table:
item_id, property_a, property_b, property_c
and another, single-row table, which contains allowed deviations of these properties,
also integers:
allowed deviations table:
property_a, property_b, property_c
This works, but there's no formal relationship between 2 tables hence no way to assure they're in sync when items table is modified in any way (except taking care of it manually or on application level).
So my question is - What's the best practice for this situation? Could and should some kind of relation between structure of these 2 tables be made on a database level, or it's good as it is?
One of my thoughts was, as deviations is a single row table, to just put it in items table, giving it specific dummy item, but the problems I see with that is:
-- dummy data, don't like that in my so far clean database
-- complicating queries that relate to items only
-- mixing apples and oranges in a single table
-- making it hard to extend if there's ever need for multiple sets of allowed deviations
A: I reckon you need to do a bit of normalisation here.
You could go with the following approach:
item table
id item
1 item1
item_property table
id item_id, property_id
1 1 1
2 1 2
3 1 3
allowed deviations table
property_id, property_type
1 a
2 b
3 c
This will allow you to set up a FK constraints on the item_property table referencing both the allowed deviations table and the item table itself. It should also allow for items that do not have all properties (without null data) and it should also allow you to add in new properties should any new ones come along (for example property d).
Hope this helps!
PS When you say "One of my thoughts was, as deviations is a single column table" do you mean "One of my thoughts was, as deviations is a single row table"?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: No database selected error only comes up when in a separate included php config file but works when in needed file Basically ive been trying to create a config file so it is much easier to edit the MYSQL connection info to the online database when ive completed my current website. The connection code i have works perfectly when in each file when needed but when i try and use an required once on the same code in a config file it says no database selected. this error never happens when the connection code is pre written into files. here is my config file code and then the working code which is already on a working page.
config php
<?php
//configures connection to the mysql database.
$con = mysql_connect("localhost","james");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cds", $con);
?>
and here is the code on a working connection to the database
<?php
//configures connection to the mysql database.
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("cds", $con);
$n = $_SESSION['news'];
// find out how many rows are in the table
if($n == 1)
{
echo '<h1>CDSRail News</h1>';
$sql = 'SELECT COUNT(*) FROM news ORDER BY news_date DESC';
$query = mysql_query($sql);
echo "<hr/>Click the links below to view our News<br><br>";
$result = mysql_query($sql);
$r = mysql_fetch_row($result);
$numrows = $r[0];...
please help!!!
A: This is not the right approach for what are trying to do here. Your config file should do nothing but define variables, and you should do the actual connection in the main file. So you should do something like this:
config.php:
<?php
$dbHost = 'localhost';
$dbUser = 'myuser';
$dbPass = 'mypass';
$dbName = 'mydbname';
?>
main.php
<?php
require('config.php');
if (!$con = mysql_connect($dbHost, $dbUser, $dbPass)) {
die('Could not connect: ' . mysql_error());
}
if (!mysql_select_db($dbName, $con)) {
die('Could not select database');
}
// Rest of code
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Setting the depth buffer content quickly in OpenGL ES 2.0 I am using OpenTK, opengl ES 2.0, and want to clear the depth buffer to one loaded externally for each redraw.
What I want to achieve is to clear the screen to a prerendered image and its depth buffer for situations where the camera and the background objects does not move, and then only render moving objects on top of this in the traditional way.
How to do this in a performance efficient way?
A: gl_FragCoord is immutable and GLES SL doesn't supply gl_FragDepth. So there's no way to set the output depth of a fragment within the fragment shader.
Two options present themselves as a result:
*
*don't use the hardware depth buffer
*set depths in the vertex shader
To do the former, you'd bind your depth texture to a spare unit and subsequently would do an explicit compare and discard in the fragment shader, based on gl_FragCoord.
To do the latter you'd submit an array of points, one per fragment, sample the depth texture within the vertex shader and output the depth appropriately. If your hardware doesn't support texture sampling within vertex shaders then you could do the same thing on the CPU. Leave the CPU-computed fragments in a VBO and you shouldn't end up paying that much frame-on-frame.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JQuery How To Flip A "Card" in 3D Space Like YP.com If you go to YP.com or Yellowpages, you'll see that they apply a 3D flip to the boxes towards the bottom when you mouse-over in a newer browser.
How is this accomplished in JQuery (by animating CSS3 props?)?
Thanks!
A: This is actually a lot closer to what he was looking for.. Just for the record..
:)
Sponsor Flip Wall With jQuery & CSS
It uses Flip! as the foundation..
A: It works on webkit browsers, so it isn't probably done by jQuery but by webkit css transforms (I did not analyze the code thoroughly so this is just an assumption but I think it's a right one).
You can get this effect in css by using:
-webkit-transform: rotateY(180deg);
You can find more information on webkit 3d transforms here:
Surfin' Safari
Sadly, it won't work on non-webkit browsers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to use one replace function to replace multiple strings in one field? In my report I need to use the built-in replace function to replace for example "a" with "b" and "c" with "d".
When I just use 2 functions like this:
Replace(Fields!field1.Value, "a", "b") & Replace(Fields!field1.Value, "c", "d")
I get the text from the field twice in my report.
Is it possible to do this? Maybe nest two replace functions? I'm new to reporting services so I could be missing a very obvious solution to this.
Note: I would write my own code to do this but the report is for Microsofts Dynamics CRM 2011 which doesn't allow custom code in a report.
A: You have to nest the function's
For example to replace 1 with a and 0 with b you can write the expression below
=Replace(Replace(Fields!field1.Value,"1","a"),"0","b")
A: This can be a bit tricky (at first) when you have a string that has part of it repeated in the string after it that you also want to replace.
To give you an example: If you use the nested function from niktrs to replace "Test" with "Test A" and "Test B" with "Test C" it returns "Test A" and "Test A B".
In this example you need to adjust the expression to:
=Replace(Replace(Fields!Field1.Value,"Test","Test A"),"Test A B","Test C")
With 2 or more of these type of strings you need to work your way (down the tablix) to the last value that needs replacing, which could leave you with a relatively lengthy expression, unfortunately. It's probably better to alter the query for the dataset you're working with.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How to shield "." char?
Possible Duplicate:
How do I get jQuery to select elements with a . (period) in their ID?
I tried to run the following code:
$('#info-mail.ru .domain-info').toggle();
example here
And #info-mail.ru as I understood interpreted as id="info-mail" and class="ru", but I have the following structure:
<div id="info-mail.ru">
<p class="domain-info">
Some cool info
Some cool info
Some cool info
Some cool info
</p>
</div>
How can I shield "." char in selector statement? Or the only way is to replace all "." with "_" (for example)?
TIA!
A: Escape . with a double backslash, one for the literal and the other for jQuery:
$('#info-mail\\.ru .domain-info').toggle();
See jQuery FAQ for details.
A: I believe you need to use two backslashes before the .
So the selector would be $('#info-mail\\.ru .domain-info').toggle();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to reload page when an ajax request returns FormsAuthentication.RedirectToLoginPage? I am a little in a trouble to find out how to redirect an ajax request to the login page when using forms authentication in asp.net mvc.
In OnAuthorize method I know that the request needs authorization. And if the cookie was deleted because of timeout etc., I want to redirect the user to the login page. But generally the requests are triggered by jquery via ajax request. So the requests are returning the html of the login page.
So how can I redirect the user to login page for an ajax request? Any ideas?
A: You could write a custom authorize attribute which would test if the request was an AJAX request and if yes return a JSON containing the url to redirect to:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
// It was an AJAX request => no need to redirect
// to the login url, just return a JSON object
// pointing to this url so that the redirect is done
// on the client
filterContext.Result = new JsonResult
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
Data = new { redirectTo = FormsAuthentication.LoginUrl }
};
}
else
{
// standard request => redirect
base.HandleUnauthorizedRequest(filterContext);
}
}
}
and then when you make an AJAX request:
$.get('/foo', function(result) {
if (result.redirectTo) {
window.location.href = result.redirectTo;
} else {
// standard stuff
}
});
and of course to avoid repeating this in every AJAX call you could use the .ajaxComplete() handler.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Pointer to struct & function pointers -> Seg Fault I always get a segmentation fault during execution of this test program. I can't figure out why. Maybe someone could explain it to me please, i'm sure i mixed up the pointer stuff.
#include <stdio.h>
struct xy {
int (*read)();
void (*write)(int);
};
struct z {
struct xy *st_xy;
};
static void write_val(int val)
{
printf("write %d\n", val);
}
static int read_val()
{
/* return something just for testing */
return 100;
}
int init(struct xy *cfg)
{
cfg->read = read_val;
cfg->write = write_val;
return 0;
}
int reset(struct z *st_z)
{
/* write something just for testing */
st_z->st_xy->write(111);
return 55;
}
int main(int argc, char **argv)
{
static struct z test;
int ret;
int ret2;
ret = init(test.st_xy);
printf("init returned with %d\n", ret);
ret2 = reset(&test);
printf("reset returned with %d\n", ret2);
return 0;
}
A: You never allocate the actual xy object. Your test.st_xy is just a garbage pointer that you're not allowed to dereference.
Instead, do something like this:
static struct z test;
static struct xy inner_test;
test.st_xy = &inner_test;
// ...
ret = init(test.st_xy);
A: You pass an uninitialized pointer to xy to the init function.
init(test.st_xy);
st_xy has not been initialized. I think there is no need for st_xy to be a pointer.
struct z {
struct xy st_xy;
};
int main(int argc, char **argv)
{
static struct z test;
init(&test.st_xy);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get the value of another component in a custom validator? I use a custom validator. The difficulty is that I just need to check two fields inputText and compare them. The first field must be greater than the second field. If not, then I have to show a message with the error information. So I need to pass in my custom validator the value of first inputText field. To do this I need to read a value of first InputText field in my validator class. How can I get a id of necessary component in a validator class? Solution using the tag does not suit me. I need to go to the desired component is directly Maybe this can be done through any methods of the FacesContext?
A: You can just grab the other field's value from the request parameter map using the input field' name attribute. To get the name attribute of the input field do a view source to see what gets generated. See example below.
public void validate(FacesContext fc, UIComponent uic, Object o) throws ValidatorException {
String newPassword = fc.getExternalContext().getRequestParameterMap().get("centerForm:newPassword");
String newPassword2 = (String) o;
if(!newPassword.equals(newPassword2)){
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_ERROR,"New Passwords do not match", null);
throw new ValidatorException(msg);
}
}
A: Just pass the whole component via <f:attribute>.
<h:form id="formId">
<h:inputText value="#{bean.start}">
<f:validator validatorId="rangeValidator" />
<f:attribute name="endComponent" value="#{endComponent}" />
</h:inputText>
...
<h:inputText binding="#{endComponent}" value="#{bean.end}" />
...
</h:form>
(note: binding code is as-is, do NOT let it refer a bean property!)
with in validator
UIInput endComponent = (UIInput) component.getAttributes().get("endComponent");
Object endComponentValue = endComponent.getSubmittedValue();
// ...
Important note is that the components are processed, converted and validated in the order as they appear in the tree. Any submitted value of components which aren't converted/validated yet is available by UIInput#getSubmittedValue() and any of those which are already converted/validated is available by UIInput#getValue(). So, in your particular example, you should get the value by UIInput#getSubmittedValue() instead of UIInput#getValue().
If you'd like to work with the already converted and validated value as available by UIInput#getValue(), then you need to move the validator to the second component and then pass the first component along instead.
<h:form id="formId">
<h:inputText binding="#{startComponent}" value="#{bean.start}" />
...
<h:inputText value="#{bean.end}" />
<f:validator validatorId="rangeValidator" />
<f:attribute name="startComponent" value="#{startComponent}" />
</h:inputText>
...
</h:form>
UIInput startComponent = (UIInput) component.getAttributes().get("startComponent");
Object startComponentValue = startComponent.getValue();
// ...
See also:
*
*JSF doesn't support cross-field validation, is there a workaround?
*Error validating two inputText fields together
*Validator for multiple fields
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: sed to match multiple lines, but only after a certain line has been seen I'm trying to do some very simple rss parsing with sed. Like plucking out enclosure urls for listening to the latest news.
Example:
sed -n -e 's/.*"\([^"]*\.mp3\)".*/\1/p' -e 's/.*<title>\([^<]*\)<.title>.*/\1/p'
Though, what I would like to do is to start this matching only after a certain token has been seen, in this case "<item>", so that I don't catch any feed <title>s, or such.
GNU sed is fine, and I think I could somehow use the two-address form '0,/REGEXP/' but I don't know how to combine this to achieve the above
Added for Dawnofthedead:
foo
bar
baz
<title>fum</title>
baz
fie
<item>
<title>1</title>
<enclosure url="one.mp3">
</item>
<item>
<title>2</title>
<enclosure url="two.mp3">
</item>
should give me
1
one.mp3
2
two.mp3
A: if you would stick to sed, try this line. this line works with given example:
kent$ sed -nr '/<item>/,/<\/item>/p' yourFile|sed -nr '/<title>/{s#[ ]*<[/]?title>##g;p}; /<enclosure/{ s#.*url="(.*)">#\1#g;p}'
test
kent$ cat t
foo
bar
baz
<title>fum</title>
baz
fie
<item>
<title>1</title>
<enclosure url="one.mp3">
</item>
<item>
<title>2</title>
<enclosure url="two.mp3">
</item>
kent$ sed -nr '/<item>/,/<\/item>/p' t |sed -nr '/<title>/{s#[ ]*<[/]?title>##g;p}; /<enclosure/{ s#.*url="(.*)">#\1#g;p}'
1
one.mp3
2
two.mp3
A: $ sed -n -f s.sed input
1
one.mp3
2
two.mp3
where s.sed is:
/<item>/,/<\/item>/{
s/^.*>\([^<]\+\).*$/\1/
s/^.*"\(.*\)".*$/\1/
/>$/d
p
}
A: If you need to parse a simple XML (like an RSS feed) in command line why don't you try xsltproc ?
It takes in input an xml and can apply an xslt transformation stylesheet.
You have to learn the xslt language but you can produce better output.
A: This might work for you:
sed '$!N;s/^\s*<title>\(.*\)<\/title>\n\s*<enclosure url="\([^"]*\)">/\1\n\2/p;D' file
1
one.mp3
2
two.mp3
Rather than look between <item>...</item>s look for the two lines <title>...<enclosure...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Multiple Facebook Connect I'm building a website photo contest and it has two registration forms on the same page, one for the models and another for users who will vote.
do I have problems if I integrate facebook connect to each form?
I really need two forms because the registry for models allows to upload photos, fill in details and so on.
A: It is generally not a great idea, nor necessary, to have two apps for the same product/site. You can easily just use one app integration for both features - only asking for the extra permissions and data when the user tries to do something which requires them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get available appartments Appartments table:
I want al the available appartments that are not booked.
This is my current mysql query:
(array) $db->getRecords('
SELECT i.id, i.num_persons, i.rating, i.lat, i.lng, i.street, i.number,
c.title, c.introduction, c.text, c.area, c.long_term_rental, c.beds, c.features,
c.services_and_equipment, c.terms_and_conditions, m.url
FROM appartments AS i
INNER JOIN appartments_content AS c on c.parent_id = i.id
INNER JOIN meta AS m on m.id = c.meta_id
LEFT JOIN appartments_bookings AS b on b.appartment_id = i.id
WHERE c.language = ?
AND i.hidden = ?
AND i.publish_on <= ?
AND i.city_id = ?
AND i.num_persons >= ?
AND (b.arrival >= ? OR b.departure <= ?)
ORDER BY i.num_persons ASC, i.publish_on DESC
LIMIT ?, ?',
array( FRONTEND_LANGUAGE, 'N', FrontendModel::getUTCDate('Y-m-d H:i') . ':00',
(int) $filter['city'], (int) $filter['persons'], $filter['arrival'],
$filter['departure'], (int) $offset, (int) $limit), 'id');
A: SELECT a.id, a.num_persons, a.rating, a.lat, a.lng, a.street, a.number
,c.title, c.introduction, c.text, c.area, c.long_term_rental, c.beds
, c.features ,c.services_and_equipment, c.terms_and_conditions
, m.url
FROM appartments AS a
INNER JOIN appartments_content AS c on c.parent_id = a.id
INNER JOIN meta AS m on m.id = c.meta_id
LEFT JOIN appartments_bookings AS b
ON (b.appartment_id = a.id
AND NOT ((? > b.departure) OR (? < b.arrival)))
-- this ? = arrival that ? = departure
WHERE b.id IS NULL
AND c.language = ?
AND a.hidden = ?
AND a.publish_on <= ?
AND a.city_id = ?
AND a.num_persons >= ?
ORDER BY a.num_persons ASC, a.publish_on DESC
LIMIT ? OFFSET ?'
Changes
the occupation test
The test NOT((param_arrival > b.departure) OR (param_departure < b.arrival)) Is a simple test for overlap, that works with 2 tests. Yours does not because it needs a total of 4 tests, so you're missing something there.
Of course this code assumes that arrival always falls before departure, so make sure you assert that assumption.
Use an anti-join on bookings
We put all the tests for occupation the the join criteria for the bookings.
And then I only select rows for with there are no bookings, i.e. for which b.id IS NULL.
LIMIT clause
This is just a pet-peeve of mine, but I prefer the much more intuitive LIMIT rowcount OFFSET pagestart syntax over the confusing LIMIT pagestart, rowcount.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: NullPointerException in ListView Hy!!
I have a listview that should be filled with data from the database
Code:
private void onCreateDBAndDBTabled() {
myDB = this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
myDB.execSQL("CREATE TABLE IF NOT EXISTS " + MY_DB_TABLE
+ " (_id integer primary key autoincrement, name varchar(100), rate integer(1), eattime datetime)"
+";");
ArrayList<Pizza> list = new ArrayList<Pizza>();
Cursor cursor = this.myDB.query(MY_DB_TABLE, new String[] { "name" },null,null,null,null,null,null);
if (cursor.moveToFirst()) {
do {
Log.e("XXX", "Courser Enter: " + cursor.getString(0));
Pizza pizza = new Pizza();
pizza.title= cursor.getString(0);
list.add(pizza);
}
while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
Log.e("XXX", "Count:" + list.size());
Log.e("XXX", "Item[0] -->" + list.toArray()[0].toString());
CustomAdapter aa = new CustomAdapter(this, R.layout.customlistitem,list);
Log.e("XXX", String.valueOf(aa.getCount()));
lv.setAdapter(aa);
}
Customadapter:
public class CustomAdapter extends ArrayAdapter<Pizza>{
private ArrayList<Pizza> pizzen;
public CustomAdapter(Context context, int textViewResourceId,ArrayList<Pizza> objects) {
super(context, textViewResourceId, objects);
this.pizzen = objects;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
Pizza pizza = pizzen.get(position);
if (v == null) {
}
return v;//super.getView(position, convertView, parent);
}
Pizza:
public class Pizza{
public String title;
public int rate;
public Date date;
}
Error:
09-30 08:58:38.661: ERROR/XXX(667): Courser Enter: EditText
09-30 08:58:38.671: ERROR/XXX(667): Count:1
09-30 08:58:38.671: ERROR/XXX(667): Item[0] -->com.korn.pizzacounter.Pizza@43b91850
09-30 08:58:38.671: ERROR/XXX(667): 1
09-30 08:58:38.751: ERROR/AndroidRuntime(667): Uncaught handler: thread main exiting due to uncaught exception
09-30 08:58:38.762: ERROR/AndroidRuntime(667): java.lang.NullPointerException
09-30 08:58:38.762: ERROR/AndroidRuntime(667): at android.widget.AbsListView.obtainView(AbsListView.java:1276)
09-30 08:58:38.762: ERROR/AndroidRuntime(667): at android.widget.ListView.makeAndAddView(ListView.java:1668)
09-30 08:58:38.762: ERROR/AndroidRuntime(667): at android.widget.ListView.fillDown(ListView.java:637)
09-30 08:58:38.762: ERROR/AndroidRuntime(667): at android.widget.ListView.fillFromTop(ListView.java:694)
09-30 08:58:38.762: ERROR/AndroidRuntime(667): at android.widget.ListView.layoutChildren(ListView.java:1521)
09-30 08:58:38.762: ERROR/AndroidRuntime(667): at android.widget.AbsListView.onLayout(AbsListView.java:1113)
09-30 08:58:38.762: ERROR/AndroidRuntime(667): at android.view.View.layout(View.java:6830)
The error is a NullPoinerException although the ListSize is 1 (see the log)
A: It's because in your getView() method you are not inflating the convertView and it is returning you null.
Your getView should be something like this inflating a row.xml which contains a TextView.
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
TextView mTextView = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.row, parent, false);
mTextView = (TextView) convertView.findViewById(R.id.txt_list);
convertView.setTag(mTextView);
}
else{
mTextView = (TextView) convertView.getTag();
}
mTextView.setText(arrList.get(position));
return convertView;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: is interactive GUI-creation possible with MacRuby's macirb? I'd like to live prototype GUIs with Macruby. Like creating a window, placing some views in it, etc.. Is that possible?
A: Yes it is.
Have a look at the HotCocoa documentation: http://www.macruby.org/hotcocoa.html
A: Yes! I just figured this out myself, so I thought I'd share (even though this is an old question). I'm assuming you have MacRuby installed (I'm using 0.11).
Install HotConsole. HotConsole is an IRB-like thing that runs MacRuby code. The nice thing is that it is multithreaded, which means the HotCocoa app doesn't block the console. To install just:
% git clone git@github.com:altirah/hotconsole.git hotconsole
% cd hotconsole
% macrake
You can then drag the HotConsole.app to your /Applications folder.
In HotConsole, you can store a HotCocoa window in a variable and then play around with it. For example, in HotConsole.app (make sure you use alt-Enter to go to a new line, else you will run what you've typed so far):
win = window frame: [100, 100, 500, 500], title: 'Hello' do |w|
w << label(text: 'Hello', layout: {start: false})
end
You should see a nice Cocoa window pop up with a label that says 'Hello'. Now for the fun part. In HotConsole.app, you can now type:
win << button
win << web_view( :layout => {:expand => [:width, :height]},
:url => "http://macruby.org")
HotConsole is pretty crashy for me, but I'm using a not-yet-released version of MacRuby to build/run it, so I don't know if that makes a difference.
A: You can, however, since all the code runs in the main thread it would block the runloop and thus views won't behave as they should.
I’ve been working on and off on another project that does allow you to do this, the only thing that's important is to note that in this case all user code is run in separate threads, so you should dispatch a message on the main thread when interacting with other views: https://github.com/alloy/interactive-macruby
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery .find("body").html() == null I have an html page called test.html, here is it's content:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>
<title></title> </head> <body style="margin: 0; padding: 0; background: #d9d9d9;">
<form name="form1" method="post" action="NewsLetterPreview.aspx?NewsletterID=1" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTA3NzM3OTc4N2Rkkk3StA9iwyEdCoR43JPpw6OyRHubNTnbXatTbxCXsVA=" />
</div>
</form> </body> </html>
I then have another page which I am using $.get to get the content of the page:
$.get("test.html", function (data) {
alert($(data).find("body").html());
});
However the alert($(data).find("body").html()) returns null. It does the same for the alert($(data).find("form").html()) also. Only if I specify alert($(data).find("div").html()) does it return the input field.
How can I select the body / form?
A: If you want to replace your body with fetched HTML, this should do it.
$.get("test.html", function (data) {
$(body).html(data);
});
EDIT:
Missread your question.
It'd suggest you to use json or .replace() instead.
Example: alert(data.replace(/^.*?\<body\>(.*?)\<\/body\>.*$/, "$1"));
If you want body tags included: alert(data.replace(/^.*?(\<body\>.*?\<\/body\>).*$/, "$1"));
I don't think jquery can work with HTML the way you wish. Either include it in the code and then use regular functions or find another workaround.
A: I am not sure of the solution, but I think I can shed some light on the problem...
From here: http://api.jquery.com/jQuery/
When passing in complex HTML, some browsers may not generate a DOM
that exactly replicates the HTML source provided. As mentioned, we use
the browser's .innerHTML property to parse the passed HTML and insert
it into the current document. During this process, some browsers
filter out certain elements such as , , or
elements. As a result, the elements inserted may not be representative
of the original string passed.
Which means that on some browsers the HTML string being input has the form, head, and body tags stripped out before jQuery processes the string - so it is as if your returned string only has the div and it's contents.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to fork opensource project without violating licence? I want to fork Maven NSIS plugin http://mojo.codehaus.org/nsis-maven-plugin/index.html at BitBucket. Codehous project seems to be dead. How should I behave to craete legal fork of it?
A: Unfortunately(1) doesn't claim what licence it has, but after checking out their code from svn, the header in the file NsisCompileMojo.java says:
* Copyright 2008 Codehaus
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
The Apache licence is quite permissive; you can easily fork of your project, but need to keep the original copyright notices of the original authors. More details can be found a Wikipedia(2) (apache.org seems to be down at the moment).
But long story short: Fork.
Edit: One more hint: The Freedom Task Force, an institution of the Free Software Foundation Europe, will be able to help you if you still have legal doubts: http://fsfe.org/projects/ftf/
A: As usual: I am not a lawyer and you should really get one, if you want proper legal advice. Anything else is just guesswork.
I don't see a license specified anywhere, which makes it hard to do: if no license is specified, that means that you have very limited rights, almost everywhere in the world. And no: the source code being publicly viewable doesn't automagically change that!
So unless you can contact the original authors to clarify that for you, you can just as easily assume that it is a closed-source project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to make maven appassembler use javaw instead of java in generated scripts Is it possible to make maven appassembler plugin to generate startup scripts that use 'javaw' instead of 'java'?
A: In Appassembler 1.3 you can do it by configuring the showConsoleWindow option in the POM:
<showConsoleWindow>flase</showConsoleWindow>
This will change the line in the resulting Script from
if "%JAVACMD%"=="" set JAVACMD=java
to this
if "%JAVACMD%"=="" set JAVACMD=start /min javaw
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JEditorPane, HTMLEditorKit - custom action inserting custom tag I'm faithing with JEditorPane. I need simple editor. I've solved the problem with loading and modified HTML containing custom (two) tags (see my older post). It displays the document properly and I can even edit it now. I can write text, delete either characters or my custom elements. I won a battle, but haven't won the war. The next step is regrettably very problematical too. I'm unable to insert my custom tags.
I have a custom action:
import my.own.HTMLEditorKit; //extends standard HTMLEditorKit
import my.own.HTMLDocument; //extends standard HTMLDocument
class InsertElementAction extends StyledTextAction {
private static final long serialVersionUID = 1L;
public InsertElementAction(String actionName) {
super(actionName);
}
@Override
public void actionPerformed(ActionEvent e) {
JEditorPane editor = getEditor(e);
if (editor == null)
return;
HTMLDocument doc = (HTMLDocument) editor.getDocument();
HTMLEditorKit ekit = (HTMLEditorKit) editor.getEditorKit();
int offset = editor.getSelectionStart();
try {
ekit.insertHTML(doc, offset, "<span>ahoj</span>", 0, 0, HTML.Tag.SPAN);
Element ele = doc.getRootElements()[0];
ele = ele.getElement(1).getElement(0);
doc.setInnerHTML(ele, "<bar medium=\"#DEFAULT\" type=\"packaged\" source=\"identifier\" />");
}
catch (BadLocationException ble) {
throw new Error(ble);
}
catch (IOException ioe) {
throw new Error(ioe);
}
}
}
It workts properly. I can insert the span element. But I cannot insert non-standard tag in this way. I can insert just code, span and so on, but not my tag. For my tag I'm forced to use this:
ekit.insertHTML(doc, offset, "x<bar medium=\"#DEFAULT\" type=\"packaged\" source=\"identifier\" />x", 0, 0, null);
There are two critical problems
*
*The custom tag must be bounded with non-whispace characters (here x)
*The current element's body is split
When I insert span element into <p>paragraph</p>, I get <p>par<span>ahoj</span>agraph</p> as expected. Howerever unknown tag is allways inserted as child of body element and the result (e.g. for unknown tag x) is <p>par</p><x>ahoj</x><p>agraph</p>.
The work is dead exhausting. I'm faithing with this relatively simple task since weeks. I'm already wasted. If the insertion won't to work, I can scrap it all...
A: Hope this helps
http://java-sl.com/custom_tag_html_kit.html
A: I've found a workaround. The tag is inserted this way:
ModifiedHTMLDocument doc = (ModifiedHTMLDocument) editor.getDocument();
int offset = editor.getSelectionStart();
//insert our special tag (if the tag is not bounded with non-whitespace character, nothing happens)
doc.insertHTML(offset, "-<specialTag />-");
//remove leading and trailing minuses
doc.remove(offset, 1); //at the current position is the minus before tag inserted
doc.remove(offset + 1, 1); //the next sign is minus after new tag (the tag is nowhere)
//Note: no, you really cannot do that: doc.remove(offset, 2), because then the tag is deleted
My ModifiedHTMLDocument contains a method insertHTML(), which calls the medhod hidden by reflection:
public void insertHTML(int offset, String htmlText) throws BadLocationException, IOException {
if (getParser() == null)
throw new IllegalStateException("No HTMLEditorKit.Parser");
Element elem = getCurrentElement(offset);
//the method insertHTML is not visible
try {
Method insertHTML = javax.swing.text.html.HTMLDocument.class.getDeclaredMethod("insertHTML",
new Class[] {Element.class, int.class, String.class, boolean.class});
insertHTML.setAccessible(true);
insertHTML.invoke(this, new Object[] {elem, offset, htmlText, false});
}
catch (Exception e) {
throw new IOException("The method insertHTML() could not be invoked", e);
}
}
The last piece of our brick-box is a method looking for the current element:
public Element getCurrentElement(int offset) {
ElementIterator ei = new ElementIterator(this);
Element elem, currentElem = null;
int elemLength = Integer.MAX_VALUE;
while ((elem = ei.next()) != null) { //looking for closest element
int start = elem.getStartOffset(), end = elem.getEndOffset(), len = end - start;
if (elem.isLeaf() || elem.getName().equals("html"))
continue;
if (start <= offset && offset < end && len <= elemLength) {
currentElem = elem;
elemLength = len;
}
}
return currentElem;
}
This method is also a member of the ModifiedHTMLDocument class.
The solution is not pure, but it solves provisionally the problem. I hope I'll find a better kit. I'm thinking about JWebEngine. That should be replacement for current poor HTMLEditorKit, but I don't know, whether it allows me to add my custom tags.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Expire cookie set through FormAuthentication I have used MemberShipUser API on Login we are validating user and creating FormAuthentication
FormAuthentication.SetAuth(username, false);
now if user doesnot logout and close the browser directly FormAuthentication.SignOut method is not called.
due to which when we reopen the website the user is already logged in.
A: Either configure the timeout value to an appropriate number or use cookie less forms authentication.
<system.web>
<authentication mode="Forms">
<forms loginUrl="Login.aspx"
protection="All"
timeout="30" <----------------------------Tune this
name=".ASPXAUTH"
path="/"
requireSSL="false"
slidingExpiration="true" <--------------------- Tune this
defaultUrl="default.aspx"
cookieless="UseDeviceProfile" <--------------------- Or Turn off cookies
enableCrossAppRedirects="false" />
</authentication>
</system.web>
http://msdn.microsoft.com/en-us/library/ff647070.aspx#pagexplained0002_cookielessforms
A: The authentication cookie will still be valid. When the user opens the site again, the cookie says the user is still logged in.
You can make the cookie short lived so it's more likely to have expired:
<authentication mode="Forms">
<forms loginUrl="Login/" timeout="5"/>
</authentication>
but afaik, if the user doesn't log out they won't be immediately logged out.
^^Unless you don't use cookies as hasan-khan says (it passes an id in the querystring which doesn't really look very nice.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android: how to get the name of apk file programmatically? For some reasons, my app can be installed with different apk names. At launch, I would like to know what is the name of the apk file. Do you know how to do that ?
Thanks !
A: final PackageManager pm = getPackageManager();
String apkName = "example.apk";
String fullPath = Environment.getExternalStorageDirectory() + "/" + apkName;
PackageInfo info = pm.getPackageArchiveInfo(fullPath, 0);
you can got it with:
info.versionCod
and
info.versionName
hope this help you
A: The apk or app name can be retrieved using package manager.
According to alex's answer here - https://stackoverflow.com/a/30348666/2026280
Assuming you have the path of the apk file.
public static String getAppLabel(PackageManager pm, String pathToApk) {
PackageInfo packageInfo = pm.getPackageArchiveInfo(pathToApk, 0);
if (Build.VERSION.SDK_INT >= 8) {
// those two lines do the magic:
packageInfo.applicationInfo.sourceDir = pathToApk;
packageInfo.applicationInfo.publicSourceDir = pathToApk;
}
CharSequence label = pm.getApplicationLabel(packageInfo.applicationInfo);
return label != null ? label.toString() : null;
}
A: try this:
ActivityManager actMngr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
string runningPkg = actMngr.getRunningTasks(1).get(0).topActivity.getPackageName();
PackageManager pm = context.getPackageManager();
ApplicationInfo ai = pm.getApplicationInfo(runningPkg , 0);
Added:
If you are not getting the apk name then you can compare it with intalled pkg and get the corresponding app name. You can fetch the installed app's pkg name and app name like this:
ArrayList<PackageInfo> res = new ArrayList<PackageInfo>();
PackageManager pm = ctx.getPackageManager();
List<PackageInfo> packs = pm.getInstalledPackages(0);
for(int i=0;i<packs.size();i++) {
PackageInfo p = packs.get(i);
String description = (String) p.applicationInfo.loadDescription(pm);
String label= p.applicationInfo.loadLabel(pm).toString();
//Continue to extract other info about the app...
}
Note: Add this permission to the manifest file:
<uses-permission android:name="android.permission.GET_TASKS" />
A: This is achieved with getPackageArchiveInfo from an already packaged apk file:
PackageInfo package_info = pm.getPackageArchiveInfo(file_path_to_apk, 0);
A: Try this it work for me:
String versionName = "null"; //String apk versionName
int versionCode = -1; //int versionCode
String APKFilePath = "/storage/emulated/0/apkname.apk"; //For example
PackageManager pm = getPackageManager();
PackageInfo packageInfo = pm.getPackageArchiveInfo(APKFilePath, 0);
// the secret are these two lines
packageInfo.applicationInfo.sourceDir = APKFilePath;
packageInfo.applicationInfo.publicSourceDir = APKFilePath;
Drawable APKicon = packageInfo.applicationInfo.loadIcon(pm); //drawable apk icon
String AppName = (String)packageInfo.applicationInfo.loadLabel(pm); // String apk name
versionName = packageInfo.versionName; //String version name
versionCode = packageInfo.versionCode; //int version code
apk_icon.setImageDrawable(APKicon); //ImageView apk icon
Apkpackage.setText(packageInfo.packageName); //TextView apk package name
Apkname.setText(AppName); //TextView apk name
Apkversion.setText(String.format("Version Name: %s Version Code:%d", versionName, versionCode)); //TextView versionName and versionCode
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: EventMachine::HttpRequest and Keep-alive connection I'm using the following code to run a couple of HTTP requests, but the second request (req2) always returns to errback.
Am I missing something obvious here?
request_options = {
:body => " ",
:keepalive => true,
:head => {
'content-type' => 'application/json',
'accept' => 'application/json',
'Accept-Encoding' => 'gzip,deflate,sdch'
}
}
EM.run do
request_options[:path] = '/default/path'
conn = EM::HttpRequest.new 'https://www.example.com'
req1 = conn.post request_options
req1.errback { p 'Uh, oh'; EM.stop }
req1.callback do
doc = JSON.parse req1.response
# do stuff with doc
request_options[:body] = 'post-data'
request_options[:path] = '/new/path'
req2 = conn.post request_options
req2.errback { p 'Uh, oh'; EM.stop }
req2.callback do
puts req2.response
EM.stop
end
end
end
A: I solved my problem by using EM-Synchrony
gem install em-synchrony
With this gem installed, I could use the following code to get the code work as I expected.
request_options = {
:body => " ",
:keepalive => true,
:head => {
'content-type' => 'application/json',
'accept' => 'application/json',
'Accept-Encoding' => 'gzip,deflate,sdch'
}
}
EM.synchrony do
request_options[:path] = '/default/path'
conn = EM::HttpRequest.new 'https://www.example.com'
req1 = conn.post request_options
doc = JSON.parse req1.response
# do stuff with doc
request_options[:body] = 'post-data'
request_options[:path] = '/new/path'
req2 = conn.post request_options
puts req2.response
EM.stop
end
I guess I was just confused about they way EM.run does asynchronous requests and di.
A: You can't use the same connection object inside the response callback.
Make sure you create a new EM::HttpRequest.new 'https://www.example.com' for the second request.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Encryption/decryption of sound file Blackberry application I need a help regarding sound file encryption/decryption. I would like to encrypt a sound file while I store this and decrypt same while play this file. I read about encryption/decryption in java and lots of sample code available for this in java. but these programs doesn't work with blackberry. My requirement is for blackberry application. Anybody have any link or sample code to encryption/decryption please provide me
Regards
Vaibhav Singh
A: Using basic encryption with BlackBerry
Using advanced encryption with BlackBerry
BlackBerry encryption and decryption lab tutorial
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.