text stringlengths 8 267k | meta dict |
|---|---|
Q: PHP Regex match words in a string excluding one specific word I have a text ($txt), an array of words ($words) i want to add a link and a word ($wordToExclude) that must be not replaced.
$words = array ('adipiscing','molestie','fringilla');
$wordToExclude = 'consectetur adipiscing';
$txt = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque
mattis tincidunt dolor sed consequat. Sed rutrum, mauris convallis bibendum
dignissim, ligula sem molestie massa, vitae condimentum neque sem non tellus.
Aenean dolor enim, cursus vel sodales ac, condimentum ac erat. Quisque
lobortis libero nec arcu fringilla imperdiet. Pellentesque commodo,
arcu et dictum tincidunt, ipsum elit molestie ipsum, ut ultricies nisl
neque in velit. Curabitur luctus dui id urna consequat vitae mattis
turpis pretium. Donec nec adipiscing velit.'
I want to obtain this result:
$txt = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque
mattis tincidunt dolor sed consequat. Sed rutrum, mauris convallis bibendum
dignissim, ligula sem <a href="#">molestie</a> massa, vitae condimentum neque sem non tellus.
Aenean dolor enim, cursus vel sodales ac, condimentum ac erat. Quisque
lobortis libero nec arcu <a href="#">fringilla</a> imperdiet. Pellentesque commodo,
arcu et dictum tincidunt, ipsum elit <a href="#">molestie</a> ipsum, ut ultricies nisl
neque in velit. Curabitur luctus dui id urna consequat vitae mattis
turpis pretium. Donec nec <a href="#">adipiscing</a> velit.'
A: $result = preg_replace(
'/\b # Word boundary
( # Match one of the following:
(?<!consectetur\s) # (unless preceded by "consectetur "
adipiscing # adipiscing
| # or
molestie # molestie
| # etc.
fringilla
) # End of alternation
\b # Word boundary
/ix',
'<a href="#">\1</a>', $subject);
A: Okie doke! While I think this is technically doable, the solutions I have provided are kind of soft at this point:
s%(?!consectetur adipiscing)(adipiscing|molestie|fringilla)(?<!consectetur adipiscing)%<a href="#LinkBasedUpon$1">$1</a>%s
turns...
sit amet, consectetur adipiscing elit. Quisque... ligula sem molestie massa... nec arcu fringilla imperdiet... nec adipiscing velit.
into...
sit amet, consectetur adipiscing elit. Quisque... ligula sem <a href="#LinkBasedUponmolestie">molestie</a> massa... nec arcu <a href="#LinkBasedUponfringilla">fringilla</a> imperdiet... nec <a href="#LinkBasedUponadipiscing">adipiscing</a> velit.
The reason it is a soft solution is that it does not handle partial words or other cases where the word(s) to exclude do not either begin or end with one of the words to be matched. e.g, if we were to append to the excluded 'word' (i.e. consectetur adipiscing elit), this expression would end up matching the adipiscing in consectetur adipiscing elit, because adipiscing does not begin or end the same as consectetur adipiscing elit
It should work as long as your exclude 'word' (A B C) always ends or begins with one of the words to be found (C|X|E has a C in it, and A B C ends with the word C, so should therefore work...)
EDIT {
The reason the 'not matched' words must begin or end with one of the matched words is that this solution uses negative lookahead before the match, and negative lookbehind after the match to ensure that the matched sequence does not match the words to not be matched (does that make sense?)
}
There are certain solutions to this, but they are either or both processor and programming effort intensive, and get exponentially more so depending on the size of the lists of words and the length of the searched text AND the specific requirements - and you never specified anything else, so I'm not gonna go into it at this point. Let me know if this is good enough for your situation!
A: I see you're doing it in PHP. I understand you have an ARRAY of words to find in a text and you need to replace those with links. Also you have ONE string that needs to be excluded when doing the replacing. Maybe instead of writing cool and clean yet complicated regular expressions what about this practical albeit probably not the nicest solution:
You split the task into subtasks:
*
*use preg_match_all to find offsets of all occurrences of the excluded string (you know the string length (strlen) and with the PREG_OFFSET_CAPTURE flag for preg_match_all you will figure out exact starts and ends - if there are more than one)
*do foreach on your word list and again use preg_match_all to get all occurrences of the words you need to replace with links
*compare the positions you found in step 2 with those found in step 1 and if they're outside do the replace or skip if you get overlap
It surely won't be a one-liner but would be quite easy to code and then probably quite easy to read later too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Strange behavior when loading mdi winform c# .net I´m getting a strange behavior in a c# MDI WinForms application. When i open a specific form together with any other form, this specific form locks up. Somehow its grouping the ControlBox of both forms into one, looking like this:
As the forms has stopped responding, its not closeable and has stopped painting:
The strange part is that any other combination of forms works fine. The forms gets loaded on top of each other and the application does not freeze.
But i can not figure out whats different about this form compared to the others. All settings are identical.
This is the code in the main MDIform that initiate new child forms, its called from a ToolStrip Button.Click event:
private void OpenForm(object sender)
{
if (sender == null) return;
ToolStripMenuItem itemSender = (ToolStripMenuItem)sender;
try
{
WinForm mapping = (WinForm)itemSender.Tag;
if (!FormList.ContainsKey(mapping.FormName))
{
Type frmType = Type.GetType(string.Format("OrderAssist.Forms.{0}", mapping.FormName));
if (frmType != null)
{
Form newForm = (Form)Activator.CreateInstance(frmType);
if (!newForm.IsDisposed)
{
newForm.Name = mapping.FormName;
newForm.Tag = itemSender;
newForm.MdiParent = this;
newForm.Show();
newForm.WindowState = System.Windows.Forms.FormWindowState.Maximized;
newForm.FormClosing += new FormClosingEventHandler(newForm_FormClosing);
FormList.Add(newForm.Name, newForm);
itemSender.Checked = true;
newForm.Activate();
}
}
else
itemSender.Enabled = false;
}
else
FormList[mapping.FormName].Activate();
}
catch (Exception e)
{
Exceptions.ProgramException(e, Settings.User.ID, "Exception occured while opening a form.");
if (itemSender != null)
itemSender.Enabled = false;
}
}
To make the matter stranger, if i populate this form that locks with data and click on some controls inside, before opening another form, the error does not occur.
Im out of ideas of what to try next.
A: newForm.WindowState = System.Windows.Forms.FormWindowState.Maximized;
The above line is called for all your controls, which results in the control boxes being grouped together.
As for that form freezing up, you need to post the code of the child form that causes the form freeze. Then I can assist you further.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UScrollView lazy loading unload view I have a question regarding the page control sample code from apple.
in the scrollViewDidScroll method there's a comment:
// A possible optimization would be to unload the views+controllers which are no longer visible
I wonder how to unload the views+controllers. As I have problems with my memory management I really need that.
Hope anyone can help.
A: From your scrollViewDidScroll you could figure out the current coordinates the user is in from the contentSize with this as the user scrolls out a certain viewController pop that viewController or view from of the current view.
[currentView removeFromSubView];
You could do this but I would suggest you try to use UITableView as this is all damn easy to do it there...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTML5 Javascript API Intellisense support in visual studio I started playing with HTML5/CSS3 and the new JavaScript API
something i noticed in VS 2010 is it doesn't have any support for the new JavaScript API i was wondering if there is anything i can do about it
so in Vs2010 if i type :
var canvas = document.getElementById('diagonal');
var context = canvas.getContext('2d');
i don't get any intellisense for the "getContext" method etc..
i dont wanna write the code and compile and pray it works.
any idea how can i enable intellisense for new javascript ?
A: vsdoc documentation for Canvas for Visual Studio 2010:
http://abstractform.wordpress.com/2010/02/18/canvas-intellisense-auto-completion-in-visual-studio/
A: I know you tagged VS2010, but the Visual Studio 11 Developer Preview, and presumably the eventual RTM, natively supports HTML5 intellisense, including support for canvas.
IntelliSense for DOM APIs has been improved, with support for many new
HTML5 APIs including querySelector, DOM Storage, cross-document
messaging, and canvas. DOM IntelliSense is now driven by a single
simple JavaScript file, rather than by a native type library
definition. This makes it easy to extend or replace.
A: This artricle describes how to add intellisense. The system looks pretty flexible. I think you'll need to download a special doc version of the JS API though.
http://msdn.microsoft.com/en-us/library/ff798328.aspx
Here is another
http://blog.turlov.com/2010/05/leveraging-visual-studio-javascript.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How can i get list of files which are matching search keyword Doing a global search box, need to get filename & directory path of matching pattern inside the file content, Can anybody help with the code? I'm new to PHP can anybody help plz.
A: set a new variable depending on the path to the document ie.
if (dirname($_SERVER['PHP_SELF'])) != "include/")
{
$linkbase = "include/";
}
include($linkbase."page.php");
any help?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: google app engine is detecting python25 as default hi i am trying to install Google app engine with windows MSI i have two python version on my windows one is python25 and other is python26, and i have python26 path set in my environmental variables, but Google app engine is detecting python25 as default prerequisite, what should i do which makes Google app engine to detect python26.
or if i let it to use python25 then can i change that later? and how?
A: At present, Google App Engine's production servers only run Python 2.5.2. You should be using Python 2.5 on the development server as well, as having a different environment for testing and production leads to scenarios where, for example, you use syntax that's valid in 2.6 which passes your tests fine, and the unexpectedly gives you frustrating errors when deployed to production.
It should be noted that the Python 2.7 runtime on the production servers is currently in the Trusted Testers stage, and should be available for use in the next few months, but until it is, it's best to stay with 2.5 for development.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails 3 and Google maps api v3 incompatibilities I have a rails 3.1 application with this simple code in the home page (rhtml file),
*
*If I run the same code in a html file it works.
*If I run this in my rails app it doesn't and I do not get any kind of errors using firebug.
Also: I have jquery-rails gem.
What could be the problem?
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script>
jQuery(document).ready(function() {
init();
});
</script>
<script type="text/javascript">
function init() {
var latlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
</script>
then I have my div:
<div id="home">
<div style="width:100%;height:400px" id="map_canvas"></div>
</div>
with this css:
#home #map_canvas {
width: 100%;
height: 400px;
position: relative;
left: 0px;
}
A: Sounds like some other JS and/or CSS that's conflicting.
PS: not sure why you're specifing the style width and height both inline and in a CSS declaration. Only need one of them, although no harm in duplicating.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add an Array element to an NSMutableArray which already contains another array Values? I have three different NSMutableArray, lets say A,B,and C. I am adding the A array to the C and from array B I need only one element. So i need to add that element to the C array. Please give me an idea.
A: NSMutableArray *a;
NSMutableArray *b;
NSMutableArray *c;
//somewhere they get initialized...
[c addObject:a];
[c addObject: [b objectAtIndex:n]];
A: int index;
NSArray *A, *B;
NSMutableArray *C = [NSMutableArray arrayWithArray:A];
[C addObject:[B objectAtIndex:index]];
A: [C addObjectsFromArray:A];
id o = [B objectAtIndex:0]; // first item, or find the item you're looking for
[C addObject:o];
That should do it. This assumes you've already alloc'd and init'd or otherwise own a created NSMutableArray for all of A, B and C.
A: [c addObjectsFromArray:a];
[c addObject:[b objectAtindex:index];
A: Do it like this:
if (A.count != 0) {
for (int i=0; i<=A.count-1; i++) {
[C addObject:[A objectAtIndex:i]];
}
}
This will add all the object of array A in array C.
[C addObject:[B objectAtIndex:n]];
This insert an object of array B which pointed by index 'n' in array C.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wait for the result of an external webservice inside a task I need to write a bunch of tasks where every task needs to query an external web service. The web service always replies with a 202 ACCEPTED status and points in the Location header to the URI where the result can be polled. The time it takes for this web service to deliver the result can vary from 2 seconds to a minute. I was wondering whats the best approach to program my celery task. For now I send the request and start a while loop till I successfully poll the result, eg:
while True:
result = poll_webservice()
if result:
break
else:
time.sleep(5)
[ continue with the rest of the task ]
While this certainly works it seems very crude to me and also I block the celery worker till the result is polled. Is there any better approach?
A: You' re surely killing your resources. Just query your external web service and save the URI to be polled (use a cache or a db).Then you can have a periodic task that collects the results, if ready...
A: I'd be thinking about a celery task that polls the Location provided by the 202 response. If it is completed, then it processes it, else it re-queues itself (or a copy of itself) for some time later.
For bonus points, if you have lots of these tasks, you could increase the time between polls each time the response is not ready.
A: How about using task.retry ?
@task(max_retries=100)
def poll_webservice_task(url):
result = poll_webservice(url)
if result:
return result
poll_webservice_task.retry(countdown=5)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Complex Insert Stored Proc unsuitable for EF? I'm trying to build a new app on top of an existing DB.
User Credentials are retrieved via a separate system and return a GUID to the client app identifying the user, however this database uses a bigInt for user identification, to get around the problem that each SP in the DB uses a Mapping function to discover the local UserIdentity based on a GUID (userID) passed into the SP.
I'd like to use EF (.Net4.0) but I can't see a way to have the GUID passed into an SP to allow the DB mapping function to determine the local UserIdentity.
Mapping the SP for returning sets works OK, taking in a GUID, deriving the local UserIdentity and returning a recordset of 'pulse'. Updates and deletes are fine because they can use the Entities own Id value.
I guess my real question is "Is there a way to send a value to a stored procedure if the entity the SP is mapped to doesn't contain a property with that value?"
Here's a typical Table (the EF Entity has the same properties) and it's corresponding Insert SP.
CREATE TABLE [dbo].[Pulse](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[UserIdentity] [bigint] NOT NULL,
[Recorded] [datetime] NOT NULL,
[Value] [int] NOT NULL,
The insert SP looks like this
ALTER PROCEDURE [dbo].[Pulse_Insert] @userId uniqueIdentifier, @recorded datetime, @pulse int AS
BEGIN
SET NOCOUNT ON;
declare @userIdentity bigint
select @userIdentity = dbo.GUIDUserMapping(@userId)
insert into dbo.Pulse (UserIdentity, recorded, value)
values(@userIdentity,@recorded,@pulse)
END
A: It's not "unsuitable for EF," but if you use a proc for one operation (INSERT / UPDATE / DELETE / SELECT," the EF expects you to use procs for the other.
Wouldn't it be easier to use an INSTEAD OF trigger, here? Then the EF won't need to know about it at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mobile web app and offline access to audio files Is it possible to cache audio files for an offline access in a mobile web app using an HTML5 cache manifest ?
I also don't understand how size limitations works. (I read 5MB limit for iOS)
I don't find resources for that or best practices.
Thanks for your help
A: Yep - all files that are listed in the AppCache are cached by the browser, no matter if they're HTML files, JavaScript, or audio files. As long as they're explictly mentioned in the CACHE section, they'll be available offline.
For a good AppCache tutorial, check out http://www.html5rocks.com/en/tutorials/appcache/beginner/, which walks you through everything you should need.
The size limit prevents you from storing too much content on a users computer. In most cases, this isn't a problem if you're just storing HTML, CSS, JavaScript and some images, but in your case, if you're storing music, you potentially will hit that limit quickly. Most browsers limit you to storing a maximum of 5 megs (for all content), so you'll need to be mindful of that.
Chrome has a great set of tools for debugging appcache, as you're developing your site, open the Developer Tools and watch the console to see what happens.
A: Caching of audio files via a cache manifest file still does not work on Android phones up to version 5.1. I cannot speak for Android 6 or iPhones, iPads, since I don't have such devices. But I tried it on Android 5.1 and Android 3 with mp3 files with a size of only 2 Kb and they were not cached on these phones whereas 200 Kb js files were cached.
The current solution seems to be to encode the mp3 files with base 64 and to put it into js files which can be cached. A nice description of that can be found on http://grinninggecko.com/2011/04/09/html5-offline-audio/.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android WebVIew WebViewClient I have a webView in my application. When a person loads a url, the webpage is loaded in the browser and not in my application as the options menu is the default and not what I have assigned. How can I stop this and make it load in my webview and not the browser?
I tried webViewClient but it doesn't seem to work.
public class webView extends Activity {
WebView myWebView;
String url;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myWebView = (WebView) findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
url = "http://d.android.com";
myWebView.setWebViewClient(new WebViewClient()
{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
//url="http://google.com";
//view.loadUrl(url);
System.out.println("hello");
return true;
}
});
//Toast.makeText(this, "", Toast.LENGTH_SHORT);
myWebView.loadUrl(url);
}
/** Creteing an options menu**/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
//return true;
// TODO Auto-generated method stub
return super.onCreateOptionsMenu(menu);
}
A: If you never want to open an URL in a browser you have to return false in shouldOverrideUrlLoading
A: another solution could be :
myWebView.setWebViewClient(new WebViewClient());
by default the default web browser opens and loads the destination URL, to overwrite this behavior, call
webView.setWebViewClient(new WebViewClient());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Manipulating Excel Spreadsheats using C sharp I need to manipulate Excel Spreadsheets in C sharp .net 2010. The sum total of what I need to do is loop through an excel spreadsheet, add three columns to the left of the original columns based on some calculations from the other spreadsheets plus some other functions. What is the latest and greatest way to do this? Currently I am opening the excel spreadsheet and reading the records I need and printing them to screen with this function succefully:
public static void parseData(string excelFileName)
{
try
{
//Workbook workBook = _excelApp.Workbooks.Open(excelFileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//Worksheet wkSheet = (Worksheet)_excelApp.Worksheets[1];
//OLEObject oleObject = wkSheet.OLEObjects(Type.Missing);
using (OleDbConnection connection = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=No;IMEX=1\""))
{
connection.Open();
OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM [Sheet1$]", connection);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(ds);
}
foreach (System.Data.DataTable myTable in ds.Tables)
{
//xmlResultSet.Append("<TemplateData>");
foreach (DataRow myRow in myTable.Rows)
{
//Console.WriteLine("Ca0mon, please work :{0}", myRow);
Console.WriteLine("This thing better Work-- MRN: {0}| Patient Name: {1}| Address: {2}| CSSV: {3}", myRow[0], myRow[1], myRow[2], myRow[3]);
}
}
}
catch(Exception ex)
{
}
}
Any advice on how to approach this with the latest and greatest .net Tools? Thanks for your help.
A: You can also use OpenXML Framework to manipulate XML based Office documents. I think it's better to use this approach when you're sure that your clients only have Office 2007 or 2010.
The approach by using Microsoft.Office.Interop.Excel is dangerous because you link your code only to your office version. It's better to write your code using LateBinding and support multiple Office Versions.
The third approach, yours, is working but I think it's only practicable in simple scenarios.
A: With your Office installation, opt to install the Interop libraries. After you have done this, go to Add Reference, click on the COM tab, and add Microsoft Excel 12.0 Objects library.
Use the namespace using Microsoft.Office.Interop.Excel;
You should then go through a tutorial such as this one on MSDN.
A: You can use open source libraries such as NPOI https://npoi.codeplex.com/
Or paid products such as Aspose.Cells, Syncfusion Excel library, Softartisan Excel library etc. The advantage of these libraries is that you don't need MS Office installed on the server.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: same provisioning profile in sample app and the original I want to add in-app purchase to my application. For this I tried a sample code to check how it is working with my provisioning profile. But now, when I tried to do it in my application, an error occurs, and the error is,
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key viewController.'
This is because the other application's viewcontroller and appdelegate is missing in my application
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Server Client Program in C In server-client program server can listen for a number of clients.
listen(sockfd,5);
Does it mean that server can handle 5 clients at the same time. Or I have to use multi threading for that?
A: No, it means 5 clients can connect without you calling accept. After those 5 clients connect (actually slightly more than 5) new connections will fail.
The stack "accepts" connections (completes the handshake) without your intervention. So without you calling accept, if you use a sniffer you'll see successful handshakes. When you actually decide to accept(2) a connection, the stack simply gives it to you.
A: It means that their is a queue of up to 5 connections before connections fail unless you start accepting them. It is working looking at the Apache source code as I think it is an excellent template to implement a server.
A: I'd say yes, the second parameter gives you the maximum length of the queue of pending connections (from the man pages http://linuxmanpages.com/man2/listen.2.php ).
And no, there's no need for multi threading.
A: The above expression means that 5 clients are being queued and the 6th client will be ignored if the queue is full. you have to use accept() to read the queue so that others can connect. you can read this link http://linux.die.net/man/2/connect and further read about select() for advance socket programming. you can use multithreading if you want to serve more than 1 client at a time using fork().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to update an XML column with value from T-SQL built-in function? I have a MS SQL 2008 R2 Standard database. I have a column with varchar(250) data and a column with xml.
CREATE TABLE [dbo].[art](
[id] [int] IDENTITY(1,1) NOT NULL,
[idstr] [varchar](250) NULL,
[rest] [xml] NOT NULL,
CONSTRAINT [PK_art] PRIMARY KEY CLUSTERED ([id] ASC)
)
The problem is I want to insert result of a string function into into xml, in about 140 records. I've tried to use xml.modify with dynamically generated text.
UPDATE [pwi_new].[dbo].[art]
SET rest.modify('insert <e><k>link</k><v>'
+ my_string_function(idstr) + '</v></e> into (/root)[1]')
WHERE parent = 160
AND idstr LIKE '%&%'
GO
However, I've got this error:
The argument 1 of the XML data type method "modify" must be a string literal.
Any ideas? I'd like to avoid using temporal fields, external languages and executing TSQL from generated string? (I've heard of sql:variable and sql:column, but this is a result of tsql function.)
A: Not sure what you want to do here. You mention a TSQL function and if that is the replace & to & it is not necessary. It is taken care of by SQL Server for you.
A test using a table variable @art:
declare @art table(parent int, idstr varchar(250), rest xml)
insert into @art values
(160, '123&456', '<root></root>')
update @art
set rest.modify('insert (<e><k>link</k><v>{sql:column("idstr")}</v></e>) into (/root)[1]')
where parent = 160 and
idstr like '%&%'
select rest
from @art
Result:
<root>
<e>
<k>link</k>
<v>123&456</v>
</e>
</root>
Update
For the not so trivial situations you can use a cross apply to get the values you need into a column.
declare @art table(parent int, idstr varchar(250), rest xml)
insert into @art values
(160, '123&456', '<root></root>')
update a
set rest.modify('insert (<e><k>link</k><v>{sql:column("T.X")}</v></e>) into (/root)[1]')
from @art as a
cross apply (select reverse(replace(idstr, '2', '8')+'NotSoTrivial')) as T(X)
where parent = 160 and
idstr like '%&%'
select rest
from @art
Result:
<root>
<e>
<k>link</k>
<v>laivirToStoN654&381</v>
</e>
</root>
A: Assuming your table has a key:
DECLARE @sql NVARCHAR(MAX) = N'';
SELECT @sql += CHAR(13) + CHAR(10) + 'UPDATE [pwi_new].[dbo].[art] '
+ ' SET rest.modify(''insert <e><k>link</k><v>'
+ REPLACE(idstr,'&','&')
+ '</v></e> into (/root)[1]'') WHERE key_column = '
+ CONVERT(VARCHAR(12), key_column) + ';'
FROM [pwi_new].[dbo].[art]
WHERE parent = 160
AND idstr LIKE '%&%';
PRINT @sql;
--EXEC sp_executesql @sql;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to display data in android page using Accordion? I need to display details of a customer. I need to use Accordion to display the details. Can anybody suggest how to do that in android? Please help me regarding this.
A: It is possible. There are a lot of ways to do it. For example visit Android - accordion widget or http://android-puremvc-ormlite.blogspot.com/2011/07/android-simple-accordion-panel.html
A: There are many ways of doing it. One way is to define a linear layout. Add different TextViews to signify the heading and the body.
Or, you can use my Accordion View component for your purpose. It already has the different components defined like the heading and the body. To add the UI elements to the body, simply add them in the XML file, the way you add elements to a RelativeLayout.
<com.riyagayasen.easyaccordion.AccordionView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:visibility="visible"
app:isAnimated="false"
app:heading="This is a demo accordion"
app:isExpanded="true"
app:isPartitioned="true">
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Demo accordion text" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Test Button"
android:id="@+id/button_2"
android:layout_below="@+id/textView" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Test Button 2"
android:layout_below="@+id/button_2" />
</com.riyagayasen.easyaccordion.AccordionView>
This renders an accordion like this
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: CONCAT() result unexpectedly truncated when LEFT JOIN or GROUP BY is used in query A MySQL query containing a CONCAT() is truncating the result unexpectedly and returning only 5 of the anticipated 6 characters ('abcd2' instead of abcd21').
A trimmed down version of the actual query follows:
SELECT c.cid, c.club, c.crewno, CONCAT(c.club,c.crewno) crewcode
FROM `crews` c
LEFT JOIN `results` r ON r.rno=c.cid
GROUP BY c.cid;
The above query returns:
54321, 'abcd', 21, 'abcd2'
65432, 'abcd', 1, 'abcd1'
However, if the LEFT JOIN is removed and/or if the GROUP BY is removed then the CONCAT() works as expected and returns:
54321, 'abcd', 21, 'abcd21'
65432, 'abcd', 1, 'abcd1'
I have no idea what the problem is...
Additional information: the field c.club has type VARCHAR(4) and the field c.crewno has type TINYINT(1) UNSIGNED. The outcome is unaffected by whether or not the results table contains rows to join.
A temporary workaround is in place using TRIM(CONCAT(c.club,c.crewno,' ')), which returns the expected values:
54321, 'abcd', 21, 'abcd21'
65432, 'abcd', 1, 'abcd1'
However, rather than live with an ugly workaround, I'd prefer to learn what the underlying problem is and fix it properly!
Edit 1: if a three digit crewno is used then only the first digit is returned and to get all three using my workaround I need to add a double space TRIM(CONCAT(c.club,c.crewno,' ')).
Edit 2: SQL for setting up tables to demonstrate the problem follows. This is not production SQL but the minimum set of fields required to replicate the issue. (Note: when the results table is completely empty the CONCAT() works as expected but as soon as it has data the CONCAT returns the unexpected results)
CREATE TABLE IF NOT EXISTS `crewsmin` (
`cid` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`club` varchar(4) NOT NULL DEFAULT '',
`crewno` tinyint(1) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`cid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 PACK_KEYS=1;
INSERT INTO `crewsmin` (`cid`, `club`, `crewno`) VALUES
(12345, 'abcd', 0),
(12346, 'bcde', 5),
(12347, 'cdef', 13),
(12348, 'defg', 42),
(12349, 'efgh', 107);
CREATE TABLE `resultsmin` (
`rid` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
`cid` mediumint(8) unsigned NOT NULL DEFAULT '0',
`result` tinyint(3) NOT NULL DEFAULT '0',
PRIMARY KEY (`rid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 PACK_KEYS=1;
INSERT INTO `resultsmin` (`rid`, `cid`, `result`) VALUES
(1, 12345, 3),
(2, 12345, 1);
SELECT c.cid, c.club, c.crewno, CONCAT(c.club,c.crewno) crew
FROM crewsmin c
LEFT JOIN resultsmin r ON r.cid=c.cid
GROUP BY c.cid;
A: It seems that MySQL doesn't always do what you would expect when you use CONCAT with numeric values. You should use CAST on the numeric values:
CONCAT(c.club,CAST(c.crewno AS CHAR))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Count processed records of a table at the runtime of a script? I have a php script and its running and using two mysql tables for processing. Now i want to check that how many records has that script processed so far as my tables are having huge amount of data more than 90 lakhs. How can i check this at the same time when that script is running ??
A: I think you need to impement a streaming to achieve that. You can have more details about that here. I have checked APE and I think this can meet your needs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Wordpress theme code in simple PHP website I have a php website, in which I have used a lot of jquery plugins and accessing another database for header and footer contents dynamically.Now I have to add a blog for which I am checking wordpress. I can create the theme, but cannot access the header and footer dynamic contents from other DB. Is there some other to access the wordpress theme loop and other theme functions in my simple php pages? If no then any suggestion about other simple php blog script to add in the website with SEO support please.
Thank you
A: You can include files as you wish in a Wordpress template using include() or require(). Just put your PHP files with your template files and you should be good to go.
Here's how you can forego Wordpress entirely and display something from your old website, if your old website now lives inside of your template folder:
add_action('template_redirect', 'show_old_page');
function show_old_page() {
if( $_GET['old_page'] == 'pagename' ) {
include( TEMPLATE_PATH . 'oldpage.php' );
exit;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514615",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Collections via MXBeans I need to define and implement an MXBean interface. One of the methods would return a Collection. This seems to be not supported by MXBeans. I get an OpenDataException saying "Cannot convert type: java.util.Collection". If I change it to List or Set then it works.
I have not found any documentation saying that Collections are not supported and this is why I am asking you experts. Do I miss something ?
A: The javadoc of the MXBean annotation describes in detail the mapping rules. List, Set, SortedSet are supported but not Collection.
A: Specification does not say it supports Java collections:
The following list specifies all data types that are allowed as
scalars or as anydimensional arrays in open MBeans:
*
*java.lang.Void
*java.lang.Short
*java.lang.Boolean
*java.lang.Integer
*java.lang.Byte
*java.lang.Long
*java.lang.Character
*java.lang.Float
*java.lang.String
*java.lang.Double
*java.math.BigDecimal
*java.math.BigInteger
*java.util.Date
*javax.management.ObjectName
*javax.management.openmbean.CompositeData (interface)
*javax.management.openmbean.TabularData (interface)
You can use either arrays or TabularData.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Can i made a text file (.txt) from my database data and store in on any particular folder on server? i have a task assigned that i have to create a text file (notepad) from database table email which have more than 12000 rows and each row have a email-id,the table just have ID int identity primary key and email nvarchar(500) columns.
i have done this in asp.net by creating a text file on server and using stream writer write text file
now my question is
Is it possible to create text file of data from sql server 2008.because i am using that version
and one more thing i want one email-id in one row in .txt file ......
thanks buddies
A: You certainly can do it in .NET code, but if you want to do it in the SQL Layer, create an SSIS job, where you make the file and select what you need into it.
FYI: http://decipherinfosys.wordpress.com/2008/07/23/ssis-exporting-data-to-a-text-file-using-a-package/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In need for free flash "image player" do you know about some free flash web application which can load images directly from folder and animate them (as a video player)?
I mean, I have a folder with set of images and I want to animate them (switch one by one) in e.g. alphabetic order. Set of images will be randomly cumulate in time therefore I want to automatize this process and that's also why I can't use common video player which works with loading of video file.
Thanks a lot for replies.
A: How about Piecemaker?
It's cool, and opensource so its customisable
It loads the pictures from an xml file. More info at the link
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Facebook share shows correct share url when I use domain name and on ip address when I share something like
mydomain.com/mypage/xxx
facebook gives me correct share link
but when i try
111.222.333.444/mypage/xxx
it shares the home page of my site insted of the page I referred to
A: Sharing ip-based url's sounds like a bad idea. Why do you need to do that? As a workaround, you could use a URL shortener like bit.ly with your ip-based url. If you really need to share a URL with an IP address, log a bug with Facebook.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to remove items from Activerecord query resultset? I get a resultset from a Rails find query. I want to iterate over that resultset and depending on certain criteria drop records from that resultset before passing it on for further processing. The additional criteria are external to the data held in the database and hence I can't include them in the original 'find' query.
Note I don't want to delete any records from the database just remove them from the resultset.
Please can someone give me the code to do that.
A: set = MyObject.find(...)
set = set.reject{|s| ... }
or
set = set.select{|s| ... }
A: Use reject as in
Model.find_all_by_xxx().reject { |r| r.something? }
A: If some processing must be done in application code that SQL can not do, and the result must be a changed query object, re-querying the objects by id might be a (very memory inefficient) option.
needed_ids = Model.where(<some original query>).map{|r| r.something? ? r.id : nil }.compact
new_collection = Model.where(id: needed_ids)
A: You can use delete_at too:
irb(main):005:0> c = Category.all
Category Load (0.3ms) SELECT "categories".* FROM "categories"
=> [#<Category id: 1, name: "15 anos", description: nil, created_at: "2011-09-22 04:52:53", updated_at: "2011-09-22 04:52:53">]
irb(main):006:0> c.delete_at(0)
=> #<Category id: 1, name: "15 anos", description: nil, created_at: "2011-09-22 04:52:53", updated_at: "2011-09-22 04:52:53">
irb(main):007:0> c
=> []
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: PHP script run via cron does not connect to database I am trying to connect to mysql database in a PHP script run via cron job. It does not connect to the database somehow. I run the same script in my browser and everything works well. I use free BSD and following is the piece of code I try to run:
ini_set(max_execution_time,1200);
require_once("../settings.php");
$query = "insert into cron_log values(null, '". date("D d-m-Y") ."')";
mysql_query($query);
exec("convert /usr/local/www/demo/cron/test.pdf /usr/local/www/demo/cron/1.jpg");
If I run the above script via cron, it does nothing.
If I run above script in browser, it creates new row in table as well as creates 1.jpg.
If I remove the Database part and run it via cron, it creates the 1.jpg file.
What can be the possible cause and solution?
A: Note that CLI does not change the current working dir. Also cron does not set it. So doing your reqire_once call relative goes to a "random" location. Try a full path:
require_once(__DIR__."/../settings.php"); // PHP >=5.3
require_once(dirname(__FILE__)."/../settings.php"); // PHP <5.3
A: The most likely cause of this is that the script fails at the require_once("../settings.php"); line. This is because the working directory for the script when called through cron is not the same as the working directory when called through a browser.
Change ../settings.php to the full path, e.g. /path/to/settings.php to confirm that this is the problem.
It is also worth changing your cron line to php /path/to/script.php >> /path/to/logfile.txt 2>&1 so that logfile.txt will be filled with the output of your script. Make sure you turn display_errors on to catch any error messages!
A: My guess is that when you run it from cron you are not in the right directory and the settings.php file is not found; therefore the whole thing fails.
When you run it from cron, make sure the script cds to the appropriate directory so that settings.php is found using the relative path.
A: Any displayed error?
Be sure you are referring to correct folder for file "settings.php" printing "getcwd()".
When executing from cron script starts as located in "/"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to call JQuery CheckBox Changed Event inside a Jquery Accordion Header? Thanks for all your valuable responses to the questions that I have asked before, those suggestions helped me a lot.
I have one more question here.
I am using a JQuery accordion control in my page,and the accordion header contains a checkbox,
Based on the checkbox selection, I need to retrieve some date from the DB.
So, I need the checkbox changed event to get fired, but The event never gets fired for some reason. I am building the checkboxes dynamically through code.
Code:
string sa= '';
sa+= '<h3><a href=#><input type=checkbox runat=server OnCheckedChanged=chkScores_CheckedChanged id=chkScorecard' + i + '>Auckland Aces</input></a></h3><div><p>';
after creating checkboxes like above, I am adding them to the accordion div.
If you observe, I am giving OnCheckedChanged event, but that event is not firing.
Any idea..Why it is happening like that. I have been trying for past 6 hours on this, but no luck.
Can you guys please tell me if I am doing anything wrong, or is there any alternate approach to this.
Thanks and appreciate your feedback.
A: you write
OnCheckedChanged=chkScores_CheckedChanged
covert it to
OnCheckedChanged="chkScores_CheckedChanged"
EDIT:
true, this will not work because it an html input and the event oncheckedchanged, and this event is for asp:CheckBox and at runtime it will covert to input html with
onclick="javascript:setTimeout('__doPostBack(\'checkBox1\',\'\')', 0)"
so, if you want, you can add onclick javascript function to the input and in this function call the server side,
Example using JQuery:
Insert input checkbox:
var htmlTags = '<input id="checkboxID" type="checkbox" runat="server" onclick="CheckboxChange(this.id)" enableviewstate="true" />';
Add an Button to call it event:
<asp:Button ID="lbtnRefreshGV" runat="server" Text="" Height="0px" Width="0px" Style="visibility: hidden" OnClick="lbtnRefreshGV_Click"></asp:Button>
Add javascript function
function CheckboxChange(id) {
alert("In CheckboxChange");
alert(id);
$('#lbtnRefreshGV').trigger('click');
alert("Out CheckboxChange");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Crm dynamics custom action after clicking Invoice Paid In MS CRM When user clicks Invoice Paid, I need to notify external site that this invoice was paid
Is this possible to achieve this?
A: Yes. There are two separate ways I can think of to do this:
*
*Hide and recreate the Invoice Paid button via the CRM's RibbonXML and use your own javascript methods to change the status of the invoice to "Paid" and also talk to the external site. This would work so long as the only way the Invoice's status is changed to Paid is via the Invoice Paid button.
*When you click the invoice paid, the value of the StateCode property of the Invoice changes to "Paid", which is a value of 2. So, you can also register a plugin that fires on the Update message of the Invoice and check the before and after properties of the entity to see if the StateCode was not equal to "Paid" in the Pre Image and equal to "Paid" in the Post Image. This would be a server-side solution and would work no matter how the Invoice Paid action was triggered, and also gives you access to the .NET framework.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Entry selection list with tkinter How can I generate a normal selection list (like the "State" field in any HTML form for postal addresses) using Python tkinter? As illustrated below, the Listbox widget displays all the selections in a large box all the time, and if you reduce the height to 1, it does not expand the list when selected. The OptionMenu widget pops up the list correctly when selected, but doesn't display the current value in an Entry-like box when closed. And the Entry widget has the desired appearance but doesn't have an associated list of values.
Please don't tell me that tkinter can't do a basic form selection :-(.
from tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
items = ["Apple", "Banana", "Cherry"]
self.list = Listbox(frame, width=8, height=1)
for item in items:
self.list.insert(END, item)
self.list.pack(side=LEFT)
fruit = StringVar()
fruit.set(items[1])
self.menu = OptionMenu(frame, fruit, *items)
self.menu.pack(side=LEFT)
self.entry = Entry(frame, width=8)
self.entry.insert(0, items[2])
self.entry.pack(side=LEFT)
root = Tk()
app = App(root)
root.mainloop()
A: You're looking for a combo box widget, TTK provides this widget:
http://docs.python.org/dev/library/tkinter.ttk.html
http://www.tkdocs.com/widgets/combobox.html
A: What you are asking for is called a combobox. If you are using an old version of python (<2.7) you can use tix.ComboBox. For python 2.7 and beyond you can use ttk.combobox (link points to latest python 3.x documentation, but it is the same widget as in python 2.7).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Override Output Caching duration for Client caching I have a REST based WCF service which returns JSON data as response. To improve performance Output Caching is enabled with location as ANY and duration 1 hr.
I want to allow clients to cache the response for a period of 1 month while keeping the data cached on the server for only 1 hr, to do this i added the following lines in my code
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(30));
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Public);
but this value is overridden by the Output Caching profile value. How can i override the value set by the Output Caching profile
A: I did not test this, but it may help you: as anir writes here:
The headers for the HttpCachePolicy are added by asp.net after the caching module runs and so are not part of the response that is cached. If you want the headers to be cached, just use HttpResponse.SetHeader/AddHeader etc in your code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Connect app users with a mutual friend I'm looking to create an app that allows people to create connections with each other. I'd like to be able to recommend that somebody connects to another user who has authorised the app if they have a mutual Facebook friend. I do not need or really want to pull out any information about that mutual friend.
I see a lot of people here asking about pulling lists of friends of friends and how that isn't allowed as those people haven't authorised your app. This seems like a very sensible (and clearly deliberate) limitation set out by Facebook.
What I want to do is a little different. I want to pull specifically friends of friends who HAVE authorised the app. It would seem that if I have offline access for this, I can access the friends lists for all my users, just not take intersections of them. Am I right?
An example already doing something like this would be http://airbnb.com. I can go there, log in with Facebook, and then search for properties that are owned by people I share a mutual friend with. Must they be doing this by downloading the list of Facebook friends for each user, storing them in their database and then computing the intersection with the logged in user themselves? Given that all the permissions are there, this seems like a rather roundabout way of doing things compared to a nice FQL query.
I guess the issue is that you can only use FQL with one access token at once. Computing mutual friends of two app users would require permissions from both of them and hence two access tokens?
Any insight anyone can provide about how to do this would be greatly appreciated. I don't think it would be using any data a user hasn't given permission for but I can't quite figure it out.
A: There is mutual friend API that you can use. Given two facebook id's it returns the list of mutual friends, so you don't need to do any of what you have written.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Branching points(OpenCV,C++) I want to identify the branching points of the lightning in this image:
http://i.stack.imgur.com/PXujf.jpg
What I did first was threshold the image such that I get the lighning part
of the image and discard the backround. This is the result
http://i.stack.imgur.com/IYNTi.jpg
I used the threshold function in openCV and the resulting image is pretty much bad
as the quality is lost, the branches are no longer visible.
Ok, basically I have 2 problems:
*
*How can i properly segment the image such that the lightning part of the image is properly captured.
*How can I then, identify the branching points? For every branch point i want to
draw a red circle over it.
Thanking you in advance
A: Segmentation / thresholding:
I would give this a try.
They also had a NIPS2012 workshop (DISCML) paper on image segmentation that seems to handle quite elegantly thin elongated objects (like the lightnings in the picture).
Branching points:
Once you have a good mask you can use morphological operations to extract the branching points (Matlab code):
bw = myGoodSegmentation( img ); % replace with whatever segmentation/thresholding that works best for you.
tbw = bwmorph( bw, 'skel', inf );
[y x] = find( bwmorph( tbw, 'branchpoints' ) ); % get x,y coordinates of branch points
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get coordinates (CGRect) for the selected text in UIWebView? I have simple UIWebView with loaded html.
I want to show the PopoverView pointed to the selected text.
I can get the menuFrame of the UIMenuController and use its rect, but the result isn't as accurate at the corners of the screen as I need.
I can calculate the screen size and get menuFrame rect and then I can suppose where the selection may be found, but I want exactly know where is the selected text.
Is it generally possible?
A: You can use the javascript function getBoundingClientRect() on the range object of the selected text.
This is how I do it:
function getRectForSelectedText() {
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var rect = range.getBoundingClientRect();
return "{{" + rect.left + "," + rect.top + "}, {" + rect.width + "," + rect.height + "}}";
}
and in a category on UIWebView, you could use it like such:
- (CGRect)rectForSelectedText{
CGRect selectedTextFrame = CGRectFromString([self stringByEvaluatingJavaScriptFromString:@"getRectForSelectedText()"]);
return selectedTextFrame;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: select count of field by group I have a table with the following table:
id | score | type
1 | 1 | "a"
2 | 4 | "b"
3 | 2 | "b"
4 | 53 | "c"
5 | 8 | "a"
I need to select the count of score based on the type. So my results will be:
totalScore | type
9 | "a"
6 | "b"
53 | "c"
I tried both DISTINCT and GROUP BY by neither seemed to work. The SQLs I tried:
SELECT * , COUNT( `score` ) AS totalScore
FROM `table`
GROUP BY `type`
and
SELECT DISTINCT `type`, COUNT(score) as totalScore FROM `table`
But these don't seem to work.
Can anyone help?
Hosh
A: This should work...
SELECT sum(score) AS total FROM table GROUP BY type
A: select sum(score),type from table group by type
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: StartActivityForResult I have 4 activities A,B,C,D. I need to start activity 'A'(It Consists of a textview,button) initially and from activity 'A' i need to start activity 'B'(With the help of a button).
Now,From 'B' i need to start 'C' & 'D' activities (Condition: Button1(Activity 'B') is hit then it should start Activity 'C' , Button2(Activity 'B') is hit then it should start Activity 'D' ).
--Activity 'C' consists of a EditText & a Button.
--Activity 'D' consists of a EditText & a Button.
Here when i enter text in Edit text of Activity 'C' & 'D' and hit the Button,the result is such that the entered text should appear in TextView of Activity 'A'.
Iam a Beginner to Android,Ple help me in getting through this.
Thanks in Advance.
A: Try this:
make a static variable in Activity 'C':
public static String text="";
then read EditText data into String in OnClick of button :
in your Activity'C' on button click:
text=edittext.getText().toString();
Intent i=new Intent(ActivityC.this,ActivityA.class)
startActivity(in);
finish();
In Activity 'A'
set this text value in OnResume method:
Protected void OnResume()
{
super.OnResume();
textview.setText(Activity'c'.text)
}
this may help you.ask any doubts
A: So you are wanting to pass data from Activity C, or D back to A at some point? Use an application class (google it) and set a variable from your C or D Activities, then call said variable when you get back to A and display the text.
A: Using `startActivityForResult() you can do like this :
*
*startActivityForResult() for activity B.
*startActivityForResult() for activity c.
*On button hit in activity c finish the activity after setting the data.
*now you will get call in onActivityResult() in activity B. repeat the process of setting data in B and finish the activity.
*now you will get call in onActivityResult() in activity A, you got the data now use it.
same process will be for activity D.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: friend function, cpp We had an assignment in school implementing a Matrix class that overloads all arithmetic operators. What I did was to (for example) define += as a member function, and then define + as a non-member function that uses += function (both in the same file, but + outside the class).
The school staff did something similar, only they've declared '+' as a friend function (and also used the implementation of +=).
Since both implementation work perfectly, I am trying to understand what does a friend function gives me that a non member function does not?
When should I prefer each over the other?
Thanks!
Yotam
A: It is preferable not to declare functions friends, if they can be implemented in terms of the class's public interface (such as operator+ in terms of member operator+=.
Somehow with operators sometimes people tend to assume that when implemented as free functions they need to be automatically declared friends. E.g you might hear that operator<< cannot be implemented as a member function (because the left-hand operand is an ostream), hence it needs to be a free friend function. In reality it only needs to be a friend if it needs access to private/protected members and member functions.
(I suspect that might be because overloaded operators, due to their special call syntax, don't feel like normal functions and seem to have some kind of magical bond with its operands that needs to be expressed in the class definition.)
A: The friend version has access to the members of your class. A plain non-member does not. This can be useful.
A: By reading the definition of a Friend Function you will get the answer to your question.
friend function is used in object-oriented programming to allow access to private or protected data in a class from the outside. Normally, a function that is not a member of a class cannot access such information; neither can an external class. Occasionally, such access will be advantageous for the programmer. Under these circumstances, the function or external class can be declared as a friend of the class using the friend keyword. The function or external class will then have access to all information – public, private, or protected – within the class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: not able to get the id of the word from sqlite android I am getting the word from the text view and passing to DB to get its id, i am able to get the word but not able to get the id.
please look at my code and tell me what is the mistake and help me correct it
public void onClick(View v) {
// TODO Auto-generated method stub
TextView txtView = (TextView) v.findViewById(R.id.rightanswer);
//Log.d("word " + txtView.getText(), "word");
String word = txtView.getText().toString().trim();
String words[] = new String[3];
words = word.split(":");
String selectedword = words[1].toLowerCase().trim();
Log.d("Word", "|" + selectedword + "|");
getWordId(selectedword);
}
};
private int getWordId(String word) {
// String selection = "Word=" + word;
int id = -1;
String query = "Select wordId from Words WHERE Word ='"+word+"'";
//Log.d("Query ::" + query + "::", "Query");
Cursor c = executeQuery(query);
Log.d("Row Count", "" + c.getCount());
if (c.moveToFirst()) {
do {
id = c.getInt(c.getColumnIndex("wordId"));
Log.d("Id is:", "" + id);
Intent intent = new Intent(getApplicationContext(), Word.class);
intent.putExtra("wordid", id);
intent.putExtra("page", "QuizResult");
startActivity(intent);
finish();
} while (c.moveToNext());
}
c.close();
return id;
}
i get the row id as 0. please help me
A: To get the row number from the database you should be getting the unique key (_id). Is wordId your unique key in the database? I althought thought it was important to android to name the column _id for whatever reason.
A: I bet that wordid is not INTEGER PRIMARY KEY therefore it returns 0. Check it at first.
Every row in table has it's own id with names rowid, oid, or _rowid_. Use it instead if you just need to distinguish rows. Or debug database in shell.
adb -e shell
cd /data/data/your.app.package.name/databases
sqlite3 database
.headers on
select * from words;
Above works on emulator and rooted devices
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create Django Apps with life cycle? We are developing a huge application on Django contains lot of apps with dependency in between. We want to implement a life-cycle(install,onload,unload,uninstall) for apps, since it is must have feature(after deployment); is there any frameworks or packages existed ?
What is the best way to implement this ?
Thanks
A: It looks like you want to replicate features of other popular languages and frameworks in Django. Reading your post OSGi springs to mind.
The problem is that 99,9% of all Django applications are not "dynamic" in the sense that apps can be installed, loaded, unloaded and uninstalled at runtime. That's not how Django applications work. You install an app before the application is started. To uninstall an app you shutdown your application and remove it from the INSTALLED_APPS (settings.py) list. Since this does not happen at runtime there won't be any signals, callbacks or other things to the Django application.
But there are certain things you can do to at least meet some of your needs. From the top of my head I think you could do something like a before_install and after_install "signal" (not in the Django signal sense).
To do so you could write some sort of "controller" or "registry" app. One for the before_install and one for after_install code. Those apps would sit before and after the rest of your apps in INSTALLED_APPS.
e.g.
INSTALLED_APPS = (
# all the Django apps and other third party apps
'before_install_controller_app',
# all your in-house apps
'after_install_controller_app',
)
These two apps iterate all the apps listed under INSTALLED_APPS. They try to import a specific python file from each of the apps. If the file is not in the app (because it's a Django or third-party app) nothing happens. But if there is a file, let's call it before_install.py and after_install.py it is loaded and the code inside is run.
The same would apply for the after_install_controller_app app, but it would look for after_install.py.
It's basically the same mechanism Django uses for it's admin. The admin app iterates all the apps and tries to import admin.py. That's why you should at first have a look at the corresponding Django source. It's pretty straight forward and easy to understand. I did something similar and it worked like a charm.
There are of course some limitations. For instance:
*
*The before_install.py code would not have access to database models of the underlying app because they may be a) not have been created yet (see order of the apps) or b) out of date.
*I am sure there are many more, but at the moment I don't find any more.
On last thing:
Don't try to hard to map/port features/paradigms of one programming language/frameworks to another. There might be fundamental differences that render good approaches in one language/framework useless in another. That certainly seems the case here.
If you have further questions I'd be glad to help if I can.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to create draggable widgets? Background
I am tasked with developing the front-end to an analytics product that presents the information to the user in a customizable dashboard like the one used by Google Analytics:
- Dashboard is comprised of draggable widgets arranged in a grid layout
- Widgets have a drag handle which can be clicked by the user to start dragging
- Widgets can be re-ordered by dragging and dropping the widget
Question
Part 1. Using jQuery (or any other open source Javascript API) can anyone explain to me how such a feature is implemented, from a high level overview.
Part 2. Can you recommend any resources for me to read that may be relevant to implementing this feature, or any foreseeable related features? (books, links, api docs, tutorials)
A: EDIT This one looks even better and more maintained! GRID by UberVU
Next one on the list is gridster.js
PS: I know this is an old thread but since this question is the first hit in Google I think its worth listing some newer libraries.
A: You can easily implement this.
You will get required info from
http://net.tutsplus.com/tutorials/javascript-ajax/inettuts/
and
http://james.padolsey.com/javascript/inettuts-with-cookies/
A: First what comes to head is jQuery UI.
A: Use HTML 5
http://html5doctor.com/native-drag-and-drop/
A: You can find a lot of info here:
http://jqueryui.com/demos/draggable/
A: *
*Use jQuery, and get on the Demo & Doc page to see how D&D is being used.
*
*http://jqueryui.com/demos/draggable/
*http://jqueryui.com/demos/droppable/
*If you wanna dive into a Widget Page/Dashboard architecture, and would like to see how others did it, take a look at Omar AL Zabir's book
*
*http://www.amazon.com/Building-Web-2-0-Portal-ASP-Net/dp/0596510500/ref=ntt_at_ep_dpt_1
A: I am pretty sure this one is going to make you happy!
http://net.tutsplus.com/tutorials/javascript-ajax/inettuts/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Android - Problem with ViewFlipper I am making a game that requires multiple views within an Activity, and i decided to use Viewflipper to do.
The thing is. I need to have 3 views in in the viewflipper, and the LAST view will transfer back to the first one.
My problem is that the buttons are acting weird, and they are either not going to the next, or skipping the third view. I tried to put vf.setDisplayedChild(R.Id.gamescreen1); at the last view but then the whole thing breaks down.
Thanks for all answers in advance, i have been stuck with this problem for DAYS! and yes, i know that i am a noob :(
[SOURCECODE]
public class GameActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_game);
final ViewFlipper vf = (ViewFlipper) findViewById(R.id.ViewFlipper01);
//SCREEN 1
Button btnSTART = (Button) findViewById(R.id.btnSTART);
//SCREEN 2
Button btnALT1 = (Button) findViewById(R.id.btnALT1);
Button btnALT2 = (Button) findViewById(R.id.btnALT1);
//SCREEN 3
Button btnALT3 = (Button) findViewById(R.id.btnALT1);
Button btnALT4 = (Button) findViewById(R.id.btnALT1);
//screen 1
btnSTART.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
vf.showNext();
}
});
//screen 2 // Either button will go to view 3
btnALT1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
vf.showNext();
}
});
btnALT2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
vf.showNext();
}
});
//screen 3 // Either button will go back to view 1
btnALT3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
vf.showNext();
}
});
btnALT4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
vf.showNext();
}
});
}
}
[XML]
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gamescreen1" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent" android:orientation="vertical" android:layout_height="435dp" android:gravity="top">
<ListView android:layout_width="fill_parent" android:id="@+id/list1" android:layout_height="184dp" android:layout_weight="0.53"></ListView>
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:orientation="vertical" android:gravity="bottom|center" android:layout_height="wrap_content">
<Button android:layout_height="wrap_content" android:id="@+id/btnSTART" android:layout_width="200dp" android:text="@string/btnstart"></Button>
</LinearLayout>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gamescreen2" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent" android:orientation="vertical" android:weightSum="1" android:gravity="top" android:layout_height="326dp">
<ListView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/list2"></ListView>
</LinearLayout>
<LinearLayout android:orientation="vertical" android:gravity="bottom|center" android:layout_width="match_parent" android:layout_height="match_parent">
<Button android:text="alt1" android:layout_width="200dp" android:layout_height="wrap_content" android:id="@+id/btnALT1"></Button>
<Button android:text="alt2" android:layout_width="200dp" android:layout_height="wrap_content" android:id="@+id/btnALT2"></Button>
</LinearLayout>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gamescreen3" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
<LinearLayout android:layout_width="match_parent" android:orientation="vertical" android:weightSum="1" android:gravity="top" android:layout_height="326dp">
</LinearLayout>
<LinearLayout android:orientation="vertical" android:gravity="bottom|center" android:layout_width="match_parent" android:layout_height="match_parent">
<Button android:text="alt3" android:layout_width="200dp" android:layout_height="wrap_content" android:id="@+id/btnALT3"></Button>
<Button android:text="alt4" android:layout_width="200dp" android:layout_height="wrap_content" android:id="@+id/btnALT4"></Button>
</LinearLayout>
</LinearLayout>
A: try this
flipper.setDisplayedChild(1);
.
.to
.
flipper.setDisplayedChild(3);
if(flipper.getCurrentView() == 3)
{
flipper.setDisplayedChild(1);
}
A: setDisplayChild takes an integer parameter that is the zero based index of the child to display NOT the id of the child to display. A bit confusing I know.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Disabling layout for AJAX module How can I disable the layout for AJAX module?
I have crated the module and tried to add the entry to view.yml referring to the module as ajax:, but it didn't work.
Currently, I use $this->setLayout(false), which is not really nice...
Also, according this doc, view.yml is deprecated.
A: You shouldn't need to. XHR requests are automatically rendered without layout.
A: About your question roman about how symfony recognize that it's a XHR. there is a function that you can use in symfony that tests the requests against that. It goes like the following
$request->isXmlHttpRequest()
this return true if the request came from an ajax call. very helpful function when making an action for ajax calls and when you want it to only respond to ajax calls.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: phonegap android ajax call not appending data I'm new to phonegap and android. I am trying to create a project which fetch pages/data from webserver but it is not working. The code i have used is shown below, facing problem in appending data from ajax call.
when application starts in emulator it shows the alert with all data fetched from local server but its not appending to #resultBlock
here's my code
<!DOCTYPE HTML>
<html>
<head>
<title>PhoneGap</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="jquery.mobile-1.0b3.min.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.mobile-1.0b3.min.js"></script>
<script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js"></script>
<script>
function onDeviceReady() {
$('#resultBlock').html('Loading');
$.ajax({
url: 'http://192.168.1.2/user/welcome/',
success: function(data) {
$('#resultBlock').html(data);
alert(data);
}
});
}
$(document).ready(function() {
document.addEventListener("deviceready", onDeviceReady, true);
});
</script>
</head>
<body >
<div data-role="page" id="page">
<div data-role="header">
<h1>Page One</h1>
</div>
<div data-role="content">
<h3>Result</h3>
<p id="resultBlock"></p>
</div>
<div data-role="footer">
<h4>Page Footer</h4>
</div>
</div>
</body>
</html>
Thanks
A: hake sure the js files are included correctly and that the path is correct. then use
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://192.168.1.2/user/welcome/functions.php',
data: { get_param: 'candidates' },
dataType:'json',
success: function (data) {
$('#resultBlock').html(data);
alert(data);
},
error: function () {
console.log(XMLHttpRequest.errorThrown);
}
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Condition in read() function CakePHP In CakePHP function edit I use read() function as:
$this->data = $this->Article->read(null, $id);
It brings all fields of $id. Now, what I am trying to tweak to give one more condition in read() to get articles only if user logged in is related to it.
eg:
$this->Article->user_id = $user_id;
$this->Article->id = $id;
$this->Article->read();
And obviously it want work as read() brings data only w.r.t. $id (primary key).
My question:
*
*Is there any way to tweak read function with condition more than $id ? Because it will just need to add a one line in all my controllers if it works ?
*Or I have to use long code of find() function to get is the only option ?
Any best solution will be appreciable.
A: If you really must do thise, you could use OOP techniques to override the way the core method works.
Just copy the Model::read() method to your AppModel class and make the changes necessary.
A: You have to use find() if you want to make the search conditionally. Another option is to read the data only if the conditions hold:
$this->Article->id = $id;
if( $this->Article->field( 'user_id' ) == $user_id ) {
$this->Article->read();
}
(read() populates $this->data automatically.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to get a SPNEGO / Kerberos Session key -and implement HTTP Authentication:Negotiate on my own client I was recently exposed to a new authentication method i had no idea of.
After reading a bit and researching to understand it,I understood it has something to do with SPNEGO, or maybe it is just spnego.
Im running windows xp on a large network, when my browser opens it automatically
connects to a web-service in the network, which requires authentication:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Negotiate
then my browser sends automatically (along with more headers ofcourse):
Authorization: Negotiate (encrypted string).
I concluded this Handshake uses the SPNEGO protocol.
What i need to do, is to create my own client (actually,its a bot that uses this webservice that requires that authentication). I Need to get that encrypted string (exactly like my browser gets it, probably by using some SPNEGO protocol) without any user interaction (again, as my browser).
the thing is, that i don't have enough time to study the spnego protocol and how to implement one.
I'm using c/c++, but if i have no option c# would be okay as well.
Are there any functions / classes / codes or maybe even good tutorials to help me implement it shortly?
A: curl works with Kerberos/spnego. I'm not sure how well this functionality works on Windows, you should try and see. It works well enough on Linux. You can look at the source to see how it is done.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery failure in javascript_include_tag during migration to Rails 3.1 I am trying to migrate an application from Rails 3 to 3.1 and having problems with jQuery. The error is bellow. If I remove 'javascript_include_tag "application"' all works fine (with no javascript), so something javascript-related is missing.
Showing C:/.../app/views/layouts/application.html.erb where line #7 raised:
couldn't find file 'jquery'
(in C:/.../app/assets/javascripts/application.js:7)
Extracted source (around line #7):
4: <title><%= @title unless @title.blank? %></title>
5: <!-- %= render 'layouts/stylesheets' % -->
6: <%= stylesheet_link_tag "application" %>
7: <%= javascript_include_tag "application", :debug => true %>
8: <%= csrf_meta_tags %>
9: </head>
10: <body>
In my Gemfile I have the entry for jquery-rails:
source 'http://rubygems.org'
gem 'rails', '3.1.0'
gem 'jquery-rails'
....
In application.js:
// This is a manifest file .......
//
//= require jquery
//= require jquery_ujs
//= require_tree .
//
As far as I know that it is the only requirement for working with jQuery in Rails 3.1.
What am I missing?
A: //= require jquery
Is a new directive in Rails 3.1, which mentions the jquery.js file required.
In Rails 3.1, the jquery.js and jquery_ujs.js files are located inside the vendor/assets/javascripts directory contained within the jquery-rails gem.
Also, did you do a bundle install ?
More about the asset pipeline at http://guides.rubyonrails.org/asset_pipeline.html.
More about using Javascript in Rails at http://guides.rubyonrails.org/asset_pipeline.html#manifest-files-and-directives.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Help to solve Apple's crash-reports logs my app was rejected for a crash that i didn't notice on the simulator.
Here are the logs, (already imported on XCode > Organizer ) can someone help me with this?
Incident Identifier: 88AD655D-3540-419C-A883-EFCEEB8CFE16
CrashReporter Key: 6b6d313765323bdd8ad35c9b99c487d423fd70ab
Hardware Model: iPad2,2
Process: MyApp [7983]
Path: /var/mobile/Applications/F9B518BA-1F72-449C-B584-45E77ECB9CB8/MyApp.app/MyApp
Identifier: MyApp
Version: ??? (???)
Code Type: ARM (Native)
Parent Process: launchd [1]
Date/Time: 2011-09-21 17:14:13.004 -0700
OS Version: iPhone OS 4.3.5 (8L1)
Report Version: 104
Exception Type: EXC_CRASH (SIGABRT)
Exception Codes: 0x00000000, 0x00000000
Crashed Thread: 0
Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 libsystem_kernel.dylib 0x361eda1c 0x361dc000 + 72220
1 libsystem_c.dylib 0x322df3b4 0x322ac000 + 209844
2 libsystem_c.dylib 0x322d7bf8 0x322ac000 + 179192
3 libstdc++.6.dylib 0x32729a64 0x326e5000 + 281188
4 libobjc.A.dylib 0x336b606c 0x336b0000 + 24684
5 libstdc++.6.dylib 0x32727e36 0x326e5000 + 273974
6 libstdc++.6.dylib 0x32727e8a 0x326e5000 + 274058
7 libstdc++.6.dylib 0x32727f5a 0x326e5000 + 274266
8 libobjc.A.dylib 0x336b4c84 0x336b0000 + 19588
9 CoreFoundation 0x35b4848a +[NSException raise:format:arguments:] + 62
10 CoreFoundation 0x35b484c4 +[NSException raise:format:] + 28
11 UIKit 0x32a51a4c -[UINib instantiateWithOwner:options:] + 1104
12 UIKit 0x32a52e02 -[NSBundle(UINSBundleAdditions) loadNibNamed:owner:options:] + 86
13 UIKit 0x329cc5e2 -[UIViewController _loadViewFromNibNamed:bundle:] + 30
14 UIKit 0x32999f9e -[UIViewController loadView] + 74
15 UIKit 0x328e1b1e -[UITableViewController loadView] + 46
16 UIKit 0x3287eeb8 -[UIViewController view] + 24
17 UIKit 0x3288d5e8 -[UIViewController contentScrollView] + 16
18 UIKit 0x3288d458 -[UINavigationController _computeAndApplyScrollContentInsetDeltaForViewController:] + 24
19 UIKit 0x3288d356 -[UINavigationController _layoutViewController:] + 18
20 UIKit 0x3288ce2e -[UINavigationController _startTransition:fromViewController:toViewController:] + 374
21 UIKit 0x3288cc3c -[UINavigationController _startDeferredTransitionIfNeeded] + 176
22 UIKit 0x3288cb80 -[UINavigationController viewWillLayoutSubviews] + 8
23 UIKit 0x3288cb1c -[UILayoutContainerView layoutSubviews] + 132
24 UIKit 0x3284d5f4 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 20
25 CoreFoundation 0x35ab5efc -[NSObject(NSObject) performSelector:withObject:] + 16
26 QuartzCore 0x309ffbae -[CALayer layoutSublayers] + 114
27 QuartzCore 0x309ff966 CALayerLayoutIfNeeded + 178
28 QuartzCore 0x30a051be CA::Context::commit_transaction(CA::Transaction*) + 206
29 QuartzCore 0x30a04fd0 CA::Transaction::commit() + 184
30 QuartzCore 0x309fe04e CA::Transaction::observer_callback(__CFRunLoopObserver*, unsigned long, void*) + 50
31 CoreFoundation 0x35b1fa2e __CFRUNLOOP_IS_CALLING_OUT_TO_AN_OBSERVER_CALLBACK_FUNCTION__ + 10
32 CoreFoundation 0x35b2145e __CFRunLoopDoObservers + 406
33 CoreFoundation 0x35b22754 __CFRunLoopRun + 848
34 CoreFoundation 0x35ab2ebc CFRunLoopRunSpecific + 224
35 CoreFoundation 0x35ab2dc4 CFRunLoopRunInMode + 52
36 GraphicsServices 0x308a7418 GSEventRunModal + 108
37 GraphicsServices 0x308a74c4 GSEventRun + 56
38 UIKit 0x32876d62 -[UIApplication _run] + 398
39 UIKit 0x32874800 UIApplicationMain + 664
40 MyApp 0x00002622 0x1000 + 5666
41 MyApp 0x000025ec 0x1000 + 5612
Thread 1:
0 libsystem_kernel.dylib 0x361ee3ec 0x361dc000 + 74732
1 libsystem_c.dylib 0x322e06d8 0x322ac000 + 214744
2 libsystem_c.dylib 0x322e0bbc 0x322ac000 + 215996
Thread 2 name: Dispatch queue: com.apple.libdispatch-manager
Thread 2:
0 libsystem_kernel.dylib 0x361eefbc 0x361dc000 + 77756
1 libdispatch.dylib 0x31d33ed4 _dispatch_mgr_invoke + 744
2 libdispatch.dylib 0x31d34f3a _dispatch_queue_invoke + 70
3 libdispatch.dylib 0x31d344ec _dispatch_worker_thread2 + 228
4 libsystem_c.dylib 0x322e058a 0x322ac000 + 214410
5 libsystem_c.dylib 0x322e0bbc 0x322ac000 + 215996
Thread 3:
0 libsystem_kernel.dylib 0x361ee3ec 0x361dc000 + 74732
1 libsystem_c.dylib 0x322e06d8 0x322ac000 + 214744
2 libsystem_c.dylib 0x322e0bbc 0x322ac000 + 215996
Thread 4 name: WebThread
Thread 4:
0 libsystem_kernel.dylib 0x361ebc00 0x361dc000 + 64512
1 libsystem_kernel.dylib 0x361eb758 0x361dc000 + 63320
2 CoreFoundation 0x35b202b8 __CFRunLoopServiceMachPort + 88
3 CoreFoundation 0x35b22562 __CFRunLoopRun + 350
4 CoreFoundation 0x35ab2ebc CFRunLoopRunSpecific + 224
5 CoreFoundation 0x35ab2dc4 CFRunLoopRunInMode + 52
6 WebCore 0x35d8327e _ZL12RunWebThreadPv + 382
7 libsystem_c.dylib 0x322df30a 0x322ac000 + 209674
8 libsystem_c.dylib 0x322e0bb4 0x322ac000 + 215988
Thread 0 crashed with ARM Thread State:
r0: 0x00000000 r1: 0x00000000 r2: 0x00000001 r3: 0x00000000
r4: 0x3f42b48c r5: 0x00000006 r6: 0x0054f56c r7: 0x2fdfd3e8
r8: 0x3f1b2964 r9: 0x00000065 r10: 0x00537f10 r11: 0x368d9d97
ip: 0x00000148 sp: 0x2fdfd3dc lr: 0x322df3bb pc: 0x361eda1c
cpsr: 0x000f0010
Apple said
We found that your app crashed on iPad 2 running iOS 4.3.5, which is
not in compliance with the App Store Review Guidelines.
Specifically, we noticed that your app crashes when selecting the
"Favorites" tab.
But to me, Favorites Tab works fine (even if i don't have an iPad, i work through the simulator)
Thanks
A: This appears to be the same problem with the SDK bug in 4.3.5 related to the method loadNibNamed.
See the accepted answer to this question for temporary resolution until Apple release a fix: UIImageView initWithCoder - unrecognized selector sent to instance... iOS 5 beta SDK
The question relates to iOS 5 beta. However, I believe it is the same ongoing problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Actions: Create and View button disappeared in cugar crm in custom modules I have added several new custom modules in SugarCRM via the module builder. Now the problem is, that in the menu tab under Actions, Create ... and View ... disappeared. Is it possible getting these two buttons back again? Thanks for help!
Normally and still in default modules it looks like this:
When opening e.g. Accounts:
Actions: | Create ACCOUNTS | View ACCOUNTS | Import ACCOUNTS
In all custom modules it looks like this:
When opening e.g. Suppliers (custom created module):
Actions: | Import
A: Is there a Menu.php file in your module? If so what is the contents?
Try this on 6.3.0RC2 as well. Updating should resolve the issue.
If you still see the problem, can you add a bug for this at http://bugs.sugarcrm.com
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I fix the indentation in a facebook like-box? I can go to facebook and get the code for a "like box". Very handy.
Problem is, the display of this box is lame. it's not consistent. The first article in the 'stream' is displayed with this sort of indentation:
The next article in the stream is displayed with different (lame) indentation.
This is in the same likebox, I merely scrolled down.
The effect is not limited to the stream for "Facebook Platform". I've seen it in the Likebox for other streams as well.
I'd like to style the box, to try to make the indentation consistent, but it appears to be rendered as an iframe, which (I think) means I cannot style it because of the S.O.P.
How can I fix this?
Is there a workaround to display a likebox in a div that is not, eventually, an iframe?
EDIT: bug logged: http://developers.facebook.com/bugs/237053466346453
EDIT: I compared the fb:fan control and the likebox control. With the fb:fan thing, it is possible to provide custom CSS to style the contents. (There are some caveats.) I set the width and margins of the text, and also erased the actorName, which is the same for every post. This is the result:
The left side is produced with this code:
<fb:fan profile_id='19292868552' width='292'
connections='0' show_faces='false' stream='true' header='false'
css='http://example.org/fb/customfanbox.css?_=6392'></fb:fan>
The right side is produced with this:
<iframe src="//www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fplatform&width=292&colorscheme=light&show_faces=false&border_color&stream=true&header=false&height=525"
scrolling="no"
frameborder="0"
style="border:none; overflow:hidden; width:292px; height:525px;"
allowTransparency="true">
For the left-hand-side, if you don't want the fb:fan element, you can use an iframe that points to fan.php, like this:
<iframe src='http://www.facebook.com/plugins/fan.php?connections=0&css=http%3A%2F%2Fexample.org%2Ffb%2Ffb%2Fcustomfanbox.css%3F_%3D0292&id=19292868552&locale=en_US&sdk=joey&stream=true&width=292&height=560'
scrolling="no"
frameborder="0"
style="border-bottom:1px grey solid; overflow:hidden; width:292px; height:525px;"
allowTransparency="true">
A: You could try using the older fan box plugin which offered loading an external CSS file. I don't know if it still works. If so, it could stop working any moment.
You certainly are not the only one with such problems. I suggest you file a feature request / vote for an existing one.
A: You cannot style pages form other domains.
That would also make XSS possible.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android Fluid Yet Restricted Layout I have a need where I need to show 3 lines of tags. Tags are just android button elements with some background and padding.
So assume my web service returns 7 tags and their size is unknown unless they are added to the view. Once they are added to the view they result into 4 lines of buttons. You can see in this picture.
Without Text
With Text
Now I have accomplished this so far using that custom RowLayout and it works. I can just add any number of buttons to that layout and it draws them fluidly. But what I want now is, I give the RowLayout, 7 tags and it decides how many buttons it can fit into 3 lines and put them there and have 2 functions there
*
*nextThree();
*prevThree();
Now nextThree() function should be called to ask the RowLayout to draw next series of buttons into 3 lines and remove previous one which are already drawn. And prevThree() would be called if the nextThree() was called to move back to those 3 lines of tags. And if nextThree() has 0 buttons next to show then goto the start to show first 3 lines of buttons so it works in a loop.
Another issue is these buttons are not responding to button.setGravity(Gravity.CENTER_VERTICAL); as you can see in the picture above.
Can you give me pointers to solve them?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UPDATE MySQL table that contains comma (,) in the field Imported into a MySQL table is a report that contains a user generated field value.
Possible field values include:
*
*PREFIX,1234
*PREFIX1234
*PREFIX_1234
All the example values represent the same thing but are typed in differently (I don't control the input system).
I would like to have all the values use this format:
*
*PREFIX_1234
I was trying to run this PHP query against the database to fix the comma values:
$sql = "UPDATE tableA
SET unit_number = replace(unit_number,'FRGN,','FRGN_')
WHERE unit_number like 'FRGN,%'";
But this doesn't seem to be working.
Do I need to escape the comma in the query in order for it to work?
A: Try this:
$sql = "UPDATE tableA
SET unit_number = concat('FRGN_', replace(replace(replace(unit_number,'FRGN,','') ,'FRGN_',''), 'FRGN', ''))";
or
$sql = "UPDATE tableA
SET unit_number = concat('FRGN_', replace(replace(text,'FRGN,','') ,'FRGN',''))
WHERE unit_number NOT LIKE 'FRGN\_%'";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jUnit test for addAll method For my assignment, I have to develop several jUnit tests for the method:
addAll(int index, Collection c)
This method is part of the class ArrayList - built in to java.
I figured out how to create the tests and run them in Eclipse IDE, but I'm a little confused as to exactly how I'm supposed to develop the tests. Could I get an example that includes what I should have in a @before, @beforeClass, @after, @test method?
To make this clear, I understand the format of the methods...I just don't understand HOW to test this method.
http://download.oracle.com/javase/1.4.2/docs/api/java/util/ArrayList.html#addAll(java.util.Collection)
A: So, what you need to test is that the method inserts all the elements in the passed Collection and that it inserts them into the appropriate position in the ArrayList.
Think of all the possible senerios and test each one.
*
*start with empty arraylist
*pass empty collection
*use index of 0
*use index > 0
*etc, etc...
After the add, verify / assert that the ArrayList now has all the elements that it should have in the correct order / locations.
Also test the error cases with @Test(expected=...).
*
*index < 0
*index > arrayList.size()
*null collection
*come up with other ideas
Also... assertThat in combination with Hamcrest's IsIterableContainingInOrder would be helpful for verification.
A: You will need to think of the behaviour you want to test, and then create a number of methods annotated with @Test to test aspects of that behaviour. Think about how should addAll behave. For example, if a collection passed to it, and an index of 0, then it should add all those elements in index 0 of ArrayList, followed by previously existing objects. So, in your test method, create an ArrayList, stick some objects in it, create a collection (c), stick some objects in it, call addAll on your arrayList with index 0 and collection (c), and assert that it has done what it was supposed to do...
(That's just an example, I am not sure what is the exact expected behaviour of addAll in your case)
Even better take a look at the wikipedia article Vakimshaar posted :)
A: Stick with @Test and @Before Methods, the rest is probably not what you need.
Methods annotated with @Before get called every time before a method annotated with @Test is executed. You can use it to initialized stuff to a clean state which might be shared among multiple tests.
A starting point could be the following code (for more cases to test take a look at John's answer) and implement them yourself.
public class ArrayListTest {
public ArrayList<String> list;
@Before
public void before() {
// This the place where everything should be done to ensure a clean and
// consistent state of things to test
list = new ArrayList<String>();
}
@Test
public void testInsertIntoEmptyList() {
// do an insert at index 0 an verify that the size of the list is 1
}
@Test
public void testInsertIntoListWithMultipleItems() {
list.addAll(Arrays.asList("first", "second"));
list.addAll(1, Arrays.asList("afterFirst", "beforeSecond"));
// Verify that the list now contains the following elements
// "first", "afterFirst", "beforeSecond", "second"
List<String> theCompleteList = // put the expected list here
// Use Assert.assertEquals to ensure that list and theCompleteList are indeed the same
}
}
A: Use annotation @Test to mark test method that should return void and should not accept arguments.
For most usages this is enough. But if you want to run specific code before or after each test use implement appropriate method and mark them with @Before and @After annotation.
If you need some code that runs before or after test case (the class where you implement several tests) annotate appropriate methods using @BeforeClass and @AfterClass method. Pay attention that these methods must be static, so "before" method is executed event before the default constructor of your test case. You can use this fact if you wish too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Package updating another package from another repository I've created repository where I store my own packages.
System uses my and some other public repositories.
So now I've a package in my repo which I want to be as an update for some other package from another repository.
The repositories are rpm package based.
Is it generally possible to mark my own package to update another package ?
A: Going to answer to my own question, yes yum treats all repositories equally. So all I need to do was setting package name the same and increased version number.
To test it you just need to create a yum repo and setup yum to use your repository for more info look here
A: (I would have made this a comment on the previous answer, but its too long.)
There's a problem with using the same package name and just bumping the version number.
Eventually the original package may increase its version number past what you're using, in which case someone may do a yum update and end up upgrading back to the original package.
To avoid this problem, you can change the package name slightly, and add some Obsoletes and Conflicts dependencies to your spec file. The Obsoletes dependency allows the original package to be upgraded to your package, while the Conflicts keeps the original package from being installed at the same time as your package.
This should keep an upstream version bump from clobbering your changes.
See http://docs.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/RPM_Guide/ch-dependencies.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514705",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mvc3 EditForModel I'm trying to get the EditFor or/and the EditForModel to work in mvc3, but it does not render anything on the page.
I can get LabelFor and TextFor to work, but not the model level stuff. Any help would be great.
My controller event is this:
public override ViewResult Index()
{
var mystate = new WelcomeModel();
return View(mystate);
}
Here is my viewmodel:
public class WelcomeModel
{
[Display(Name = "Email", ResourceType = typeof(Addresses))] //resource file value
[DataType(DataType.EmailAddress)]
public Email RecoverEmail { get; set; }
/// <summary>
/// Holds a list of attributes to the display elements
/// </summary>
public IDictionary<string, object> htmlAttrbutes = new Dictionary<string, object>();
public WelcomeModel()
{
RecoverEmail = new Email();
htmlAttrbutes.Add("class", "largeText");
}
}
Here is my view itself:
@model IdentityManager.Models.WelcomeModel
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset class="nolabel">
<div class="row">
<div class="col">
@Html.EditForModel()
</div>
</div>
</fieldset>
<div id="FormSubmitDiv" class="buttonBar" runat="server">
<input type="submit" value="Save" />
</div>
}
A: Your view model has a property called RecoverEmail which itself is a complex type Email. This is not supported automatically by the default editor templates (they recourse into complex sub-types). Brad Wilson explains this scenario. Another possibility is to write a custom editor template for the Email class (~/Views/Shared/EditorTemplates/Email.cshtml) where you can personalize what you need:
@model Email
<div>
@Html.LabelFor(x => x.Address)
@Html.EditorFor(x => x.Address)
@Html.ValidationMessageFor(x => x.Address)
</div>
... some other fields
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why isn't my data getting saved in Core Data? I am trying to save multiple rows into my coredata database using the following code. It only saves the last row. Why is it doing that?
nsManagedObject1.column1 = @"First row";
nsManagedObject1.column2 = @"Test 2";
//insert first row
if (![context save:&error]) {
NSLog(@"Could not save the data: %@",[error localizedDescription]);
}
//insert second row
nsManagedObject1.column1 = @"Second row";
nsManagedObject1.column2 = @"Test 2";
if (![context save:&error]) {
NSLog(@"Could not save the data: %@",[error localizedDescription]);
}
//see how many rows exist in the database
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"TestDB" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
NSLog(@"Number of rows: %d",[fetchedObjects count]);
In the count, I get only one row. When I print the data in the rows, it only finds the last row that I entered into the database. Why is it doing that? Since I did save on the context, I was expecting the two rows to be available in the database. Please help! I also do not get any errors.
PS - I know that I should not be doing this but I feel that I should understand why all the rows are NOT getting saved.
A: Two have two rows you need two managed objects. All you are doing here:
//insert second row
nsManagedObject1.column1 = @"Second row";
nsManagedObject1.column2 = @"Test 2";
is updating nsManagedObject1's column1 and column2 to have new values.
You need to create a nsManagedObject2, and that will give you two rows in the database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: DIVs overlapping. Need to move it over so they don't Basically what the title says. Though the spacing needs to be the same on any resoulution. I tried to do it with css but on different resolutions it moves around a bit. It dosn't matter how you do it (javascript, css, html), as long as it works.
You can view the site that im having issues on here.
A: If the error is the Fatal Error. Check Code. bit at the top, then do this
Change
#newscontent {
top: 4px;
left: 14%;
position: fixed;
}
to
#newscontent {
top: 4px;
left: 18%; //CHANGE HERE
position: fixed;
}
This will keep the text from overlapping the Latest News bit, at least until the page shrinks smaller than the BB.
Even better would be to make #newscontent a span and place it inside the #news div, so there would be no overlapping or separation no matter what the screen size.
A: only #topbar should be positioned absolute (if needed), child divs can have float left and margin/padding right
A: OK, so bottom line is you don't want to solve this using absolute or fixed positioning with left-offset percentages. This approach will fail depending on screen resolution and length of text. A better approach is to float the items, which will allow them to "push" the next element to the right, if need be. Try this:
First, remove all your CSS for your #serverstats, #news, and #newscontent selectors.
Second, on all three of those divs, add a menu-item class:
<div id="serverstats" class="menu-item">...</div>
<div id="news" class="menu-item">...</div>
<div id="newscontent" class="menu-item">...</div>
Third, add the following CSS to your style sheet:
.menu-item {
float: left;
font: bold 120% Arial,Helvetica,sans-serif;
margin-left: 15px;
padding-top: 3px;
text-decoration: none;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: System.TypeInitializationException using Emgu.CV in C# At this point I have a function which calls for an image from my camera interface. This image is then saved to hard drive and also displayed in the Windows Forms GUI.
The function inside the camera interface which returns the image is as follows:
height and width are both integers that are part of the camera interface class. In this case they were set to 800x600.
public Image<Bgr,byte> QueryFrame()
{
Image<Bgr, byte> temp;
lock (key)
{
using (Capture cap = new Capture())
{
cap.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, height);
cap.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, width);
temp = cap.QueryFrame().Copy();
}
}
return temp;
}
Calling the function a number of times revealed first that capturing a frame took a comparatively long time, locking the program out of use for a few seconds. Then, after capturing a few frames while running the program in Debug with Visual C# 2010, a windows error popped up for vshost.exe:
Faulting application DashboardGUI.vshost.exe, version 10.0.30319.1, time stamp 0x4ba2084b, faulting module MSVCR90.dll, version 9.0.30729.6161, time stamp 0x4dace5b9, exception code 0xc0000005, fault offset 0x00024682, process id 0xe78, application start time 0x01cc792086025f01.
I then proceeded to publish the application and run it from the executable and got the error:
Application: DashboardGUI.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.TypeInitializationException
Stack:
at Emgu.CV.CvInvoke.cvReleaseCapture(IntPtr ByRef)
at Emgu.CV.Capture.DisposeObject()
at Emgu.Util.DisposableObject.Finalize()
However I have also had it throw the same exception with Emgu.CV.CvInvoke.cvCreateCameraCapture(Int32).
What is causing these problems? How can they be avoided? And is there any way to make capturing a frame faster than it currently does (when it doesn't crash)?
A: I've looked at you code and I see the problem. The reason it crashes I expect is due to the using statement which I suggested Sorry :s. Well not exactly the using statement. You would appear to be accessing the code to often for the system to handle.
Capture cap = new Capture()
Does a large amount of operations for a small amount of code. Not only does it set up communication with your camera but checks it exists, handles drivers and creates ring buffers etc. Now while the code given does ensure only an updated image is returned it generally only works well if your using a button or a timer with a period of time delay. Now as I am aware of what your trying to achieve and since you want images more regularly than what can reasonably be achieved with this method you have a more practical option.
Set your Capture device up globally and set it of recording and calling ProcessFrame to get an image from the buffer whenever it can. Now change your QueryFrame simply to copy whatever frames its just acquired. This will hopefully stop your problem of getting the previous frame and you will now have the most recent frame out of the buffer.
private Capture cap;
Image<Bgr, Byte> frame;
public CameraCapture()
{
InitializeComponent();
cap= new Capture();
cap.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_HEIGHT, height);
cap.SetCaptureProperty(Emgu.CV.CvEnum.CAP_PROP.CV_CAP_PROP_FRAME_WIDTH, width);
Application.Idle += ProcessFrame;
}
private void ProcessFrame(object sender, EventArgs arg)
{
frame = _capture.QueryFrame();
grayFrame = frame.Convert<Gray, Byte>();
}
public Image<Bgr,byte> QueryFrame()
{
return frame.Copy();
}
Hope this helps get you to a solution this time,
and sorry the other method was of no use,
Cheers
Chris
A: http://www.emgu.com/wiki/index.php/Setting_up_EMGU_C_Sharp
- this really helped me when I was stuck on the same issue, it might be worth a look.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Enable and disable button using javascript and asp.net I am checking if user exists in database if exists I am showing message as "existed user" and then I need to disable the signup button if not I need to enable it.
I am unable to enable and disable the sign Up button.
Can anyone help me in this issue?
Here is my code:
<script type="text/javascript">
$(function () {
$("#<% =btnavailable.ClientID %>").click(function () {
if ($("#<% =txtUserName.ClientID %>").val() == "") {
$("#<% =txtUserName.ClientID %>").removeClass().addClass('notavailablecss').text('Required field cannot be blank').fadeIn("slow");
} else {
$("#<% =txtUserName.ClientID %>").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
$.post("LoginHandler.ashx", { uname: $("#<% =txtUserName.ClientID %>").val() }, function (result) {
if (result == "1") {
$("#<% =txtUserName.ClientID %>").addClass('notavailablecss').fadeTo(900, 1);
document.getElementById(#<% =btnSignUp.ClientID %>').enabled = false;
}
else if (result == "0") {
$("#<% =txtUserName.ClientID %>").addClass('availablecss').fadeTo(900, 1);
document.getElementById('#<% =btnSignUp.ClientID %>').enabled = true;
}
else {
$("#<% =txtUserName.ClientID %>").addClass('notavailablecss').fadeTo(900, 1);
}
});
}
});
$("#<% =btnavailable.ClientID %>").ajaxError(function (event, request, settings, error) {
alert("Error requesting page " + settings.url + " Error:" + error);
});
});
</script>
A: Try this...
document.getElementById('<%= button.ClientID %>').disabled = true;
OR
document.getElementById('<%= button.ClientID %>').disabled = false;
A: JavaScript:
function Enable() {
$("#btnSave").attr('disabled', false);
}
function Disable() {
$("#btnSave").attr('disabled', true);
}
ASPX Page:
<asp:Button runat="server" ID="btnSave" Text="Save" UseSubmitBehavior="false" OnClientClick="if(Page_ClientValidate('Validation')){javascript:Disable();}" ValidationGroup="Validation"/>
Code Behind:
ScriptManager.RegisterStartupScript(Me, Me.GetType(), "Disable", "javascript:Disable();", True)
A: u can just set visibility of your button to false visibility="false"
A: Unfortunately your problem is something as small as the difference between enabled and disabled
.enabled = true;
Should be :
.disabled = false;
A: You can play with this:
$('#ButtonId').prop("disabled", true); ->> disabled
$('#ButtonId').prop("disabled", false); ->> Enabled
A: The .disabled does work, have you used break point to make sure your code was even being reached ? Your conditional if / else's may not be returning your expected values.
A: I do this:
Disable:
var myButton = document.getElementById('<%= this.myButton.ClientID %>');
$(myButton).attr('disabled', 'disabled');
Enable:
$(myButton).removeAttr('disabled');
A: To enable and disable the buttons using JavaScript, this is what should be done-
Example:
<asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="a(); return false;"/>
<asp:Button ID="Button2" runat="server" Text="Button" OnClientClick="b(); return false;" />
and
<script type="text/javascript">
function a() {
alert('1');
document.getElementById('<%=Button1.ClientID %>').disabled = true;
document.getElementById('<%=Button2.ClientID %>').disabled = false;
}
function b() {
alert('2');
document.getElementById('<%=Button2.ClientID %>').disabled = true;
document.getElementById('<%=Button1.ClientID %>').disabled = false;
}
</script>
NOTE: While other posts had similar code, they fail because of the reload on the page. So to avoid the reload a return false should be added like OnClientClick="a(); return false;"
A: This JavaScript code should work.
document.getElementById("<%=btnSignUp.ClientID%>").disabled = true; //To disable the button
document.getElementById("<%=btnSignUp.ClientID%>").disabled = false;//To enable the button
Your code should look like
<script type="text/javascript">
$(function () {
$("#<% =btnavailable.ClientID %>").click(function () {
if ($("#<% =txtUserName.ClientID %>").val() == "") {
$("#<% =txtUserName.ClientID %>").removeClass().addClass('notavailablecss').text('Required field cannot be blank').fadeIn("slow");
} else {
$("#<% =txtUserName.ClientID %>").removeClass().addClass('messagebox').text('Checking...').fadeIn("slow");
$.post("LoginHandler.ashx", { uname: $("#<% =txtUserName.ClientID %>").val() }, function (result) {
if (result == "1") {
$("#<% =txtUserName.ClientID %>").addClass('notavailablecss').fadeTo(900, 1);
document.getElementById("<%=btnSignUp.ClientID%>").disabled = true;
}
else if (result == "0") {
$("#<% =txtUserName.ClientID %>").addClass('availablecss').fadeTo(900, 1);
document.getElementById("<%=btnSignUp.ClientID%>").disabled = false;
}
else {
$("#<% =txtUserName.ClientID %>").addClass('notavailablecss').fadeTo(900, 1);
}
});
}
});
$("#<% =btnavailable.ClientID %>").ajaxError(function (event, request, settings, error) {
alert("Error requesting page " + settings.url + " Error:" + error);
});
});
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: "Web service call failed: 0" when calling from DynamicPopulateExtender I am calling a web service from an ASP DynamicPopulateExtender, but seem to get the "Web Service Call Failed: 0" error, as if it's not finding the web service. Is there another reason why error code 0 would apply?
Here's the .aspx file:
<asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</asp:ToolkitScriptManager>
<h1>Stock Updates</h1>
<asp:Panel ID="upExtenderContent" runat="server" CssClass="dynamicPopulate_Normal">
Stock file import has STARTED please wait....<br /><br />
<asp:Image ID="imgLoading" runat="server" ImageUrl="~/admin/adminimages/uploading.gif" />
</asp:Panel>
<asp:DynamicPopulateExtender ID="dpeAjaxImport" runat="server"
TargetControlID="upExtenderContent"
BehaviorID="dp1"
ClearContentsDuringUpdate="false"
ServiceMethod="importStock"
ServicePath="importFile.asmx"
ContextKey="none"
PopulateTriggerControlID="btnImport">
</asp:DynamicPopulateExtender>
<br />
<asp:Button ID="btnImport" runat="server" OnClick="importFile" Text="Upload" />
<script type="text/javascript">
function uploadData(value) {
var behavior = $find('dp1');
if (behavior) {
behavior.populate(value);
}
}
Sys.Application.add_load(function () { uploadData('c:/Ben_Saved_Small.csv'); });
</script>
The importFile.asmx file, where the service resides is in the same directory as the above .aspx file so should be found easily:
<%@ WebService Language="C#" CodeBehind="importFile.asmx.cs" Class="GG.co.uk.admin.importFile" %>
This file header reference the following file content:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.Text;
using System.IO;
using GG.co.uk.App_Code;
using GGDAL;
namespace GG.co.uk.admin
{
/// <summary>
/// Summary description for importFile
/// </summary>
[WebService(Namespace = "http://GG.co.uk.admin/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class importFile : System.Web.Services.WebService
{
[WebMethod]
public static string importStock(string contextKey)
{
string returnResponse="";
//Load data into website database
try
{
//Read and process files
}
catch (Exception ex)
{
returnResponse = returnResponse + "<span style=\"color:red;font-weight:bold;\">Uh-Oh! " + ex.Message + "</span> : " + contextKey;
}
return returnResponse + "<br />";
}
}
}
An light shed on this would be really helpful.
Thanks.
A: Remove
ContextKey="none"
in
DynamicPopulateExtender tag
and try
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: phone gap adding contacts problem iam just practicing with phone gap for android app. I found a piece of code in docs.phonegap.com, regarding adding contacts
function onDeviceReady()
{
alert('onDeviceReady: PhoneGap1');
var myContact = navigator.contacts.create({"displayName": "Test User"});
alert('onDeviceReady: PhoneGap2');
myContact.gender = "male";
console.log("The contact, " + myContact.displayName + ", is of the " + myContact.gender + " gender");
}
When i run this i am getting only the alert box and the name is not added in my contacts. How to add the contacts....
Please tell me how to add data and open the device default contacts...
A: Simon Mac Donald has written a great blog post on contacts with PhoneGap and Android.
http://simonmacdonald.blogspot.com/2011/09/saving-contacts-with-phonegap-android.html
It should help you out as there are a few steps to it.
A: The quick answer for those of you searching, is that you have to call
myContact.save()
in order to persist the contact that you just created.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the best way to profile my javascript code ? I am interested in know how much memory my JavaScript code running inside a browser is consuming and how it is increasing decreasing with time. How do I do it ?
A: http://getfirebug.com/javascript
Firebug includes a powerful JavaScript debugger that lets you pause execution at any time and see what each variable looked like at that moment. If your code is a little sluggish, use the JavaScript profiler to measure performance and find bottlenecks fast.
Edit : You may refer previously answered questions on stackoverflow.
JavaScript Profiler in IE
Javascript memory profiler for Firefox
Measuring Javascript performance in IE
How to profile and and get Javascript performance
http://www.imnmotion.com/documents/html/technical/dhtml/jsprof.html
A: If you are using FireFox then Firebug is perfect for this application. I'd highly recommend it for debugging javascript in browser.
StackOverflow: what-is-the-best-way-to-profile-javascript-execution
Looks like this would be a good answer for you too.
A: It depends on your browser...
If you're using Chrome (that's what i'm using...):
*
*Open up the page
*Right click anywhere -> Inspect element (opens up Dev toolbar)
*Go to Profiles tab
*Click the little "recording" icon (cirle) at the bottom of the screen (4th button)
*When it's read it's indicating it's recording
*Do your thing
*Click the rec button again
*enjoy the statistics
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What are the benefits available in itextsharp.dll commercial license than in open source I am developing a tool. i want to know the benefits available in itextsharp.dll commercial license than in open source.
thanks in advance...
A: Open source license is AGPL. If you extend their source or link to the binary you need to open source your code as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is one memory leak normal for an app? I tested my app with the Leaks tool to determine leaks. I resolved all leaks but one.
This one seems difficult to remove. I am working on it but not sure what will remove the leak.
Is it normal for apps to have one or two leaks which don't leak that much memory over the usage of the app?
A: A memory leak is a bug much like any other bug. They are very easy to measure, though, and in some situations they can cause fatal crashes, so a lot of effort is put into dealing with memory leaks.
But most apps, memory leaks or not, have bugs in them. And a bug isn't automatically a blocker just because the bug causes leaking of memory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: NPM Keeps Having Issues Finding My Node Path Here's an example for me trying to install Node-Proxy because NowJS needs it:
sudo npm install node-proxy
> node-proxy@0.5.2 install /home/jennifer/node_modules/node-proxy
> make
BUILDING: C++ Component
Checking for program g++ or c++ : /usr/bin/g++
Checking for program cpp : /usr/bin/cpp
Checking for program ar : /usr/bin/ar
Checking for program ranlib : /usr/bin/ranlib
Checking for g++ : ok
Checking for node path : not found
Checking for node prefix : ok /usr/local
'configure' finished successfully (0.034s)
Waf: Entering directory `/home/jennifer/node_modules/node-proxy/src/build'
no such environment: default
Traceback (most recent call last):
File "/usr/local/bin/node-waf", line 16, in <module>
Scripting.prepare(t, os.getcwd(), VERSION, wafdir)
File "/usr/local/bin/../lib/node/wafadmin/Scripting.py", line 145, in prepare
prepare_impl(t, cwd, ver, wafdir)
File "/usr/local/bin/../lib/node/wafadmin/Scripting.py", line 135, in prepare_impl
main()
File "/usr/local/bin/../lib/node/wafadmin/Scripting.py", line 188, in main
fun(ctx)
File "/usr/local/bin/../lib/node/wafadmin/Scripting.py", line 386, in build
return build_impl(bld)
File "/usr/local/bin/../lib/node/wafadmin/Scripting.py", line 399, in build_impl
bld.add_subdirs([os.path.split(Utils.g_module.root_path)[0]])
File "/usr/local/bin/../lib/node/wafadmin/Build.py", line 981, in add_subdirs
self.recurse(dirs, 'build')
File "/usr/local/bin/../lib/node/wafadmin/Utils.py", line 634, in recurse
f(self)
File "/home/jennifer/node_modules/node-proxy/src/wscript", line 13, in build
obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')
File "/usr/local/bin/../lib/node/wafadmin/Build.py", line 335, in new_task_gen
ret = cls(*k, **kw)
File "/usr/local/bin/../lib/node/wafadmin/Tools/ccroot.py", line 162, in __init__
TaskGen.task_gen.__init__(self, *k, **kw)
File "/usr/local/bin/../lib/node/wafadmin/TaskGen.py", line 118, in __init__
self.env = self.bld.env.copy()
AttributeError: 'NoneType' object has no attribute 'copy'
cp: cannot stat `src/build/*/node-proxy.node': No such file or directory
make: *** [all] Error 1
npm ERR! error installing node-proxy@0.5.2 Error: node-proxy@0.5.2 install: `make`
npm ERR! error installing node-proxy@0.5.2 `sh "-c" "make"` failed with 2
npm ERR! error installing node-proxy@0.5.2 at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/exec.js:49:20)
npm ERR! error installing node-proxy@0.5.2 at ChildProcess.emit (events.js:67:17)
npm ERR! error installing node-proxy@0.5.2 at ChildProcess.onexit (child_process.js:192:12)
npm ERR! node-proxy@0.5.2 install: `make`
npm ERR! `sh "-c" "make"` failed with 2
npm ERR!
npm ERR! Failed at the node-proxy@0.5.2 install script.
npm ERR! This is most likely a problem with the node-proxy package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR! make
npm ERR! You can get their info via:
npm ERR! npm owner ls node-proxy
npm ERR! There is likely additional logging output above.
npm ERR!
npm ERR! System Linux 2.6.38-11-generic
npm ERR! command "node" "/usr/local/bin/npm" "install" "node-proxy"
npm ERR! cwd /home/jennifer/node_modules
npm ERR! node -v v0.4.11
npm ERR! npm -v 1.0.30
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! /home/jennifer/node_modules/npm-debug.log
npm not ok
A: Seems like this issue has also been reported here:
https://github.com/joyent/node/issues/1716
The solution is here: http://permalink.gmane.org/gmane.comp.lang.javascript.nodejs/29563
A: I got this when trying to downgrade from node v0.6x to v0.4x. Fix was to run sudo make uninstall in the v0.6x directory and then reinstall v0.4x.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: SolrJ's UpdateRequest worth trying instead setting autoCommit in config? I am getting sometimes timeouts while inserting documents into Solr with SolrJ. Now I am searching for a solution and thought, maybe the autocommit could be a possible approach. I can set it directly in the solrConfig.xml or I can use CommitWithin in e.g. SorlJ.
Currently I am inserting documents, via addBeans, which is nice, because it's so comfortable.
The UpdateRequest only offers me the possibility to add SolrInputDocuments directly, so no beans. E.g. from http://wiki.apache.org/solr/CommitWithin:
UpdateRequest req = new UpdateRequest();
req.add(mySolrInputDocument);
req.setCommitWithin(10000);
req.process(server);
I don't know, if the general autoCommit is wise to set. It sounds like a 'hard' approach to me. And when I read the comment written in the solrconfig.xml
Instead of enabling autoCommit, consider using "commitWithin" when adding documents.
I'm even more against this solution. Is the CommitWithin the smarter solution, which then of course means to write more code?
BTW: is it possible to add beans using the commitWithin feature?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get the locale from a string if have a problem getting the locale out of a string like:
menu_title_en_US
menu_title_en
The locale in this string would be "en_US". The string that i have to deal with only have alphanumeric characters and underscores. Like variable names in Python.
I have tried the following regex so far:
re.compile(r'_(?P<base_code>[a-z]{2,5})(_(?P<ext_code>[a-z]{2,5})){0,1}$')
which is working fine for strings like "menu_en" and "menu_en_US" but for stings like "menu_title_en" or "menu_title_en_US" it's not working as expected (extracting en or en_US).
Maybe someone has a quick idea how to solve this Problem.
A: If you know the locale is always en, en_us, or en_US (stated in a comment), then you don't need a regex at all:
locale = the_string[-6:]
if not locale.startswith('_en_'):
locale = locale[3:]
locale = locale[1:]
or
locale = the_string[-3:]
for code in '_en', '_en_us', '_en_US':
if code.endswith(locale):
break
else:
# no locale found
You could add more checks if the data could contain something that looked like a locale but wasn't -- these just check for the underscore plus two characters after.
However, the regex can be fixed / simplified a bit, too:
re.compile(r'_(?P<base_code>[a-z]{2})(_(?P<ext_code>[a-zA-z]{2}))?$')
? is the same as {0,1}, and since the codes are always two characters you want {2] not {2,5}. You want to accept either lower or upper case for the second code.
It still will have false positives, though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTML & Javascript Code within PHP How's that for a title!
Once again I find myself stumbling through lines of code that I don't really understand, and in doing so failing at almost every hurdle.
I have a php file xxxxx.php and what I'm trying to do is: from within a javascript function, set the properties of a div, and then execute some more javascript - I'm sure it's easy for someone who understands (but clearly not for me)
This piece of code works fine as it is:
<script type="text/javascript">
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
{
alert("Welcome again " + username);
}
else
{
username=prompt("Please enter your name:","");
if (username!=null && username!="")
{
setCookie("username",username,7);
}
}
}
</script>
</head>
<body onload="checkCookie()">
</body>
But then I want to insert this bit of code (which works fine on its own) directly after the 'setCookie' line:
<div style="position:absolute;top:125px;left:-67px;z-index:10000000">
<script src="AC_RunActiveContent.js" type="text/javascript"></script>
<script type="text/javascript">
AC_FL_RunContent('codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0','width','320','height','220','id','HTIFLVPlayer','src','HTIFLVPlayer','flashvars','&MM_ComponentVersion=1&skinName=HTI_Skin&streamName=nigel&autoPlay=true&autoRewind=true','quality','high','scale','noscale','name','HTIFLVPlayer','salign','lt','pluginspage','http://www.macromedia.com/go/getflashplayer','wmode','transparent','movie','HTIFLVPlayer'); //end AC code
</script> </div>
Any thoughts or suggestions would be greatly appreciated.
I tried setting the div style in javascript using:
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.top = "125px";
div.style.left = "-67px";
div.style.zIndex = "10000000";
document.body.appendChild(div);
...but this simply threw the flash player (called with the 'AC_FL_RunContent' line) onto a new blank page, not within the existing page (as required).
Hopefully someone will be able to make sense of my ramblings.
Rob.
A: seems like your new code with <div> tag is inside main <head> tag - it won't work, try putting new code inside <body> tag.
another thing, you can't put any html tags inside <script> just like that. you have to document.write them somewhere.
EDIT
use sth like this after setCookie();:
document.write('<div style="position:absolute;top:125px;left:-67px;z-index:10000000">');
document.write('<script src="AC_RunActiveContent.js" type="text/javascript"></script>');
document.write("<script type=\"text/javascript\"> AC_FL_RunContent('codebase','http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0','width','320','height','220','id','HTIFLVPlayer','src','HTIFLVPlayer','flashvars','&MM_ComponentVersion=1&skinName=HTI_Skin&streamName=nigel&autoPlay=true&autoRewind=true','quality','high','scale','noscale','name','HTIFLVPlayer','salign','lt','pluginspage','http://www.macromedia.com/go/getflashplayer','wmode','transparent','movie','HTIFLVPlayer'); //end AC code</script> </div>");
I hope it helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get css values in IE7 when "auto" is returned I'm trying to read the height of a div in IE7. Element.currentStyle returns "auto". How do I now calculate the height of this element? How does jQuery accomplish this? Its height() function is able to retrieve the value(http://api.jquery.com/height/) when IE developer's bar shows me the value is set to auto?
EDIT: I'm not using jQuery, so I'm hoping for a solution that does this in pure javascript
A: Maybe document.getElementById("idHere").offsetHeight works!
A: I think this is the jQuery function that calculates height:
function getWH( elem, name, extra ) {
// Start with offset property
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
which = name === "width" ? cssWidth : cssHeight;
if ( val > 0 ) {
if ( extra !== "border" ) {
jQuery.each( which, function() {
if ( !extra ) {
val -= parseFloat( jQuery.css( elem, "padding" + this ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + this ) ) || 0;
} else {
val -= parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0;
}
});
}
return val + "px";
}
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ] || 0;
}
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
// Add padding, border, margin
if ( extra ) {
jQuery.each( which, function() {
val += parseFloat( jQuery.css( elem, "padding" + this ) ) || 0;
if ( extra !== "padding" ) {
val += parseFloat( jQuery.css( elem, "border" + this + "Width" ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + this ) ) || 0;
}
});
}
return val + "px";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Select Case query not working New to SQL and in the process of developing query, with the to replicate part of an ETL process.
A billing code1 = bf, is then set to debt code 1. If billing field (debt code) exceeds 100 characters then add '*' as prefix.
However query will fall down because billing code1 = bf returns a single resultset to a debt code1 that returns large resultset.
select
case when len(format) > 100 then left(format, 100) + '*'
else format end as format
from (select case when exists (select _hs_eb_code1 from hbl_cat where hs_eb_code = 'bf)
then tbm_bllgrp._hs_eb_det1 end) as format
from tbm_bllgrp
Ideas welcomed.
A: select
case when len(format) > 100 then left(format, 100) + '*'
else format end as format
from tbm_bllgrp b
inner join hbl_cat hc on hc._hs_eb_code1 = b._hs_eb_det1
This is just a guess since I don't have your exactl schema and expected output, but I hope this gives you some ideas
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514761",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: which method to choose for jmx communication I am developing a monitoring management java application using jmx api.I have seen examples in internet and be able to make remote calls from client application to server.My question ath this point is what will be best practise for communication parameters of remote method(s) between client and server.for instance, i can use some collection object like hashtable and turn back again a hashmap as response.Another aproach can be generating a string on client side and parsing it at server side.Another aproach can be generating different serialiable objects at both side and passing its xml represantations may be(I'didnt try this so not sure about its technical possibility).
Which approach(considerin method signatures below) will be best and adaptable for different input/output pair.
1)Hashmap methodCollection(Hashmap);
2)String methodRawString(String);
3)String methodObjectToXML(String inputObjectXML) ;
A: It depends on your task. Theoretically custom serializable classes (value objects) are better and easier approach.
But in this case you should be sure that you have exactly the same version of these classes on both sides (client and server).
If you cannot guarantee this and your data model is relatively simple, i.e. can be represented as primitives and collections (or maps) of primitives, use maps and collections.
The formatted strings (XML, JSON etc) is the most portable and the hardest way. You have to generate and parse XML, handle different versions of your format etc. But you will never get serialization exception and will be theoretically able to support cross version comparability.
A: With JMX, there are the MXBean features which are very interesting: you can have quite complex objects on the server without deploying any JAR on the client side. There is a good article here: http://java.sun.com/developer/technicalArticles/J2SE/mxbeans/.
Also, there is http://www.jolokia.org/ which is a JMX/HTTP bridge that provides REST/JSON access to your JMX beans. Very useful if the client side is not a Java app (a shell script for instance).
A: Jolokia has a sophisticated way for serializing objects in both directions. In the downstream (from server to client), every object can be serialized into a JSON object. For the upstream (from client to server for ojbects used in as method arguments or values in write operations), serializing is a bit more limited, however maps and list collections can be easily used when the type of the elements are basic ones (strings, number, boolean, other maps or lists). So, Jolokia is quite nice for typeless JMX remoting.
Yet another solution would be to restrict yourself to OpenTypes which are available on both sides without extra type information. With OpenType you can also easily model collections (TabularData). For the translation from an arbitrary Java-Object to an OpenType the MXBean framework is indeed very helpful (although the translation from a map results in a rather complex TabularData format).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Weblogic 10.3.4 jsf 1.2 encodes special characters We have a web application, which uses weblogic jsf 1.2 implementation from deployable-libraries(jsf-1.2.war). We started to use weblogic jsf impl after having some problems with compatibility of packed jsf-impl and weblogic 10.3.4.
So the problem is that, we have outputLink with several params, these params' values could contain spacial chars, so we explicitly encode them(we have taglib function for this purpose), but jsf impl on weblogic 10.3.4 also encodes these chars, so we have double encoded link URL. Does anybody know is there a possibility to disable this option on weblogic and encode params only manually.
A: Just do not encode it yourself with a custom taglib. The <f:param> will already implicitly do it.
<h:outputLink value="page.jsf">
<h:outputText value="Click" />
<f:param name="foo" value="#{bean.foo}" />
<f:param name="bar" value="#{bean.bar}" />
</h:outputLink>
That's all. The #{bean.foo} and #{bean.bar} in above example can just return the raw and unencoded string value.
Update as per the comments, this suggests that those two servers JBoss AS 4.2.3 and WebLogic 10.3.2 are using a specific JSF implementation/version which exposes a bug in URL-encoding of <f:param>. As far, I can only find the following related reports (it's not clear if you're using MyFaces or Mojarra, so I searched in both):
*
*Mojarra (a.k.a. Sun RI): http://java.net/jira/browse/JAVASERVERFACES-791 fixed in 1.2_10.
*MyFaces: https://issues.apache.org/jira/browse/MYFACES-1832 fixed in 1.1.6 and > 1.2.2(?).
I recommend to replace/upgrade the JSF version of the servers in question to a newer version than the ones mentioned in those reports, or to ship JSF libraries along with the webapp itself and add web.xml context parameters to instruct the server to use the webapp bundled JSF instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a way for C++ application function to turn on the computer? i need to find away to turn on the pc from c++ application ,
is there any way to do this?
Thanks
A: If the computer is off, it can't be executing code, and therefore can't turn itself on programmatically.
ACPI changes that somewhat, but for us to be able to help, you have to be more specific about your exact requirements.
If you need to turn on a different computer, take a look at Wake-on-LAN.
A: You will not be able to write a program to turn a computer on that the program itself is installed on.
If you need to write an application that will turn on a different computer, Wake-on-LAN is the tool for you. Modern desktops have NICs that is always receiving power - even if the computer is in an S5 state. Assuming the BIOS supports it and it is enabled.
Wake-On-LAN works by sending a Magic Packet to the NIC. The details of what the payload consists of is outlined in the article.
A: This is possibly a duplicate of C#: How to wake up system which has been shutdown? (although that is C#).
One way to do it under windows is to create a timer with CreateWaitableTimer(), set the time with SetWaitableTimer() and then do a WaitForSingleObject(). Your code will pause, and you can put the computer into standby (maybe also hibernation, but not shutdown). When the timer is reached, the PC will resume and so will your program.
See here for a complete example in C. The example shows how to calculate the time difference for the timer, and how to do the waiting in a thread (if you are writing a graphical application).
I have to add, you can also schedule the computer to wake up using the Windows Task Scheduler ('Wake the computer to run this task'). This possibly also works when the computer is shut down. There is also an option in some computers BIOS to set a wake time.
Under Linux, you can set the computer to wake up by writing to a special file:
echo 2006-02-09 23:05:00 > /proc/acpi/alarm
Note that I haven't tested all of this, and it is highly dependent on the hardware (mainboard), but some kind of wake-up should be available on all modern PCs.
See also: http://en.wikipedia.org/wiki/Real-time_clock_alarm ,
and here is a program that claims to do it on windows: http://www.dennisbabkin.com/wosb/
A: Use strip. If you require a Windows computer to be turned on, the cross-tools i686-w64-mingw32-strip or x86_64-w64-mingw32-strip should be used. These command-line programs modify an executable, and the result is able to turn on a computer.
A: How could you turn on a computer from an application, when no processes are running on it when it's shut down ? You can turn on another computer (Wake on Lan), but not the one you are running.
A: It is possible.
First thing to do is configure Wake On Lan. Check out this post on Lifehacker on how to do it: http://lifehacker.com/348197/access-your-computer-anytime-and-save-energy-with-wake+on+lan.
(Or this link: http://hblg.info/2011/08/21/Wake-on-LAN-and-remote-login.html)
Then you need to send a magic packet from your C++ application. There are several web services that already do this from javascript (wakeonlan.me) , but it can be done from within a C++ application as well.
A: Chances are, that if you want to do this, you are working with servers.
In such case, your mainboard may should an IMPI baseboard management controller.
IPMI may be used to cycle the chassis power remotely.
Generally, the BMC will have its own IP address, to which you may connect to send control messages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Shortest way to generate a string from objects values in JavaScript I've got an object :
var obj = {
a: 'hello',
b: 32,
c: 'foo'
}
I need to extract to following string:
'hello, 32, foo'
My current method is:
var ar = [];
for (var key in obj){
if (obj.hasOwnProperty(key)){
ar.push(obj[key]);
}
}
var str = ar.join(', ');
Is there a shorter way than this?
ExtJs is allowed (jQuery can not be used).
A: var obj = {
a: 'hello',
b: 32,
c: 'foo'
}
var stringValues = `${Object.values(obj)}`
alert('The String Values are:',stringValues)
The String Values are: hello,32,foo
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: XML attribute Parsing in Android I have an Xml.may i know how can i parse it.
i need to get all OfficeName in to an Dictionary/array from the below XML.
eg:
Dictionary[key:tblOffice1]= "!-Everett Corporate Office"
Dictionary[key:tblOffice2]= "!-Fullterton SCE Call Center"
etc..
.
the above thing is not a exact code.
please help me .
my XML is
<DataTable xmlns="http://www.myoffice.com:1212/">
<xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="NewDataSet">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="tblOffice" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="tblOffice">
<xs:complexType>
<xs:sequence>
<xs:element name="OfficeName" type="xs:string" minOccurs="0"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
<DocumentElement xmlns="">
<tblOffice diffgr:id="tblOffice1" msdata:rowOrder="0">
<OfficeName>!-Everett Corporate Office</OfficeName>
</tblOffice>
<tblOffice diffgr:id="tblOffice2" msdata:rowOrder="1">
<OfficeName>!-Fullterton SCE Call Center</OfficeName>
</tblOffice>
<tblOffice diffgr:id="tblOffice3" msdata:rowOrder="2">
<OfficeName>Columbus Office</OfficeName>
</tblOffice>
<tblOffice diffgr:id="tblOffice4" msdata:rowOrder="3">
<OfficeName>Edison Office</OfficeName>
</tblOffice>
<tblOffice diffgr:id="tblOffice5" msdata:rowOrder="4">
<OfficeName>Franklin Office</OfficeName>
</tblOffice>
<tblOffice diffgr:id="tblOffice6" msdata:rowOrder="5">
<OfficeName>Fullterton Office</OfficeName>
</tblOffice>
<tblOffice diffgr:id="tblOffice7" msdata:rowOrder="6">
<OfficeName>Hatfield Office</OfficeName>
</tblOffice>
<tblOffice diffgr:id="tblOffice8" msdata:rowOrder="7">
<OfficeName>Hayward Office</OfficeName>
</tblOffice>
<tblOffice diffgr:id="tblOffice9" msdata:rowOrder="8">
<OfficeName>Las Vegas Office</OfficeName>
</tblOffice>
<tblOffice diffgr:id="tblOffice10" msdata:rowOrder="9">
<OfficeName>Phoenix Office</OfficeName>
</tblOffice>
<tblOffice diffgr:id="tblOffice11" msdata:rowOrder="10">
<OfficeName>Portland Office</OfficeName>
</tblOffice>
<tblOffice diffgr:id="tblOffice12" msdata:rowOrder="11">
<OfficeName>Salt Lake Office</OfficeName>
</tblOffice>
<tblOffice diffgr:id="tblOffice13" msdata:rowOrder="12">
<OfficeName>Snohomish Office</OfficeName>
</tblOffice>
<tblOffice diffgr:id="tblOffice14" msdata:rowOrder="13">
<OfficeName>Spokane Office</OfficeName>
</tblOffice>
</DocumentElement>
</diffgr:diffgram>
</DataTable>
may i know , how can i do it.
i wrote the method
package com.timetracker.app;
import java.io.StringReader;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class OfficeLocation extends ListActivity {
private static String SOAP_ACTION = "http://www.myoffice.com:1212/getTTofficeNames";
private static final String METHOD_NAME = "getTTofficeNames";
private static String NAMESPACE = "http://www.markdevweb.com:8082/";
private static String URL = "http://www.markdevweb.com:8082/ttwss/ttadmin.asmx";
ProgressDialog pbd;
TextView tv;
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// for getting header in the list view
//View offheader = getLayoutInflater().inflate(R.layout.offheader,null);
//ListView listView = getListView();
//listView.addHeaderView(offheader);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
System.out.println("the soap object request in officeloc = " +request);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
System.out.println("the soapserializationenvelope= "+envelope);
envelope.dotNet=true;
envelope.setOutputSoapObject(request);
System.out.println("under the request in officeloc");
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
System.out.println("under the url in officeloc");
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
System.out.println("Under the soap action2 in officeloc");
//SoapPrimitive resultString=(SoapPrimitive)envelope.getResponse();
SoapObject resultString=(SoapObject)envelope.getResponse();
System.out.println("the result string displayed ab in officeloc :" +resultString);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput( new StringReader (resultString.toString() ) );
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if(eventType == XmlPullParser.START_DOCUMENT) {
System.out.println("Start document");
} else if(eventType == XmlPullParser.START_TAG) {
System.out.println("Start tag "+xpp.getName());
} else if(eventType == XmlPullParser.END_TAG) {
System.out.println("End tag "+xpp.getName());
} else if(eventType == XmlPullParser.TEXT) {
System.out.println("Text "+xpp.getText());
}
eventType = xpp.next();
}
System.out.println("End document");
/* try {
XmlPullParser parsers=new org.kxml2.io.KXmlParser();
parsers.setInput(new java.io.StringReader("<tblOffice><OfficeName>hayword</OfficeName></tblOffice>"));
//parsers.nextTag();
parsers.require(XmlPullParser.START_DOCUMENT, null, null);
parsers.nextTag();
parsers.require(XmlPullParser.START_TAG, null, "tblOffice");
parsers.nextTag();
parsers.require(XmlPullParser.START_TAG, null, "OfficeName");
System.out.println("the elements"+ parsers.getText());
parsers.require(XmlPullParser.END_TAG, null, "OfficeName");
parsers.nextTag();
parsers.require(XmlPullParser.END_TAG, null, "tblOffice");
parsers.nextTag();
parsers.require(XmlPullParser.END_DOCUMENT, null, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
String result=resultString.toString();
System.out.println("the new value in officeloc "+result);
String[] names = new String[] {result};
this.setListAdapter(new ArrayAdapter<String>(this, R.layout.officelayout,R.id.label, names));
}
catch (Exception e)
{
tv.setText(e.getMessage());
}
// Create an array of Strings, that will be put to our ListActivity
//"Everett","Hayword","SaltLake","Vegas","Snohomish","Hatfield","Bothell"
// Use your own layout and point the adapter to the UI elements which
// contains the label
//with larger size this.setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, names));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
Toast.makeText(OfficeLocation.this, "you have pressed" + keyword+"the position is"+position+"the ID is"+id, Toast.LENGTH_LONG)
.show();
if(position==0)
{
Context localContext1 = this.getApplicationContext();
Intent localIntent1 = new Intent(localContext1, Everett.class);
this.startActivity(localIntent1);
}
if(position==1)
{
Context localContext2 = this.getApplicationContext();
Intent localIntent2 = new Intent(localContext2, Everett.class);
this.startActivity(localIntent2);
}
if(position==2)
{
Context localContext3 = getApplicationContext();
Intent localIntent3 = new Intent(localContext3, Everett.class);
startActivity(localIntent3);
}
if(position==3)
{
Context localContext4 = getApplicationContext();
Intent localIntent4 = new Intent(localContext4, Everett.class);
startActivity(localIntent4);
}
if(position==4)
{
Context localContext5 = getApplicationContext();
Intent localIntent5 = new Intent(localContext5, Everett.class);
startActivity(localIntent5);
}
if(position==5)
{
Context localContext6 = getApplicationContext();
Intent localIntent6 = new Intent(localContext6, Everett.class);
startActivity(localIntent6);
}
if(position==6)
{
Context localContext7 = getApplicationContext();
Intent localIntent7 = new Intent(localContext7, Everett.class);
startActivity(localIntent7);
}
}
}
However it like I am able to see get in to that method. of webservice.
and able to see the whole page I am not able to filter it out by line by line.
Its like a list of values.. but comming as the page as a whole
A: Here's a nice post that will help you understand how to parse XML in Android. Hope this helps.
A: I guess what you need here is XPath, should be something like that, not tested though:
ArrayList<String> officeNames = new ArrayList<String>();
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "//OfficeName";
InputSource inputSource = new InputSource("offices.xml");
NodeList nodeList;
try {
nodeList = (NodeList) xpath.evaluate(expression, inputSource,
XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); ++i) {
Node node = nodeList.item(i);
officeNames.add(node.getNodeValue());
}
} catch (XPathExpressionException e) {
e.printStackTrace();
}
More info about XPath in android: http://developer.android.com/reference/javax/xml/xpath/package-summary.html
Tutorial to get the full power of XPath:
http://www.w3schools.com/xpath/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get a number in one table and print the number's referenced name in another table I need to create a friend system, but my loop always skips the first match and sometimes it prints copies of the same name
$result = mysql_query("SELECT * FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.username_id");
while($row = mysql_fetch_array($result))
{
if ($row['username_id'] == 1)//the 1 will be a variable, username_id is in friends
$count = $row['friendname'];//friendname is in friends
if ($row['id'] == $count)//id is in users
echo $row['username'];//username is in users
}
Can someone see what my problem is ?
A: 2 things:
if ($row['username_id'] == 1)
you should put that in your sql:
$result = mysql_query("SELECT username, friendname FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.username_id where tbusers.id = ".$yourVariable);
In your query, user and friend are linked, and can only be equal.
Now, this:
$count = $row['friendname'];//friendname is in friends
if ($row['id'] == $count)//id is in users
is equal to
if ( $row['id'] == $row['friendname'] )
this sounds plain wrong. You compare a numerical id with a name. Moreover, your sql query already retrives all friends from users. In the version I showed here, it retrieves only friends of the user you are interested in.
finally, you print (echo) the name of the user, not of the friend. In my opinion the following code will do what you want:
$result = mysql_query("SELECT friendname FROM tbfriends WHERE username_id = ".$yourUserVariable);
while($row = mysql_fetch_array($result))
{
echo $row['friendname']; // or better: echo $row['friendname'], '<br>';
}
edit: after comment...
so if ( $row['id'] == $row['friendname'] ) means the user is his own friend. can that happen?
this code shall print what you want, friend names.
/*
$result = mysql_query("
SELECT username as friend_name,
friendname as friend_id,
username_id as user_id
FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.username_id
WHERE tbusers.id = ".$yourVariable);
*/
$result = mysql_query("
SELECT username as friend_name,
friendname as friend_id,
username_id as user_id
FROM tbusers INNER JOIN tbfriends ON tbusers.id = tbfriends.friendname
WHERE tbfriends.username_id = ".$yourVariable);
while($row = mysql_fetch_array($result))
{
echo $row['friend_name']; // or better: echo $row['friend_name'], '<br>';
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Scrollable Divs inside web page independent from main scroll I have a series of scrollable divs on a page. When a DIV gets scrolled to say the top and the user keeps scrolling it starts to scroll the page up instead (not so much on Firefox) but on Safari and Chrome it does.
This is annoying, and I notices that on Facebook, the activity monitor, friends online and chat window do not do this. If your mouse is in the div the you can only scroll that div not the page when you reach the top or bottom.
How have they done this?
Marvellous
A: Facebook use a custom scrollbar instead of those that come with the browser (at least, for the friends online sidebar).
Custom made controller = custome made control. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to guarantee the existence of static members in a type? Since C# has not provided support of static members for interfaces It is very hard to guarantee of existence of certain static members in class. I know that there is abstract class-ancestor for it, but I can't use it because in such case static members will be the same. For example:
class StaticClass
{
protected static int _secretNumber = 10;
public static int SecretNumber { get { return StaticClass._secretNumber; } }
}
class SomeData : StaticClass
{
SomeData() { SomeData._secretNumber = 25; }
}
class SomeData2 : StaticClass
{
SomeData2() { SomeData2._secretNumber = 50; }
}
In such case StaticClass.SecretNumber = SomeData.SecretNumber = SomeData2.SecretNumber = 10.
What I must to do in order to guarantee that a type contains a own static member?
A: Short answer - you can't. And why would you want to? To access the fields you have to refer to them directly (unless you're using reflection), so the compiler will check for you.
Why do you want to do this?
If you just want subclasses to assign the variable, then that's a contract of the class you simply can't specify in code. Use documentation to explain that subclasses have to assign a particular number to this variable instead.
A: First off, "protected static" is unsuggested, so I'd avoid it.
Secondly, why not defining "secretNumber" as instance, instead of static?
I don't see any valid reason for having "static interfaces", unless you will play with reflection.
A: DISCLAIMER: I think what you are proposing has a very distinct smell
For the sake of the exercise he's a generic solution to part of the problem. Is is possible to do part of what you wish. It's a bit of trickery to accomplish something I think at best will be a design error. But as a code exercise that kind of code is fun to write.
The below code does not require the Derived to initialize the static field but ensures that any derived class will have it's own instance. however when using the static member you still have to access it through the concrete class. So I can't see how it's really useful
class BaseClass<T, K> where T : BaseClass<T, K>
{
protected static K _secret;
public static K Secret { get { return _secret; } }
}
class Derived : BaseClass<Derived, int>
{
static Derived()
{
_secret = 10;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Protect user's information in the referral URL I decided to refresh my site today with a pair of upgrades. One of them is referring availability. So, as I method of referrer recognition, I am going to use special URL with referrer ID in it (if there is some other but better method, feel free to let me know about it). After I implemented the basics of that availability, I made a decision to make the system more secure. With that, I mean hiding the referrer's ID. Now, I am here, looking for suggestion on how can I make it secure (hidden or encrypted), but still be able to decrypt it on the server-side. Don't suggest me to use Base64 encryption, it's too simple and everyone can decrypt it these days.
I could try making my own system of encryption, what do you think?
A: It depends on what you want to pass.
First of all don't pass info that is not supposed to be publicly passed.
Second, you could create a token, save that in the DB next to the user, and authenticate on that token.
That token could be something that is valid only for a few hours... you make the choice, what works best for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CheckBox Listener I have some CheckBoxes which are made of my database table names
if(event.getSource()==connect){
CheckBox check;
Connection connection = null;
try {
Class.forName("org.postgresql.Driver");
String url = "jdbc:postgresql://localhost:5432/db";
String username = "username";
String password = "password";
connection = DriverManager.getConnection(url, username, password);
// Gets the metadata of the database
DatabaseMetaData dbmd = connection.getMetaData();
String[] types = {"TABLE"};
ResultSet rs = dbmd.getTables(null, null, "%", types);
while (rs.next()) {
String tableCatalog = rs.getString(1);
String tableSchema = rs.getString(2);
String tableName = rs.getString(3);
check = new CheckBox(tableName);
Tables.addComponent(check);
}
} catch (SQLException e) {
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Tables.addComponent(generate);
}
now lets say I get 10 checkboxes (with different names ofc.). How do I know which of them was checked?
e.g. I check box nr 1.5.7 and click on a button "Print". How do I print them out?
System.out.println("Checked items : " +check);?
A: You need a data structure like a Map to map between your checkboxes and the tables... I usually work with SWT and you have a map in each GUI component to store whatever you want, but as far as I know, you don't have this in awt, so you need to do this manually... (I assume you are using awt, although CheckBox class in awt is actually Checkbox not CheckBox!!!)
Bottom line is, you need to bind some data to your GUI components so you can recognize them later in your code...
I would use a map:
Map<Checkbox, String> checkToTableId;
Map<String, Checkbox> tableIdToCheck;
And build them up as you create the checks...
A: Use CheckboxGroup.
CheckboxGroup cbg=new CheckboxGroup();
add a CheckboxGroup as follows:
while (rs.next()) {
String tableCatalog = rs.getString(1);
String tableSchema = rs.getString(2);
String tableName = rs.getString(3);
Tables.addComponent(new Checkbox(tableName,cbg,false););
}
and you get the selected value.
String value = cbg.getSelectedCheckbox().getLabel();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Convert image to png byte array in Matlab I would like to take a 512x512 image and convert it into a png byte array in Matlab so that I can stream it via a socket.
At the moment I take the array, write it to a png file using imwrite(I,'file.png'), then read it as a binary file and send it through the socket. This is obviously horribly inefficient because I first write to disk and then read from disk. I want to skip the and write to disk.
Is there anyway to do this in Matlab?
A: Probably not directly using the base MATLAB toolbox since the PNG file itself is created by the PNGWRITEC MEX-function. However, there may be some Java classes that can help, such as those in the javax.imageio package.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is it possible to remove UISearchBar's tint image? i have to hide searchbar tint.
i write foll0wing code
UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 15, 270, 15)];
searchBar.delegate = self;
searchBar.barStyle = UISegmentedControlStylePlain;
searchBar.placeholder =@"search";
searchBar.tintColor=[UIColor clearColor];
[imageview addSubview:searchBar];
here search bar add on imageview. i want to hide tint side but bydeaflt it comes .i also chage the color to tint color but it not work.is anybody have idea of removing or hide tint on searchbar .Thanks
A: Hope this helps.
[searchBar setBackgroundImage:[UIImage new]];
Will also work in iOS 7.1
A: I have used this code. It completely removed the tint around the search text bar.
for (id v in [self.search subviews]) {
if (![v isKindOfClass:NSClassFromString(@"UISearchBarTextField")]) {
[v setAlpha:0.0f];
[v setHidden:YES];
}
else {
[v setBackgroundColor:[UIColor clearColor]];
}
}
A: Here's how I customized the UISearchBar
if ([[[searchBar subviews] objectAtIndex:0] isKindOfClass:[UIImageView class]]){
[[[searchBar subviews] objectAtIndex:0] removeFromSuperview];
}
This removes the background bar style.
You can then add any custom subview you want.
A: Try this
[searchBar setTranslucent:YES];
Also, don't set the tintColor when using translucent
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: node, session store remove expired sessions I am trying to implement a session store for an express.js node app
My question are :
*
*How do you delete cookie that have a browser session lifetime (marked with expires = false according to connect doc)
*Should I store session data as a json string or directly as an object
this is the coffee script I came up with so far, using mongoose as I this is the orm I chose for the app
express = require 'express'
mongoose = require "mongoose"
util = require "util"
# define session schema
SessionSchema = new mongoose.Schema
sid : { type: String, required: true, unique: true }
data : { type: String, default: '{}' }
expires : { type: Date, index: true }
module.exports =
class SessionStore extends express.session.Store
constructor: (options) ->
console.log "creating new session store"
options ?= {}
# refresh interval
options.interval ?= 60000
options.url ?= "mongodb://localhost/session"
# create dedicated session connection
connection = mongoose.createConnection options.url
# create session model
@Session = connection.model 'Session', SessionSchema
# remove expired session every cycles
removeExpires = => @Session.remove expires: { '$lte': new Date() }
setInterval removeExpires, options.interval
get: (sid, fn) ->
@Session.findOne sid: sid, (err, session) ->
if session?
try
fn null, JSON.parse session.data
catch err
fn err
else
fn err, session
set: (sid, data, fn) ->
doc =
sid: sid
data: JSON.stringify data
expires: data.cookie.expires
try
@Session.update sid: sid, doc, upsert: true, fn
catch err
fn err
destroy: (sid, fn) ->
@Session.remove { sid: sid }, fn
all: (fn) ->
@Session.find { expires: { '$gte': new Date() } }, [ 'sid' ], (err, sessions) ->
if sessions?
fn null, (session.sid for session in sessions)
else
fn err
clear: (fn) -> @Session.drop fn
length: (fn) -> @Session.count {}, fn
A: I'm pretty new to node so take this with a grain of salt.
While not directly session oriented the remember me tutorial on dailyjs will help a bit I think. Specifically the last bit of code where he verifies login tokens.
Also, I believe it's better to parse the JSON and store as an object. Should be easier to get access to the different cookie bits that way if you take care of the parse up front.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: YouTube API and the video tag Is there a way to use something like this:
<video width="320" height="240" controls="controls">
<source src="http://www.youtube.com/v/YJp7tqRyJAI" type="video/mp4" />
<source src="http://www.youtube.com/v/YJp7tqRyJAI" type="video/ogg" />
Your browser does not support the video tag.
</video>
I've looked into the api and all I've found is that i can use an iframe which embeds a flash version... But on Google I've found people wondering how to build a custom ui or an autoplay feature with the html5-youtube-api...
A: http://www.filsh.net/ did the job!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Strange Timezone issue with Tapku Library Calendar I have a weird problem with the Tapku Library Calendar.
I am showing events in Tapku Library Calendar. I am getting date from my server in America/Toronto Time zone. ie. -500.
My system and calendar time zone set to Toronto,Canada in Setting app.
So, the problem is when Calendar show one event in wrong day view (day tiles). Event is on 16th November 2011 and it is showing on 17th on to the Calendar.
11/16/2011 17:00 -0500
So I found solution to make time zone as GMT.
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
And above working fine with Toronto time zone. Now, I set my timezone to Rome,Italy and It suppose to show that event on 16th too but it is showing on 17th.
so, the problem is if I keep above line it works fine with the Toronto, Canada Timezone and problem with the Rome,Italy Timezone and If I remove this line then it works fine for Rome,Italy and problem with Toronto,Italy.
For this I tried to set systemTimeZone and localTimeZone as well but still no luck.
So, what should I do to keep event on correct day view for all the timezones ?
Please let me know if you require any further details.
A: Here is an answer to a similar problem:
https://stackoverflow.com/a/9405625/220154
I think the tapku calendar sets GMT:0 as the date it uses to compare against your dates, so it mess a lot with timezones. probably you would need to reduct the date to GMT midnight when you are checking what dates to include in the calendar.
hope it helps.
A: All [NSTimeZone timeZoneForSecondsFromGMT:0]; should be replaced with [NSTimeZone systemTimeZone];
When it is not systemTimeZone you have to edit your dates coming out of the UIDatePicker to reflect time zone hour change, and all dates would be displayed a day later if you don't.
Here is the issue : https://github.com/devinross/tapkulibrary/issues/40
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: simpleHTMLdom - Using multiple URLs from an array In my UI there is a text area that has a list of URLs separated by new line.
I am getting this into a string and exploding it using newline character. I am getting this error:
Fatal error: Call to a member function find() on a non-object in C:\xampp\htdocs\apps\lt\track-them.php on line 34
$myurl = "http://mydomain.com/testpage1.html";
$str = "http://www.domain.com/page1.html
http://www.homepage.com/page2.html
http://www.internet.com/index.html";
$backlinkarr = explode("\n", $str);
echo '<table border=1>';
foreach ($backlinkarr as $backlinkitem) {
$backlinkitem = trim($backlinkitem);
$LinkCount = 0;
$html = file_get_html($backlinkitem);
foreach ($html->find('a') as $link) {
if ($link->href == $myurl) {
$LinkCount += $LinkCount + 1;
}
}
echo $backlinkitem . ' (' . $linkCount . ')';
}
A: on windows new line is \r\n
also, your error suggests that $html is not an object, meaning previous line fails. so, debug there with var_dump($backlinkitem) if it is correct and also you can use file_exists to verify if that file actually exists.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Why is margin-top off by 2px on a Mac? If you view my website on a PC, the image under the links should fit snugly under the links.
However, if you view it on a Mac, the image is about 2px overlappin the links above it.
Do Mac browsers interpret CSS values differently? Such as margin-top, which is what I'm using?
Is there an easy solution to this with CSS, or do I need to designate separate CSS values after detecting the platform with PHP?
A: The display lines up in Mac Chrome if I set body { font: 12px/20px Verdana; }, forcing the line height of the nav text. This isn't a fix, it just demonstrates that it's the font size that's breaking your world.
This method of applying design elements to a page is (in my opinion) pretty old-school and fragile. My recommendation would be to break up the background so its components can be tied to individual elements on the page rather than relying on little nudges to line things up. Pretty much everything you're doing could be accomplished with straight CSS, anyway.
A: You may want to use a reset CSS stylesheet:
http://meyerweb.com/eric/tools/css/reset/
A: Try to add this css file. It will be reset all style. http://necolas.github.com/normalize.css/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Monodroid tabs view After implementing the Tabs Widget Sample I tried to play with it and add the third tab only after changing to the second tab
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
TabHost.TabSpec spec;
spec = TabHost.NewTabSpec("tab_test1").SetIndicator("TAB 1").SetContent(Resource.Id.textview1);
TabHost.AddTab(spec);
spec = TabHost.NewTabSpec("tab_test2").SetIndicator("TAB 2").SetContent(Resource.Id.textview2);
TabHost.AddTab(spec);
//spec = TabHost.NewTabSpec("tab_test3").SetIndicator("TAB 3").SetContent(Resource.Id.widget0);
//TabHost.AddTab(spec);
TabHost.TabChanged += new EventHandler<Android.Widget.TabHost.TabChangeEventArgs>(TabHost_TabChanged);
TabHost.CurrentTab = 0;
}
void TabHost_TabChanged(object sender, TabHost.TabChangeEventArgs e)
{
if (TabHost.TabWidget.TabCount < 3)
{
TabHost.TabSpec spec;
spec = TabHost.NewTabSpec("tab_test3").SetIndicator("TAB 3").SetContent(Resource.Id.widget0);
TabHost.AddTab(spec);
}
}
The problem is that I see the 3rd view overlay-ed on the first view before clicking the tabs, even though the 3rd tab appears only after clicking the 2nd tab. What's going on?
A: I'm guessing it's because the Third tab doesn't have tab to go to (since we don't create a TabSpec) so it just displays it directly on the screen.
You could set the content you want to display when the third tab is visible to invisible shown in the example below;
<TextView
android:visibility="invisible"
android:id="@+id/textview3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="this is a third tab" />
and then when the tab is displayed, the text view is made visible again.
Hope this helps,
ChrisNTR
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I monitor COM calls to my VisualBasic 6 ActiveX control? I wrote a little ActiveX control in VisualBasic 6 which is going to be used as a plugin for some 3rd party framework. The framework expects that my control exposes a few properties and methods. It all seems to work well except that one of my properties seems to be ignored.
In C++, I could put debug statement into the reimplementations of IDispatch::GetIDsOfNames and IDispatch::Invoke to see which members the framework attempts to access - maybe the documentation is wrong, and it's expecting a different property name or something.
Is it possible to monitor the accesses to COM properties/methods in Visual Basic 6, too?
A: The easiest way is to add logging of some form in the methods/properties in question. I don't think you can hook the lower level COM calls though.
For the logging, you can use OutputDebugString().
A: There's a rather old 'Hardcore Visual Basic' book around that teaches you exactly how to implement IUnknown, IDispatch etc. in VB5/6.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to implement MAC-DOCK-like selection behavior with vertical sections scrollbar in UITableViewController? Currently, I'm displaying vertical section scrollbar in my table view:
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView{
return [SectionModel getAllSectionNames];
}
I need to zoom-in the section name that is tapped on scrollbar, and zoom-in a little bit previous and next section names. The desired effect should be similar to DOCK behavior in MAC OS X. Any suggestions where to start?
UPDATE: Currently, I'm trying to find any scroll-to-section event but with no luck. UIScrollViewDelegate do not have such method.
A: Currently, I have realized that it's impossible to do that with native Apple methods. You need to implement that scrollbar from scratch.
Another option would be to use UIScrollViewDelegate method sectionForSectionIndexTitle:atIndex: that gets called when you tap on concrete section on scrollbar.Then you might create custom UIView with zoomed-in letter and present it on tableviews superview (for example at center). It's not the desired effect but some workaround.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to receive notification from web to android? In the app I am developing, I need to receive notification from a php server without using c2dm. Help me anyone.
A: You can't have push notifications without C2DM.
The "other way" is to make the client pull the server for info every X minutes..which is by several reasons not very good.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JSON Webservice calling repeatedly iphone sdk I have two webservices (JSON), one is called at the ViewDidLoad and it returned a array of values and loaded into Array1. And I need to call another webservice, by parsing each values of Array1. I tried something like this:
for (pointer=0; pointer<=[Array1 count]; pointer++) {
NSString *test = [Array1 objectAtIndex:pointer];
NSString *urlString2 = [NSString stringWithFormat:@"http://service=%@",test];
NSURLRequest *request2 = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString2]];
connection2 = [[NSURLConnection alloc] initWithRequest:request2 delegate:self];
}
How to call this function to load the output into an array?
A help will be much appreciated..
Thank you
A: You have not shown how you are executing the NSURLRequests requests you created within your loop. If you are trying to call them synchronously, then you can do something like:
NSMutableArray *result = [[NSMutableArray alloc] init];
for (pointer=0; pointer<=[Array1 count]; pointer++) {
NSString *test = [Array1 objectAtIndex:pointer];
NSString *urlString2 = [NSString stringWithFormat:@"http://service=%@",test];
NSURLRequest *request2 = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString2]];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *currentResult = [NSURLConnection sendSynchronousRequest:request2 returningResponse:&response error:&error];
[result addObject:currentResult];
}
return result;
If instead you are trying to call the request asynchronously using self as the delegate, then you will have to do some trickier work here because all of your responses for all of your requests will come in to the same delegate. It's possible but you may want to define a dedicated objects to act as delegates for each individual request in this case...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is this part of the script is safe from sql injection? Is this part of the script is safe from sql injections? Because i used this
foreach(array_keys($_POST) as $key)
{
$clean[$key] = mysql_real_escape_string(trim($_POST[$key]));
}
the guide of web said it should work more effectively and faster.
<?
session_start();
include("db.php");
if(empty($_POST['token']) || $_POST['token'] !== $_SESSION['token']){
exit("Error!");
}
unset($_SESSION['token']);
foreach(array_keys($_POST) as $key)
{
$clean[$key] = mysql_real_escape_string(trim($_POST[$key]));
}
$name=$clean['name'];
$country=$clean['country'];
$ip=$clean['ip'];
$map=$clean['map'];
Thanks for any help.
A: Yes, this is save in case you put it in quotes (in mysql query).. However, I'd change foreach to
foreach($_POST as $key => $value)
{
$clean[$key] = mysql_real_escape_string(trim($value));
}
A: If you want to prevent SQL injection easily and get good habits, you should check parameterized queries using PDO or mysqli.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cassandra for storing of Documents I am currently running a project where we need to annually store 40 billion documents (PDF,TIFF) for roughly 200 million accounts and was wondering if it is possible to use Cassandra for that? this is mainly because of the scalability, stability and multiple datacenter use in the Cassandra design.
But I wonder if it is a good idea to use Cassandra for this at all - or would another alternative like CouchDB be a better option?
Just a note, we don't need full text search in the documents and for each document there will only be a limited of metadata attached to each - like date, time, origin, owner and unique id, plus a few keywords. Access to documents will normally be done through a query on owner id and from there choose the document needed through origin and optionally date/time. So nothing fancy.
Thanks for your thoughts on this.
A: Just a few thoughts:
You might want to also consider a distributed file system such as HDFS.
40 billion per year is 1361 per second - Cassandra can handle this kind of write load, assuming the documents are modestly sized and not all huge multi-megabyte files.
What kind of read load are you anticipating?
Will the documents be preserved for ever i.e. 40 billion added per year indefinitely?
If a document is 100KB (say), that's 4 petabytes per year, I think? I've not heard of a Cassandra cluster that big - it would be worth asking on the Cassandra mailing list (with some realistic figures rather than my guesses!).
I've heard that a Cassandra node can typically manage 1TB under heavy load, maybe 10TB under light load. So that's at least a 400-node cluster for year one, possibly much more, especially if you want replication.
This page gives some 2009 figures for HDFS capabilities - 14 petabytes (60 million files) using 4000 nodes, plus a lot of other interesting detail (e.g. name nodes needing 60GB of RAM).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514820",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it OK to find out what the method returns calling the method itself inside it? I know the question sounds confusing, but it should sound simpler if I just show it with code:
Is it OK to do the following:
- (void)foo {
if (bar()) { // do something }
}
BOOL bar() {
return [self foo];
}
A: This will be called recursively until [self foo] returns NO.
Technically its 'ok' just make sure you know what you're doing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ArgumentException (parameter is not valid) error when instantiating Bitmap object I have the following code:
Bitmap bitmap = new Bitmap(pathtoimage);
Pathtoimage is the full, absolute path to a jpg. I get an ArgumentException (parameter is not valid) error. What am I doing wrong?
CODE:
Bitmap bitmap = new Bitmap(imageFilename);
var sobelEdgeDetector = new SobelEdgeDetector();
sobelEdgeDetector.Apply(bitmap);
Called with:
var sobelEdgeDetector = new Sobel();
sobelEdgeDetector.OutlineEdges(@"E:\Users\Me\Pictures\Error.jpg");
Thanks
A: I had the same problem but i resolved after study the library carefully..
SobelEdgeDetector() needs the Grayscale Image
So your code will be
Private Image getEdge(Bitmap img)
{
Bitmap originalImage = img; //
// get grayscale image
originalImage = Grayscale.CommonAlgorithms.RMY.Apply(img);
// apply edge filter
IFilter ff = new SobelEdgeDetector();
Bitmap b = ff.Apply(originalImage);
originalImage.Dispose();
return (Image)b;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android web request to string I want to collect the text from a webpage, put it into a string and then show it on my device's screen.
This is my WebRequest activity:
package com.work.webrequest;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class WebRequest extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView txt = (TextView) findViewById(R.id.textView1);
txt.setText(getPage());
}
private String getPage() {
String str = "***";
try
{
HttpClient hc = new DefaultHttpClient();
HttpPost post = new HttpPost("http://zapmenow.co.uk/zapme/?getDetails=true&secret=zjXvwX5frK1po0adXyKJsbbyUe2ZY2PkW9M8r7sb1soIDppIWdTlgt1xmL5VM6g&UDID=401ceca29af68e4569a25e8c16a6987bb8cf1f5a&id=41");
HttpResponse rp = hc.execute(post);
if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
str = EntityUtils.toString(rp.getEntity());
}
}catch(IOException e){
e.printStackTrace();
}
return str;
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView android:layout_height="wrap_content"
android:id="@+id/textView1"
android:text=""
android:layout_width="wrap_content"></TextView>
</LinearLayout>
I don't have any errors in Eclipse, but the application crashes on my device.
PS: I've added the line
<uses-permission android:name="android.permission.INTERNET" />
in manifest, so the Internet permission is not the problem.
A: This is the code that worked for me:
private String getPage(String url) {
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.connect();
if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
return inputStreamToString(con.getInputStream());
} else {
return null;
}
}
private String inputStreamToString(InputStream in) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
bufferedReader.close();
return stringBuilder.toString();
}
Later, you can use it by:
String response = getPage("http://example.com");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Help with hover jquery The below code hides .titlerow on hover of .row. How do I change the code so if the mouse isn't hovered on any row then the first .titlerow is hidden?
echo "<div class='row'><div class='titlerow'></div></div>
<div class='row'><div class='titlerow'></div></div>
<div class='row'><div class='titlerow'></div></div>
<div class='row'><div class='titlerow'></div></div>";
$(function() {
$('.row').hover(function() {
$(this).find('.titlerow').hide();
}, function() {
$(this).find('.titlerow').show();
});
});
A: i hope this is what you mean, if not please elaborate on what your intensions are...
html:
<div class='row'><div class='titlerow'></div></div>
<div class='row'><div class='titlerow'></div></div>
<div class='row'><div class='titlerow'></div></div>
<div class='row'><div class='titlerow'></div></div>
script:
$(function() {
$('.row').hover(function() {
$('.titlerow').first().show();
$(this).find('.titlerow').hide();
}, function() {
$(this).find('.titlerow').show();
$('.titlerow').first().hide();
});
// hide the first titlerow
$('.titlerow').first().hide();
});
edit
in the code above i made some fixes for your new request. + a working example can be found below
working example:
http://jsfiddle.net/muqxj/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: browser is not reflecting changes, wordpress installed. Can you please help I have strange problem.
For a project we are using following cloud hosting.
http://www.rackspace.com
I have installed wordpress on four sub-domains on this server.
Now i am facing a strange problem.
Sometimes when i make changes in theme flies, browser does not reflect those changes.
Like in abc.php file i have included xyz.php file.
I made some changes to xyz.php but when i open that page in browser, i can not see changes.
The issue is more worst, because even i tried to delete/rename xyz.php but i can still see previous include on abc.php page.
It was happening before, but after some time behaviour was normal.
Now its been 2 weeks and i am facing this problem.
I have contact hosting supprt, but they do not accept any issue. They say there is some issue in your wordpress.
I am sure that i do not have any cache plugin in wordpress.
Can you help me how to resolve this issue?
A: Usually CMS implement some cache mechanism. I guess your problem comes from that.
Check if you have some "flush cache" option in the admin panels.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Why does this ptrace program say syscall returned -38? It's the same as this one except that I'm running execl("/bin/ls", "ls", NULL);.
The result is obviously wrong as every syscall returns with -38:
[user@ test]# ./test_trace
syscall 59 called with rdi(0), rsi(0), rdx(0)
syscall 12 returned with -38
syscall 12 called with rdi(0), rsi(0), rdx(140737288485480)
syscall 9 returned with -38
syscall 9 called with rdi(0), rsi(4096), rdx(3)
syscall 9 returned with -38
syscall 9 called with rdi(0), rsi(4096), rdx(3)
syscall 21 returned with -38
syscall 21 called with rdi(233257948048), rsi(4), rdx(233257828696)
...
Anyone knows the reason?
UPDATE
Now the problem is :
execve called with rdi(4203214), rsi(140733315680464), rdx(140733315681192)
execve returned with 0
execve returned with 0
...
execve returned 0 twice,why?
A: The code doesn't account for the notification of the exec from the child, and so ends up handling syscall entry as syscall exit, and syscall exit as syscall entry. That's why you see "syscall 12 returned" before "syscall 12 called", etc. (-38 is ENOSYS which is put into RAX as a default return value by the kernel's syscall entry code.)
As the ptrace(2) man page states:
PTRACE_TRACEME
Indicates that this process is to be traced by its parent. Any signal (except SIGKILL) delivered to this process will cause it to stop and its parent to be notified via wait(). Also, all subsequent calls to exec() by this process will cause a SIGTRAP to be sent to it, giving the parent a chance to gain control before the new program begins execution. [...]
You said that the original code you were running was "the same as this one except that I'm running execl("/bin/ls", "ls", NULL);". Well, it clearly isn't, because you're working with x86_64 rather than 32-bit and have changed the messages at least.
But, assuming you didn't change too much else, the first time the wait() wakes up the parent, it's not for syscall entry or exit - the parent hasn't executed ptrace(PTRACE_SYSCALL,...) yet. Instead, you're seeing this notification that the child has performed an exec (on x86_64, syscall 59 is execve).
The code incorrectly interprets that as syscall entry. Then it calls ptrace(PTRACE_SYSCALL,...), and the next time the parent is woken it is for a syscall entry (syscall 12), but the code reports it as syscall exit.
Note that in this original case, you never see the execve syscall entry/exit - only the additional notification - because the parent does not execute ptrace(PTRACE_SYSCALL,...) until after it happens.
If you do arrange the code so that the execve syscall entry/exit are caught, you will see the new behaviour that you observe. The parent will be woken three times: once for execve syscall entry (due to use of ptrace(PTRACE_SYSCALL,...), once for execve syscall exit (also due to use of ptrace(PTRACE_SYSCALL,...), and a third time for the exec notification (which happens anyway).
Here is a complete example (for x86 or x86_64) which takes care to show the behaviour of the exec itself by stopping the child first:
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <sys/reg.h>
#ifdef __x86_64__
#define SC_NUMBER (8 * ORIG_RAX)
#define SC_RETCODE (8 * RAX)
#else
#define SC_NUMBER (4 * ORIG_EAX)
#define SC_RETCODE (4 * EAX)
#endif
static void child(void)
{
/* Request tracing by parent: */
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
/* Stop before doing anything, giving parent a chance to catch the exec: */
kill(getpid(), SIGSTOP);
/* Now exec: */
execl("/bin/ls", "ls", NULL);
}
static void parent(pid_t child_pid)
{
int status;
long sc_number, sc_retcode;
while (1)
{
/* Wait for child status to change: */
wait(&status);
if (WIFEXITED(status)) {
printf("Child exit with status %d\n", WEXITSTATUS(status));
exit(0);
}
if (WIFSIGNALED(status)) {
printf("Child exit due to signal %d\n", WTERMSIG(status));
exit(0);
}
if (!WIFSTOPPED(status)) {
printf("wait() returned unhandled status 0x%x\n", status);
exit(0);
}
if (WSTOPSIG(status) == SIGTRAP) {
/* Note that there are *three* reasons why the child might stop
* with SIGTRAP:
* 1) syscall entry
* 2) syscall exit
* 3) child calls exec
*/
sc_number = ptrace(PTRACE_PEEKUSER, child_pid, SC_NUMBER, NULL);
sc_retcode = ptrace(PTRACE_PEEKUSER, child_pid, SC_RETCODE, NULL);
printf("SIGTRAP: syscall %ld, rc = %ld\n", sc_number, sc_retcode);
} else {
printf("Child stopped due to signal %d\n", WSTOPSIG(status));
}
fflush(stdout);
/* Resume child, requesting that it stops again on syscall enter/exit
* (in addition to any other reason why it might stop):
*/
ptrace(PTRACE_SYSCALL, child_pid, NULL, NULL);
}
}
int main(void)
{
pid_t pid = fork();
if (pid == 0)
child();
else
parent(pid);
return 0;
}
which gives something like this (this is for 64-bit - system call numbers are different for 32-bit; in particular execve is 11, rather than 59):
Child stopped due to signal 19
SIGTRAP: syscall 59, rc = -38
SIGTRAP: syscall 59, rc = 0
SIGTRAP: syscall 59, rc = 0
SIGTRAP: syscall 63, rc = -38
SIGTRAP: syscall 63, rc = 0
SIGTRAP: syscall 12, rc = -38
SIGTRAP: syscall 12, rc = 5324800
...
Signal 19 is the explicit SIGSTOP; the child stops three times for the execve as just described above; then twice (entry and exit) for other system calls.
If you're really interesting in all the gory details of ptrace(), the best documentation I'm aware of is the
README-linux-ptrace file in the strace source. As it says, the "API is complex and has subtle quirks"....
A: You can print a human-readable description of the last system error with perror or strerror. This error description will help you substantially more.
A: At a punt I'd say you're examining eax, or its 64 bit equivalent (presumably rax) for the return code of a system call. There's an additional slot for saving this register named orig_eax, used for restarting system calls.
I poked around into this stuff quite a lot but can't for the life of me locate my findings. Here are some related questions:
*
*In Linux, on entry of a sys call, what is the value in %eax? (not orig_eax)
*Why is orig_eax provided in addition to eax?
Update0
Poking around again it seems my memory serves correct. You'll find everything you need right here in the kernel source (the main site is down, fortunately torvalds now mirrors linux at github).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: JSON Array Loop Inserting into Android SQLite Database I have the following snippet the loops through a JSON Array and inserts the data into a database. My problem is that it's not inserting all the records. If I have 6 records it will only inserts 5 of the 6. If I have 5 records it will only insert 4? When I debug the storesArray.length it shows the total records in the array as 6. What I'm I doing wrong that it won't loop and insert all the records in the array?
Here's the SQL String that's coming in from the server:
[{"id":"29","cId":"3","sName":"Milford Plaza Hotel","sNumber":"3061","sCustNm":"VS7997","sSalesman":"1234","sAddress":"","sContact":"","sPhone":""},{"id":"26","cId":"7","sName":"Circle K Bowling Green","sNumber":"5670","sCustNm":"VS7976","sSalesman":"1234","sAddress":"1091 N Main Street\r\nBowling Green, Ohio 43402","sContact":"","sPhone":""},{"id":"25","cId":"7","sName":"Circle K Bowling Green","sNumber":"5669","sCustNm":"VS7975","sSalesman":"1234","sAddress":"966 S Main Street\r\nBowling Green, OH 43402","sContact":"","sPhone":""},{"id":"22","cId":"6","sName":"Rock Branch Exxon","sNumber":"122","sCustNm":"VS7983","sSalesman":"1234","sAddress":"Rt 1 Box 34 A\r\nPoca, W.V.","sContact":"","sPhone":""},{"id":"23","cId":"6","sName":"Marathon Food Mart","sNumber":"156","sCustNm":"VS7984","sSalesman":"1234","sAddress":"2300 Pike Street\r\nParkerburg, W.V.","sContact":"Jenny","sPhone":""},{"id":"27","cId":"7","sName":"Circle K Dayton","sNumber":"5346","sCustNm":"VS7992","sSalesman":"1234","sAddress":"816 Waterveilt Ave\r\nDayton, OH 45420","sContact":"","sPhone":""}]
JSONArray storesArray = new JSONArray(restults);
for(int i = 0; i < storesArray.length(); i++){
JSONObject store = storesArray.getJSONObject(i);
db.execSQL("INSERT INTO stores ( sId, cId, sName, sAddress, sNumber, sSalesman, sCustNum, sPhone ) " +
"VALUES ('"+store.getString("id")+"', '"+store.getString("cId")+"', '"+store.getString("sName")+"', '"+store.getString("sAddress")+"', '"+store.getString("sNumber")+"', '"+store.getString("sSalesman")+"', '"+store.getString("sCustNm")+"', '"+store.getString("sPhone")+"' )");
}
A: I guess store.getString("id") should be your primary column ID? You shouldn't define that in an insert query, the database will do that for you.
More important: Don't put strings directly in your query since this is a great way to destroy your query (called SQL injection)
Do something like that:
db.execSQL("INSERT INTO stores ( sId, cId, sName, sAddress, sNumber, sSalesman, sCustNum, sPhone ) " +
"VALUES (?, ?, ?, ?, ?, ?, ?)",
new Object [] {
store.getString("cId"),
store.getString("sName"),
store.getString("sAddress"),
store.getString("sNumber"),
store.getString("sSalesman"),
store.getString("sCustNm"),
store.getString("sPhone")});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adding Header in ListView in android I need add header in my listview and header should always displayed even scrolling list.
Is it possible in android list view?
A: you can add header in list view like this:
View headerView = ((LayoutInflater)Activity.this.getSystemService(Activity.this.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.header, null, false);
list.addHeaderView(headerView)
A: The solution that works for me is to create a TableLayout that has a row with the heading and a row with the list like this:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include layout="@layout/header" />
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</TableLayout>
Please make sure that the ListView has @android:id/list as the ID.
A: Yes, here is what i 've done:
For a custom layout with ListActivity or ListFragment, your layout must contain a ListView with the android:id attribute set to @android:id/list.
1) main_layout.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
// custom Headers
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:gravity="center"
android:text="@string/systolic" />
<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:gravity="center"
android:text="@string/diastolic" />
<TextView
android:id="@+id/textView3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_weight="1"
android:gravity="center"
android:text="@string/date" />
</LinearLayout>
// This is important to be exactly like below ,android:id="@android:id/list"
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="@+id/linearLayout1" >
</ListView>
</RelativeLayout>
For custom layout for each row of list,
2) custom_list_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/bpSysHolder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:layout_gravity="center_vertical"
android:text="TextView" >
</TextView>
<TextView
android:id="@+id/bpDiaHolder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:layout_gravity="center_vertical"
android:text="TextView" >
</TextView>
<TextView
android:id="@+id/bpDtHolder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:layout_gravity="center_vertical"
android:text="TextView" >
</TextView>
</LinearLayout>
3) ListActivity:
public class HistoryActivity extends ListActivity {
private SimpleCursorAdapter dbAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// this is neccessery for you
setContentView(R.layout.main_layout);
dao = new BpDAO(this);
Cursor bpList = dao.fetchAll_bp();
String[] from = new String[] { BpDAO.bp_SYS, BpDAO.bp_DIA, BpDAO.bp_DT };
int[] target = new int[] { R.id.bpSysHolder, R.id.bpDiaHolder,
R.id.bpDtHolder };
// And this for custom row layout for each list row
dbAdapter = new SimpleCursorAdapter(this, R.layout.custom_list_row,
bpList, from, target);
setListAdapter(dbAdapter);
}
@Override
protected void onDestroy() {
super.onDestroy();
dao.close();
}
@Override
public void onListItemClick(ListView l, View view, int position, long id) {
// TODO something on item click
}
}
In case you need it check: "Attaching a sticky (fixed) header/footer to a listview"
A: Do one thing. Put one TextView just above the list view and set text as your header .It will achieve your need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7514844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.