text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Table row Image size problems I want to put one image on the beginning of each row in my application . The problem is that it shrinks the image too much . I want to make it occupy the whole space .
main.xml :
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:scrollbars="vertical"
>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:id="@+id/tableView"
android:layout_height="fill_parent"
android:layout_weight=".90"
android:stretchColumns="1"
></TableLayout>
</ScrollView>
This is how I add the image :
TableLayout tableView = (TableLayout) findViewById(R.id.tableView);
TableRow row = new TableRow(this);
ImageView im;
Bitmap bmp;
im = new ImageView(this);
bmp=getbmp(s);
im.setImageBitmap(bmp);
row.addView(im, new TableRow.LayoutParams(70, 30));
tableView.addView(row, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
If I change the parameters from TableRow.LayoutParams(70, 30)); the image stays the same , only the row gets bigger/smaller. Also , the image could get smaller if I make those parameters small enough but that is not what I want to do . I don't need necessarily the whole picture , a cropped zoomed in one that fills that space would be nice too . This is an example image from the website . If I put the image like this : row.addView(im); the image gets too big , and there is no more space for the text .
A: May be it's helpful to you
TableLayout tableView = (TableLayout) findViewById(R.id.tableView);
TableRow row = (TableRow) inflater.inflate(R.layout.tablerow, tableView, false);
ImageView imgDis = (ImageView) row.findViewById(R.id.spinnerEntryContactPhoto);
imgDis.setPadding(5, 5, 5, 5);
imgDis.setAdjustViewBounds(true);
// set row height width
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 50);
params.topMargin = 0;
params.bottomMargin = 0;
params.leftMargin = 0;
params.rightMargin = 0;
// If you want to set margin of row
tableView.addView(row, params);
tablerow.xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView android:id="@+id/spinnerEntryContactPhoto"
android:layout_gravity="center_vertical"
android:layout_width="70dip"
android:layout_height="30dip"/>
</TableRow>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: html email issue for a tag value I am sending html email to the client via php mail function. while & sign shown in bold creating problems in email replacing ! %20 something like characters within my ids such as below(in bold).
http://test.com/test-page.php?id=abcd**!**1234&cat_id=23
Below is my code.
$to = 'test@abc.com';
// subject
$subject = 'test';
//message
$message.='<html><head><meta charset="UTF-8" /></head><body><p><a href="http://test.com/test-page.php?id=abcd1234&cat_id=23" target="_blank">Wine **&** Dine Offers</a></p></body></html>';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
// Additional headers
$headers .= 'To: test <test@abc.com>' . "\r\n";
$headers .= 'From: test user <no-reply@test.com>' . "\r\n";
// Mail it
mail($to, $subject, $message, $headers);
After sending mail i am getting ! and %20 like characters in email.
I also tried & except & in email but no use still ! adding within my email html.
A: Try running urldecode() on the incoming parameters. Example:
$id = urldecode( $_GET['id'] );
A: I think you should encode the URL on the email. Plus, you probable have magic_quotes_gpc "on" that is not recommended.
I always use PHPMailer, it saves a lot of work and helps on these problems
A: try this:
$toName = 'test';
$toAddress = 'test@abc.com';
$fromName = 'test user';
$fromAddress = 'no-reply@test.com';
// subject
$subject = 'test';
// URL for link
// this should have any URL encoded characters literally in the string
$url = 'http://test.com/test-page.php?id=abcd1234&cat_id=23&msg=URL%20encode%20this%20string';
// HTML for message
// Call htmlspecialchars() on anything that may need it (like the URL)
$messageHTML = '<html><head><meta charset="UTF-8" /></head><body><p><a href="'.htmlspecialchars($url).'" target="_blank">Wine & Dine Offers</a></p></body></html>';
// Text version of message
// Remember, not everyone has an HTML email client!
$messageText = "Wine & Dine Offers: $url";
// Build a multipart MIME message
$boundary = '------'.md5(microtime()).'------';
$body =
"This is a multipart message in MIME format.\r\n"
."$boundary\r\n"
."Content-Type: text/plain\r\n"
."\r\n"
."$messageText\r\n"
."$boundary\r\n"
."Content-Type: text/html; charset=UTF-8\r\n"
."\r\n"
."$messageHTML\r\n"
."--$boundary";
// To send HTML mail, the Content-type header must be set correctly
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: multipart/alternative; boundary=\"$boundary\"\r\n";
// Additional headers
// the To: header will be set by mail() and is not required here
$headers .= "From: $fromName <$fromAddress>\r\n";
// Mail it
mail("$toName <$toAddress>", $subject, $body, $headers);
A: I changed the encoding settings on phpmailer to use base64 encoding using
$mail->Encoding=”base64"
This solved my problem.
As there is issue for HTML mail meassage exceeds length 998 or something i got the above solution to it. :)
http://www.jeremytunnell.com/posts/really-hairy-problem-with-seemingly-random-crlf-and-spaces-inserted-in-emails
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: When scripting, what's the difference between #!/usr/bin/perl and #!/usr/bin/env perl? Obviously this applies equally with python, bash, sh, etc substituted for perl!
Quentin's answer below was clearly correct, and so I've accepted it, but I guess what I actually meant was 'what are the pros and cons of the two ways of using #! to invoke perl/python/bash as the interpreter of a script?'
A: These are good rules, if you have a good reason to break them, don't hesitate to do so:
Use #!/usr/bin/env perl where possible for portability between heterogenous systems. But that's a dumb way to do it because it makes the assumption that the Perl that is first in the path is also the Perl you always want. That may not be so, and usually when there are several Perls on a system they are there for a certain reason.
A better approach is to package scripts up in a CPAN-ready distro. Distribute the distros to the systems where you want to have them installed and install them in the usual way (manually or with the CPAN toolchain), specifiying the full path to perl or cpan. During that process, the shebang line is rewritten to the correct path to Perl.
Examples:
tar -xvf Local-OurCompany-Scripts-1.000.tar.gz
cd Local-OurCompany-Scripts-1.000
## automated installation
/usr/bin/cpan .
# or perhaps
/opt/ourcompany/perls/perl-5.14.2/bin/cpan .
## manual installation
/usr/bin/perl Makefile.PL ; make ; make install
# or perhaps
`which perl5.14.2` Makefile.PL ; make ; make install
A: Using env to find the executable, rather than finding it yourself, does an additional exec, but that shouldn't really matter most of the time. It's convenient and I often use it myself.
However, I have had issues with people using env in system scripts. On one occasion, installing a /usr/local/bin/perl broke my system so that I could not update it anymore until I resolved the problem. On another occasion, installing a /usr/local/bin/python broke the ID3 tagger I was using. I think this is more a packaging issue than an inherent problem with env. If you're installing something on a system, why are you carefully checking that it has a version of Python that satisfies all of your dependencies if you're just going to leave a shebang line that fishes around for any old version of Python each time it is run?
A: One references a common place that perl is installed. The other references a common place that env is installed and asks it what the path to the default perl is.
A: I can give you a concrete example:
Imagine you have a LAMP package installed in /opt/ (i.e. XAMPP) that includes it's own perl executable, libraries and pakage manager.
You actually want to run that executable so you add the path to the LAMP executables in your PATH environment variable (PATH="/opt/XAMPP/bin:$PATH").
Now any script that uses "#!/usr/bin/env perl" will execute the perl binary in the LAMP stack directory. The other path will execute the pre-installed perl binary in your system, in "/usr/bin/perl".
It's up to you to decide what's better for your perl script.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Editing Multiple Rows by Their Order Index Q: How would I go about using / applying the row number of each row in a query to a certain column in the entire query?
I've added a screenshot to try and make things more obvious:
[The picture is only a simple example]
I would like to be able to directly use the value of the row number in such a context.
(Iterate over the values, somehow?)
Thanks in advance.
(Sorry if the question is a bit vague)
A: Try this :
;WITH TEST AS
(
SELECT *,
ROW_NUMBER() OVER (ORDER BY id DESC) AS RowNo
FROM [UserTable]
)
UPDATE TEST
SET myindex = RowNo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Richtextbox vertical scrollbar when my RichTextBox full of words, i did use GetScrollInfo to get nMax, nMin & nPage. but after i clear all text (scroll bar is gone), the nMax, nMin & nPage still remain the previous data. is there any way to make it auto update the GetScrollInfo?
A: Subscribe to the event RichTextBox.TextChanged:
private void myRichTextBox_TextChanged(object sender, EventArgs e)
{
// Get whatever you need in here
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Background Image on a List Item Think its a simple one.
I am working on a site.
The design is here
I've hit a little snag as to how to do the footer strategy | management | recovery.
As each item has a background image associated with it, How do I position the background image so that it is at the very bottom of the list item. I've tried background: bottom center;
But it just seems to push it behind.
Any help on this appreciated.
A: Something like this? I've used some random image I found of a red square, this could just as easily be your image.
http://jsfiddle.net/chricholson/5NC7L/
http://jsfiddle.net/chricholson/5NC7L/1/
HTML:
<ul>
<li>link</li>
<li>link</li>
<li>link</li>
</ul>
CSS:
li {
padding: 0 0 50px 0;
display: inline-block;
background: url('http://www.martin.com/color/small/red305.1.gif') no-repeat bottom center;
}
A: I'd probably do something like this:
a.strategy { border-bottom: 44px solid #CC7A16;}
a.management { border-bottom: 44px solid #00718C;}
a.recovery { border-bottom: 44px solid #954256;}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: XML/HTML markup text - nightmare with translators All we know that in Android internationalization can be done using XML'ed resources, which are supposed to be translated by translators. So I have done - hired several translators and send them resources with explanations what to translate and so on. In the end I've got bunch of files saved in different formats/encodings. Some of them sent using Excel, some in DOC, others MS-formatted XML's (nightmare) most sophisticated ones in Trados - list is endless.
Now the question is: how do you guys/girls used to handle translators? What kind of tools/approaches you're using? Please share with your personal experience or solutions.
A: Translator hell was solved by building a custom web-app that ensured that XML-challenged translators didn't do anything funny - and also built & commited the finished translations to our DCVS in the correct place.
A: Generally, it depends how bug your company is. If you have tons of translations, the best way is to probably centralize your efforts by hiring professional translation company which will care about providing your resources in desired format as well as handling individual translators. This cost more and sometimes result in a delay but in the end will save you a bit on fixing format issues.
Several MT/TM systems will allow you to process XML files as their input/output format (sometimes these files need to be annotated) but you actually cannot force your translators to use them. Unless you are really big, that is. But in such case, you could create your own TM and force translators to translate strings directly using some kind of web interface...
For small companies, there is a bit of a problem... You might want to write some kind of transformation tool that will take XML file as an input and transform it into key=value pairs (similar to Java properties). This is something that most translators will get right (in the end this is just plain text). The only thing you need to ensure, is that they use UTF-8.
BTW. Make sure that Excel is not in use (you need to force them to avoid this thing). It tends to modify text on its own in totally unpredictable way (I am speaking from experience, but I am not allowed to give you really painful examples).
A: I would not really recommend building your own tools like Jens did. There are good Translation tools out there that can handle XML and HTML perfectly.
There are even free open source tools such as OmegaT (Simple) and GlobalSight (Complete TMS).
We are using SDL Trados, which costs around 2000 EUR (The version you would need).
As for Pawel: You don't have to be a big company to use a professional translation agency. We (Supertext) can handle almost all filetypes nativly and a translation starts at 60 EUR.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How do I terminate request processing when implementing custom authentication in MVC? In my MVC2 application I want most requests to use Forms authentication and requests to some specific URIs to use my custom authentication. In order to do so I added FormsAuthentication_OnAuthenticate() method and inside I check the URI and if it's one of those exclusive URIs I want to check the username and password in the request headers.
The problem is how to terminate the request if the credentials provided are wrong.
I tried:
HttpContext context = args.Context;
context.Response.Write( "Wrong credentials" );
context.Response.StatusCode = 401;
context.Response.End();
but once that happens the request is forwarded to the URI that is specified in web.config under
<authentication mode="Forms">
<forms loginUrl="~/LogOn"/>
</authentication>
I want the request to be terminated - so that the response is sent to the client and the connection is closed. How do I achieve that?
A: As long as you send 401 status code the Forms Authentication module intercepts this code and automatically redirects to the logon page. The correct way to handle authentication in ASP.NET MVC is using the [Authorize] attribute. And if you don't want it to redirect to the login page but instead show some view you could write a custom authorize attribute and override the HandleUnauthorizedRequest method:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new ViewResult
{
ViewName = "~/Views/Shared/unauthorized.cshtml"
};
}
}
UPDATE:
In addition to overriding the HandleUnauthorizedRequest you could override the AuthorizeCore method which allows you to perform custom authentication.
A: The easier way to secure your application is to use the PrincipalPermissionAttribute, you can apply this to the whole controller, or just actions on the controller. E.g.
[PrincipalPermission(SecurityAction.Demand, Role="Administrator")]
public class AdminController : Controller
{
...
}
or
[PrincipalPermission(SecurityAction.Demand, Role="Administrator")]
public ActionResult DeleteUser(int id)
{
...
}
You can find more information in this article.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why we implement GetHashCode in IEqualityComparer? I want to get distinct items from List in C# by using IEqualityComparer interface. But I don't know about GetHashCode. I have implement both GetHashCode and Equals methods. And how can I call Equals method to get distinct items from a list having user define data type.
A: You can use the Distinct extension method passing it your custom equality comparer.
The reason why you need GetHashCode() is that without it you need O(n^2) comparisons. With GetHashCode() the items can be divided into buckets, which leads to O(n) for a good hash implementation.
If the item type is your own, you can override Equals and GetHashCode in the type itself instead of creating an IEqualityComparer<T>
A:
And how can I call Equals method to get distinct items from a list having user define data type.
Use the overload of Enumerable.Distinct that takes an IEqualityComparer to get the distinct items from a sequence using your custom equality comparer.
Why we implement GetHashCode in IEqualityComparer?
So that the IEqualityComparer can be used as a test for equality in a hash table (hash the items as per the IEqualityComparer.GetHashCode method, use IEqualityComparer.Equals to check for equality when needed (searching for an item in the hash table, for example).
A:
Why we implement GetHashCode in IEqualityComparer?
Because it gets called on IEqualityComparer, usually first, before Equals, at least for the LINQ extension methods which require IEqualityComparer. Otherwise it would be questionable whether you'd really need to implement GetHashCode for determining equality, since you could just use the Equals method for that. Why does LINQ prefer to call GetHashCode? See
Why use GetHashCode() over Equals()?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Shell Script for checking log and running a program I have this script that checks the last line of the file newlog.log and if it finds the word Stream closed there it should run the program test.jar because it would have stopped and hence written Stream closed in the log file.
#!/bin/sh
SUCCESS=0
while (true);
do
sleep 5
tail -1 ~newlog.log | grep -q "Stream closed" .
if [$? -eq 1]
then
java -jar test.jar &
fi
done
The error I get is :
run.sh: 11: [1: not found
Please tell me if there's some syntax error or what?
A: I think you can use
tail -f file.log
A: Instead of using the Exit Status of the grep command, store the output in a variable and loop until it's length is non-zero.
Grep will return exit status of 0 even when it doesn't return any output.
var1=tail -1 ~newlog.log | grep -q "Stream closed"
until [ -n "${var1}" ];
do
echo "Sleeping for next 5 seconds"
sleep 5
done
java -jar test.jar &
A: The original error '[1' caused by the OP not putting spaces around the square brackets in the if statement.
It seems that the tail command is returning an exit code of 1.
The if statement should be
if [ $? -eq 1 ]
then
...
and not
if [$? -eq 1]
then
....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CGContextSetRGBStrokeColor won't draw borders I am trying to create a pie chart. Each pie should be with different color and have it's border. So I made my own class PieChart.m:
#import "PieChart.h"
@implementation PieChart
@synthesize startDeg, endDeg, isSelected, colorNumber;
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
// Drawing code
int centerX = 120;
int centerY = 160;
int radius = 94;
CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSetRGBStrokeColor(ctx, 255.0/255.0, 255.0/255.0, 255.0/255.0, 1.0);
CGContextSetLineWidth(ctx, 2.0);
CGContextSetRGBFillColor(ctx, [self getColorFor:1]/255.0, [self getColorFor:2]/255.0, [self getColorFor:3]/255.0, 1.0);
CGContextMoveToPoint(ctx, centerX, centerY);
CGContextAddArc(ctx, centerX, centerY, radius, (startDeg)*M_PI/180.0, (endDeg)*M_PI/180.0, 0);
CGContextClosePath(ctx);
CGContextFillPath(ctx);
}
- (void)dealloc
{
[super dealloc];
}
-(float)getColorFor:(int)rgb {
if (colorNumber == 1) {
switch (rgb) {
case 1:
return 232.0;
break;
case 2:
return 96.0;
break;
case 3:
return 104.0;
break;
default:
return 255.0;
break;
}
}
if (colorNumber == 2) {
switch (rgb) {
case 1:
return 248.0;
break;
case 2:
return 198.0;
break;
case 3:
return 6.0;
break;
default:
return 255.0;
break;
}
}
return 255.0;
}
@end
The problem is that the borders would never draw. Or if I manage to draw the border the fill wouldn't be there! Any suggestions how this should be achieved?
Here is how I use the class in my viewcontroller:
- (void)viewDidLoad
{
[super viewDidLoad];
PieChart *pie1 = [[PieChart alloc] initWithFrame:CGRectMake(10, 10, 300, 400)];
pie1.startDeg = 0;
pie1.endDeg = 127;
pie1.colorNumber = 1;
pie1.backgroundColor = [UIColor clearColor];
PieChart *pie2 = [[PieChart alloc] initWithFrame:CGRectMake(10, 10, 300, 400)];
pie2.startDeg = 127;
pie2.endDeg = 360;
pie2.colorNumber = 2;
pie2.backgroundColor = [UIColor clearColor];
[self.view addSubview:pie1];
[self.view addSubview:pie2];
}
A: The problem with your code is that you only fill your path, not stroking it - so naturally border is now drawn. You need to replace CGContextFillPath call with
CGContextDrawPath (ctx, kCGPathFillStroke);
A: Stroking or filling the path clears the current path. That's why one works but not the other (whichever one you try first).
You can fix this by re-adding your path before stroking, or using CGContextDrawPath
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python capture stdout from subprocess line by line I've read many of the questions related to this and learned a lot but I still haven't been able to solve my problem. I'm building a wxPython app that runs a c++ executable and displays the stdout from that executable in real time. I've run into several strange results trying to make this work. Here's my current setup/problem:
//test.cc (compiled as test.out with gcc 4.5.2)
#include <stdio.h>
int main()
{
FILE* fh = fopen("output.txt", "w");
for (int i = 0; i < 10000; i++)
{
printf("Outputting: %d\n", i);
fprintf(fh, "Outputting: %d\n", i);
}
fclose(fh);
return 0;
}
#wxPythonScript.py (running on 2.7 interpreter)
def run(self):
self.externalBinary = subprocess.Popen(['./test.out'], shell=False, stdout=subprocess.PIPE)
while not self.wantAbort:
line = self.externalBinary.stdout.readline()
wx.PostEvent(self.notifyWindow, Result_Event(line, Result_Event.EVT_STDOUT_ID))
print('Subprocess still running')
print('Subprocess aborted smoothly')
If I run the above code the subprocess takes a very long time to complete, even though all it has to do is write out the data and exit. However if I run the following it completes very quickly:
#wxPythonScript.py (running on 2.7 interpreter)
def run(self):
outFile = open('output.txt', 'r+')
self.externalBinary = subprocess.Popen(['./test.out'], shell=False, stdout=outFile)
while not self.wantAbort:
#line = self.externalBinary.stdout.readline()
#wx.PostEvent(self.notifyWindow, Result_Event(line, Result_Event.EVT_STDOUT_ID))
print('Subprocess still running')
print('Subprocess aborted smoothly')
So basically whenever I redirect stdout from the subprocess to a PIPE it slows down/hangs, but if I write it to a file or don't redirect it at all then it's fine. Why is that?
A: I only tested this on Windows, but it works in 2.6.6, 2.7.2, and 3.2.1:
from __future__ import print_function
from subprocess import PIPE, Popen
from threading import Thread
import sys
try:
from Queue import Queue, Empty
except ImportError:
from queue import Queue, Empty # python 3.x
ON_POSIX = 'posix' in sys.builtin_module_names
def enqueue_output(out, queue):
for line in iter(out.readline, b''):
line = line.decode(sys.stdout.encoding)
queue.put(line)
out.close()
def main():
p = Popen(['c/main.exe'], stdout=PIPE, bufsize=1, close_fds=ON_POSIX)
q = Queue()
t = Thread(target=enqueue_output, args=(p.stdout, q))
t.daemon = True # thread dies with the program
t.start()
#initially the queue is empty and stdout is open
#stdout is closed when enqueue_output finishes
#then continue printing until the queue is empty
while not p.stdout.closed or not q.empty():
try:
line = q.get_nowait()
except Empty:
continue
else:
print(line, end='')
return 0
if __name__ == '__main__':
sys.exit(main())
Output:
Outputting: 0
Outputting: 1
Outputting: 2
...
Outputting: 9997
Outputting: 9998
Outputting: 9999
Edit:
readline() will block until the program's stdout buffer flushes, which may take a long time if the data stream is intermittent. If you can edit the source, one option is to manually call fflush(stdout), or you can instead disable buffering using setvbuf at the start of the program. For example:
#include <stdio.h>
int main() {
setvbuf(stdout, NULL, _IONBF, 0);
FILE* fh = fopen("output.txt", "w");
int i;
for (i = 0; i < 10; i++) {
printf("Outputting: %d\n", i);
fprintf(fh, "Outputting: %d\n", i);
sleep(1);
}
fclose(fh);
return 0;
}
Also look into using unbuffer or stdbuf to modify the output stream of an existing program.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Are there any downsides to using data attribute to edit content with javascript? I am developing a simple web app and I need to update the displayed data after certain events or conditions. This data is scattered in many different places and within completely separate markup structures.
I have used classes in the past but found some dangerous cases when using classes to edit data has come to bite me (especially as we are using OOCSS and there are many classes we want to change and should not be bound to js data or behaviour). The solution below should be buletproof in this respect but as I have never seen it used before I fear I may be missing something.
Is there any downside to a solution like the following?
Example code below - using jQuery
The follow may be bound to a specific data-change event:
$('.data[data-type=user_data]').each(function(){
$(this).find('.data[data-type=user_name]').html($.user.userName)
.end().find('.data[data-type=user_location]').html($.user.userLocation)
.end().find('.data[data-type=incident_date]').html($.user.incidentDate)
.end().find('.data[data-type=incident_cost]').html($.user.incidentCost)
.end().find('.data[data-type=user_hair_color]').html($.user.hairColor);
//more data will be added here ...
});
Markup will be this in some places:
<div class="data incident_result bubbled_box" data-type="user_data">
<h3>Some heading</h3>
<ul>
<li>Username: <span class="data highlight name" data-type="user_name">Igor Wassel</span></li>
<li>User location: <span class="data" data-type="user_location">Estonia</span></li>
<li>Provider: <span class="data" data-type="incident_date">21/08/11</span></li>
</ul>
Other places the markup will include the other data but within a completely different html structure.
A:
Are there any downsides to using data attribute to edit content with
javascript?
No, unless you write to these attributes and read them back with JavaScript. As too many people do, unfortunately. DOM isn't the place to store your JavaScript state.
Otherwise, it's perfectly OK to send data from server to client side via data-attributes. To stay completely failsafe append some common prefix to all your data-attributes.
Only I doubt it's performant to select elements by attribute value. Methods like getElementsByName are optimized for the task.
One could, at least, expand internal jQuery find-loops to iterate over all elements and automatically retrieve their values.
$('.data[data-type=user_data] *').each(function (el) {
el = $(el);
type = el.data('type');
if (type) {
el.html($.user[type.toCamelCase()]);
}
});
String.prototype.toCamelCase = function () { /* implement me */ };
And don't forget the HTML5 doctype declaration.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608884",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to handle potential leak of an object warning - CLLocationManager I did a build and analyze and was warned about a potential leak of an object stored into 'locationManager'. I was wondering how this should be handled properly. Here's the code:
// Compass Code
CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
if ([CLLocationManager locationServicesEnabled] &&
[CLLocationManager headingAvailable]) {
[locationManager startUpdatingLocation];
[locationManager startUpdatingHeading];
locationManager.headingFilter = 2; // 2 degrees
} else {
NSLog(@"Can't report heading");
}
thanks for any help
A: On the first line you alloc the location manager. This means you own that reference, and you should release it when you are done.
You need to either release the location manager when you have finished setting it up:
// ...
locationManager.headingFilter = 2; // 2 degrees
[locationManager release];
Or autorelease it on the same line you alloc it:
CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];
Having said that, you should probably be storing the location manager in an instance variable so you can stop the location updates at some point. Otherwise self might get deallocated and the location manager will continue sending messages to that deallocated object. This will cause a crash.
After making an instance variable, your dealloc should probably have this:
- (void)dealloc
{
// ...
locationManager.delegate = nil;
[locationManager stopUpdatingLocation];
[locationManager release];
// ...
[super dealloc];
}
Clearing the delegate will make sure the location manager will not send any messages to us once we have been deallocated. Then we stop the location updates and release the instance variable because we no longer need it.
A: Manually releasing the variables might be risky sometimes. We don't know where exactly to release the variables. One thing we can do to avoid the manual work of releasing the variables is click on the project in Build setting search for automatic reference counting set the value of it to "YES". By setting the value to "YES" no need to release the variables manually.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Accordian menu - how to keep first div open by default <html>
<head>
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".content").hide();
$('.button').click(function()
{
$('.content').slideUp('normal');
$(this).next().slideDown('normal');
$(".button1").removeClass().addClass("button");
$(this).removeClass().addClass("button1");
});
});
</script>
<style>
li { list-style:none;}
.button { width: 800px; float: left; background:green; color:#fff; cursor: pointer;}
.button1 { width: 800px; float: left; background:blue; color:#fff; cursor: pointer;}
.content { width: 800px; float: left; background: #95B1CE; display: none; }
</style>
</head>
<body>
<ul>
<li class="button">accordian button</li>
<li class="content">Content 1</li>
<li class="button">accordian button</li>
<li class="content">Content 2</li>
<li class="button">accordian button</li>
<li class="content">Content 3</li>
</ul>
</body>
</html>
A: You should use ids to reference your elements. Also I don't think your html structure is the best one.
I personally recommend using something like this:
<ul>
<li class="selected" id="button1">
<div class="button">accordion button</div>
<div class="content">Content 1</div>
</li>
<li id="button2">
<div class="button">accordion button</div>
<div class="content">Content 2</div>
</li>
<liid="button3">
<div class="button">accordion button</div>
<div class="content">Content 3</div>
</li>
</ul>
Now that the first one is selected by default, use css.
.content {
display: none;
}
.selected .content {
display: block;
}
The script should also change:
$(".button").click(function () {
var selected = $(".selected");
selected.children(".content").slideUp();
selected.removeClass("selected");
var button = $(this);
button.next().slideDown();
button.parent().addClass("selected"); // optional
});
Not tested but I think it's understandable.
A: Add $(".content:eq(0)").show(); after $(".content").hide();
Actually $(".content").hide(); is not required. Your are making display:none in css
it will work jsfilddle
find below full Js:
$(document).ready(function() {
//$(".content").hide();
$(".content:eq(0)").show();
$('.button:eq(0)').addClass('button1');
$('.button').click(function()
{
$('.content').slideUp('normal');
$(this).next().slideDown('normal');
$(".button").removeClass("button1");
$(this).addClass("button1");
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: What should I replace Core Data with? I'm having a problem updating our core data sqlite DB. So far our DB is only used to cache stuff coming back from our API, but with the next release of the app we're planning to save user data, so we need the DB to work, and unless I can fix that problem Core Data+sqlite just doesn't. Hopefully we will, but just in case, I need to look at alternatives.
We need something that will do:
*
*Partial updates (so we can save 1 record without saving the whole DB)
*Migrations (so we can support upgrading old versions)
*Relationships (because our data has those)
*Transient objects (because we don't always want to save them to the DB)
We also need something which doesn't require too big a rewrite to our model classes - ideally we'd just change the superclass and go from there. Bonus points if it's thread-safe. Do you know of any ORMs for iOS that fit those criteria?
A: It seems that your question has been resolved satisfactorily. Core Data does all the things you mention out of the box, so you should not have any problem there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: I get a null class with NSClassFromString I have the same code shared by 2 apps, and depending on the current app a different class is used.
className is the string which can be "PrefixClass1" or "PrefixClass2" (and it is correct for both apps, I've checked in the debugger).
However currentClass is null for app2. (It perfectly works for app1)
NSString *className = [NSString stringWithFormat:@"Prefix%@", [[NSApp delegate] applicationName]];
Class currentClass = NSClassFromString(className);
This means is null right ? http://cl.ly/AYSn
thanks
A: 1.) check you are really using the right class name and NSString (@"class2" Syntax)
2.) add the "-all_load" linker flag to your build settings (if linker finds no references, the class might not be loaded into the runtime)
A: I've solved by adding the .m file to the target > Compile Sources... Since I had many targets, xCode didn't know where to put it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't see differences in remote branch after a git fetch I'm a little confused about git fetch and comparing differences .
I have the following local branches;
*
*master
*remote/origin/master
In master branch I have a text file which I make changes to, commit and then push to the origin/master.
In another local repo (for test purposes) I have a remote to the same repo as above. I run
*
*git fetch origin master
*git diff master origin/master
It displays no differences, but if i do git pull origin master it pulls and merges the changes I made to the text file. I'm probably wrong but I thought a pull did a fetch and a merge, so doing a fetch allowed me to see the changes to the remote branch before merging them.
A: What you need to do to perform a diff (after a fetch) in respect to the head of your branch and the origin at the same branch is a
git diff HEAD...origin
Please note the 3 dots. By the way, the question can possibly be considered a duplicate of this one, at least in terms of the accepted answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: WHERE AND in Sqlite Statement I am having a problem combining two WHERE statements in the following SQL statement :
query = [[NSString alloc] initWithFormat: @"SELECT Name, Description,Postcode,AddressLine1, ImageURL, Free, Area, OpeningTimes, NearestTube, Cost,UniqueID, URL, Number, FirstLetter FROM MainDetails WHERE Free ='Y' AND FirstLetter = '%@%'",tmpLike];
I want to say where Free is equal to Y and FirstLetter is equal to tmplike, however the above is not working.
Can anyone help ?
A: Your using a wildcard so you want LIKE not equality (=);
... WHERE Free ='Y' AND FirstLetter LIKE '%@%'"
A: TRY THIS REMOVE % FROM LAST
query = [[NSString alloc] initWithFormat: @"SELECT Name, Description,Postcode,AddressLine1, ImageURL, Free, Area, OpeningTimes, NearestTube, Cost,UniqueID, URL, Number, FirstLetter FROM MainDetails WHERE Free ='Y' AND FirstLetter = '%@'",tmpLike];
A: try with escape char '/'
query = [[NSString alloc] initWithFormat: @"SELECT Name, Description,Postcode,AddressLine1, ImageURL, Free, Area, OpeningTimes, NearestTube, Cost,UniqueID, URL, Number, FirstLetter FROM MainDetails WHERE Free ='Y' AND FirstLetter = '%@\%'",tmpLike];
A: use this one it work fine
query = [[NSString alloc] initWithFormat: @"SELECT Name, Description,Postcode,AddressLine1, ImageURL, Free, Area, OpeningTimes, NearestTube, Cost,UniqueID, URL, Number, FirstLetter FROM MainDetails WHERE Free ='Y' AND FirstLetter LIKE '%@ %%'",tmpLike];
A: Maybe simply brackets ?
... WHERE (Free ='Y') AND (FirstLetter LIKE '%@')",tmpLike];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error in Android --Unable to find instrumentation info for: ComponentInfo For Example I had an application that will invoke contacts and has to select one of the contact.
But its not doing exactly what I want. It is showing me error Unable to find instrumentation info for: ComponentInfo{com.sample/com.sample.ContactsSelectInstrumentation}
Following is my Code..
This is my Activity class
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.go);
button.setOnClickListener(mGoListener);
}
private OnClickListener mGoListener = new OnClickListener() {
public void onClick(View v) {
startInstrumentation(new ComponentName(Test.this,
ContactsFilterInstrumentation.class), null, null);
}
};
And this is my Intrumentation class.
class ContactsFilterInstrumentation extends Instrumentation {
@Override
public void onCreate(Bundle arguments) {
super.onCreate(arguments);
start();
}
@Override
public void onStart() {
super.onStart();
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClassName(getTargetContext(), "com.android.phone.Dialer");
Activity activity = startActivitySync(intent);
Log.i("ContactsFilterInstrumentation", "Started: " + activity);
sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_M));
sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_M));
sendKeySync(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_A));
sendKeySync(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_A));
waitForIdleSync();
Log.i("ContactsFilterInstrumentation", "Done!");
finish(Activity.RESULT_OK, null);
}
}
Can Any help me out.
Thanks in Advance.
A: An Instrumentation implementation is described to the system through an AndroidManifest.xml's <instrumentation> tag.
A: Directory structure should be:
src
package.x.y.z.test
MainTest.java
CustomInstrumentationRunner.java
Then in the AndroidManifest.xml, set
<manifest package="package.x.y.z" ...
<instrumentation
android:name="package.x.y.z.test.CustomInstrumentationRunner"
Invoke the above package with the command line:
adb shell am instrumentation -w package.x.y.z/package.x.y.z.test.CustomInstrumentationRunner
A: I solved this problem by doing the following:
*
*Use a upper-level package name in the manifest:
*Implement the test packages one level down:
Java file 1:
package com.xxx.yyy.zzz.ptest.onlylogin;
Java file 2:
package com.xxx.yyy.zzz.ptest.register;
*
*Specify the command line like the following:
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Creating Dynamic Acl in Zend - Framework (check list for acl) I am trying to build a group based acl in the zend framework. Basically there will be three roles: admin, guest and user. And there will be different groups for the user role. How it will work is I have a check list of modules/controllers and action using the check list admin will be allowed to create group. Group could be something like editor (role will be user for editor aswell ). This group will be saved in database in a table group (group_id, group_name) and the resources selected will be saved in a table resource (resource_id, resource, group_id). resource will be saved in a format somewhat like module:controller:action (eg : user:user:login)
What I want to know is, Is what I am trying to do is the correct way or not if it has overhead or any suggestion you could post.
class App_AccessCheck extends Zend_Controller_Plugin_Abstract{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
if(!$this->_acl->isAllowed(Zend_Registry::get('role'),"Controller","Action")){
$request->setModuleName('user')
->setControllerName('user')
->setActionName('login');
}
}
class App_Acl extends Zend_Acl
{
public function __construct()
{
$this->addRole(new Zend_Acl_Role('guest'));
$this->addRole(new Zend_Acl_Role('user'));
$this->addRole(new Zend_Acl_Role('admin'));
$this->add(new Zend_Acl_Resource('Controller'))
->add(new Zend_Acl_Resource('Controller'), 'Action');
$resource = new App_Resource();
$params = $resource->getResource();
$this->allow('user', 'Controller', 'Action', new App_ActionAssertion($params));
}
public function isAllowed($role = null, $resource = null, $privilege = null)
{
// by default, undefined resources are allowed to all
if (!$this->has($resource)) {
$resource = 'nullresources';
}
return parent::isAllowed($role, $resource, $privilege);
}
}
class App_Resource extends Zend_Controller_Request_Abstract{
protected $params;
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$module = $request->getModuleName();
$controller = $request->getControllerName();
$action = $request->getActionName();
$params = $module.":".$controller":".$action;
$this->setParams($params);
}
public function getParams()
{
return $params;
// String representing current module:controller:action
}
}
class App_ActionAssertion implements Zend_Acl_Assert_Interface
{
//this class will check the access of the group to the particular resource in the database table: resource based on the params passed
//admin will be allowed all privilege
//return true/false
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to run C2DM sample program in Android? Hi I am very new to android. I would like to develop an application in android with C2DM. I have a sample code for C2DM from the following site http://www.ipragmatech.com/power-mobile-app-android-push-notification-c2dm.html . I did the following steps device-> settings-> account & sync -> google account-> add account-> sign in-> gave my account name and password. And then I ran my code ,but its shows some thing
09-30 15:28:22.868: WARN/C2DMReceiver-onRegistered(491): Sending request to Server
09-30 15:36:52.888: ERROR/C2DMReceiver-onRegistered(614): Connect to /192.168.1.4:8080 timed out
09-30 15:36:52.888: WARN/C2DMReceiver-onRegistered(614): APA91bGI7fsthXytTrOMWxcldx5haV21e4b98XqLV2C4cnCrq0betXuUa2vrklD0w_Qn6LuzNFDQqqkegfKe1-UL5W8Gce9IXrHjEmBajeAN2lcW7LnTyY0
09-30 15:37:20.008: DEBUG/SntpClient(71): request time failed: java.net.SocketException: Address family not supported by protocol
09-30 15:42:20.059: DEBUG/SntpClient(71): request time failed: java.net.SocketException: Address family not supported by protocol
And then it doesn't works. Anybody tell me the procedure for get the registration ID from c2dm server?
A: Try this doc and this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Difference between .call and .apply Is there a simple way to passing all arguments from one function to another and sending this also.
I have tried this: http://jsfiddle.net/v92Xr/
var f1 = function() {
f2.call(this, arguments);
};
var f2 = function() {
console.log(arguments);
};
f1("abc", "def", "hij");
but it leaves me all the arguments from f1 is stacked in f2 arguments 0:
f2->arguments[0] == f1->arguments
Ok and when i run the apply method instead it works: http://jsfiddle.net/v92Xr/1/
var f1 = function() {
f2.apply(this, arguments);
};
var f2 = function() {
console.log(arguments);
};
f1("abc", "def", "hij");
So can anyone please tell me what's the difference between call and apply is?
A: I think you've just discovered the difference yourself.
call is almost identical to way you would normally call a function except there is an extra parameter at the start of the parameter list where you place the reference for the this object.
apply also has the first parameter as the this object but the second parameter is expected to be an array. This array is used to supply all the arguments that the called function is expecting. Element 0 maps to the first argument in the functions argument list, element 1 to the second and so on.
A: call MDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call
Calls a function with a given this value and arguments provided individually.
fun.call(thisArg[, arg1[, arg2[, ...]]])
apply MDN: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply
Calls a function with a given this value and arguments provided as an array.
fun.apply(thisArg[, argsArray])
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: glassfish v3 starting slowly...? I am suffering from starting up glassfish v3 .
it allways taking very long time to start the server. even not starts , all the time it will be idle.
I am trying to deploy ejb of about 160 .
It is not able to deploy all ejbs . for every restart it shows diff no of ejbs deployed.
what may be the problem.
console will be like this ..
[#|2011-09-30T15:13:19.718+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Glassfish-specif
ic (Non-portable) JNDI names for EJB CoManagerAccount : [com.wellzio.service.cus
tomer.ICoManagerAccount, com.wellzio.service.customer.ICoManagerAccount#com.well
zio.service.customer.ICoManagerAccount]|#]
[#|2011-09-30T15:13:19.828+0530|WARNING|glassfish3.1.1|javax.enterprise.system.t
ools.monitor.org.glassfish.admin.monitor|_ThreadID=10;_ThreadName=main;|MNTG0201
:Flashlight listener registration failed for listener class : com.sun.ejb.monito
ring.stats.StatelessSessionBeanStatsProvider , will retry later |#]
[#|2011-09-30T15:13:22.171+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Portable JNDI na
mes for EJB TrialWap : [java:global/com.wellzio.service.customer/TrialWap!com.we
llzio.service.customer.ITrialWap, java:global/com.wellzio.service.customer/Trial
Wap]|#]
[#|2011-09-30T15:13:22.171+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Glassfish-specif
ic (Non-portable) JNDI names for EJB TrialWap : [com.wellzio.service.customer.IT
rialWap#com.wellzio.service.customer.ITrialWap, com.wellzio.service.customer.ITr
ialWap]|#]
[#|2011-09-30T15:13:22.296+0530|WARNING|glassfish3.1.1|javax.enterprise.system.t
ools.monitor.org.glassfish.admin.monitor|_ThreadID=10;_ThreadName=main;|MNTG0201
:Flashlight listener registration failed for listener class : com.sun.ejb.monito
ring.stats.StatelessSessionBeanStatsProvider , will retry later |#]
[#|2011-09-30T15:13:24.156+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Portable JNDI na
mes for EJB States : [java:global/com.wellzio.service.customer/States, java:glob
al/com.wellzio.service.customer/States!com.wellzio.service.customer.IStates]|#]
[#|2011-09-30T15:13:24.171+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Glassfish-specif
ic (Non-portable) JNDI names for EJB States : [com.wellzio.service.customer.ISta
tes, com.wellzio.service.customer.IStates#com.wellzio.service.customer.IStates]|
#]
[#|2011-09-30T15:13:24.281+0530|WARNING|glassfish3.1.1|javax.enterprise.system.t
ools.monitor.org.glassfish.admin.monitor|_ThreadID=10;_ThreadName=main;|MNTG0201
:Flashlight listener registration failed for listener class : com.sun.ejb.monito
ring.stats.StatelessSessionBeanStatsProvider , will retry later |#]
[#|2011-09-30T15:13:25.656+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Portable JNDI na
mes for EJB PatientWapAssociation : [java:global/com.wellzio.service.customer/Pa
tientWapAssociation, java:global/com.wellzio.service.customer/PatientWapAssociat
ion!com.wellzio.service.customer.IPatientWapAssociation]|#]
[#|2011-09-30T15:13:25.656+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Glassfish-specif
ic (Non-portable) JNDI names for EJB PatientWapAssociation : [com.wellzio.servic
e.customer.IPatientWapAssociation, com.wellzio.service.customer.IPatientWapAssoc
iation#com.wellzio.service.customer.IPatientWapAssociation]|#]
[#|2011-09-30T15:13:25.765+0530|WARNING|glassfish3.1.1|javax.enterprise.system.t
ools.monitor.org.glassfish.admin.monitor|_ThreadID=10;_ThreadName=main;|MNTG0201
:Flashlight listener registration failed for listener class : com.sun.ejb.monito
ring.stats.StatelessSessionBeanStatsProvider , will retry later |#]
[#|2011-09-30T15:13:29.250+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Portable JNDI na
mes for EJB WapAccount : [java:global/com.wellzio.service.customer/WapAccount!co
m.wellzio.service.customer.IWapAccount, java:global/com.wellzio.service.customer
/WapAccount]|#]
[#|2011-09-30T15:13:29.250+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Glassfish-specif
ic (Non-portable) JNDI names for EJB WapAccount : [com.wellzio.service.customer.
IWapAccount, com.wellzio.service.customer.IWapAccount#com.wellzio.service.custom
er.IWapAccount]|#]
[#|2011-09-30T15:13:29.375+0530|WARNING|glassfish3.1.1|javax.enterprise.system.t
ools.monitor.org.glassfish.admin.monitor|_ThreadID=10;_ThreadName=main;|MNTG0201
:Flashlight listener registration failed for listener class : com.sun.ejb.monito
ring.stats.StatelessSessionBeanStatsProvider , will retry later |#]
[#|2011-09-30T15:26:06.562+0530|SEVERE|glassfish3.1.1|com.sun.grizzly.config.Gri
zzlyServiceListener|_ThreadID=17;_ThreadName=admin-thread-pool-4848(2);|service
exception
java.lang.RuntimeException: java.lang.NullPointerException
at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:24
3)
at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java
:168)
at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java
:117)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(Container
Mapper.java:238)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:8
28)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFil
ter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultPro
tocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.jav
a:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.jav
a:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java
:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextT
ask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.
java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadP
ool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool
.java:513)
at java.lang.Thread.run(Thread.java:619)
Caused by: java.lang.NullPointerException
at com.sun.enterprise.v3.services.impl.monitor.MonitorableSelectionKeyHa
ndler$CloseHandler.notifyClosed(MonitorableSelectionKeyHandler.java:94)
at com.sun.enterprise.v3.services.impl.monitor.MonitorableSelectionKeyHa
ndler$CloseHandler.remotlyClosed(MonitorableSelectionKeyHandler.java:90)
at com.sun.grizzly.BaseSelectionKeyHandler.notifyRemotlyClose(BaseSelect
ionKeyHandler.java:233)
at com.sun.grizzly.util.OutputWriter.notifyRemotelyClosed(OutputWriter.j
ava:353)
at com.sun.grizzly.util.OutputWriter.flushChannel(OutputWriter.java:148)
at com.sun.grizzly.util.OutputWriter.flushChannel(OutputWriter.java:76)
at com.sun.grizzly.http.SocketChannelOutputBuffer.flushChannel(SocketCha
nnelOutputBuffer.java:326)
at com.sun.grizzly.http.SocketChannelOutputBuffer.flushBuffer(SocketChan
nelOutputBuffer.java:398)
at com.sun.grizzly.http.SocketChannelOutputBuffer.flush(SocketChannelOut
putBuffer.java:376)
at com.sun.grizzly.http.ProcessorTask.action(ProcessorTask.java:1247)
at com.sun.grizzly.tcp.Response.action(Response.java:268)
at com.sun.grizzly.tcp.http11.GrizzlyOutputBuffer.doFlush(GrizzlyOutputB
uffer.java:434)
at com.sun.grizzly.tcp.http11.GrizzlyOutputBuffer.flush(GrizzlyOutputBuf
fer.java:405)
at com.sun.grizzly.tcp.http11.GrizzlyOutputStream.flush(GrizzlyOutputStr
eam.java:140)
at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:24
0)
... 17 more
|#]
[#|2011-09-30T15:23:13.625+0530|INFO|glassfish3.1.1|org.hibernate.validator.util
.Version|_ThreadID=16;_ThreadName=admin-thread-pool-4848(1);|Hibernate Validator
4.1.0.Final|#]
[#|2011-09-30T15:29:36.406+0530|INFO|glassfish3.1.1|org.hibernate.validator.engi
ne.resolver.DefaultTraversableResolver|_ThreadID=16;_ThreadName=admin-thread-poo
l-4848(1);|Instantiated an instance of org.hibernate.validator.engine.resolver.J
PATraversableResolver.|#]
[#|2011-09-30T15:29:36.656+0530|INFO|glassfish3.1.1|javax.enterprise.system.core
.com.sun.enterprise.v3.admin.adapter|_ThreadID=18;_ThreadName=Thread-39;|The Adm
in Console is already installed, but not yet loaded.|#]
[#|2011-09-30T15:29:36.656+0530|INFO|glassfish3.1.1|javax.enterprise.system.core
.com.sun.enterprise.v3.admin.adapter|_ThreadID=18;_ThreadName=Thread-39;|The Adm
in Console is starting. Please wait.|#]
[#|2011-09-30T15:29:39.312+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Portable JNDI na
mes for EJB CustomerAuthentication : [java:global/com.wellzio.service.customer/C
ustomerAuthentication!com.wellzio.service.customer.ICustomerAuthentication, java
:global/com.wellzio.service.customer/CustomerAuthentication]|#]
[#|2011-09-30T15:29:39.312+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Glassfish-specif
ic (Non-portable) JNDI names for EJB CustomerAuthentication : [com.wellzio.servi
ce.customer.ICustomerAuthentication#com.wellzio.service.customer.ICustomerAuthen
tication, com.wellzio.service.customer.ICustomerAuthentication]|#]
[#|2011-09-30T15:29:39.437+0530|WARNING|glassfish3.1.1|javax.enterprise.system.t
ools.monitor.org.glassfish.admin.monitor|_ThreadID=10;_ThreadName=main;|MNTG0201
:Flashlight listener registration failed for listener class : com.sun.ejb.monito
ring.stats.StatelessSessionBeanStatsProvider , will retry later |#]
[#|2011-09-30T15:30:07.093+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Portable JNDI na
mes for EJB CreditCards : [java:global/com.wellzio.service.customer/CreditCards,
java:global/com.wellzio.service.customer/CreditCards!com.wellzio.service.custom
er.ICreditCards]|#]
[#|2011-09-30T15:30:07.093+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Glassfish-specif
ic (Non-portable) JNDI names for EJB CreditCards : [com.wellzio.service.customer
.ICreditCards#com.wellzio.service.customer.ICreditCards, com.wellzio.service.cus
tomer.ICreditCards]|#]
[#|2011-09-30T15:30:07.203+0530|WARNING|glassfish3.1.1|javax.enterprise.system.t
ools.monitor.org.glassfish.admin.monitor|_ThreadID=10;_ThreadName=main;|MNTG0201
:Flashlight listener registration failed for listener class : com.sun.ejb.monito
ring.stats.StatelessSessionBeanStatsProvider , will retry later |#]
[#|2011-09-30T15:30:08.671+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Portable JNDI na
mes for EJB TrialResponse : [java:global/com.wellzio.service.customer/TrialRespo
nse, java:global/com.wellzio.service.customer/TrialResponse!com.wellzio.service.
customer.ITrialResponse]|#]
[#|2011-09-30T15:30:08.671+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Glassfish-specif
ic (Non-portable) JNDI names for EJB TrialResponse : [com.wellzio.service.custom
er.ITrialResponse#com.wellzio.service.customer.ITrialResponse, com.wellzio.servi
ce.customer.ITrialResponse]|#]
[#|2011-09-30T15:30:08.796+0530|WARNING|glassfish3.1.1|javax.enterprise.system.t
ools.monitor.org.glassfish.admin.monitor|_ThreadID=10;_ThreadName=main;|MNTG0201
:Flashlight listener registration failed for listener class : com.sun.ejb.monito
ring.stats.StatelessSessionBeanStatsProvider , will retry later |#]
[#|2011-09-30T15:30:09.687+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Portable JNDI na
mes for EJB TrialRoleTypes : [java:global/com.wellzio.service.customer/TrialRole
Types, java:global/com.wellzio.service.customer/TrialRoleTypes!com.wellzio.servi
ce.customer.ITrialRoleTypes]|#]
[#|2011-09-30T15:30:09.687+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Glassfish-specif
ic (Non-portable) JNDI names for EJB TrialRoleTypes : [com.wellzio.service.custo
mer.ITrialRoleTypes#com.wellzio.service.customer.ITrialRoleTypes, com.wellzio.se
rvice.customer.ITrialRoleTypes]|#]
[#|2011-09-30T15:30:09.812+0530|WARNING|glassfish3.1.1|javax.enterprise.system.t
ools.monitor.org.glassfish.admin.monitor|_ThreadID=10;_ThreadName=main;|MNTG0201
:Flashlight listener registration failed for listener class : com.sun.ejb.monito
ring.stats.StatelessSessionBeanStatsProvider , will retry later |#]
[#|2011-09-30T15:30:10.828+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Portable JNDI na
mes for EJB TrialCustomerRoles : [java:global/com.wellzio.service.customer/Trial
CustomerRoles, java:global/com.wellzio.service.customer/TrialCustomerRoles!com.w
ellzio.service.customer.ITrialCustomerRoles]|#]
[#|2011-09-30T15:30:10.828+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Glassfish-specif
ic (Non-portable) JNDI names for EJB TrialCustomerRoles : [com.wellzio.service.c
ustomer.ITrialCustomerRoles, com.wellzio.service.customer.ITrialCustomerRoles#co
m.wellzio.service.customer.ITrialCustomerRoles]|#]
[#|2011-09-30T15:32:27.703+0530|WARNING|glassfish3.1.1|javax.enterprise.system.t
ools.monitor.org.glassfish.admin.monitor|_ThreadID=10;_ThreadName=main;|MNTG0201
:Flashlight listener registration failed for listener class : com.sun.ejb.monito
ring.stats.StatelessSessionBeanStatsProvider , will retry later |#]
[#|2011-09-30T15:32:28.984+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Portable JNDI na
mes for EJB CustomerRoles : [java:global/com.wellzio.service.customer/CustomerRo
les, java:global/com.wellzio.service.customer/CustomerRoles!com.wellzio.service.
customer.ICustomerRoles]|#]
[#|2011-09-30T15:32:28.984+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Glassfish-specif
ic (Non-portable) JNDI names for EJB CustomerRoles : [com.wellzio.service.custom
er.ICustomerRoles#com.wellzio.service.customer.ICustomerRoles, com.wellzio.servi
ce.customer.ICustomerRoles]|#]
[#|2011-09-30T15:32:29.109+0530|WARNING|glassfish3.1.1|javax.enterprise.system.t
ools.monitor.org.glassfish.admin.monitor|_ThreadID=10;_ThreadName=main;|MNTG0201
:Flashlight listener registration failed for listener class : com.sun.ejb.monito
ring.stats.StatelessSessionBeanStatsProvider , will retry later |#]
[#|2011-09-30T15:32:30.875+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Portable JNDI na
mes for EJB Trials : [java:global/com.wellzio.service.customer/Trials, java:glob
al/com.wellzio.service.customer/Trials!com.wellzio.service.customer.ITrials]|#]
[#|2011-09-30T15:32:30.875+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Glassfish-specif
ic (Non-portable) JNDI names for EJB Trials : [com.wellzio.service.customer.ITri
als, com.wellzio.service.customer.ITrials#com.wellzio.service.customer.ITrials]|
#]
[#|2011-09-30T15:32:31.015+0530|WARNING|glassfish3.1.1|javax.enterprise.system.t
ools.monitor.org.glassfish.admin.monitor|_ThreadID=10;_ThreadName=main;|MNTG0201
:Flashlight listener registration failed for listener class : com.sun.ejb.monito
ring.stats.StatelessSessionBeanStatsProvider , will retry later |#]
[#|2011-09-30T15:32:32.312+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Portable JNDI na
mes for EJB PhysicianAccount : [java:global/com.wellzio.service.customer/Physici
anAccount!com.wellzio.service.customer.IPhysicianAccount, java:global/com.wellzi
o.service.customer/PhysicianAccount]|#]
[#|2011-09-30T15:32:32.312+0530|INFO|glassfish3.1.1|javax.enterprise.system.cont
ainer.ejb.com.sun.ejb.containers|_ThreadID=10;_ThreadName=main;|Glassfish-specif
ic (Non-portable) JNDI names for EJB PhysicianAccount : [com.wellzio.service.cus
tomer.IPhysicianAccount#com.wellzio.service.customer.IPhysicianAccount, com.well
zio.service.customer.IPhysicianAccount]|#]
[#|2011-09-30T15:32:32.468+0530|WARNING|glassfish3.1.1|javax.enterprise.system.t
ools.monitor.org.glassfish.admin.monitor|_ThreadID=10;_ThreadName=main;|MNTG0201
:Flashlight listener registration failed for listener class : com.sun.ejb.monito
ring.stats.StatelessSessionBeanStatsProvider , will retry later |#]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Accessing to a NSMutableArray in UITableViewController crashes I'm new in Object-c and want to make a UITableViewController based app with JSON data source in Xcode 4.
I imported the JSON framework and defined an NSMutableArray to fill it with the response:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
items = [responseString JSONValue];
[self.tableView reloadData];
}
I Everything went well but when I try to access my items array in the
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
function, it crashes my app.
What could be the problem?
Thanks in advance!
UPDATE:
I modified the array filling part of the code and it solved the crash problem:
NSMutableArray *a = [responseString JSONValue];
for(NSDictionary *it in a) {
[items addObject:it];
}
But I still don't know why...
A: It semms like you assign the JSON-Value to an instance variable.
The object is autoreleased ("JSONValue" doesn't contain the words alloc, init or copy) so it will go away some near time in the future.
Try adding a property for your object:
Header:
@property (nonatomic, retain) NSArray *items;
Implementation:
@synthesize items;
...
self.items = [responseString JSONValue];
...
- (void)dealloc {
...
self.items = nil;
[super dealloc];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608927",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Method to instantiate objects Would like to create a method that instantiate objects.
- (NSArray *) make3Of : (Class) type
{
...
type * temp = [[type alloc] ...
...
}
But I get a warning from Xcode ...
Actual warning:
"Class method +alloc not found (return type defaults to 'id')"
Is there a better/correct way to do this?
Actual code:
- (NSArray *) getBoxesOfType: (Class <ConcreteBox>) type StartingFrom: (uint64_t) offset
{
NSMutableArray *valueArray = [[NSMutableArray alloc]initWithObjects: nil];
for (uint64_t i = offset; i< boxStartFileOffset + self.size; i += [self read_U32_AtBoxOffset:i])
{
if ([[self read_String_OfLen:4 AtBoxOffset:offset + 4] isEqual:[type typecode]]) {
[[type alloc]initWithFile:file withStartOffset:i]; //warning here;
//yes I plan to assign it to a variable
//(originally of "type" but that won't work as AliSoftware pointed out, will be using "id" instead.
...
}
}
}
Same as example, I'm trying to instantiate a couple of objects.
Code for protocol:
#import <Foundation/Foundation.h>
@protocol ConcreteBox
+ (NSString *) typecode;
- (id) initWithFile: (NSFileHandle *) aFile withStartOffset: (uint64_t) theOffset;
@end
A: You can't use a variable (in your case type)... as a type for another variable!
In your code, both type and temp are variables, that's a syntax error.
As you don't know the type of the variable as compile time, use the dynamic type id instead. This type is specifically designed to handle cases when the type is not defined at compile time.
So your code will look like this:
-(NSArray*)make3Of:(Class)type {
id obj1 = [[[type alloc] init] autorelease];
id obj2 = [[[type alloc] init] autorelease];
id obj3 = [[[type alloc] init] autorelease];
return [NSArray arrayWithObjects:obj1, obj2, obj3, nil];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can i put text under each imagaview In my project i am using images as button in horizontalscrollview. When i click an image it shows the image above the horizantalscrollview. What i want is to show a description text under the image when i click it. Can anyhone help?
Here is my xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout android:id="@+id/LinearLayout01"
android:layout_width="match_parent" android:layout_height="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:orientation="vertical" android:background="@color/white">
<ImageView android:layout_gravity="center" android:src="@drawable/a1"
android:layout_height="200dp" android:id="@+id/IVdisplay"
android:layout_width="200dp"></ImageView>
<TextView android:layout_width="wrap_content"
android:id="@+id/Aciklama"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#AA000000" android:textColor="#ffffffff"
android:text="fghhhhhhhhhhhhhhtyuyjhjkghklşklşkl"
/>
<HorizontalScrollView android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_gravity="bottom">
<LinearLayout android:layout_gravity="bottom"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<ImageView android:src="@drawable/a1"
android:layout_height="125dp" android:id="@+id/IVimage1"
android:layout_width="125dp" android:padding="15dp"></ImageView>
<ImageView android:src="@drawable/a2"
android:layout_height="125dp" android:id="@+id/IVimage2"
android:layout_width="125dp" android:padding="15dp"></ImageView>
<ImageView android:src="@drawable/a3"
android:layout_height="125dp" android:id="@+id/IVimage3"
android:layout_width="125dp" android:padding="15dp"></ImageView>
<ImageView android:src="@drawable/a4"
android:layout_height="125dp" android:id="@+id/IVimage4"
android:layout_width="125dp" android:padding="15dp"></ImageView>
<ImageView android:src="@drawable/a5"
android:layout_height="125dp" android:id="@+id/IVimage5"
android:layout_width="125dp" android:padding="15dp"></ImageView>
<ImageView android:src="@drawable/a6"
android:layout_height="125dp" android:id="@+id/IVimage6"
android:layout_width="125dp" android:padding="15dp"></ImageView>
<ImageView android:src="@drawable/a7"
android:layout_height="125dp" android:id="@+id/IVimage7"
android:layout_width="125dp" android:padding="15dp"></ImageView>
<ImageView android:src="@drawable/a8"
android:layout_height="125dp" android:id="@+id/IVimage8"
android:layout_width="125dp" android:padding="15dp">
</ImageView>
</LinearLayout></HorizontalScrollView></LinearLayout>
Here is my java file.
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import android.app.Activity;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ImageView;
public class varningsmarken extends Activity implements View, OnClickListener {
ImageView display;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.varningsmarken);
AdView ad = (AdView) findViewById(R.id.adView2);
ad.loadAd(new AdRequest());
display = (ImageView) findViewById (R.id.IVdisplay);
ImageView image1 = (ImageView) findViewById (R.id.IVimage1);
ImageView image2 = (ImageView) findViewById (R.id.IVimage2);
ImageView image3 = (ImageView) findViewById (R.id.IVimage3);
ImageView image4 = (ImageView) findViewById (R.id.IVimage4);
ImageView image5 = (ImageView) findViewById (R.id.IVimage5);
ImageView image6 = (ImageView) findViewById (R.id.IVimage6);
ImageView image7 = (ImageView) findViewById (R.id.IVimage7);
ImageView image8 = (ImageView) findViewById (R.id.IVimage8);
ImageView image9 = (ImageView) findViewById (R.id.IVimage9);
ImageView image10 = (ImageView) findViewById (R.id.IVimage10);
ImageView image11 = (ImageView) findViewById (R.id.IVimage11);
ImageView image12 = (ImageView) findViewById (R.id.IVimage12);
ImageView image13 = (ImageView) findViewById (R.id.IVimage13);
ImageView image14 = (ImageView) findViewById (R.id.IVimage14);
ImageView image15 = (ImageView) findViewById (R.id.IVimage15);
ImageView image16 = (ImageView) findViewById (R.id.IVimage16);
ImageView image17 = (ImageView) findViewById (R.id.IVimage17);
ImageView image18 = (ImageView) findViewById (R.id.IVimage18);
ImageView image19 = (ImageView) findViewById (R.id.IVimage19);
image1.setOnClickListener(this);
image2.setOnClickListener(this);
image3.setOnClickListener(this);
image4.setOnClickListener(this);
image5.setOnClickListener(this);
image6.setOnClickListener(this);
image7.setOnClickListener(this);
image8.setOnClickListener(this);
image9.setOnClickListener(this);
image10.setOnClickListener(this);
image11.setOnClickListener(this);
image12.setOnClickListener(this);
image13.setOnClickListener(this);
image14.setOnClickListener(this);
image15.setOnClickListener(this);
image16.setOnClickListener(this);
image17.setOnClickListener(this);
image18.setOnClickListener(this);
image19.setOnClickListener(this);
public void onClick(android.view.View v) {
switch (v.getId()){
case R.id.IVimage1:
display.setImageResource(R.drawable.a1);
break;
case R.id.IVimage2:
display.setImageResource(R.drawable.a2);
break;
case R.id.IVimage3:
display.setImageResource(R.drawable.a3);
break;
case R.id.IVimage4:
display.setImageResource(R.drawable.a4);
break;
case R.id.IVimage5:
display.setImageResource(R.drawable.a5);
break;
case R.id.IVimage6:
display.setImageResource(R.drawable.a6);
break;
case R.id.IVimage7:
display.setImageResource(R.drawable.a7);
break;
case R.id.IVimage8:
display.setImageResource(R.drawable.a8);
break;
}
}
}
A: You can do something like
TextView desc = (TextView)findViewById(R.id.Aciklama);
desc.setText(DESCRIPTION);
You do exactly what you did with the display imageview. Create a reference to the textview and setText to it on click.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Resources$NotFoundException in ListView I always get a Resources$NotFoundException but i don't know why. Please help
Code:
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
LayoutInflater li = (LayoutInflater)CustomAdapter.this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = li.inflate(R.layout.customlistitem,null);
holder.mTexttitle = (TextView) convertView.findViewById(R.id.item_title);
holder.mTextrate = (TextView) convertView.findViewById(R.id.item_rate);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
holder.mTexttitle.setText(pizzen.get(position).title);
holder.mTextrate.setText(pizzen.get(position).rate);
//holder.mTextdate.setText(pizzen.get(position).date.toString());
return convertView;
}
public class ViewHolder {
public TextView mTexttitle;
public TextView mTextrate;
public TextView mTextdate;
public ImageView mImageView;
}
Stacktrace:
09-30 10:11:07.001: ERROR/XXX List View(1032): android.widget.ListView@43d133c0
09-30 10:11:07.021: ERROR/XXX(1032): Courser Enter: EditText
09-30 10:11:07.031: ERROR/XXX(1032): Count:1
09-30 10:11:07.031: ERROR/XXX(1032): Item[0] -->com.korn.pizzacounter.Pizza@43d16468
09-30 10:11:07.031: ERROR/XXX(1032): 1
09-30 10:11:07.101: ERROR/AndroidRuntime(1032): Uncaught handler: thread main exiting due to uncaught exception
09-30 10:11:07.121: ERROR/AndroidRuntime(1032): android.content.res.Resources$NotFoundException: String resource ID #0x2
09-30 10:11:07.121: ERROR/AndroidRuntime(1032): at android.content.res.Resources.getText(Resources.java:200)
09-30 10:11:07.121: ERROR/AndroidRuntime(1032): at android.widget.TextView.setText(TextView.java:2813)
09-30 10:11:07.121: ERROR/AndroidRuntime(1032): at com.korn.pizzacounter.CustomAdapter.getView(CustomAdapter.java:44)
09-30 10:11:07.121: ERROR/AndroidRuntime(1032): at android.widget.AbsListView.obtainView(AbsListView.java:1274)
09-30 10:11:07.121: ERROR/AndroidRuntime(1032): at android.widget.ListView.makeAndAddView(ListView.java:1668)
09-30 10:11:07.121: ERROR/AndroidRuntime(1032): at android.widget.ListView.fillDown(ListView.java:637)
A: holder.mTextrate.setText(pizzen.get(position).rate);
If rate is int, then android thinks you passed resource id and tries to find resource. You need explicitly convert int to String: String.valueOf(pizzen.get(position).rate)
Is rate really int?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Google App Engine(java) - App upload failed due to app size limit exceeded - (free account) i am using Google app engine for my development, my project involves around 60 PDfs to be available for users to download.
when i try to upload the project by clicking deploy button in eclipse i get the error app limit exceeded.
i just want to know if i try to use the paid account is there is a different in the application size in paid account or not?
as far as i know its 150 MB for now
A: You should use Blobstore service to store your PDF files and keep application only for files needed by your application logic and presentation, not data. Here is description of the Blobstore:
The Blobstore API allows your app to serve data objects, called blobs,
that are much larger than the size allowed for objects in the
Datastore service. Blobs are created by uploading a file through an
HTTP request. Typically, your apps will do this by presenting a form
with a file upload field to the user. When the form is submitted, the
Blobstore creates a blob from the file's contents and returns an
opaque reference to the blob, called a blob key, which you can later
use to serve the blob.
A: All good advice above, try to avoid putting content like that in your code. My app hit this issue and only has about 10MB of code/images/resources. What takes up a lot of space is the GWT compiling of 15 permutations of your app.
One thing that helped me, was changing my GWT javascript generation output style from Details to Obfuscated, resulting in much smaller code. You can also limit the number of permutations being created.
https://developers.google.com/web-toolkit/doc/1.6/FAQ_DebuggingAndCompiling#Can_I_speed_up_the_GWT_compiler?
A: upto 10MB data u can upload to ur app engine
see following link
http://code.google.com/appengine/docs/quotas.html
A: According to http://code.google.com/intl/de/appengine/docs/quotas.html#Deployments the applications may not exceed 10 MB.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: sencha-touch width of tab panel decreases -I have a problem here
tabBarDock: 'bottom'
reduces the height of the tab panel, from default top height.
-Please help
Ext.setup({
icon:'icon.png',
glossOnIcon: false,
onReady:function(){
new Ext.TabPanel({
fullscreen: true,
type: 'dark',
sortable: true,
tabBarDock: 'bottom',
items: [{
title: 'Tab 1',
html: '1',
cls: 'card1'
}, {
title: 'Tab 2',
xtype:'map',
useCurrentLocation: true,
fullscreen:true,
layout:'fit',
cls: 'card2'
}, {
title: 'Tab 3',
html: '3',
cls: 'card3'
}]
});
}});
A: When the tab bar is docked to the bottom you must include a iconCls property in order to have get the default top height. See example:
Ext.setup({
icon:'icon.png',
glossOnIcon: false,
onReady:function(){
new Ext.TabPanel({
fullscreen: true,
ui: 'dark',
sortable: true,
tabBarDock: 'bottom',
items: [{
title: 'Tab 1',
iconCls:'home',
html: '1',
cls: 'card1'
}, {
title: 'Tab 2',
iconCls:'locate',
xtype:'map',
useCurrentLocation: true,
fullscreen:true,
layout:'fit',
cls: 'card2'
}, {
title: 'Tab 3',
html: '3',
iconCls:'search',
cls: 'card3'
}]
});
}});
Also the Ext.TapPanel doesn't have type property. I think you meant the ui property.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What does the 'hides constructor for' warning mean when compiling C++ with g++? Using the following code:
#include <stdio.h>
struct my_struct {
int a;
int b;
my_struct();
};
my_struct::my_struct(void)
{
printf("constructor\n");
}
void my_struct(void)
{
printf("standard function\n");
}
int main (int argc, char *argv[])
{
struct my_struct s;
s.a = 1;
s.b = 2;
printf("%d-%d\n", s.a, s.b);
return 0;
}
I get a warning compiling with g++ -Wshadow main.cpp:
main.cpp:15:20: warning: ‘void my_struct()’ hides constructor for ‘struct my_struct’
I would be ok with that warning if the void my_struct function actually replaced the my_struct::my_struct one. But it does not appears to be the case. If I run the program, I get:
constructor
1-2
Any idea what this warning mean ? It is quite annoying especially when I include C headers into C++ code
A: The warning points out that the my_struct() function has the same name as the my_struct structure. It means you will be unable to write:
my_struct s; // Error.
Because the compiler will think that you're using a function as a type. However, as you probably realized, you can still instantiate your structure with the struct keyword:
struct my_struct s; // Valid.
A: void my_struct(void) has the same name of your class/struct and since it is in the global namespace it is conflicting with your class/struct's constructor.
You could try something like:
#include <cstdio>
struct my_struct {
int a;
int b;
my_struct();
};
my_struct::my_struct(void)
{
printf("constructor\n");
}
namespace mbonnin
{
void my_struct(void);
}
void mbonnin::my_struct(void)
{
printf("standard function\n");
}
int main (int argc, char *argv[])
{
my_struct s;
s.a = 1;
s.b = 2;
printf("%d-%d\n", s.a, s.b);
mbonnin::my_struct();
return 0;
}
And by the way the struct in struct my_struct s; is redundant in C++.
A:
warning: ‘void my_struct()’ hides constructor for ‘struct my_struct’
Any idea what this warning mean ?
It means that sometimes the warnings issued by the GNU compiler suite are a bit off. (Try omitting the semicolon after the close brace on the definition of struct my_struct. If you are using anything but a very recent version of g++ the error message will be a bit off.)
Something is being hidden here, but it is not the constructor for struct my_struct. What is being hidden is the name my_struct as a type identifier. You can see this in action if you remove the struct from the declaration of the variable s: Use my_struct s; instead of struct my_struct s; Without the contextual information offered by the struct keyword, the compiler now must interpret my_struct as a function name.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Generic keyCompare method please look through the following program..
#include <stdio.h>
#include <malloc.h>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char *key1 = (char*)malloc(sizeof(char)*26);
char *key2 = (char*)malloc(sizeof(char)*26);
int intkey1 = 10;
int intkey2 = 10;
float floatkey1 = 13.5f;
float floatkey2 = 13.5f;
double doublekey1 = 18.5;
double doublekey2 = 18.5;
char charkey1[10] = "nikhil";
char charkey2[10] = "nikhil";
//cout<<sizeof(int)<<" "<<sizeof(float)<<" "<<sizeof(double)<<endl;
memcpy(key1,&intkey1,sizeof(int));
memcpy(key2,&intkey2,sizeof(int));
int offset = sizeof(int);
memcpy(&key1[offset],&floatkey1,sizeof(float));
memcpy(&key2[offset],&floatkey2,sizeof(float));
offset = offset + sizeof(float);
memcpy(&key1[offset],&doublekey1,sizeof(double));
memcpy(&key2[offset],&doublekey2,sizeof(double));
offset = offset + sizeof(double);
memcpy(&key1[offset],charkey1,sizeof(charkey1));
memcpy(&key2[offset],charkey2,sizeof(charkey2));
int diff = memcmp(key1,key2,26);
if( diff > 0)
cout<<"Key1 is greater than key2"<<endl;
else if(diff < 0)
cout<<"Key1 is smaller than key2"<<endl;
else
cout<<"Both keys are equal"<<endl;
}
I am developing a B+ tree for a database engine for which i need a generic keyCompare method...Is this way of comparing byte streams by memcpy always the safe and foolproof or should i need to compare based on the types of the fields present in char key that i get from scanning column information present in the database engine? IS this fastest?
A:
Is this way of comparing byte streams by memcpy always the safe and foolproof
It doesn't produce the correct result with integers and floats on little-endian architectures. And it can't handle special floating point values like inf and nan.
or should i need to compare based on the types of the fields present in char key that i get from scanning column information present in the database engine?
It should compare types using type-specific methods. For strings that involves using locales.
A: All those extra allocations are not going to improve your performance, not to speak of the difficulties in writing that code correctly.
Since all the types are just primitives or arrays of primitives, you should probably just go with the straight-forward lexicographic comparison. For your ordering you only need to implement "less than", so do this lexicographically for each key. If the key is itself an array, you can use std::lexicographical_compare as a primitive.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: URL validation/connectivity using javascript I want to verify if an external url valid/exists/responsive using javascript. For example, "www.google.com" should return true and "www.google123.com" should return false.
I thought to use AJAX for this purpose by testing : if (xmlhttp.readyState == 4 && xmlhttp.status == 200) but it seems that this doesn't work for remote servers(external urls). As my server uses a proxy, i planned to use browser side script so that it automatically uses user's browser proxy if present.
Please tell me do I have to use "AJAX Cross Domain"? How to achieve this, as i simply want to validate a url.
Any way other than using AJAX?
A: I'm pretty sure this is not possible. Any AJAX that allowed you to call a random page on another domain in the user's context would open up all sorts or security holes.
You will have to use a server-side solution.
A: The usual way to avoid cross-domain issues is to inject a tag. Tags like image or script kan load their content from any domain. You could inject, say a script tag with type "text/x-unknown" or something, and listen to the tags load-event. When the load event triggers, you can remove the script tag from the page again.
Of course, if the files you are looking for happens to be images, then you could new Image() instead. That way you don't have to pollute the page by injecting tags, because images load when they are created (this can be used to preload images). Again, just wait for the load event on the image.
UPDATE
Okay, it seems I am jumping to conclusions here. There is some differences between browsers on how this can be supported. The following is a complete example, of how to use the script tag for validating urls in IE9 and recent versions of Firefox, Chrome and Safari.
It does not work in older versions of IE (IE8 at least) because apparently they don't provide load/error events for script-tags.
Firefox refuses to load anything if the contenttype for the script-tag is not empty or set to 'text/javascript'. This means that it may be somewhat dangerous to use this approach to check for scriptfiles. It seems like the script tag is deleted before any code is executed in my tests, but I don't for sure...
Anyways, here is the code:
<!doctype html>
<html>
<head>
<script>
function checkResource(url, callback) {
var tag = document.createElement('script');
tag.src = url;
//tag.type = 'application/x-unknown';
tag.async = true;
tag.onload = function (e) {
document.getElementsByTagName('head')[0].removeChild(tag);
callback(url, true);
}
tag.onerror = function (e) {
document.getElementsByTagName('head')[0].removeChild(tag);
callback(url, false);
}
document.getElementsByTagName('head')[0].appendChild(tag);
}
</script>
</head>
<body>
<h1>Testing something</h1>
<p>Here is some text. Something. Something else.</p>
<script>
checkResource("http://google.com", function (url, state) { alert(url + ' - ' + state) });
checkResource("http://www.google.com/this-does-not-exists", function (url, state) { alert(url + ' - ' + state) });
checkResource("www.asdaweltiukljlkjlkjlkjlwew.com/does-not-exists", function (url, state) { alert(url + ' - ' + state) });
</script>
</body>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jqplot enhancedLegendRendrer seriesToggle functionality override I am trying to change the default functionality of enhancedLegendRendrer.js where in on clicking on the legend series that particular bar item in the graph gets visible/hidden.I want to change this default functionality, wherein if the user clicks on the legend series item only that series is displayed while rest of the bars are made invisible.
A: Jumped the gun on the post and now cannot delete. Thought the above was asking how to enable toggling on legend. Anyway, for anyone interested:
https://bitbucket.org/jab/jqplot/src/edd2f5972593/examples/legendLabels.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# Regular Expression: How to extract a collection I have collection in text file:
(Collection
(Item "Name1" 1 2 3)
(Item "Simple name2" 1 2 3)
(Item "Just name 3" 4 5 6))
Collection also could be empty:
(Collection)
The number of items is undefined. It could be one item or one hundred. By previous extraction I already have inner text between Collection element:
(Item "Name1" 1 2 3)(Item "Simple name2" 1 2 3)(Item "Just name 3" 4 5 6)
In the case of empty collection it will be empty string.
How could I parse this collection using .Net Regular Expression?
I tried this:
string pattern = @"(\(Item\s""(?<Name>.*)""\s(?<Type>.*)\s(?<Length>.*)\s(?<Number>.*))*";
But the code above doesn't produce any real results.
UPDATE:
I tried to use regex differently:
foreach (Match match in Regex.Matches(document, pattern, RegexOptions.Singleline))
{
for (int i = 0; i < match.Groups["Name"].Captures.Count; i++)
{
Console.WriteLine(match.Groups["Name"].Captures[i].Value);
}
}
or
while (m.Success)
{
m.Groups["Name"].Value.Dump();
m.NextMatch();
}
A: Try
\(Item (?<part1>\".*?\")\s(?<part2>\d+)\s(?<part3>\d+)\s(?<part4>\d+)\)
this will create a collection of matches:
Regex regex = new Regex(
"\\(Item (?<part1>\\\".*?\\\")\\s(?<part2>\\d+)\\s(?<part3>\\d"+
"+)\\s(?<part4>\\d+)\\)",
RegexOptions.Multiline | RegexOptions.Compiled
);
//Capture all Matches in the InputText
MatchCollection ms = regex.Matches(InputText);
//Get the names of all the named and numbered capture groups
string[] GroupNames = regex.GetGroupNames();
// Get the numbers of all the named and numbered capture groups
int[] GroupNumbers = regex.GetGroupNumbers();
A: I think you might need to make your captures non-greedy...
(?<Name>.*?)
instead of
(?<Name>.*)
A: I think you should read file and than make use of Sting.Split function to split the collection and start to read it
String s = "(Collection
(Item "Name1" 1 2 3)
(Item "Simple name2" 1 2 3)
(Item "Just name 3" 4 5 6))";
string colection[] = s.Split('(');
if(colection.Length>1)
{
for(i=1;i<colection.Length;i++)
{
//process string one by one and add ( if you need it
//from the last item remove )
}
}
this will resolve issue easily there is no need of put extra burden of regulat expression.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Loading a view specific stylesheet in an asp.net mvc3 app? I'm trying to load a view specific stylesheet in an asp.net mvc3 application (just learning this stuff!), so in my _Layout.cshtml I have:
<head>
<!--- All the common css & JS declarations here -->
@ViewBag.PageIncludes
</head>
<body>
Then in my controller I have:
public ActionResult Index()
{
ViewBag.PageIncludes = "<link rel='stylesheet' type='text/css' href='../Content/viewspecificstylesheet.css')' />";
return View();
}
However, when I view the page, even though the declaration is in the head, the text is rendered in the body, and thus rendered as text.
A couple of questions as a result:
Why, even though I declare in the head is this rendered in the body?
What is the best practice for loading a specific stylesheet for a given view/controller?
Thanks
A: You could use sections:
<head>
<!--- All the common css & JS declarations here -->
@RenderSection("Styles", false)
</head>
<body>
...
</body>
and then in the Index.cshtml view:
@section Styles {
<link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/viewspecificstylesheet.css")" />
}
<div>This is the index view</div>
and your controller no longer needs to worry about styles which is purely view specific responsibility:
public ActionResult Index()
{
return View();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Spring - jdbcTemplate I'm just beginning with Spring framework. I'm also using DBCP pooling and i'm still not sure how to work right with jdbcTemplate.
It is best practice to reuse created/injected jdbcTemplate instance between multiple DAOs or it is right to create jdbcTemplate for each DAO ?
I'm currently using annotation approach:
public class FooDAO {
private JdbcTemplate jdbcTemplate;
@Autowired
public void setDatasource( DataSource dataSource ) {
this.jdbcTemplate = new JdbcTemplate( dataSource );
}
}
I'm aware about JdbcDaoSupport, but I don't know how to inject datasource, because method setDatasource is marked as final.
But still, I'm not sure if is best practice to reuse created jdbcTemplate or not.
A: Inject it in and share it. Don't call "new"; that takes control out of the hands of the Spring bean factory.
A: I'm aware about JdbcDaoSupport, but I don't know how to inject datasource, because method setDatasource is marked as final.
public class JdbcDaoSupportTest extends JdbcDaoSupport {
public void insert() {
this.getJdbcTemplate().execute("insert into tb_test1 values(1,'ycl','123')");
System.out.println("complete...");
}
}
Spring call set Method, don't care whether the method is final or not.
<bean id="jdbcDaoSupportTest" class="com.xxxxx.JdbcDaoSupportTest">
<property name="dataSource" ref="dataSource" />
</bean>
then in your JdbcDaoSupportTest, you can call this.getJdbcTemplate() to get JdbcTemplate do
any operator.
A: try {
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
String sql = "select user.id as id,user.roll_no as createdId,user.name as name,user.type as company,role.role as year "
+ "from user_role join user on user.id=user_role.user_id "
+ "join role on role.id=user_role.role_id "
+ "where (user.status='ACTIVE' or user.status='ADMIN') AND user.username='" + userName + "'";
UserVo userDetails = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<UserVo>(UserVo.class));
or
Long company = jdbcTemplate.queryForObject(sql, Long.class);
or
List<UserVo> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<UserVo>(UserVo.class));
logger.info("Retrieve user details by username");
return userDetails;
} catch (Exception e) {
logger.error("error in getting UserDetails using UserName", e);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: android.view.InflateException: Binary XML , and OutOfMemoryError? I am, using nearly 90 very big images,and i am using lazy loading for displaying that images in Gallery,and grid view.so after loading the images ,if you click on any button,it giving outofmemory(oom) error,and sometimes it giving Xml binary inflate exception.
I am using very big images,equal to tablet size images,and my apk size is 25MB,.and i am using single activity with multiple FrameLayouts but before loading new View I am removing current view but still problem is there,I dont know why it is happening ?Its giving the oom error but its not giving the exact location of error,and its giving error at random position and error coming frequently.
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): FATAL EXCEPTION: main
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): android.view.InflateException: Binary XML file line #13: Error inflating class <unknown>
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.view.LayoutInflater.createView(LayoutInflater.java:596)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:644)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:669)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.view.LayoutInflater.rInflate(LayoutInflater.java:724)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.view.LayoutInflater.inflate(LayoutInflater.java:479)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.view.LayoutInflater.inflate(LayoutInflater.java:391)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at com.maheshbabu.app.JustIn.initialize(JustIn.java:143)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at com.maheshbabu.app.JustIn.<init>(JustIn.java:135)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at com.maheshbabu.app.MaheshBabuHomePage.showLatestPage(MaheshBabuHomePage.java:671)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at com.maheshbabu.app.MaheshBabuHomePage.onClick(MaheshBabuHomePage.java:363)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.view.View.performClick(View.java:3110)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.view.View$PerformClick.run(View.java:11934)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.os.Handler.handleCallback(Handler.java:587)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.os.Handler.dispatchMessage(Handler.java:92)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.os.Looper.loop(Looper.java:132)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.app.ActivityThread.main(ActivityThread.java:4123)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at java.lang.reflect.Method.invokeNative(Native Method)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at java.lang.reflect.Method.invoke(Method.java:491)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at dalvik.system.NativeStart.main(Native Method)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): Caused by: java.lang.reflect.InvocationTargetException
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at java.lang.reflect.Constructor.constructNative(Native Method)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at java.lang.reflect.Constructor.newInstance(Constructor.java:416)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.view.LayoutInflater.createView(LayoutInflater.java:576)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): ... 21 more
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): Caused by: java.lang.OutOfMemoryError
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:483)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:351)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:738)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.content.res.Resources.loadDrawable(Resources.java:1918)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.view.View.<init>(View.java:2450)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.view.View.<init>(View.java:2389)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.view.ViewGroup.<init>(ViewGroup.java:359)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): at android.widget.RelativeLayout.<init>(RelativeLayout.java:173)
09-30 15:23:07.490: ERROR/AndroidRuntime(5527): ... 24 more
A: I think this exception is comming from
setContentView(R.layout.main);
line this may be because of various reasons.
1) Because you are changing your screen orientation from potrait to landscape and vice versa
Sol) Fix your view to any one orientation. Actually on orientation change new views and new objects are created along with old view and object . thus taking your memory
2) Objects are not freed
sol) Removing views will not solve your problem you have to free all the objects related to those views. Call Bitmap.recycle() on every image related to those views.
also check out these links which may be helpful to you
How to get rid of out of memory exception
Check out this video which may be very useful for you
Memory management for Android Apps
Happy coding friend
A: I have solved it in a tricky way.
I have two layout
1) layout_splash : layout of Splash
2) layout_map: Layout which contain map fragment and which cause crash;
In onCreate of My first activity (Launching Activity - SplashActivity.java) I have done like the following.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
if(close){
finish();
System.exit(0);
}
setContentView(R.layout.layout_map);
setContentView(R.layout.layout_splash);
.......
.......
.......
} catch (Exception e) {
Intent intent = new Intent(SplashScreenActivity.this,LowMemoryDialogActivity.class);
startActivity(intent);
//The below code will prevent showing crash dialog.
System.exit(1);
}
}
LowMemoryDialogActivity.java
public class LowMemoryDialogActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_low_memory_dialog);
}
@Override
public void onBackPressed() {
SplashScreenActivity.close=true;
super.onBackPressed();
}
}
activity_low_memory_dialog.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Low Memory"
android:id="@+id/textView6"
android:layout_above="@+id/textView5"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Please insert SD card for proper working!"
android:id="@+id/textView5"
android:textSize="20sp"
android:gravity="center"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</LinearLayout>
by inserting setContentView(R.layout.layout_map) first time in a try catch, we can understand the possibilities of future crash and we can handle that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Tokenize a string in KornShell I need to tokenize in string in KornShell (ksh). I have got the following script for bash; but it does not seem to work in ksh.
The script is below. Please help in making work for ksh.
OLDIFS=$IFS
IFS=","
read -a array <<< "$(printf "%s" "$APPLICATION_NAMES")"
IFS=$OLDIFS
for i in "${array[@]}"
do
:
# do whatever on $i
echo "Checking status of $i"
done
A: # s=a,b,c
# IFS=,
# set -A arr $s
# for e in "${arr[@]}"; do print -- "$e"; done
a
b
c
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: move() element on window.resize() function not working on Android This is the move() function
function move(){
/*calculate*/
var size = { x: $(window).width(), y: $(window).height() };
var scroll = { x: $(window).scrollLeft(), y: $(window).scrollTop() };
var height = h!=null ? h : this.esqueleto.lightbox.outerHeight();
var width = w!=null ? w : this.esqueleto.lightbox.outerWidth();
var y = 0;
var x = 0;
//vertically center
x = scroll.x + ((size.x - width) / 2);
if (this.visible) {
y = scroll.y + (size.y - height) / 2;
} else if (this.options.emergefrom == "bottom") {
y = (scroll.y + size.y + 14);
} else {// top
y = (scroll.y - height) - 14;
}
/*Process*/
if (!this.animations.move) {
this.morph(this.esqueleto.move, {
'left' : x
}, 'move');
}
this.morph(this.esqueleto.move, {
'top' : y
}, 'move');
} else {
this.esqueleto.move.css({
'left' : x,
'top' : y
});
}
}
Any idea why is this working in desktop (all browsers), iphone, .. but not in Android?
A: I'm pretty certain scrollLeft doesn't work on android for some reason. Works beautifully on iOS, but I could never get it to work on android. Give it a test and see if you are actually getting a value back for it.
Edit: not just the function scrollLeft(), but really anything to do with horizontal scrolling doesn't seem to work in android.
A workaround I'm using to get things to actually move left/right is are the css properties:
-webkit-transform
-webkit-transition-property
-webkit-transition-timing-function
-webkit-transition-duration
However that might not work for you since you're really just trying to get the value rather than actually move something.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Incomplete definition of type "struct objc_method" I'm really confused with this problem. What I need to do is use some obj-c runtime feature in my project. Here is simple code in my .m file:
#import "Base.h"
#import <objc/runtime.h>
@implementation Base
- (void)someMethod {
NSUInteger numberMethods = 0;
Method *classMethods = class_copyMethodList([self class], &numberMethods);
for (int i = 0; i < numberMethods; i ++) {
classMethods[i]->method_name; //incomplete definition of type "struct objc_method"
}
@end
I got the following error: incomplete definition of type "struct objc_method". After some inspecting objc/runtime.h file I found something like this:
some code...
typedef struct objc_method *Method;
...some code...
struct objc_method {
SEL method_name OBJC2_UNAVAILABLE;
char *method_types OBJC2_UNAVAILABLE;
IMP method_imp OBJC2_UNAVAILABLE;
}
Is this something like forward declaration problem, or something else?
A: In addition to Martin answer, you should use functions like method_getName to retrieve the name of the method classMethods[i].
This is much more portable (especially these fields in the structure no longer exists since Objective-C 2.0 as the macro suggests) and will avoid problems like the one you have when the Runtime evolves.
A: These members cannot be accessed!
OBJC2_UNAVAILABLE macro indicates that a member is not available and only provides some insight into the structure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: error return code from pthread_create is 35 error due to many processes,I have used pthread_exit which should kill the thread isn't it? I have create a pthread_create inside a pthread_create, I have used socket programming, where I receive a packet and then create a thread which does the writing to the file. When I send a very large file, i get this error...??
The code is as follows...
void *writePack(void *sock)
{
size_t nbyte;
ssize_t writeSize;
nbyte = 1466;
off_t offset;
offset = (((struct writePacket *)sock)->seq * 1466);
char* buffer = new char();
buffer = ((struct writePacket *)sock)->datamsg;
writeSize = pwrite(((struct writePacket *)sock)->pp,(const void *)buffer, nbyte, offset );
free(buffer);
pthread_exit(NULL);
}
this is the code of the parent receive code...
recvfrom(sockA->sockid, (void *)&recvdata, sizeof(struct data), 0, (struct sockaddr *) &cli_addr, &clilen);
if (n<0)
error("Error on reading");
pthread_mutex_lock(&qlock);
struct writePacket* a;
a=new writePacket;
a->sockID = sockA->sockid;
a->pp = sockA->pp;
a->seq = recvdata.seq;
memcpy(a->datamsg,recvdata.datamsg,1466);
pc = pthread_create(&write[counter], NULL, writePack,(void *) a);
if (pc)
{
printf("ERROR; return code from pthread_create() is %d\n", pc);
exit(-1);
}
A: It could be that the threads you create didn't get a chance to execute, while you've been creating more and more threads reading from the socket.
Instead, create a thread that would do the reading from the socket, another thread that would do the writing, and pass the data in messages between the two threads.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Conversion error in VS 2010 I have a web application in VS 2003 (1.1) that i need to upgrade to Visual Studio 2010 and target to framework 4.0. But it showing the error like
"Internal MSBuild Error: Setting property without a project and without a pending global properties collection."
A: I had this problem, and the only thing wrong was that something in the folder was reaonly. Make everything writable and try again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Submit hidden form once upon clicking text I have a set of members who have stored their login credentials (usr | pwd) of other websites as our partners. As is the situation, I am supposed to provide them just a text link and submit a form upon clicking that link.
// Getting values from db and storing them in javascript variables
<script type="text/javascript">
// values from db stored in javascript variables
var at_Cara = "<? echo $at;?>";
var ln_Cara = "<? echo $ln;?>";
var wd_Cara = "<? echo $pw;?>";
</script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript">
// I am submitting a form with hidden values, which is as follows:
$(document).ready(function() {
$("#goto").click(function() {
var site = "http://franka.finexp.net/login.aspx";
$('<input>').attr({type: 'hidden',id: 'Auto',name: 'Auto',value: at_Cara}).appendTo('#valgoogexp');
$('<input>').attr({type: 'hidden',id: 'LoginName',name: 'LoginName',value: do_ln_Cara}).appendTo('#valgoogexp');
$('<input>').attr({type: 'hidden',id: 'Password',name: 'Password',value: wd_Cara}).appendTo('#valgoogexp');
$("#valgoogexp").attr("action", site);
$("#valgoogexp").submit();
});
return false;
});
</script>
<a href="javascript:void(0);" id="goto" >Research Tool</a>
<form id="valgoogexp"></form>
The problem is that the form submits twice upon clicking the link. And subsequently the landing page says its a string error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: red5 actionscript code examples I am writing a Red5 application that provides video chat to a Flash client over RTMP.
How to control the internet speed by reducing the clarity of the video transmission
Can any one please tell me where to look at the source for red5 with AS and mxml.
I have looked at the following links
http://www.red5chat.com/
&
http://www.red5chat.com/features-webcamchat.htm
Any links which would provide a brief tutorial would be very helpful
A: you can build a hard wired one I am not sure it will work for you though the way you are intending.
And apparently there are some plugins for you also.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: get and set string onmouseover js value I want to run some onmousedown function, but how can I run this function without onmousedown event, in twebbrowser?
Can you suggest me a proper function, please?
A: Try setting the function name to null, like this:
alert('test'); // will show 'test'
alert = null;
alert('test'); // will do nothing
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to shorten path names in grep buffer? Is it possible to shorten paths in grep results buffer? By default each line of grep results in Emacs looks like this:
/home/pawel/tmp/avro-src-1.5.4-fixed/lang/c/src/datum.c:107:int avro_string_set(avro_datum_t datum, const char *p)
which takes a lot of space and looks messy and not very readable, especially if there is another window beside.
I'd like to see just filenames or partial paths - as long as they are unique in grep buffer, e.g:
datum.c:107:int avro_string_set(avro_datum_t datum, const char *p)
or
/home/(...)/src/datum.c:107:int avro_string_set(avro_datum_t datum, const char *p)
I guess emacs needs to know full paths internally, so it's about displaying grep results only rather than playing with 'grep' parameters. How to do this? Would hide-show mode definitions for grep buffer do the trick, or is there an easier way of doing this?
Thanks.
A: I made one for you: scf-mode. It works as a minor-mode, so the original file-name can be restored when you turn it off.
For installation instructions see the file header.
A: If you know Emacs lisp then it may be not hard to implement. You just have to find the common part of the path names, remove it, store the common part in a local variable and then when a grep result is opened assemble the full pathname from the stored parts.
It is a good idea and it would improve the readability of grep-find output, so if you don't get an answer here then I suggest posting the question to emacs help. There are expert users there who can put together a solution quickly if they find the idea worthwile.
A: what version of emacs are you using? when i run grep on my emacs (23.3.1), i get no path, e.g.:
file1:25:some result
file2:26:some other result
also, what happens on your box when you run the same grep command outside of emacs?
A: Just M-x cd /home/pawel/tmp/avro-src-1.5.4-fixed/lang/c/src/ before you run M-x grep.
You only get the directory parts for grep hits if the files hit are not in the current directory (default-directory).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: upload size on multiple file upload with django I'm using Django to upload some files with one multiple file input. Using this upload-handler that writes the cumulated size of uploaded chunks in a session-variable and some jQuery I finally got a progress-bar working. But I still got a problem with the uploaded file size, i.e. the files are uploaded to astonishing 144% of their original size. At least that's what the progress bar says. The size of the uploaded files on the server directory actually is as it should be.
As you see in the handler-script, the size is cumulated via:
data['uploaded'] += self.chunk_size
My guess is that self.chunk_size is a static value and not the actual size of the received chunks. So when there is a chunk received with a smaller size - in case I upload files that are smaller than the chunk-limit set - there is more cumulated than actually uploaded.
Now my question: Is there a way to get the actual chunk size?
A: I think you can use the length of the raw_data instead:
data['uploaded'] += len(raw_data)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery: Colorbox close iFrame onsubmit i´ve got a question about closing a form withing a colorbox after submit. I found this question so i now know how to close the form after submit. The problem is that another javascript validates the input fields of my form and there will be an error message (a simple alert()) when some fields are not filled in...i wanne close the clorbox iframe onsubmit only when the validation returns no error..otherwise the user will get the hint that he missed some input fields but the form will close anyway...so how can i check this with jQuery..is there a possiblity to maybe check if an "alert()" is shown on screen...then is could say, when the alertpopup is shown don´t close the colorbox window, otherwise close it because there was no error...does anyone understand what i mean? Again: I cannot change the validation script! Then i could simply add the .colorbox.close(); within this script...
The validation is a simple function which is executed onsubmit...there is a variable "msg" which contains the errormessage within this function..there must be a way to get this "msg" variable when the function executes and to check whether it´s empty or not....?
Can anyone help me with this...it´s a bit difficult to explain for me..
A: You can probably get the contents of the "msg" element from the iFramed content by referring to it this way:
parent.msg-field-name
What I have done in a similar situation is this:
*
*Leave a way for the user to cancel the iFrame form. This exit path uses ColorBox's "built-in" close methods
*on Submit, test for error validation. If it passes, use allow the built-in close method to succeed, if it doesn't then don't leave the form.
You can find out exactly how to do form the plugin author's website:
Prevent ColorBox from closing / Change the behavior of $.colorbox.close()
The close method ($.colorbox.close()) can be cached and redefined as to offer some control over what happens when ColorBox is closed. This affects controls that are bind to it (such as the escKey, overlayClose, and the close button) and calling the close method directly.
For example, lets say we open ColorBox to display an html snippet containing a form, and we want to warn the visitor that they are discarding their form if they try to close ColorBox before they submit their data.
var originalClose = $.colorbox.close;
$.colorbox.close = function(){
var response;
if($('#cboxLoadedContent').find('form').length > 0){
response = confirm('Do you want to close this window?');
if(!response){
return; // Do nothing.
}
}
originalClose();
};
$('a#example').colorbox();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: usage of validate request and enable event validation in page tag of aspx
Possible Duplicate:
enableEventValidation and validateRequest difference
can someone explain correctly the need of
validateRequest="false"
enableEventValidation="false"
in page tag
A: For enableEventValidation="false"
Read the documentation.
EDIT: For security reasons, it's probably best to leave it set to true wherever you can.
I would therefore recommend that you set it to false only on the individual AJAX pages where it causes problems, while leaving it true in web.config.
For validateRequest="false"
The "benefit" is that you have more control over the input validation. If ValidateRequest = true and the input has invalid characters then an ugly error page is showed to the user.
Although a little old, here you have a MSDN post about "Prevent Cross-Site Scripting in ASP.NET"
A: I am assuming that you are asking for a valid scenario where I would set validateRequest="false" and/or enableEventValidation="false".
enableEventValidation="false" is typically required when you use java-script to manipulate server control generated html. For example, if server side drop-down control was bound to have three values say "A","B","C" then those are only values expected when post-back happens. But if you are doing client-side manipulation and hence introduce extra value "D" and select it then ASp.NET will raise event validation error. So we have to suppress it. Particularly, changing the drop-down value (without post-back) can be quite common - populating cities based on state selection etc
validateRequest="false" is needed when you want to allow user to enter character sequences those are deemed dangerous - e.g. <script>bla bla...</script> will raise request validation error but if you are developing a developer forum/QA site such as SO that allows to post the code then request validation has to be disabled.
A: The ValidateRequest setting examines user input for potentially harmful information. For example, if ValidateRequest is set to true and you enter some markup into an TextBox, the request validation will fail and the page will error out.
The EnableEventValidation setting determines whether postback and callback events should validate that a control event originated from the user interface that was rendered by the control. This is usually encountered when server-side events are triggered by the user through JavaScript, like calling the __doPostBack function for example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ternary operator always evaluating to true part I have a statement:
var sep = ' | ';
var r = '';
for (var i = 0; i < menuItems.length; i++) {
r += function(menuObject) {
console.log(menuObject);
console.log(
'<a class="" href="' +
menuObject.url + '">' + menuObject.name + '</a>' +
(i < menuItems.length - 1) ? sep : ""); //logs the contents of sep
) //console.log expanded for readability
}
}
Why is it not logging the full string, and instead only evaluating to sep?
A: Because you are not wrapping your if line in parenthesis and it is process all of the string before it as the condition.
Try this...
var sep = ' | ';
var r = '';
for (var i=0;i<menuItems.length; i++) {
r += function (menuObject) {
console.log(menuObject);
console.log(
'<a class="" href="' +
menuObject.url + '">' + menuObject.name + '</a>'+
((i <menuItems.length-1 ) ? sep : "")); //logs the contents of sep
}
}
A: The issue is operator precedence.
console.log(
('<a class="" href="' +
menuObject.url + '">' + menuObject.name + '</a>'+
(i <menuItems.length-1 )) ? sep : "");
is being executed (mind the extra parenthesis I added). When using the ternary operator (which has only little to do with if clauses btw.) you should always use parenthesis like here:
console.log(
'<a class="" href="' +
menuObject.url + '">' + menuObject.name + '</a>'+
((i <menuItems.length-1 ) ? sep : ""));
A: Operator precedence. Put your expression before ? in parentheses:
console.log(
('<a class="" href="' +
menuObject.url + '">' + menuObject.name + '</a>'+
(i <menuItems.length-1 )) ? sep : "");
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C# What construct am I Looking for Lamba / Expression / Func / Reflection for runtime property substitution? I've a method on a generic base class that I want to execute for all superclasses of it
The logic is something like:
BuildAverageDateStats(List<type> items, DateProperty1 exp, DateProperty2 exp2)
{
return new Stat{
Value = items.Average(c => (c.DateProperty2 - c.DateProperty1).Milliseconds)
};
}
myobject.BuildAverageDateStats(list, () => c.QueuedDate, () => c.CompletedDate);
myobject.BuildAverageDateStats(list, () => c.ActionedDate, () => c.CompletedDate);
I think I need expressions, but not sure how...
I could send it in as Func i.e. Value = items.Average(c => myfunc(c)) but looking for a property substitution example.
A: Stat BuildAverageDateStats<U>(List<type> items, Func<U, double> exp)
where U:type
{
return new Stat{
Value = items.OfType<U>().Average(exp);
};
}
You can call it like this
BuidlAverageDateStats<Dog>(items, d=>d.Age - d.Height);
Though my example doesn't make sense.
A: If you are really only ever going to use one of the three DateTime properties that you have right now, I would keep the method signature the way you have it right now.
To make things neater, make some public static readonly delegate fields on your class for your properties, and use those, instead of writing the same expression time and time again:
public static readonly DateSelector Date1Property = delegate(CompareTest c) { return c.Date1; };
public static readonly DateSelector Date2Property = delegate(CompareTest c) { return c.Date2; };
public static readonly DateSelector Date3Property = delegate(CompareTest c) { return c.Date3; };
If, on the other hand, you expect inheriting classes to implement more properties than the three you have right now, you could consider passing in the properties as String and using the Dynamic Linq Library (and build a dynamic expression that returns the property) or a DynamicMethod to return your property. Both would have the benefits of reflection with the painful performance. If you need it, I have some code laying around for that.
Type safety will be out the window though, so I wouldn't use it unless necessary, and it sounds like it isn't.
Menno
A: static Stat BuildAverageDateStats<T>(List<T> items, string pname1, string pname2){
return new Stat {
Value = items.Average( c =>
{
var ty = c.GetType();
var pv1 = (dynamic)ty.GetProperty(pname1).GetValue(c,null);
var pv2 = (dynamic)ty.GetProperty(pname2).GetValue(c,null);
return pv2 - pv1;
})
};
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What "|" character do?
Possible Duplicate:
Reference - What does this symbol mean in PHP?
I googled much for finding answer but i couldn't find any.
I saw in few free source codes that they use "|" sign to combine values or something. can someone enlighten what is different between "|" and "+"?
sample:
<?php
define('PERMISSION_DENIED', 0);
define('PERMISSION_READ', 1);
define('PERMISSION_ADD', 2);
define('PERMISSION_UPDATE', 4);
define('PERMISSION_DELETE', 8);
$read_only = PERMISSION_READ;
$read_delete = PERMISSION_READ | PERMISSION_DELETE;
$full_rights = PERMISSION_DENIED | PERMISSION_READ | PERMISSION_ADD | PERMISSION_UPDATE | PERMISSION_DELETE;
$myrights = PERMISSION_READ;
$myrights |= PERMISSION_UPDATE;
?>
why not just:
<?php
define('PERMISSION_DENIED', 0);
define('PERMISSION_READ', 1);
define('PERMISSION_ADD', 2);
define('PERMISSION_UPDATE', 4);
define('PERMISSION_DELETE', 8);
$read_only = PERMISSION_READ;
$read_delete = PERMISSION_READ + PERMISSION_DELETE;
$full_rights = PERMISSION_DENIED + PERMISSION_READ + PERMISSION_ADD + PERMISSION_UPDATE + PERMISSION_DELETE;
$myrights = PERMISSION_READ;
$myrights += PERMISSION_UPDATE;
?>
A: it's the bitwise or operator, so you're operating with numbers in base 2 notation.
for example:
1000 | 0001 = 1001 ==> (8 | 1 = 9)
http://www.php.net/manual/en/language.operators.bitwise.php
In your code each permission is represented by one bit in a different position, I mean:
1 = 0001 = perm1
2 = 0010 = perm2
4 = 0100 = perm3
8 = 1000 = perm4
so doing or with those numbers gives you the number with all the permissions together. then if you wanna check if a permission is set you gotta do an and operation with the permission that you're checking, for example:
$user_perms = perm1 | perm3;
if ($user_perms & perm4) echo "user does not have this permission";
A: Okay, there is a difference. In order to see the difference you can just see how these numbers appear in binary:
0 = 00000000
1 = 00000001
2 = 00000010
4 = 00000100
8 = 00001000
As you can see, each of these numbers have only one bit set to one each in a different position.
Now, having a bitwise OR between them will make the result with one on each position as the operands:
00000010 |
00000100
----------
00000110
In this case it's the same as just adding the numbers.
0 | 0 = 0; 0 + 0 = 0
0 | 1 = 1 | 0 = 1 + 0 = 1
The difference comes here:
1 | 1 = 1
while
1 + 1 = 10 !!
The difference in this example is that bit-wise operator is faster because you just operate on the bits.
A: | is the bitwise OR (every bit of the result is 1 iff at least one of the corresponding bits in the inputs is 1). Using addition would work as well, but doesn't make it clear one is assembling a bitmask, and can lead to bugs, because
PERMISSION_READ + PERMISSION_READ != PERMISSION_READ
but
PERMISSION_READ | PERMISSION_READ == PERMISSION_READ
A: This is a bitwise OR operator.
You can find more information about it here : http://php.net/manual/en/language.operators.bitwise.php
Bitwise operators usual are good for soft encription methods
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Silverlight XAP is getting shared across 2 session in the same machine I have a problem on my silverlight application.
I login in my application using my ID (assume x) (using Internet explore 8),
so assume i can see some reports which is releated to my ID.
Without closing the above browser in another Internet explore 8 in the same machine i am login into the
same application using another ID(assume y), so now i can see 2nd set of reports which is related to this ID.
Now If i refresh the report page of the first browser which is got logged with the ID (x), I am seeing the (y)
userid's report not the earlier.
How to fix this?
Thanks
A: In internet explorer choose "New Session" from the "File" menu. This will create a new IExplore.exe process tree which manages its own set of session level cookies. This should allow you to maintain two separate logins at the same time.
A: Sounds like you are using the ASP membership provider... if so that is limited to 1 session per browser/user on the same PC (same limitation if it was a web app).
Why are you trying to login 2 different users from the same machine? If it is for testing you can probably open two different browsers (IE and FireFox?) and get two session that way.
Update (based on comments below):
Option A. As you need multiple user logins on the same machine in the same browser type, you cannot use the asp membership provider and will have to replace that provider with a Silverlight-specific credential/login system.
Option B. The alternative is to change your application to allow selection of client from within the app (this would be my choice as you are misusing users as a convenience).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Call command line after installation in Wix I am using wix and want to call command line after installation.
How can I do this?
My command line is here "bcdedit.exe /set {current} nx AlwaysOff" // this makes dep off
Yes, I've read about custom actions, but I didn't see any example with command line.
P.S. bcdedit is usual exe in Win 7 and higher.
P.S. currently I have next script and it does not work:
Directory ="INSTALLLOCATION"
ExeCommand ='echo hello> echo_test.txt'
Execute ="immediate"
Return ="asyncNoWait"
/>
A: Ok, this example works...
<CustomAction Id ="echo_test"
Directory ="INSTALLLOCATION"
ExeCommand ='NOTEPAD.EXE echo_test.txt'
Execute ="immediate"
Return ="asyncNoWait"
/>
My test example with echo didn't worked for some reason.
And bcdedit does not exist on WinXP, where I am testing now...
A: Hi there are lots of example available on net...
try these links
http://wix.sourceforge.net/manual-wix2/qtexec.htm
Execute Command Line In WiX Script?
WiX - CustomAction ExeCommand - Hide Console
Or try this example:
<CustomAction Id="SetQtExecCmd" Property="SetQtExec"
Value=""[PutPathOfThisFileHere]bcdedit.exe" /set {current} nx AlwaysOff" />
<CustomAction Id="SetQtExec" BinaryKey="WixCA" DllEntry="CAQuietExec" Execute="immediate" Return="check" />
A: echo is not an executable, it is the command of the command processor cmd.exe. Change your ExeCommand value to cmd.exe /c "echo hello >echo_test.txt".
Your echo_test.txt would be in an arbitrary directory, you have to use absolute paths to get predictable results.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Ajax content, and noscript alternative- best practice? I have a content listings page on a site I'm developing that uses ajax to pull items based on filtering picked by the user. (filter by date/ tag/ genre etc)
In order for the page to work for crawlbots and non-javascript users I have a standard listing of content as well, hidden, but with a noscript tag in the header making it display:block
(Have been told this is okay in html5).
Trouble is- the site is doing everything twice now- loading the content via ajax as well as the alternative, only to be hidden with CSS.
I know for sure this isn't best practice, but I'm struggling to think of a solution where the content only loads once. Any thoughts on the matter would be greatly appreciated.
A: You could display them always with CSS, and then hide them with JS. (Without the use of noscript)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Configure Shadow Copy using app.config Let me explain the scenario first.
I have installed multiple copies (Say 10) of Services from a single install base. Now I want to update one of the dll. I need to Stop all the services, update the dll and restart the Service again.
To avoid the situation, I used ShadowCopying in code. So that the dlls can be updated without stopping all the services. It is as follows.
static void Main(string[] args)
{
AppDomain.CurrentDomain.SetCachePath(@"C:\Cache");
AppDomain.CurrentDomain.SetShadowCopyPath(AppDomain.CurrentDomain.BaseDirectory);
AppDomain.CurrentDomain.SetShadowCopyFiles();
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new SampleService(serviceName)
};
ServiceBase.Run(ServicesToRun);
}
Now I am trying to achieve the same via app.config file, as follows, from Asp.Net
<hostingEnvironment
idleTimeout="Infinite"
shutdownTimeout="30"
shadowCopyBinAssemblies="true" />
Any suggestions?
A: The ASP.Net hosting environment has built-in support for managing application recycling.
Windows .Net services use the standard CLR host which does not have this support. You would have to implement your own e.g.
*
*Create a child AppDomain to host your service code, and configure shadow copying.
*Use something like a FileSystemWatcher to monitor the original bin directory.
*When files change, tear down your AppDomain and create a new one and reload.
The ASP.Net host does something along these lines (but also has the ability to manage existing requests, queue new requests whilst this is going on, etc).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: trouble with WHEN NOT NULL I want to create a switch around the following. I've tried various permutations but I just cant get IS NOT NULL to work.
(CASE billing_code WHEN NOT NULL THEN billing_amount END) AS Billing Amount
Thanks in advance
A: You need to use the "searched" form of the CASE statement. Additionally as the column alias contains spaces it needs to be delimited as below.
CASE WHEN billing_code IS NOT NULL THEN billing_amount END AS [Billing Amount]
A: Try as below
(Case When billing_code is Not Null then billing_amount End) As "Billing Amount"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Robots.txt Allow sub folder but not the parent Can anybody please explain the correct robots.txt command for the following scenario.
I would like to allow access to:
/directory/subdirectory/..
But I would also like to restrict access to /directory/ not withstanding the above exception.
A: I would recommend using Google's robot tester. Utilize Google Webmaster tools - https://support.google.com/webmasters/answer/6062598?hl=en
You can edit and test URLs right in the tool, plus you get a wealth of other tools as well.
A: Be aware that there is no real official standard and that any web crawler may happily ignore your robots.txt
According to a Google groups post, the following works at least with GoogleBot;
User-agent: Googlebot
Disallow: /directory/
Allow: /directory/subdirectory/
A: If these are truly directories then the accepted answer is probably your best choice. But, if you're writing an application and the directories are dynamically generated paths (a.k.a. contexts, routes, etc), then you might want to use meta tags instead of defining it in the robots.txt. This gives you the advantage of not having to worry about how different browsers may interpret/prioritize the access to the subdirectory path.
You might try something like this in the code:
if is_parent_directory_path
<meta name="robots" content="noindex, nofollow">
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: Tools for orchestration of web services Let's say I have many web services (REST or normal HTTP request) and I want to define in which order they should be called. I want the order to be easily configured (through XML files) and return error responses in case they are called in the wrong way.
When I say tools I mean some framework in Java. The framework should have good documentation with examples.
I don't want only a name but I would like pros/cons - why should I choose one or another.
EDIT: I forgot to mention it has to be an OpenSource (or any free licence for unlimited usage). And the application will probably run on GoogleAppEngine or Tomcat.
A: If you want to orchestrate long running processes then what you need is a BPEL engine.. if not you can go for an Enterprise Service Bus..
WSO2 ESB is an open source Enterprise Service Bus and WSO2 BPS is a business process server built on top of Apache ODE.
eBAY using WSO2 ESB to process 1 Billion messages per day.
Disclaimer: I am an architect from WSO2.
A: You need a Service Bus.
Bea's Aqualogic was a good one.
Pros: integrated with weblogic, support XQuery for message manipulation. Has persistency queues. Flows are defined within it's user interface.
Cons: not so easy to use. Costly.
Regards,
M.
PS: On the pros I would add Bea's good support, but since now they're Oracle I doubt that quality will be high as in the past
EDIT: ops, OpenSource solution needed. So this answer was actually wrong. Sorry.
A: I am wondering how "WSO2 ESB" or "WSO2 BPS" will address the issues presented in the original question.
The more I look into that project the more it looks to me it is BPEL driven which will probably not play good with "REST/normal http".
I believe Apache Camel should be a good start point.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: disable the window function in jsf/primefaces <p:commandButton id="cmdCancel" value="#{label.cancel}" action="cancel"/>
<p:hotkey bind="Alt+C" action="cancel" />
Hi ,
I have one button cancel and i binded it to short cut key "Alt+C" (refer above code) in prime faces.
And when i use press short cut key "Alt+C", it perform the cancel action and
but it also open the browser favorites menu on pressing the "Alt+C".
How can i stop this opening browser operation?Please suggest me any solution,.......
A: I guess that you simply can not override some of the browser's hardwired default hotkeys.
Think of pressing Alt+F4 to close the browser window etc.
Even the normal HTML hotkey attribute is not guaranteed to work if the browser already does something else when pressing the hotkey combination.
My answer is thus; Do not rely on hotkeys in a website to work at all.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: detect Touch on UIButton Ok, Here is the Hierarchy of my View.
Main View
|---------------|---------------|
UIView UIView UIView
| | |
UIButtons UIButtons UIButtons
As Above figure shows I have 3 subViews of Tag 111,222,333.
And Each Sub-view contains 25 buttons.
One view is visible at a time, so m hiding the other 2 view by tag property.
App Description: My app having images on buttons and m showing those image on click of buttons. User can be able to click only one button at a time , and on second click m comparing the images of the buttons if the two images of buttons are not same, the image of button is hided and if they are same, they r not hidden.
All is going well on simulator, but on device, if I click Two button simultaneously, they both open at same time. (while btnClickCount is 2)
i want my button to open only one at a time.
What i have tried :
*
*I hav set NO to multiTouch.
*I tried to use Touches Began, but it was of no use as m getting tap on UIButton n not on UIView.
*I tried
self.view.userInteractionEnabled = NO;
[self performSelector:@selector(EnableUserInteraction) withObject:nil afterDelay:0.5];
on first button click but if touches are occuring at same time, then nothing happens, but it is working for single tap.
dont know what to do with this !!!!!
Please Help , Thanks in advance..........
A: UIButton has a boolean property 'enabled'
So when you get a button click, you could set all the other buttons to
buttonName.enabled = NO;
Then, when you want them to be active again, set
buttonName.enabled = YES;
I'm not sure how your buttons are declared, but if they are IBOutlets with different names, you can easily by put all the names in an array, remove the one that is active, and enumerating through the rest.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Default values of int when not initialized in c. why do i get different outputs? i was just trying to check the default value of int and char when not initialised in c.
my problem is that i get two different outputs when i use clrscr() to clear the screen between 2 runs.could someone explain this behavior to me?
here is the code
void main()
{
int i;
char c;
printf("%d %c",i,c);
}
output: 0
void main()
{
int i;
char c;
clrscr();
printf("%d %c",i,c);
}
output:-29542 //some garbage value which is what i was expecting in both cases
A: You shouldn't be expecting anything in particular. The values are uninitialized, i.e.: can be anything.
Why the garbage value in the first case differs from the garbage value in the second case? Who knows? Different memory map, different execution paths - different garbage.
A: I think it always give some garbage value ..you can't determine the behavior... :-/
A: In case of your code, you will get garbage values, but if the integer varibale was declared globally then its default value will be 0 for sure in C.
I mentioned this because question's title was-"Default values of int when not initialized in c".
A: Actually zeros were garbage as well. After you add clrscr(); you changed stack so you did to garbage.
A: In managed code, there are default values, usually 0 or equivalent.
In the unmanaged world, there is no default value. When the memory is allocated, the system just tells you "You can write here is you want, but I don't know what mess the previous program let behind".
This behaviour is seen for some people as bad since their program can be unpredictable for some obscure reasons, but it is also a way to be able to optimize as much as we can memory management, think of large buffer allocation which when allocated would be filled with 0s, and then filled with actual data. You get twice the performance in unmanaged code!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Binary Heap Implemented via a Binary Tree Structure For an assignment, we were instructed to create a priority queue implemented via a binary heap, without using any built-in classes, and I have done so successfully by using an array to store the queued objects. However, I'm interested in learning how to implement another queue by using an actual tree structure, but in doing so I've run across a bit of a problem.
How would I keep track of the nodes on which I would perform insertion and deletion? I have tried using a linked list, which appends each node as it is inserted - new children are added starting from the first list node, and deleted from the opposite end. However, this falls apart when elements are rearranged in the tree, as children are added at the wrong position.
Edit: Perhaps I should clarify - I'm not sure how I would be able to find the last occupied and first unoccupied leaves. For example, I would always be able to tell the last inserted leaf, but if I were to delete it, how would I know which leaf to delete when I next remove the item? The same goes for inserting - how would I know which leaf to jump to next after the current leaf has both children accounted for?
A: A tree implementation of a binary heap uses a complete tree [or almost full tree: every level is full, except the deepest one].
You always 'know' which is the last occupied leaf - where you delete from [and modifying it is O(logn) after it changed so it is not a problem], and you always 'know' which is the first non-occupied leaf, in which you add elements to [and again, modifying it is also O(logn) after it changed].
The algorithm idea is simple:
insert: insert element to the first non-occupied leaf, and use heapify [sift up] to get this element to its correct place in the heap.
delete_min: replace the first element with the last occupied leaf, and remove the last occupied leaf. then, heapify [sift down] the heap.
EDIT: note that delete() can be done to any element, and not only the head, however - finding the element you want to replace with the last leaf will be O(n), which will make this op expensive. for this reason, the delete() method [besides the head], is usually not a part of the heap data structure.
A: I really wanted to do this for almost a decade.Finally sat down today and wrote it.Anyone who wants it can use it.I got inspired by Quora founder to relearn Heap.Apparently he was asked how would you find K near points in a set of n points in his Google phone screen.Apparently his answer was to use a Max Heap and to store K values and remove the maximum element after the size of the heap exceeds K.The approach is pretty simple and the worst case is nlog K which is better than n^2 in most sorting cases.Here is the code.
import java.util.ArrayList;
import java.util.List;
/**
* @author Harish R
*/
public class HeapPractise<T extends Comparable<T>> {
private List<T> heapList;
public List<T> getHeapList() {
return heapList;
}
public void setHeapList(List<T> heapList) {
this.heapList = heapList;
}
private int heapSize;
public HeapPractise() {
this.heapList = new ArrayList<>();
this.heapSize = heapList.size();
}
public void insert(T item) {
if (heapList.size() == 0) {
heapList.add(item);
} else {
siftUp(item);
}
}
public void siftUp(T item) {
heapList.add(item);
heapSize = heapList.size();
int currentIndex = heapSize - 1;
while (currentIndex > 0) {
int parentIndex = (int) Math.floor((currentIndex - 1) / 2);
T parentItem = heapList.get(parentIndex);
if (parentItem != null) {
if (item.compareTo(parentItem) > 0) {
heapList.set(parentIndex, item);
heapList.set(currentIndex, parentItem);
currentIndex = parentIndex;
continue;
}
}
break;
}
}
public T delete() {
if (heapList.size() == 0) {
return null;
}
if (heapList.size() == 1) {
T item = heapList.get(0);
heapList.remove(0);
return item;
}
return siftDown();
}
public T siftDown() {
T item = heapList.get(0);
T lastItem = heapList.get(heapList.size() - 1);
heapList.remove(heapList.size() - 1);
heapList.set(0, lastItem);
heapSize = heapList.size();
int currentIndex = 0;
while (currentIndex < heapSize) {
int leftIndex = (2 * currentIndex) + 1;
int rightIndex = (2 * currentIndex) + 2;
T leftItem = null;
T rightItem = null;
int currentLargestItemIndex = -1;
if (leftIndex <= heapSize - 1) {
leftItem = heapList.get(leftIndex);
}
if (rightIndex <= heapSize - 1) {
rightItem = heapList.get(rightIndex);
}
T currentLargestItem = null;
if (leftItem != null && rightItem != null) {
if (leftItem.compareTo(rightItem) >= 0) {
currentLargestItem = leftItem;
currentLargestItemIndex = leftIndex;
} else {
currentLargestItem = rightItem;
currentLargestItemIndex = rightIndex;
}
} else if (leftItem != null && rightItem == null) {
currentLargestItem = leftItem;
currentLargestItemIndex = leftIndex;
}
if (currentLargestItem != null) {
if (lastItem.compareTo(currentLargestItem) >= 0) {
break;
} else {
heapList.set(currentLargestItemIndex, lastItem);
heapList.set(currentIndex, currentLargestItem);
currentIndex = currentLargestItemIndex;
continue;
}
}
}
return item;
}
public static void main(String[] args) {
HeapPractise<Integer> heap = new HeapPractise<>();
for (int i = 0; i < 32; i++) {
heap.insert(i);
}
System.out.println(heap.getHeapList());
List<Node<Integer>> nodeArray = new ArrayList<>(heap.getHeapList()
.size());
for (int i = 0; i < heap.getHeapList().size(); i++) {
Integer heapElement = heap.getHeapList().get(i);
Node<Integer> node = new Node<Integer>(heapElement);
nodeArray.add(node);
}
for (int i = 0; i < nodeArray.size(); i++) {
int leftNodeIndex = (2 * i) + 1;
int rightNodeIndex = (2 * i) + 2;
Node<Integer> node = nodeArray.get(i);
if (leftNodeIndex <= heap.getHeapList().size() - 1) {
Node<Integer> leftNode = nodeArray.get(leftNodeIndex);
node.left = leftNode;
}
if (rightNodeIndex <= heap.getHeapList().size() - 1) {
Node<Integer> rightNode = nodeArray.get(rightNodeIndex);
node.right = rightNode;
}
}
BTreePrinter.printNode(nodeArray.get(0));
}
}
public class Node<T extends Comparable<?>> {
Node<T> left, right;
T data;
public Node(T data) {
this.data = data;
}
}
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
class BTreePrinter {
public static <T extends Comparable<?>> void printNode(Node<T> root) {
int maxLevel = BTreePrinter.maxLevel(root);
printNodeInternal(Collections.singletonList(root), 1, maxLevel);
}
private static <T extends Comparable<?>> void printNodeInternal(
List<Node<T>> nodes, int level, int maxLevel) {
if (nodes.isEmpty() || BTreePrinter.isAllElementsNull(nodes))
return;
int floor = maxLevel - level;
int endgeLines = (int) Math.pow(2, (Math.max(floor - 1, 0)));
int firstSpaces = (int) Math.pow(2, (floor)) - 1;
int betweenSpaces = (int) Math.pow(2, (floor + 1)) - 1;
BTreePrinter.printWhitespaces(firstSpaces);
List<Node<T>> newNodes = new ArrayList<Node<T>>();
for (Node<T> node : nodes) {
if (node != null) {
String nodeData = String.valueOf(node.data);
if (nodeData != null) {
if (nodeData.length() == 1) {
nodeData = "0" + nodeData;
}
}
System.out.print(nodeData);
newNodes.add(node.left);
newNodes.add(node.right);
} else {
newNodes.add(null);
newNodes.add(null);
System.out.print(" ");
}
BTreePrinter.printWhitespaces(betweenSpaces);
}
System.out.println("");
for (int i = 1; i <= endgeLines; i++) {
for (int j = 0; j < nodes.size(); j++) {
BTreePrinter.printWhitespaces(firstSpaces - i);
if (nodes.get(j) == null) {
BTreePrinter.printWhitespaces(endgeLines + endgeLines + i
+ 1);
continue;
}
if (nodes.get(j).left != null)
System.out.print("//");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(i + i - 1);
if (nodes.get(j).right != null)
System.out.print("\\\\");
else
BTreePrinter.printWhitespaces(1);
BTreePrinter.printWhitespaces(endgeLines + endgeLines - i);
}
System.out.println("");
}
printNodeInternal(newNodes, level + 1, maxLevel);
}
private static void printWhitespaces(int count) {
for (int i = 0; i < 2 * count; i++)
System.out.print(" ");
}
private static <T extends Comparable<?>> int maxLevel(Node<T> node) {
if (node == null)
return 0;
return Math.max(BTreePrinter.maxLevel(node.left),
BTreePrinter.maxLevel(node.right)) + 1;
}
private static <T> boolean isAllElementsNull(List<T> list) {
for (Object object : list) {
if (object != null)
return false;
}
return true;
}
}
Please note that BTreePrinter is a code I took somewhere in Stackoverflow long back and I modified to use with 2 digit numbers.It will be broken if we move to 3 digit numbers and it is only for simple understanding of how the Heap structure looks.A fix for 3 digit numbers is to keep everything as multiple of 3.
Also due credits to Sesh Venugopal for wonderful tutorial on Youtube on Heap data structure
A: public class PriorityQ<K extends Comparable<K>> {
private class TreeNode<T extends Comparable<T>> {
T val;
TreeNode<T> left, right, parent;
public String toString() {
return this.val.toString();
}
TreeNode(T v) {
this.val = v;
left = null;
right = null;
}
public TreeNode<T> insert(T val, int position) {
TreeNode<T> parent = findNode(position/2);
TreeNode<T> node = new TreeNode<T>(val);
if(position % 2 == 0) {
parent.left = node;
} else {
parent.right = node;
}
node.parent = parent;
heapify(node);
return node;
}
private void heapify(TreeNode<T> node) {
while(node.parent != null && (node.parent.val.compareTo(node.val) < 0)) {
T temp = node.val;
node.val = node.parent.val;
node.parent.val = temp;
node = node.parent;
}
}
private TreeNode<T> findNode(int pos) {
TreeNode<T> node = this;
int reversed = 1;
while(pos > 0) {
reversed <<= 1;
reversed |= (pos&1);
pos >>= 1;
}
reversed >>= 1;
while(reversed > 1) {
if((reversed & 1) == 0) {
node = node.left;
} else {
node = node.right;
}
reversed >>= 1;
}
return node;
}
public TreeNode<T> remove(int pos) {
if(pos <= 1) {
return null;
}
TreeNode<T> last = findNode(pos);
if(last.parent.right == last) {
last.parent.right = null;
} else {
last.parent.left = null;
}
this.val = last.val;
bubbleDown();
return null;
}
public void bubbleDown() {
TreeNode<T> node = this;
do {
TreeNode<T> left = node.left;
TreeNode<T> right = node.right;
if(left != null && right != null) {
T max = left.val.compareTo(right.val) > 0 ? left.val : right.val;
if(max.compareTo(node.val) > 0) {
if(left.val.equals(max)) {
left.val = node.val;
node.val = max;
node = left;
} else {
right.val = node.val;
node.val = max;
node = right;
}
} else {
break;
}
} else if(left != null) {
T max = left.val;
if(left.val.compareTo(node.val) > 0) {
left.val = node.val;
node.val = max;
node = left;
} else {
break;
}
} else {
break;
}
} while(true);
}
}
private TreeNode<K> root;
private int position;
PriorityQ(){
this.position = 1;
}
public void insert(K val) {
if(val == null) {
return;
}
if(root == null) {
this.position = 1;
root = new TreeNode<K>(val);
this.position++;
return ;
}
root.insert(val, position);
position++;
}
public K remove() {
if(root == null) {
return null;
}
K val = root.val;
root.remove(this.position-1);
this.position--;
if(position == 1) {
root = null;
}
return val;
}
public static void main(String[] args) {
PriorityQ<Integer> q = new PriorityQ<>();
System.out.println(q.remove());
q.insert(1);
q.insert(11);
q.insert(111);
q.insert(1111);
q.remove();
q.remove();
q.remove();
q.remove();
q.insert(2);
q.insert(4);
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How can I make safe mp3 files for AVAudioPlayer, without getting errors I have problem when trying to play some mp3 files on iOS app.
First, I noticed that these files was also not working on Safari for iOS, but now I am having files that works on Safari for iOS, and doesn't work on my App.
I am using thi code to play mp3 audio files:
NSString *pronociationPath = …..
if (pronociationPath != nil)
{
NSURL *fileURL = [[NSURL alloc] initFileURLWithPath:pronociationPath];
NSError *error;
self.player=[[[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error] autorelease];
[fileURL release];
[self.player setNumberOfLoops:0];
if (self.player == nil) {
NSLog(@"%@",error);
}
else
{
[self.player prepareToPlay];
[self.player play];
}
}
And I am having this error for a file that works on Safari iOS:
Error Domain=NSOSStatusErrorDomain Code=1685348671 "The operation
couldn’t be completed. (OSStatus error 1685348671.)"
Is something wrong with my code?
Is there any guide to create safe mp3 files for iOS Apps ?
I've seen Apple documentation, but I don't see any useful informations https://developer.apple.com/library/archive/documentation/AudioVideo/Conceptual/MultimediaPG/UsingAudio/UsingAudio.html#//apple_ref/doc/uid/TP40009767-CH2-SW28
A: I also received same error (OSStatus error 1685348671) when I tried to play mp3 files on iOS 4.3.
Later on I found that it was the mp3 sound problem which made it incompatible to be played in iOS 4.3. So, I used iTunes Player to convert new version of mp3 sound with existing one. Now it works fine and better.
Steps:
*
*Open your current mp3 sound in iTunes
*Select it and Click on "Advanced" Menu >> "Create MP3 Version"
It wil create copy of current audio. Use newly created mp3 file for your app.
It helped me. I hope it might help others as well. All the best!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Open Source implementation of a Spaced Repetition Algorithm in Java I work on a project where Spaced Repetition is essential, however I am not a specialist on the subject and I am afraid to reinvent the square wheel. My research pointed me two different systems, namely the Leitner system and the SM family of algorithms.
I haven't decided yet which system would best fit into my project. If I was to take a SM orientation, I guess I would try to implement something similar to what Anki uses.
My best option would be to use an existing Java library. It could be quite simple, all I need is to compute the time for the next repetition.
Has anyone heard of such an initiative ?
A: Anki uses the SM2 algorithm. However, SM2 as described by that article has a number of serious flaws. Fortunately, they are simple to fix.
Explaining how to do so would be too lengthy of a subject for this post, so I've written a blog post about it here. There is no need to use an open-source library to do this, as the actual implementation is incredibly simple.
A: I haven't looked at Anki's implementation but have you seen this one? quiz-me an SRS in Java.
Basically it goes like this
public static void calcuateInterval(Card card) {
if (card.getEFactor() < 3) {
card.setCount(1);
}
int count = card.getCount();
int interval = 1;
if (count == 2) {
interval = 6;
} else if (count > 2) {
interval = Math.round(card.getInterval() * card.getEFactor());
}
card.setInterval(interval);
}
If you really want Anki's algorithm, look through the source of Anki in Android available in Github. It is GPL though so you might need to buy a license.
A: I did reinvent the square wheel in my own flashcard app. The algorithm is quite simple: The weight of an item is the product of an age component, a progress component, and an effort component.
Age component
The formula is A(x) = Cn^x, where
*
*x is the time in days since the item was last tested,
*C is the value you want when x is zero, and
*n is a constant based on how fast you want the value to increase as x increases.
For example, if you want the value to double every five days, n = e^(ln(2/C)/5).
Progress component
The formula is P(x) = Cn^-x, where
*
*x is a number that corresponds to how successful you've been with the item,
*C is the value you want when x is zero, and
*n is a constant based on how fast you want the value to decay as x increases.
For example, if you want the value to halve every five consecutive successes, n = e^(ln(1/2)/-5).
Effort component
This takes on one of two values:
*
*10 if you found your last recall of the item to be "hard", or
*1 otherwise.
The progress is adjusted thus:
*
*New entries start with progress 0.
*If you find an answer easy, the item's progress is increased by 1.
*If you find an answer hard, the item's progress goes to min(int(previous / 2), previous - 1).
*If you get an answer wrong, the item's progress goes to min(-1, previous - 1).
Yes, values can go negative. :)
The app selects the next item to test by making a random selection from all the items, with the probability of selection varying directly with an item's weight.
The specific numbers in the algorithm are tweakable. I've been using my current values for about a year, leading to great success in accumulating and retaining vocabulary for Spanish, German, and Latin.
(Sorry for potato quality of the math expressions. LaTeX isn't allowed here.)
A: Here is a spaced repetition algorithm that is well documented and easy to understand.
Features
*
*Introduces sub-decks for efficiently learning large decks (Super
useful!)
*Intuitive variable names and algorithm parameters. Fully
open-source with human-readable examples.
*Easily configurable
parameters to accommodate for different users' memorization
abilities.
*Computationally cheap to compute next card. No need to
run a computation on every card in the deck.
https://github.com/Jakobovski/SaneMemo.
Disclaimer: I am the author of SaneMemo.
import random
import datetime
# The number of times needed for the user to get the card correct(EASY) consecutively before removing the card from
# the current sub_deck.
CONSECUTIVE_CORRECT_TO_REMOVE_FROM_SUBDECK_WHEN_KNOWN = 2
CONSECUTIVE_CORRECT_TO_REMOVE_FROM_SUBDECK_WHEN_WILL_FORGET = 3
# The number of cards in the sub-deck
SUBDECK_SIZE = 15
REMINDER_RATE = 1.6
class Deck(object):
def __init__(self):
self.cards = []
# Used to make sure we don't display the same card twice
self.last_card = None
def add_card(self, card):
self.cards.append(card)
def get_next_card(self):
self.cards = sorted(self.cards) # Sorted by next_practice_time
sub_deck = self.cards[0:min(SUBDECK_SIZE, len(self.cards))]
card = random.choice(sub_deck)
# In case card == last card lets select again. We don't want to show the same card two times in a row.
while card == self.last_card:
card = random.choice(sub_deck)
self.last_card = card
return card
class Card(object):
def __init__(self, front, back):
self.front = front
self.back = back
self.next_practice_time = datetime.utc.now()
self.consecutive_correct_answer = 0
self.last_time_easy = datetime.utc.now()
def update(self, performance_str):
""" Updates the card after the user has seen it and answered how difficult it was. The user can provide one of
three options: [I_KNOW, KNOW_BUT_WILL_FORGET, DONT_KNOW].
"""
if performance_str == "KNOW_IT":
self.consecutive_correct_answer += 1
if self.consecutive_correct_answer >= CONSECUTIVE_CORRECT_TO_REMOVE_FROM_SUBDECK_WHEN_KNOWN:
days_since_last_easy = (datetime.utc.now() - self.last_time_easy).days
days_to_next_review = (days_since_last_easy + 2) * REMINDER_RATE
self.next_practice_time = datetime.utc.now() + datetime.time(days=days_to_next_review)
self.last_time_easy = datetime.utc.now()
else:
self.next_practice_time = datetime.utc.now()
elif performance_str == "KNOW_BUT_WILL_FORGET":
self.consecutive_correct_answer += 1
if self.consecutive_correct_answer >= CONSECUTIVE_CORRECT_TO_REMOVE_FROM_SUBDECK_WHEN_WILL_FORGET:
self.next_practice_time = datetime.utc.now() + datetime.time(days=1)
else:
self.next_practice_time = datetime.utc.now()
elif performance_str == "DONT_KNOW":
self.consecutive_correct_answer = 0
self.next_practice_time = datetime.utc.now()
def __cmp__(self, other):
"""Comparator or sorting cards by next_practice_time"""
if hasattr(other, 'next_practice_time'):
return self.number.__cmp__(other.next_practice_time)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: MVC3 - Submission of custom input attributes on input button when submitting a form Basically I have a form that I am dynamically adding objects to. I am doing this with AJAX so can just initialise the object and return it with JSON. Each new object has a unique GUID assigned to it so we can identify each object in the model collection when it is passed back into the action.
However, I need to support non JavaScript so am trying to write a solution that will post back the model and add or remove the given object from the model. There can be any number of these new objects on the model so I need to pass back several things to find out which object to delete before returning the model back to the view. This could be either
a) The GUID for the object the user has deleted.
b) The button that has been clicked to identify which object to delete.
The problem is that the partial view is generic and I would like to keep it that way so I'm trying to pass the identifying GUID back with the input button on each partial view but don't know how. I can easily do this with JavaScript because I just remove the created AJAX object from the page before posting it when the user clicks the remove link but can't figure out how to do it with a submit. Basically I want to do something like this:
@using (Project.Namespace.Infrastructure.Helpers.HtmlPrefixScopeExtensions.HtmlFieldPrefixScope _scope = Html.BeginCollectionItem())
{
<ul class="ulMedicationsControl">
@Html.ActionLink("Remove This Object", "RemoveObject", null)
@Html.Input("RemoveObject", "Remove This Object", new { Prefix = _scope.Prefix, objectGUID = IdentifyingGUID })
@Html.HiddenFor(m => m.IdentifyingGUID);
<li class="liQuestion">
@Html.MandatoryLabelFor(m => m.myField)
@Html.TextBoxFor(m => m.myField)
</li>
</ul>
<div id="@(_scope.Prefix).ajaxPlaceholder"></div>
}
In the controller:
[ActionName("FormName")]
[AcceptParameter(Name = "RemoveObject", Value = "Remove This Object")]
public ActionResult RemoveObject(MyParentModel model, string Prefix, string objectGUID)
{
Guid ID = new Guid(objectGUID);
foreach (ObjectModel object in model.objects){
if (object.IdentifyingGUID == ID)
{
model.objects.Remove(object);
break;
}
}
return View(model);
}
Any help I would really appreciate as I simple can't figure out how to do this!
EDIT
Also just to add the prefix attribute simply identifies where in the form the object sits. This will be needed for me to find which object list to go through and remove the object from as there may be several lists in different placed in the model.
A: An HTML input only passes "name=value" when a form post occurs so that's all you have to work with. With <input type=submit> you're further limited by the fact that the button's value is its caption (i.e. "myControl=Click Me!" is posted), so you can't stick anything programmatically meaningful in the value.
Method 1: So you're left with encoding all the information you need into the input's name - an approach that works fine, but you'll have to have to go digging into the controller action method's FormCollection parameter rather than relying on model binding. For example:
<input name="delete$@(_scope.Prefix)$@objectGUID" type="submit" value="Delete me" />
Better, have a helper class that encapsulates the string format with a ToString override and has Parse/TryParse/etc static methods, which could be used like this:
<input name="@(new DeleteToken{Prefix=_scope.Prefix, objectGUID=IdentifyingGUID})" type="submit" value="Delete me" />
In your action method:
[HttpPost]
public ActionResult Foo(FormCollection formData)
{
var deleteTokens = DeleteToken.ParseAll(formData.AllKeys);
foreach (var token in deleteTokens)
{
//...do the deletion
}
}
Method 2: An alternative approach is to group each item into its own <form> (bear in mind you can't nest forms) - so when the submit happens, only its surrounding form is posted in which you can stash hidden inputs with the necessary data. e.g.
<ul class="ulMedicationsControl">
<form ... >
<!-- hidden field and submit button and whatever else here -->
...
</form>
</ul>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Way to determine/circumvent if an AJAX request timed out? I have a simple web-page (PHP, JS and HTML) that is displayed to illustrate that a computation is in process. This computation is triggered by a pure JavaScript AJAX-request of a PHP-script doing the actual computations.
For details, please see
here
What the actual computation is, does not play a role, so for simplicity, it is just a sleep()-command.
When I execute the same code locally (browser calls website under localhost: linux, apache, php-mod) it works fine, independant of the sleep-time.
However, when I let it run on a different machine (not localhost, but also Linux, apache, php-mod), the PHP-script does run through (results are created), but the AJAX-request does not get any response, so there is no "onreadystatechange" if the sleep-time is >= 900 seconds. When sleep-time < 900 seconds it also works nicely and the AJAX-request is correctly terminated (readyState==4 and status==200).
The apache and php-configuration are more or less default and I verified the crucial options there already (max_execution_time etc.) but none seems to be valid here as they are either shorter (<1 min.) or bigger, e.g. for the garbage-collector (24 min.).
So I am absolutely confused what may cause this. I am thinking it might be network-related, although I didn't find any appropriate option in my router or so.
Also no error is reported in the apache-logs or in PHP (error loggin to file).
Letting the JavaScript with the AJAX-request display the request.status upon successfull return, surprisingly when I hit "Esc" in the browser window after the sleep is over, I also get the status "200" displayed but not automatically as it should do it.
In any case, I am hoping that you may have an idea how to circumvent this problem?
Maybe some dummy-communication between client and server every 10 minutes or so might do the trick, but I don't have an idea how to best do something like this, especially letting this be transparent to the user and not interfering with the actual work of doing the computations/sleep.
Best,
Shadow
P.S. The post that I am referencing is written by me, but seems to tramsit the idea that it might be related to some config-option, which seems not to be the case. This is why I am writing this post here, basically asking for a way to circumvent such an issue regardless of it's origin.
A: I'm from the other post you mentioned!
Now that I know more about what you are trying to do: monitor a possibly long running server job, I can recommend something which should turn out a lot better, its not a direct answer to your question, but its a design consideration which includes by its nature a more suitable solution.
Basically, unlink the actions of "starting" the server side task, from monitoring its progress.
*
*execute.php kicks off your background job on the server, and immediately returns.
*Another script/URL (lets call it status.php) is available to check the progress of the task execute.php is performing.
*
*When status.php is requested, it won't return until it has something to report, UNLESS 30 seconds (or some other fixed) amount of time passes, at which point it returns a value that you know means "check again". Do this in a loop, and you can be notified immediately of when the background task has completed.
More details on an approach similar to this: http://billhiggins.us/blog/2011/04/27/resty-long-ops
I hope this help give you some design ideas to address your problem!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: position fixed div in iframe not working I am working on facebook iframe application . I have one pop up message box inside this application. That pop up is having fixed possition . But its not working as added inside iframe having no scroll.
Is it possible to make pop up fixed in position if its in the iframe having no scroll?
A:
Is it possible to make pop up fixed in position if its in the iframe having no scroll?
Nope - the iframe is a document in itself. Anything with position: fixed in there is not fixed relative to the main document.
If you want something to be fixed relative to the main document, you need to put it into the main document - either directly, or by copying the node using JavaScript (using jQuery is a good idea in such a case.)
For the latter to work, both the main document and the iframed document need to be on the same protocol, port, and domain.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: how to show two customers in the one table row MVC 2 with asp.net ,i have used ListView to show tow customers per row:
<asp:ListView ID="CustListView" runat="server"
GroupItemCount="2" cellpadding="0" cellspacing="0" style="border-collapse: collapse;border-color:#111111;width:100%;" >
<LayoutTemplate>
<table>
<tr>
<td>
<table cellpadding="0" cellspacing="5" >
<asp:PlaceHolder runat="server" ID="groupPlaceHolder"></asp:PlaceHolder>
</table>
</td>
</tr>
</table>
</LayoutTemplate>
<GroupTemplate>
<tr>
<asp:PlaceHolder runat="server" ID="itemPlaceHolder"></asp:PlaceHolder>
</tr>
</GroupTemplate>
<ItemTemplate>
<%#Eval("Customer.Name")%>
<ItemTemplate>
</ListView/>
How can i do that in mvc 2.any links?
A: In ASP.NET MVC the first thing is to forget about any WebForms controls that you might have used. Things like ListView are irrelevant. In ASP.NET MVC you work with Models, Controllers and Views. So you could start by defining a view model:
public class CustomerViewModel
{
public string Name { get; set; }
}
which your controller should fill:
public ActionResult Index()
{
var model = new[]
{
new CustomerViewModel { Name = "John" },
new CustomerViewModel { Name = "Peter" },
new CustomerViewModel { Name = "Mary" },
};
return View(model);
}
and finally you have a view which is strongly typed to CustomerViewModel[] in which you could generate a table:
<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<% for (var i = 0; i < Model.Length; i++) { %>
<tr>
<td><%= Html.DisplayFor(x => x[i].Name) %></td>
</tr>
<% } %>
</tbody>
</table>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to emulate wicket setResponsePage() in spring security Situation: user is forced to change password when button "Change password" is clicked. This click fires form overridden method onSubmit() (Wicket). In this method:
protected void onSubmit() {
//changing password by updating it in DB
// autologin user with changed password in system
//set response page (wicket style)
setResponsePage(RestorePasswordPage.class);
}
Actually call setResponsePage(...) is the call to Wicket Component.setResponsePage()
public final <C extends Page> void setResponsePage(final Class<C> cls)
{
getRequestCycle().setResponsePage(cls);
}
My task was to substitute wicket on Spring security and it was solved - I intercept call to this method in Spring Filter Security Chain (class below is one of the components of this chaing). And can do all the things from code snippet above except one - I don't know how to make redirection to RestorePasswordPage
public class ForgotPasswordForcePasswordChangeEventHandler implements CustomEventHandler {
public void handle(HttpServletRequest request, HttpServletResponse response) {
// 1. Extract current customer
// 2. Extract changed password
// 3. Updates user through external web service
// 4. Prepares data for authentication
// 5. Clears security context to remove current authentication
//redirect to the same page as in wicket
HOW???
}
}
Questions:
*
*Is it any way to get access to Wicket RequestCycle if I got only HttpServletRequest request as input.
*Any other way to solve this problem?
A: Wicket supports "bookmarkable" pages – Page classes that have a no-parameter constructor, or just accept a PageParameters object. (PageParameters is an abstraction over query string parameters et al.)
If you do not need customise the page instance being redirected to in code, you can use WebApplication#mountPage inside your WebApplication#init to mount it at a "nice" static URL. You then configure Spring Security to redirect to that URL. IIRC, Spring Security intercepts the request before Wicket gets involved, so there is no need and likely no sane way to access Wicket's request processing.
If you do need parameters in the page you're redirecting to, take a look at the request mapping documentation. Essentially, you give the page a constructor with a PageParameters argument. Using PageParameters, you can always access any paramaters given in a standard query string, and "positional parameters" (unmapped extra URL components) without any configuration. When mounting the page, you can also define "named" parameters (extra URL components that are put into the PageParameters map under predefined names) and whatnot.
A: You could perform redirection by throwing a RestartResponseException.
throw new RestartResponseException(RestorePasswordPage.class, somePageParameters);
or
throw new RestartResponseException(new RestorePasswordPage(Object parameters));
RequestCycle, and other elements such as Session are automatically stored by Wicket in ThreadLocal variables, so you can get them whenever you want through static methods:
RequestCycle.get()
By the way, here's a question elaborating on RestartResponseException: Wicket: how to redirect to another page?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How long is the animation of the transition between views on a UINavigationController? Ideally, there would be some kind of constant containing this value.
I'm implementing code that has it's own transition animations, and I'd like those to have the same length as the platform transition animations.
A: In iOS 7 and later you can have exact value by setting the UINavigationController delegate and using the method:
- (void)navigationController:(UINavigationController *)navigationController
willShowViewController:(UIViewController *)viewController
animated:(BOOL)animated {
NSTimeInterval duration = [viewController.transitionCoordinator transitionDuration];
}
This is future proof method if the defult duration will ever change. At the moment it's value is 0.35 second.
A: There's no constant containing this value. However, using the following UINavigationControllerDelegate methods:
- (void) navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
startTime = [[NSDate date] retain];
}
- (void) navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
NSLog(@"Duration %f", [[NSDate date] timeIntervalSinceDate: startTime]);
}
... I can see that the duration is approx 0.35 seconds
Interestingly, different parts of the views take different times to transition into place. See this great blog post for more details:
http://www.iclarified.com/12396/a-closer-look-at-iphone-transition-animations
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Extend or override Session in ASP.NET (cookieless) I have an webapp multi domain and country. And I like to have other HttpCookieMode more complex. I like to mix UseDeviceProfile with country and wap gateway for determinating cookieless. Do you know what class do i have to inherit o method override?
I have tried changing SessionIdManager, but it isn´t work.
Thx in advance,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: can't send the postString to json i'm using json Framework for sending the jsonstring. my json post string is
{
"firstName": "string1",
"lastName": "string2",
"contactSource": "Leter",
"permanentAddress": {},
"deliveryAddress": {},
"preferredContactTimes": []
}
my coding......
NSString *postString = [NSString stringWithFormat:@"[\"firstName\":\"barani\",\"lastName\":\"Tharn\",\"contactSource\":\"Leter\",\"permanentAddress\":{},\"deliveryAddress\":{},\"preferredContactTimes\":[]]",fName.text,lName.text,contactSource.text,address,address,add];
NSURL *purchaseURL = [NSURL URLWithString:@"http://localhost/Cali/addContact"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:purchaseURL];
NSData *requestData = [NSData dataWithBytes:[postString UTF8String] length:[postString length]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [requestData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:requestData];//[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSLog(@"post String :%@",[[NSString alloc] initWithData:requestData encoding:NSASCIIStringEncoding]);
NSURLConnection *purchaseConn =[[NSURLConnection alloc]
initWithRequest:request
delegate:self];
if (purchaseConn) {
NSLog(@"connection!!!");
webData = [[NSMutableData data] retain];
}
and in connection did finish loading
NSString *jsonString = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSLog(@"hai:%@",[[NSString alloc] initWithData:webData encoding:NSASCIIStringEncoding]);
NSDictionary *jsonValue = [jsonString JSONString];
NSLog(@"output:%@",jsonValue);
here the permanentAddress and deliveryAddress also a sub json string adn preferredContactTimes is array
i got the json failed error
JSONValue failed. Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=11 \"Unexpected end of string\" UserInfo=0x4c8d820 {NSLocalizedDescription=Unexpected end of string}"
)
please give me the solution
A: Not sure if this is causing your problem, but it is possible especially if your name and other text fields contain non-ASCII characters. You create your NSData as such:
NSData *requestData = [NSData dataWithBytes:[postString UTF8String] length:[postString length]];
The [postString UTFString] will convert your string into a nil-terminated buffer of bytes. If there are any non-ASCII characters in that string then the length of that buffer will be longer than the number of characters. So if the number of characters in the string is 10, then the number of bytes would be at least 11 (one byte for the nil terminator) and possibly longer.
You then tell NSData that the length of the buffer is equal to the length of the string. So if result of [postString UTF8String] is longer, then you could be getting a truncated buffer and bring to parse it.
Try doing this instead:
NSData *requestData = [postString dataUsingEncoding:NSUTF8StringEncoding]
A: Thanks to all i found the problem where it occurs.... i discussed with web service developer. He told that the format i send is correct. But in server side it create junk value automatically because of they create mapping. So they create the new one for me its working fine now...
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: tomcat ajp connector with multiple webapps I have a tomcat server, with a webapps/ROOT application, fronted by Apache.
LoadModule proxy_ajp_module modules/mod_proxy_ajp.so
and
ProxyPass / ajp://localhost:8009/
ProxyPassReverse / ajp://localhost:8009/
I need to add a second webapp to this box, so I unpacked it into webapps/pib.war/ and changed the Apache conf:
ProxyPass /pib http://localhost:8009/pib
ProxyPassReverse /pib http://localhost:8009/pib
ProxyPass / ajp://localhost:8009/
ProxyPassReverse / ajp://localhost:8009/
My tomcat/conf/server.xml contains:
<Service name="Catalina">
<Connector port="8009" protocol="AJP/1.3" />
<Engine name="Catalina" defaultHost="localhost">
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase" />
<Host name="localhost" appBase="webapps" />
</Engine>
</Service>
I have only one context.xml file - there are none under the webapps - in conf/context.xml
<Context>
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
When I visit https://myserver/ then the existing, default, ROOT application works as normal, but https://myserver/pib/ gives, in catalina.out:
org.apache.jk.common.MsgAjp processHeader
SEVERE: BAD packet signature 18245
which the intertubes suggest means I'm talking HTTP to the AJP connector, instead of AJP, yet the first webapp is working properly.
What am I missing? I've seen mention of context.xml files under each webapp, but I'm not sure what they're for or what to put in them.
I don't normally use AJP, but this box is already working that way, so I'm a little lost right now.
Thanks,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: php ip location I have a simple question.
Is it possible to redirect people in my website by the IP location?
Example:
one person navigates on the site and when go to pay, if the ip location is from Portugal pay by bank transfer, if not pay by paypal?
sorry my english.
thanks,
Pedro Lopes
A: In the end, it sounds like you only really care about which billing platform to send them to. It is far easier and more reliable to allow your users to select their country from a list of countries you support. This is both more accurate than the IP-based solution and it solves for travelers who may not be at their home computer. There are more potential issues with IP-based location in the link @Piskvor provided in the comments above.
For the example you gave, you could offer your standard billing address form. If the user selects a country other than Portugal, the bank transfer tender type gets disabled, and PayPal is selected.
A: Of course and you can do it. But I thing that not so accurate.
In example I am from Corfu, Greece. My geolocation is always pointing in Athens Greece.
Another example. I have try to lock out a whole country from accessing my web site for a personal reason. But while that work good, is not perfect, still I have visits from that country.
A: Yes. It is totally possible to track and redirect based on visitor's IP-Location.
You can use ipgeolocation.io API. It is free for use up to 30K requests per month (1K requests per day). It has integrations available for many languages like PHP, Java, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: 2 byte representation of command line arguments in Visual Studio 2008 I have a problem when handling command line arguments in a simple C++ application written in Visual Studio 2008. I have written the following code:
#include <iostream>
using namespace std;
int _tmain(int argc, char **argv)
{
char* c = *argv;
for(int i=0; i< argc ; ++i)
{
cout << argv[i] << endl;
}
int a;
cin >> a;
return 0;
}
My problem is that only the first character of each command line argument is written to cout.
I identified the cause to be that the characters in the command line arguments are represented as 2 bytes, making every other 1 byte char contain only zeros, i.e '\0'.
My question is, why do this happen? from what i found in samples on the net it should work as i have written it. Also, is there a way to force the characters in the arguments to be of 1 byte representation?
I hope my question is clear enough.
A: Your _tmain is receiving UTF-16 characters which, when fed Latin text, have a 0 in every other byte. You are interpreting them as single byte characters. You need to interpret them as wide characters.
I would write it something like this:
#include <iostream>
using namespace std;
int wmain(int argc, wchar_t* argv[])
{
for(int i=0; i<argc; ++i)
{
wcout << argv[i] << endl;
}
int a;
wcin >> a;
return 0;
}
If you don't want to use UTF-16 then you can stick with char like this:
int main(int argc, char* argv[])
{
for(int i=0; i<argc; ++i)
{
cout << argv[i] << endl;
}
int a;
cin >> a;
return 0;
}
Note the change in the naming of the main function. In MS world, wmain receives wchar_t* and main receives char*.
If you do switch to char* then you should also update your project configuration to target MBCS rather than Unicode.
More information on the main function handling of the MS compiler can be found here: main: Program Startup.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PHP $_POST values i have a little problem with storing the $_POST data, think i might be confusing myself a little.
So i have some data being posted from a loop, this data is posted as id and points, but each has a number to it so if three records are being posted we'll have
id1, id2, id3
points1, points2, points3
to collect. Now i'm using a for loop to go through the data and post it into two arrays to work with. The problem is When I want to store the data i have to use one of the names listed above ie id1 or id2. Here is my code
for($i = 0; i< $_POST['count']; i++){
//Order input data into an array
$inputid[$i] = $_POST['id1'];
}
Now the number part of the 'id' of the $_POST['id1'] has to be the same as $i in the for loop so it will increment as the loop does.
Thanks for the help and i hope i explained the question right.
A: Why not name the inputs: name="id[1]" and name="points[1]" so you'll have $_POST['id'][...] and $_POST['points'][...] arrays to work with?
Reference: Variables From External Sources (specifically Example #3).
A: Firstly, don't use POST variables in loops or anything else unless you've checked them out first to make sure they don't contain anything nasty.
You could try this within the loop:
$idnumber = "id" . $i;
$inputid[$i] = $_POST[$idnumber];
A: Simply concatenate the string in the index:
for($i = 0; i< $_POST['count']; i++){
//Order input data into an array
$inputid[$i] = $_POST['id' . ($i+1)];
}
A: for($i = 0; i< $_POST['count']; i++){
//Order input data into an array
$inputid[$i] = $_POST['id'.$i];
}
A: if i am not going wrong you want the posted id same as the increment var $i try this out
for($i = 0; $i< $_POST['count']; $i++){
$post_id = 'id'.$i;
$inputid[$i] = $_POST[$post_id];
}
A: If I understand this question, there are already a known amount of inputs that are going to be posted, so I don't understand why you need a loop at all for adding them to the array. Why not do this:
$value = array($_POST['id1'], $_POST['id2'], $_POST['id3'], $_POST['points1'], $_POST['points2'], $_POST['points3']);
than loop like this:
for(x=0;x<$value.count;x++){
$value[x]=$value.$x;
}
That should work
A: I think you can go for something like this:
for($i = 0; $i< $_POST['count']; $i++){
//Order input data into an array
$inputid[$i] = $_POST["id$i"];
}
Is this what you want?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Database independent string comparison with JPA I'm working with JPA (Hibernate as provider) and an underlying MySQL database.
I have a table containing every name of streets in Germany. Every streetname has a unique number. For one task I have to find out the number of the name. To do this I wrote a JPQL-Query like the following
"SELECT s FROM Strassencode s WHERE s.name = :name"
Unfortunately there are streetnames in Germany which only differ in small and capital letters like "Am kleinen Feld" and "Am Kleinen Feld". Obviously one of them is gramatical wrong, but as a name for a street, both spellings are allowed and both of them have a different number.
When I send my JPQL-Query to the database, I'm using
query.getSingleResult();
because of the fact, that every streetname in the table is unique. But with the underlying MySQL-Database, I'll get a NonUniqueResultException, because a mySQL database is doing a case insensitive comparison by default. The common way to force mySQL is to write a query like
SELECT 'abc' LIKE BINARY 'ABC';
as discribed in chapter 11.5.1 in the mySQL Reference Manual, but there is no corresponding keyword in JPQL.
My first attempt was to annotade the field name in the class with
@Column(nullable = false, columnDefinition = "varbinary(128)")
Annotated like this, the database is automatically doing a case sensitive comparison, because one of the strings is binary. But when I use this solution, I'm running into troubles when I'm reading the names out of the databse, to write them into a file, because letters like ä, ö, ü are interpreted wrong then.
I know, that the field name should get a uniqueConstraint and it's one of my goals to do so, but this is only possible if the database will do a case sensitive string comparison.
Is there a solution, where I can configure JPA to do case sensitive string comparison without having to manually fine-tune the database?
A: To stay "independant" as you say for database and JPA provider i would avoid the getSingleResult() and fetch the list() and match in memory for the name. Probably you will get more than one but not 100 or more.
Another way could be to save the name normalised (trimmed, to lower case) in a new field.
A: Seems like there is no way in configuring JPA to solve this problem. But what I found is, that it is possible to set the collation not only on the table-level, you can also set it for the whole database as discribed in the Reference Manual 12.1.10 CREATE DATABASE SYNTAX and 9.1.3.2. Database Character Set and Collation
CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name
[create_specification] ...
create_specification:
[DEFAULT] CHARACTER SET [=] charset_name
| [DEFAULT] COLLATE [=] collation_name
I only had to create the database with:
CREATE DATABASE db_name CHARACTER SET latin1 COLLATE latin1_general_cs;
With this, I could put a uniqueConstraint on the field name and insert both "Am kleinen Feld" and "Am Kleinen Feld" and when I query for one of them, I'll only receive one.
However, thanks for the help
A: You also write a SQL query. It is like a normal query:
Query sqlQuery = session.createSqlQuery("select * from CITY where name like binary :name').addString('name', name);
Note that the code is roughly done.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Add-on SDK calling dispatchEvent does not send event from content script to a page I have simple Firefox extension (based on Add-on SDK) with pageMod.
pageMod injects some script to a page, which calls one function:
function dispatchEvent(name, data){
try {
data = data || {};
// passing some data through html element
document.getElementById('MyDiv').innerText = JSON.stringify(data);
var evt = document.createEvent('Event');
evt.initEvent(name.toString(), true, true);
if(document.getElementById('MyDiv').dispatchEvent(evt))
console.log("Dispatch event: "+name+" data: "+JSON.stringify(data));
} catch (e) {
console.log("Error:" + e);
}
}
dispatchEvent("MyEvent", {});
On the web page I have event listener, added through MyDiv.addEventListener(...).
Problem is the injected script does not dispatch any event to a page. The dispatchEvent function returns true, but nothing happens.
Here is my pageMod code:
var myMod = pageMod.PageMod({
include: ["http://localhost/mysite/*"],
contentScriptFile: [data.url("js/script.js")],
contentScriptWhen: "end",
onAttach: function onAttach(worker) {
console.log("CS injected");
}
});
If I run contentScript code through Firebug console, it works, but I need to dispatch events from contentScript.
P.S. I also tried to use unsafeWindow.document instead of document, and use jQuery events/event listeners and it's not working either.
A: I took time to convert your question into a testcase, and it works for me: https://builder.addons.mozilla.org/addon/1018586/revision/13/
Please provide the complete testcase the next time, as the problem often lies not in the piece of code you think it does.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Server 2008 R2 SQLXML and xpath query filter not working I have the following schema returning four projects when running sql xml:
<xsd:element name="iati-activities" sql:relation="IATI.ACTIVITIES" sql:key-fields="BUSINESS_UNIT">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="iati-activity" sql:relation="IATI.PROJECT_METADATA" sql:relationship="ACTIVITIES_ACTIVITY">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="ProjectId" type="xsd:string" sql:field="PROJECT_ID" sql:key-fields="PROJECT_ID" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:sequence>
<xsd:complexType>
</xsd:element>
I want to get:
<iati-activities>
<iati-activity>
<ProjectId>00072877</ProjectId>
</iati-activity>
</iati-activities>
But when running it does not filter. Here is the xpath-query I use:
<root xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<sql:header sql:nullvalue="ISNULL">
<sql:param name="ProjectId">00072877</sql:param>
</sql:header>
<sql:xpath-query mapping-schema="activity_schema.xsd">
iati-activities[iati-activity/ProjectId=$ProjectId]
</sql:xpath-query>
</root>
This is what I get:
<iati-activities>
<iati-activity>
<ProjectId>00072877</ProjectId>
</iati-activity>
<iati-activity>
<ProjectId>00059626</ProjectId>
</iati-activity>
<iati-activity>
<ProjectId>...</ProjectId>
</iati-activity>
<iati-activity>
<ProjectId>...</ProjectId>
</iati-activity>
</iati-activities>
If I use the following query:
<root xmlns:sql="urn:schemas-microsoft-com:xml-sql">
<sql:header sql:nullvalue="ISNULL">
<sql:param name="ProjectId">00072877</sql:param>
</sql:header>
<sql:xpath-query mapping-schema="activity_schema.xsd">
iati-activities/iati-activity[ProjectId=$ProjectId]
</sql:xpath-query>
</root>
I get the below without the iati-acitivties element:
<iati-activity>
<ProjectId>00072877</ProjectId>
</iati-activity>
Any one know what I'm doing wrong?
A: I know what it is... The xpath I was using is only pointing to the element and by selecting the parent of that I get the entire tree under the parent node and not only the filtered one.
It needs to be exported fully and an xslt applied where I define the parent element manually.
<xsl:template match="/">
<iati-activities version="1.01" GENERATED_DATE="{$GENERATED_DATE}">
<xsl:for-each select="/iati-activities/iati-activity[ProjectId=$ProjectId]">
<xsl:copy-of select="." />
</xsl:for-each>
</iati-activities>
</xsl:template>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java JXTreeTable tab character support Is tab character(\t) or Tab Key is supported in JXTreeTable? As I am entering some input like "My Name" where the space between My & Name is not through spacebar instead it is using the Tab key from the key board. Now when I am seeing this input in JXTreeTable, I am only able to see as MyName. Without Tab space in it, can any one have any inputs regarding this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there an xml_encode() like json_encode() in PHP? In PHP, it is easy to pass back JSON objects by using the json_encode() function.
Is there an XML equivalent for this?
A: JSON can express php arrays, integers, strings, etc. natively. XML has no such concepts - just elements, attributes, and text. If you want to transfer an object verbatim, use JSON. If you want to implement a complex API, use XML, for example the php DOM interface.
A: You could use xmlrpc_encode.
xmlrpc_encode ($your_array);
Be careful because this function is EXPERIMENTAL.
Reference: http://php.net/manual/en/function.xmlrpc-encode.php
A: here is one for php7.0+ , i bet it is far from optimal , the code is non-trivial, and it has NOT been tested much, but at least it works for my data (unlike Seph's code)...
example:
$test = array (
'normal1' => 'foo',
'normal2' => 'bar',
'foo_assoc' => [
'foo',
'bar',
'baz',
[
'derp',
'derpmore'
]
],
'foo_nonassoc' => [
'derppp' => 'yes',
'daarpp' => 'no',
'lel',
'far' => 'away'
],
'normal3' => 'lala',
'deep' => [
'deeper' => [
'deeper2' => [
'deepest' => [
'quite',
'deep',
'indeed'
],
'checkmate'
]
]
],
'special' => 'encoding<special>characters&test',
'me_n_you' => 'true'
);
echo (hhb_xml_encode ( $test ));
output:
<normal1>foo</normal1>
<normal2>bar</normal2>
<foo_assoc>foo</foo_assoc>
<foo_assoc>bar</foo_assoc>
<foo_assoc>baz</foo_assoc>
<foo_assoc>derp</foo_assoc>
<foo_assoc>derpmore</foo_assoc>
<foo_nonassoc>
<derppp>yes</derppp>
<daarpp>no</daarpp>
<foo_nonassoc>lel</foo_nonassoc>
<far>away</far>
</foo_nonassoc>
<normal3>lala</normal3>
<deep>
<deeper>
<deeper2>
<deepest>quite</deepest>
<deepest>deep</deepest>
<deepest>indeed</deepest>
<deeper2>checkmate</deeper2>
</deeper2>
</deeper>
</deep>
<special>encoding<special>characters&test</special>
<me_n_you>true</me_n_you>
function:
*
*Edit: fixed a bug with encoding empty arrays.
*Edit: made the code PHP8-compatible
function hhb_xml_encode(array $arr, string $name_for_numeric_keys = 'val'): string {
if (empty ( $arr )) {
// avoid having a special case for <root/> and <root></root> i guess
return '';
}
$is_iterable_compat = function ($v): bool {
// php 7.0 compat for php7.1+'s is_itrable
return is_array ( $v ) || ($v instanceof \Traversable);
};
$isAssoc = function (array $arr): bool {
// thanks to Mark Amery for this
if (array () === $arr)
return false;
return array_keys ( $arr ) !== range ( 0, count ( $arr ) - 1 );
};
$endsWith = function (string $haystack, string $needle): bool {
// thanks to MrHus
$length = strlen ( $needle );
if ($length == 0) {
return true;
}
return (substr ( $haystack, - $length ) === $needle);
};
$formatXML = function (string $xml) use ($endsWith): string {
// there seems to be a bug with formatOutput on DOMDocuments that have used importNode with $deep=true
// on PHP 7.0.15...
$domd = new DOMDocument ( '1.0', 'UTF-8' );
$domd->preserveWhiteSpace = false;
$domd->formatOutput = true;
$domd->loadXML ( '<root>' . $xml . '</root>' );
$ret = trim ( $domd->saveXML ( $domd->getElementsByTagName ( "root" )->item ( 0 ) ) );
assert ( 0 === strpos ( $ret, '<root>' ) );
assert ( $endsWith ( $ret, '</root>' ) );
$full = trim ( substr ( $ret, strlen ( '<root>' ), - strlen ( '</root>' ) ) );
$ret = '';
// ... seems each line except the first line starts with 2 ugly spaces,
// presumably its the <root> element that starts with no spaces at all.
foreach ( explode ( "\n", $full ) as $line ) {
if (substr ( $line, 0, 2 ) === ' ') {
$ret .= substr ( $line, 2 ) . "\n";
} else {
$ret .= $line . "\n";
}
}
$ret = trim ( $ret );
return $ret;
};
// $arr = new RecursiveArrayIterator ( $arr );
// $iterator = new RecursiveIteratorIterator ( $arr, RecursiveIteratorIterator::SELF_FIRST );
$iterator = $arr;
$domd = new DOMDocument ();
$root = $domd->createElement ( 'root' );
foreach ( $iterator as $key => $val ) {
// var_dump ( $key, $val );
$ele = $domd->createElement ( is_int ( $key ) ? $name_for_numeric_keys : $key );
if (! empty ( $val ) || $val === '0') {
if ($is_iterable_compat ( $val )) {
$asoc = $isAssoc ( $val );
$tmp = hhb_xml_encode ( $val, is_int ( $key ) ? $name_for_numeric_keys : $key );
// var_dump ( $tmp );
// die ();
$tmpDom = new DOMDocument();
@$tmpDom->loadXML ( '<root>' . $tmp . '</root>' );
foreach ( $tmpDom->getElementsByTagName ( "root" )->item ( 0 )->childNodes ?? [ ] as $tmp2 ) {
$tmp3 = $domd->importNode ( $tmp2, true );
if ($asoc) {
$ele->appendChild ( $tmp3 );
} else {
$root->appendChild ( $tmp3 );
}
}
unset ( $tmp, $tmp2, $tmp3, $tmpDom );
if (! $asoc) {
// echo 'REMOVING';die();
// $ele->parentNode->removeChild($ele);
continue;
}
} else {
$ele->textContent = $val;
}
}
$root->appendChild ( $ele );
}
$domd->preserveWhiteSpace = false;
$domd->formatOutput = true;
$ret = trim ( $domd->saveXML ( $root ) );
assert ( 0 === strpos ( $ret, '<root>' ) );
assert ( $endsWith ( $ret, '</root>' ) );
$ret = trim ( substr ( $ret, strlen ( '<root>' ), - strlen ( '</root>' ) ) );
// seems to be a bug with formatOutput on DOMDocuments that have used importNode with $deep=true..
$ret = $formatXML ( $ret );
return $ret;
}
A: You can define your own xml_encode() function such as this the one from http://darklaunch.com/2009/05/23/php-xml-encode-using-domdocument-convert-array-to-xml-json-encode
function xml_encode($mixed, $domElement=null, $DOMDocument=null) {
if (is_null($DOMDocument)) {
$DOMDocument =new DOMDocument;
$DOMDocument->formatOutput = true;
xml_encode($mixed, $DOMDocument, $DOMDocument);
echo $DOMDocument->saveXML();
}
else {
// To cope with embedded objects
if (is_object($mixed)) {
$mixed = get_object_vars($mixed);
}
if (is_array($mixed)) {
foreach ($mixed as $index => $mixedElement) {
if (is_int($index)) {
if ($index === 0) {
$node = $domElement;
}
else {
$node = $DOMDocument->createElement($domElement->tagName);
$domElement->parentNode->appendChild($node);
}
}
else {
$plural = $DOMDocument->createElement($index);
$domElement->appendChild($plural);
$node = $plural;
if (!(rtrim($index, 's') === $index)) {
$singular = $DOMDocument->createElement(rtrim($index, 's'));
$plural->appendChild($singular);
$node = $singular;
}
}
xml_encode($mixedElement, $node, $DOMDocument);
}
}
else {
$mixed = is_bool($mixed) ? ($mixed ? 'true' : 'false') : $mixed;
$domElement->appendChild($DOMDocument->createTextNode($mixed));
}
}
}
A: My contrib:
function xml_encode(mixed $value=null, string $key="root", SimpleXMLElement $parent=null){
if(is_object($value)) $value = (array) $value;
if(!is_array($value)){
if($parent === null){
if(is_numeric($key)) $key = 'item';
if($value===null) $node = new SimpleXMLElement("<$key />");
else $node = new SimpleXMLElement("<$key>$value</$key>");
}
else{
$parent->addChild($key, $value);
$node = $parent;
}
}
else{
$array_numeric = false;
if($parent === null){
if(empty($value)) $node = new SimpleXMLElement("<$key />");
else $node = new SimpleXMLElement("<$key></$key>");
}
else{
if(!isset($value[0])) $node = $parent->addChild($key);
else{
$array_numeric = true;
$node = $parent;
}
}
foreach( $value as $k => $v ) {
if($array_numeric) xml_encode($v, $key, $node);
else xml_encode($v, $k, $node);
}
}
return $node;
}
Simple Example:
$a = "hello";
$xml_element = xml_encode($a,'a');
echo $xml_element->asXML();
Null Example:
$xml_element = xml_encode(null,'example');
echo $xml_element->asXML();
Complex Example:
$w = new stdClass();
$w->special = true;
$w->name = 'Birthday Susan';
$v = new stdClass();
$v->name = 'John';
$v->surname = 'Smith';
$v->hobbies = array('soccer','cinema');
$v->job = 'policeman';
$v->events = new stdClass();
$v->events->tomorrow = false;
$v->events->yesterday = true;
$v->events->list = array($v->hobbies, $w);
$xml_element = xml_encode($v,'oembed');
echo $xml_element->asXML();
A: This works for me in most cases:
$str = htmlentities($str , ENT_XML1);
Docs:
http://php.net/manual/en/function.htmlentities.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: How do I match the content of two HTML tags? Multi-line strings inbetween them. - AS3 I want to match all contents inside the <div class="post_body" id="pid_"></div> tags... A sample of what I need to parse is below.
<tr>
<td class="trow2 post_content ">
<div class="post_body" id="pid_">
This is <span style="font-style: italic;">just a test</span> message.<br />
With an image.<br />
[img]http://www.somesite.com/wp-content/something.jpg[/img]<br />
Blah blah <span style="font-weight: bold;">blah</span>.<br />
<br />
The quick brown fox jumps over the lazy <span style="text-decoration: underline;">dawg</span>.<br />
<br />
[video=youtube]http://www.youtube.com/watch?v=MbYZa4gTxzM[/video]<br />
<br />
<a href="mailto:test@test.com">asd</a><br />
<ul>
<li>item number 1</li>
<li>item nubmer 2<br />
</li></ul>
<br />
<div class="codeblock phpcodeblock"><div class="title">PHP Code:<br />
</div><div class="body"><div dir="ltr"><code><span style="color: #66CCFF"><?php </span><span style="color: #7AC07C">echo </span><span style="color: #FF99FF">'hello world'</span><span style="color: #7AC07C">; </span><span style="color: #66CCFF">?></span></code></div></div></div>
<br />
<div style="text-align: center;">i am centered.</div>
<div style="text-align: right;">i am not centered.</div>
</div>
<div class="post_meta" id="post_meta_">
</div>
</td>
</tr>
As you can see, I intentionally added a whole bunch of stuff in-between the tags. This was the part where I needed help for. How do I detect the insides of the two tags I specified above given the fact that there are other tags in their way.
This is done in AS3 on Flash Builder.
A: If your HTML is XHTML, you can use XPath to parse and get the values inside those tags. See this question Parsing XML/XHTML in Actionscript
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: tinyMCE: Remove last inserted code Following from this: TinyMCE editor fixed size with no scrollers?
How can I remove the last inserted code in tinyMCE?
setup : function(ed){
ed.onKeyDown.add(function (ed, evt) {
var currentfr=document.getElementById(ed.id + '_ifr');
if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) { //ns6 syntax
currentfr.height = currentfr.contentDocument.body.offsetHeight + 26;
}
else if (currentfr.Document && currentfr.Document.body.scrollHeight) { //ie5+ syntax
currentfr.height = currentfr.Document.body.scrollHeight;
}
if( currentfr.height >= 156 ){
// Remove last inserted code here
}
});
},
So if the height is 156 or more, it should remove what you just typed (code).
How can i do this?
A: I made a few tests and this is what i came up with:
setup : function(ed){
ed.onKeyDown.add(function (ed, evt) {
var currentfr=document.getElementById(ed.id + '_ifr');
if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) { //ns6 syntax
currentfr.height = currentfr.contentDocument.body.offsetHeight + 26;
}
else if (currentfr.Document && currentfr.Document.body.scrollHeight) { //ie5+ syntax
currentfr.height = currentfr.Document.body.scrollHeight;
}
if (evt.keyCode != 8 && evt.keyCode != 46 && currentfr.height < 156){
ed.bookmark = ed.selection.getBookmark(2,true);
ed.latest_content = ed.getContent({format:'raw'});
}
});
ed.onKeyUp.add(function (ed, evt) {
var currentfr=document.getElementById(ed.id + '_ifr');
if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) { //ns6 syntax
currentfr.height = currentfr.contentDocument.body.offsetHeight + 26;
}
else if (currentfr.Document && currentfr.Document.body.scrollHeight) { //ie5+ syntax
currentfr.height = currentfr.Document.body.scrollHeight;
}
if( currentfr.height >= 156 && evt.keyCode != 8 && evt.keyCode != 46){
// Remove last inserted code here
// save and reset the caret using a bookmark
ed.setContent(ed.latest_content);
ed.selection.moveToBookmark(ed.bookmark);
ed.execCommand('mceCleanup');
}
});
},
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android SSL error: certificate not trusted In the app I'm working on, I have to make an HTTPS connection to my web server which uses self signed certificate. I was getting certificate not trusted errors and after consulting SO, I found this blog posting: http://blog.antoine.li/index.php/2010/10/android-trusting-ssl-certificates/
I created a JKS keystore for my tomcat running on my local machine using Keytool with following command
keytool -genkey -keyalg RSA -alias selfsigned -keystore keystore.jks -storepass password -validity 360 -keysize 2048
And i extracted certificate from that JKS keystore in DER Encoded format using a open source tool called portecle
And then i created a new BKS KeyStore with the above certificate using the same portecle tool as android has built support for Bouncy Castle provider.
Now if i make a http post as shown in the first URL, I am getting the following exception in the logcat.
WARN/System.err(498): javax.net.ssl.SSLException: Not trusted server certificate
WARN/System.err(498): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:371)
WARN/System.err(498): at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:92)
WARN/System.err(498): at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:381)
WARN/System.err(498): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:164)
WARN/System.err(498): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
WARN/System.err(498): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
WARN/System.err(498): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:348)
WARN/System.err(498): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
WARN/System.err(498): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
WARN/System.err(498): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
WARN/System.err(498): at com.portal.activity.Registration$ProgressThread.run(Registration.java:324)
WARN/System.err(498): Caused by: java.security.cert.CertificateException: java.security.InvalidAlgorithmParameterException: the trust anchors set is empty
WARN/System.err(498): at org.apache.harmony.xnet.provider.jsse.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:151)
WARN/System.err(498): at org.apache.harmony.xnet.provider.jsse.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:366)
WARN/System.err(498): ... 10 more
WARN/System.err(498): Caused by: java.security.InvalidAlgorithmParameterException: the trust anchors set is empty
WARN/System.err(498): at java.security.cert.PKIXParameters.checkTrustAnchors(PKIXParameters.java:611)
WARN/System.err(498): at java.security.cert.PKIXParameters.<init>(PKIXParameters.java:86)
WARN/System.err(498): at org.apache.harmony.xnet.provider.jsse.TrustManagerImpl.<init>(TrustManagerImpl.java:82)
WARN/System.err(498): at org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl.engineGetTrustManagers(TrustManagerFactoryImpl.java:132)
WARN/System.err(498): at javax.net.ssl.TrustManagerFactory.getTrustManagers(TrustManagerFactory.java:226)
WARN/System.err(498): at org.apache.http.conn.ssl.SSLSocketFactory.createTrustManagers(SSLSocketFactory.java:263)
WARN/System.err(498): at org.apache.http.conn.ssl.SSLSocketFactory.<init>(SSLSocketFactory.java:190)
WARN/System.err(498): at org.apache.http.conn.ssl.SSLSocketFactory.<init>(SSLSocketFactory.java:216)
WARN/System.err(498): at com.portal.httpclient.MyHttpClient.newSslSocketFactory(MyHttpClient.java:51)
WARN/System.err(498): at com.portal.httpclient.MyHttpClient.createClientConnectionManager(MyHttpClient.java:31)
WARN/System.err(498): at org.apache.http.impl.client.AbstractHttpClient.getConnectionManager(AbstractHttpClient.java:221)
WARN/System.err(498): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:539)
WARN/System.err(498): ... 3 more
My HttpClient is same as in the first URL except that ports for http and https are changed to 8080 and 8443 instead of 80 and 443 respectively.
Please help.
A: You can find instructions for using custom truststores with Android here http://blog.crazybob.org/2010/02/android-trusting-ssl-certificates.html
Briefly:
*
*Get the public cert for the server
*Create a BKS truststore with that certificate
*Create and use a custom HttpClient for your post
Sounds like you've done the top two but not the bottom step.
Also, did Portecle use the correct flags? You need the trustcacerts flag when creating the BKS store or it won't work.
A: I stopped using portecle and did everything using commandline
i am using just keytool for doing everything as shown in the URL of my question.
It worked for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: slicing sparse (scipy) matrix I would appreciate any help, to understand following behavior when slicing a lil_matrix (A) from the scipy.sparse package.
Actually, I would like to extract a submatrix based on an arbitrary index list for both rows and columns.
When I used this two lines of code:
x1 = A[list 1,:]
x2 = x1[:,list 2]
Everything was fine and I could extract the right submatrix.
When I tried to do this in one line, it failed (The returning matrix was empty)
x=A[list 1,list 2]
Why is this so? Overall, I have used a similar command in matlab and there it works.
So, why not use the first, since it works? It seems to be quite time consuming. Since I have to go through a large amount of entries, I would like to speed it up using a single command. Maybe I use the wrong sparse matrix type...Any idea?
A: for me the solution from unutbu works well, but is slow.
I found as a fast alternative,
A = B.tocsr()[np.array(list1),:].tocsc()[:,np.array(list2)]
You can see that row'S and col's get cut separately, but each one converted to the fastest sparse format, to get index this time.
In my test environment this code is 1000 times faster than the other one.
I hope, I don't tell something wrong or make a mistake.
A: Simultaneous indexing as in B[arr1, arr2] does work and it's faster than listener's solution on my machine. See In [5] in the Jupyter example below. To compare it with the mentioned answer refer to In [6]. Furthermore, my solution doesn't need the .tocsc() conversion, making it more readable IMO.
Please note that for B[arr1, arr2] to work, arr1 and arr2 must be broadcastable numpy arrays.
A much faster solution, however, is using B[list1][:, list2] as pointed out by unutbu. See In [7] below.
In [1]: from scipy import sparse
: import numpy as np
:
:
In [2]: B = sparse.rand(1000, 1000, .1, format='lil')
: list1=[1,4,6,8]
: list2=[2,4]
:
:
In [3]: arr1 = np.array(list1)[:, None] # make arr1 a (n x 1)-array
: arr1
:
:
Out[3]:
array([[1],
[4],
[6],
[8]])
In [4]: arr2 = np.array(list2)[None, :] # make arr2 a (1 x m)-array
: arr2
:
:
Out[4]: array([[2, 4]])
In [5]: %timeit A = B.tocsr()[arr1, arr2]
100 loops, best of 3: 13.1 ms per loop
In [6]: %timeit A = B.tocsr()[np.array(list1),:].tocsc()[:,np.array(list2)]
100 loops, best of 3: 14.6 ms per loop
In [7]: %timeit B[list1][:, list2]
1000 loops, best of 3: 205 µs per loop
A: The method you are already using,
A[list1, :][:, list2]
seems to be the fastest way to select the desired values from a spares matrix. See below for a benchmark.
However, to answer your question about how to select values from arbitrary rows and columns of A with a single index,
you would need to use so-called "advanced indexing":
A[np.array(list1)[:,np.newaxis], np.array(list2)]
With advanced indexing, if arr1 and arr2 are NDarrays, the (i,j) component of A[arr1, arr2] equals
A[arr1[i,j], arr2[i,j]]
Thus you would want arr1[i,j] to equal list1[i] for all j, and
arr2[i,j] to equal list2[j] for all i.
That can be arranged with the help of broadcasting (see below) by setting
arr1 = np.array(list1)[:,np.newaxis], and arr2 = np.array(list2).
The shape of arr1 is (len(list1), 1) while the shape of arr2 is
(len(list2), ) which broadcasts to (1, len(list2)) since new axes are added
on the left automatically when needed.
Each array can be further broadcasted to shape (len(list1),len(list2)).
This is exactly what we want for
A[arr1[i,j],arr2[i,j]] to make sense, since we want (i,j) to run over all possible indices for a result array of shape (len(list1),len(list2)).
Here is a microbenchmark for one test case which suggests that A[list1, :][:, list2] is the fastest option:
In [32]: %timeit orig(A, list1, list2)
10 loops, best of 3: 110 ms per loop
In [34]: %timeit using_listener(A, list1, list2)
1 loop, best of 3: 1.29 s per loop
In [33]: %timeit using_advanced_indexing(A, list1, list2)
1 loop, best of 3: 1.8 s per loop
Here is the setup I used for the benchmark:
import numpy as np
import scipy.sparse as sparse
import random
random.seed(1)
def setup(N):
A = sparse.rand(N, N, .1, format='lil')
list1 = np.random.choice(N, size=N//10, replace=False).tolist()
list2 = np.random.choice(N, size=N//20, replace=False).tolist()
return A, list1, list2
def orig(A, list1, list2):
return A[list1, :][:, list2]
def using_advanced_indexing(A, list1, list2):
B = A.tocsc() # or `.tocsr()`
B = B[np.array(list1)[:, np.newaxis], np.array(list2)]
return B
def using_listener(A, list1, list2):
"""https://stackoverflow.com/a/26592783/190597 (listener)"""
B = A.tocsr()[list1, :].tocsc()[:, list2]
return B
N = 10000
A, list1, list2 = setup(N)
B = orig(A, list1, list2)
C = using_advanced_indexing(A, list1, list2)
D = using_listener(A, list1, list2)
assert np.allclose(B.toarray(), C.toarray())
assert np.allclose(B.toarray(), D.toarray())
A: slicing happens with this syntax :
a[1:4]
for a = array([1,2,3,4,5,6,7,8,9]), the result is
array([2, 3, 4])
The first parameter of the tuple indicates the first value to be retained, and the second parameter indicates the first value not to be retained.
If you use lists on both sides, it means that your array has as many dimensions as the lists length.
So, with your syntax, you will probably need something like this :
x = A[list1,:,list2]
depending on the shape of A.
Hope it did help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: authorization failed when i installed my app with installer.app on mac os lion I have a problem with my app to copy/delete a plist file in "/Library/LaunchAgents/" to control the auto-start function on checking/unchecking a checkbox.
I made an installer which has a "open file" action in "postinstall actions". After install, the app is started successfully, but when I check the checkbox and enter my admin password to enable "auto-start" for all the users, the auto start .plist file is not copied to /Library/LauchAgents/ . If I kill the app then re-open the app manually, and then check the auto start option, the file can be copied to the folder successfully.
Here is the AppleScript i used for coping files to "/Library/LauchAgents/". I'm sure the sourcepath and the destinpath are right.
do shell script "cp '<sourcepath>' '<destinpath>'" with administrator privilege
Here are the error messages i got in Console:
9/30/11 11:12:18.217 AM authorizationhost: SFBuiltinEntitled: Installer.app is not entitled for system.install.app-store-software
9/30/11 11:12:18.219 AM com.apple.SecurityServer: Failed to authorize right 'system.install.app-store-software' by client '/System/Library/PrivateFrameworks/PackageKit.framework/Versions/A/Resources/installd' [2042] for authorization created by '/System/Library/CoreServices/Installer.app' [2033]
9/30/11 11:12:18.277 AM installd: PackageKit:
----- Begin install -----
9/30/11 11:12:19.977 AM MyAppDemo: awakeFromNib()
9/30/11 11:12:20.007 AM installd: Installed "My Application Package" ()
9/30/11 11:12:20.035 AM installd: PackageKit:
----- End install -----
A: The correct code is:
do shell script "cp '<sourcepath>' '<destinpath>'" with administrator privileges
Notice how privileges has an 's' on the end. Your script must be having errors when it's run because of the misspelling.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iOS download data from the web issues, NSURL Need your quick advise. I am create a "Currency Converter" iPhone app to retrieve the data from google currency websites. It is work perfectly to download the string of USD -> AUD, USD->CAD, USD->HKD, USD->HUF, USD->JPY. However, I don't why is NOT working and return NULL when try to retrieve USD->KRW and USD->ZMK. Please refer the code as below.
-(void)loadData:(NSString*)countryName{
self.responseData = [NSMutableData data];
NSString *responseURL = [NSString stringWithFormat: @"http://www.google.com/ig/calculator?q=1USD=?%@", countryName];
NSLog(@"URL:%@", responseURL);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:responseURL]];
theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString* responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"This is the responseString %@", responseString);
[responseString release];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self loadData:@"AUD"];
[self loadData:@"CAD"];
[self loadData:@"HKD"];
[self loadData:@"HUF"];
[self loadData:@"JPY"];
[self loadData:@"KRW"];
[self loadData:@"ZMK"];
}
Result from Console:
2011-09-30 18:03:50.877 Converter[1691:f503] URL:http://www.google.com/ig/calculator?q=1USD=?AUD
2011-09-30 18:03:50.879 Converter[1691:f503] URL:http://www.google.com/ig/calculator?q=1USD=?CAD
2011-09-30 18:03:50.879 Converter[1691:f503] URL:http://www.google.com/ig/calculator?q=1USD=?HKD
2011-09-30 18:03:50.879 Converter[1691:f503] URL:http://www.google.com/ig/calculator?q=1USD=?HUF
2011-09-30 18:03:50.879 Converter[1691:f503] URL:http://www.google.com/ig/calculator?q=1USD=?JPY
2011-09-30 18:03:50.879 Converter[1691:f503] URL:http://www.google.com/ig/calculator?q=1USD=?KRW
2011-09-30 18:03:50.879 Converter[1691:f503] URL:http://www.google.com/ig/calculator?q=1USD=?ZMK
2011-09-30 18:03:50.952 Converter[1691:f503] This is the responseString {lhs: "1 U.S. dollar",rhs: "1.02228583 Australian dollars",error: "",icc: true}
2011-09-30 18:03:50.962 Converter[1691:f503] This is the responseString {lhs: "1 U.S. dollar",rhs: "7.79149947 Hong Kong dollars",error: "",icc: true}
2011-09-30 18:03:50.966 Converter[1691:f503] This is the responseString {lhs: "1 U.S. dollar",rhs: "215.889465 Hungarian forints",error: "",icc: true}
2011-09-30 18:03:50.982 Converter[1691:f503] This is the responseString {lhs: "1 U.S. dollar",rhs: "1.03910031 Canadian dollars",error: "",icc: true}
2011-09-30 18:03:50.993 Converter[1691:f503] This is the responseString {lhs: "1 U.S. dollar",rhs: "76.5579544 Japanese yen",error: "",icc: true}
2011-09-30 18:03:51.010 Converter[1691:f503] This is the responseString (null)
2011-09-30 18:03:51.047 Converter[1691:f503] This is the responseString (null)
Please help and much appreciated.
A: You shouldn't share responseData with all the requests, since they're sent asynchronously they will all finish at a random time, and you're probably writing all received data (from all requests) in responseData. Each request should have its own resources (resourceData, theConnection).
Have a look at ASIHTTPRequest for a simple solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Symfony: uploading a file without sfWidgetFormInputFile() i'm trying to develope a file uploading system for my symfony app. I tryed to use the sfWidgetFormInputFile object, but did'nt know how to use it >_<. Now i'm trying to do it traditionally, with a code like this in the view:
<form action="<?php echo url_for('home/saveFile')?>" method="post">
<input type="file" id="file" name="file">
<input type="submit" value="Upload">
</form>
How can i access the submitted file information in the action class?
PS: I think i did something wrong in the form because in the symfony dev bar, in config section, in global subsection, there is a parameter called 'files' and is empty. The sent files should be there, right?
Thank you very much for your time! :D
A: The sfWidgetFileInputFile is a much better way of doing what you want to do ... but if you really want to do it manually - this is what you need in your action.class.php function ->
(where $request is an sfWebRequest object)
foreach ($request->getFiles() as $fileName) {
$fileSize = $fileName['size'];
$fileType = $fileName['type'];
$theFileName = $fileName['name'];
move_uploaded_file($fileName['tmp_name'], "$newdirectory/$theFileName");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Custom RouteMap Hi I have to route an old path, that was containing the old webform, to my new controller.
I tried this:
routes.MapRoute(
"DownloadLink",
"products/pippo/download/{*catchall}",
new { controller = "Downloads", action = "Index"}
);
To have my controller called with http://mysite.com/products/pippo/download/ but what I receive it's a 404 Status Code, what am I doing wrong?
Thanks in advance
A: Put the DownloadLink route registration before all the other routes registrations in your Global.asax RegisterRoutes method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Set the value of an input field How would you set the default value of a form <input> text field in JavaScript?
A: I use setAttribute():
<input type="text" id="example"> // Setup text field
<script type="text/javascript">
document.getElementById("example").setAttribute('value','My default value');
</script>
A: The simple answer is not in Javascript the simplest way to get the placeholder is through the place holder attribute
<input type="text" name="text_box_1" placeholder="My Default Value" />
A: document.getElementById("fieldId").value = "Value";
or
document.forms['formId']['fieldId'].value = "Value";
or
document.getElementById("fieldId").setAttribute('value','Value');
A: It's simple; An example is:
<input type="text" id="example"> // Setup text field
<script type="text/javascript">
var elem = document.getElementById("example"); // Get text field
elem.value = "My default value"; // Change field
</script>
A: if your form contains an input field like
<input type='text' id='id1' />
then you can write the code in javascript as given below to set its value as
document.getElementById('id1').value='text to be displayed' ;
A: 2023 Answer
Instead of using document.getElementById() you can now use document.querySelector() for different cases
more info from another Stack Overflow answer:
querySelector lets you find elements with rules that can't be
expressed with getElementById and getElementsByClassName
EXAMPLE:
document.querySelector('input[name="myInput"]').value = 'Whatever you want!';
or
let myInput = document.querySelector('input[name="myInput"]');
myInput.value = 'Whatever you want!';
Test:
document.querySelector('input[name="myInput"]').value = 'Whatever you want!';
<input type="text" name="myInput" id="myInput" placeholder="Your text">
A: If you are using multiple forms, you can use:
<form name='myForm'>
<input type='text' name='name' value=''>
</form>
<script type="text/javascript">
document.forms['myForm']['name'].value = "New value";
</script>
A: Try out these.
document.getElementById("current").value = 12
// or
var current = document.getElementById("current");
current.value = 12
A: If the field for whatever reason only has a name attribute and nothing else, you can try this:
document.getElementsByName("INPUTNAME")[0].value = "TEXT HERE";
A: The answer is really simple
// Your HTML text field
<input type="text" name="name" id="txt">
//Your javascript
<script type="text/javascript">
document.getElementById("txt").value = "My default value";
</script>
Or if you want to avoid JavaScript entirely: You can define it just using HTML
<input type="text" name="name" id="txt" value="My default value">
A: This is one way of doing it:
document.getElementById("nameofid").value = "My value";
A: <input id="a_name" type="text" />
Here is the solution using jQuery:
$(document).ready(function(){
$('#a_name').val('something');
});
Or, using JavaScript:
document.getElementById("a_name").value = "Something";
Happy coding :)
A: <form>
<input type="number" id="inputid" value="2000" />
</form>
<script>
var form_value = document.getElementById("inputid").value;
</script>
You can also change the default value to a new value
<script>
document.getElementById("inputid").value = 4000;
</script>
A: This part you use in html
<input id="latitude" type="text" name="latitude"></p>
This is javaScript:
<script>
document.getElementById("latitude").value=25;
</script>
A: You can also try:
document.getElementById('theID').value = 'new value';
A: Direct access
If you use ID then you have direct access to input in JS global scope
myInput.value = 'default_value'
<input id="myInput">
A: The following code work perfectly well:
var $div = ('#js-div-hour input');
$div.attr('value','2022/01/10');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "623"
}
|
Q: how to search between comma separated field in linq How to search for a value which is comma separated in database through linq. My scenario is user can select Multiple value from listbox and then search those item in comma separated field in database.
I select two items so the value will be 2,3 and database field have values
1,2,4,5
1,4,3,6
2,3,4,5
1,4
The selected records must be record no 1 because it has 2, record no 2 because it has 3 and record no 3 because it has both and reject record no 4.
What i try is
string Commodites = "2,3";
obj.Where(e => Commodites.Contains(e.Id)).Distinct()
but it select only those record which have value 2,3 only
A: For CSV splitting I advise you to use any CSV parser, not simply use string.Split method.
string[] input = { "1,2,4,5", "1,4,3,6", "2,3,4,5", "1,4" };
var result = input.Where(l => l.Split(',').Any(s => new[] { "2", "3" }.Contains(s)));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Mongoid + devise error Mongoid::Errors::InvalidCollection I have download the template Rails 3 + Mongoid + Devise and installed.
I have create a scaffold Car for relation with User model of Devise. I have in my User model this code:
class User
include Mongoid::Document
# Include default devise modules. Others available are:
# :token_authenticatable, :encryptable, :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
field :name
validates_presence_of :name
validates_uniqueness_of :name, :email, :case_sensitive => false
attr_accessible :name, :email, :password, :password_confirmation, :remember_me
embeds_many :cars
end
and My Cars Model I have the next code:
class Car
include Mongoid::Document
field :title
field :description
field :image_url
field :price
field :published_on, :type => Date
validates_presence_of :title, :description, :image_url, :price
validates :title, :length => { :maximum => 70 }
validates :description, :length => { :maximum => 2000 }
validates :price, numericality: {greater_than_or_equal_to: 0.01}
validates :image_url, allow_blank: true, format: {
with:
%r{\.(gif|jpg|png)$}i,
message: 'must be a URL for GIF, JPG or PNG image.'
}
embedded_in :user, inverse_of: :cars
end
When I refresh the page I get the next error:
Mongoid::Errors::InvalidCollection in Cars#index
Access to the collection for Car is not allowed since it is an embedded document, please access a collection from the root document.
What its the problem in this code? Thankyou
A: There is nothing wrong with your model but the routes and controller actions that the scaffold generated are attempting to run a query on the Cars collection directly and because Cars are embedded in User you cannot do that with Mongoid as the error message indicates. As it stands Cars are only accessible through a User object.
There are a couple of possible ways around this. First, without changing the model, you would need to alter the routes and actions. With this model (Cars embedded in Users) it probably makes sense to use a nested route:
resources :users do
resources :cars
end
This will mean lead to the URL users/:user_id/cars mapping to the index action in the CarsController which might look something like this:
def index
user = User.find(params[:user_id])
@cars = user.cars
# code to render view...
end
The important point here is that you are accessing the cars for a given user. The same principle applies to the other actions.
The second option would be to change your model to use a referenced relation rather than an embedded one but if the model is right the way it is then its better to change the controller and routes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Base64 encoded data maximum size I have a security mechanism that implements symmetric algorithm RijndaelManaged. I managed to find information what is the maximum size of encrypted data using RijndaelManaged for particular IV. According to my calculations it will be 128 bytes. However I need to convert these 128 bytes to string using Base64. Is there a way to calculate maximum number of chars that Base64 encoding will use to encode input byte array of size 128?
Thanks,Pawel
A: A base 64 encoded string will use 4 characters for every 3 bytes (or part thereof). So 128 bytes would be 172 base 64 characters.
A: Absolutely - Base64 takes 4 characters to represent every 3 bytes. (Padding is applied for binary data which isn't an exact multiple of 3 bytes.) So 128 bytes will always be 172 characters. (The way to work this out is that base64 represents 6 bits in each character (26 = 64); therefore 3 bytes = 24 bits = 4 base-64 characters.)
A: If you need to check this programatically, you can do so by checking the modulus. Here's some psudocode (no particular language) :
function base64Inflation (numBytes)
minimumBase64Bytes = roundDown(numBytes / 3 * 4)
modulus = numberOfBytes % 3 // Assuming % is the modulo operator
if modulus == 0
return minimumBase64Bytes // Exact fit! No padding required.
else
return minimumBase64Bytes + 4 // Doesn't quite fit. We need to pad.
I've also implemented the same logic in golang:
http://play.golang.org/p/JK9XPAle5_
A: In Java:
byte[] bytes = new byte[128];
int base64Length = bytes.length / 3 * 4; // Strictly integer division
if (bytes.length % 3 != 0)
{
base64Length += 4; // Extra padding characters will be added
}
System.out.println(bytes.length + " bytes will be encoded in " + base64Length + " characters.");
So, where the input bytes.length == 128, the output will be base64Length == 172 characters.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: ViewFlipper With One Child (LinearLayout) I' have a ViewFlipper, which contains one child only (a linearlayout), the problem I have is when I switch view's, it goes well and displays the next view and so on. But the animation doesn't goes smoothly, by that I mean that the current screen moves while next one shows up!
In this case, the current screen gets removed and the next one slides in.
How can I make the current screen to slide away, and let the next one slide in while have one child in the ViewFlipper? I've been looking all over, can't find anything!
xml code:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/layout">
<ViewFlipper
android:id="@+id/flipper"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:id="@+id/dateView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="2"
/>
<ListView
android:id="@+id/myListView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
/>
</LinearLayout>
</ViewFlipper>
android code:
case MotionEvent.ACTION_UP:{
currentX = event.getX();
if (Math.abs(currentX - downXValue) >= v.getWidth()/5){
if(currentX < downXValue){
calendar.add(Calendar.DAY_OF_MONTH, 1);
dateAdapter.notifyDataSetChanged();
todoAdapter.clear();
todoAdapter.notifyDataSetChanged();
vf.setInAnimation(v.getContext(), R.anim.push_left_in);
vf.setOutAnimation(v.getContext(), R.anim.push_left_out);
vf.showPrevious();
}
else{
calendar.add(Calendar.DAY_OF_MONTH, -1);
dateAdapter.notifyDataSetChanged();
todoAdapter.clear();
todoAdapter.notifyDataSetChanged();
vf.setInAnimation(v.getContext(), R.anim.push_right_in);
vf.setOutAnimation(v.getContext(), R.anim.push_right_out);
vf.showNext();
}
}
break;
}
Best regards!
A: Use a ViewSwitcher instead. Implement a ViewSwitcher.ViewFactory to provide the inside view (you can use a LayoutInflater with a layout xml), set it using ViewSwitcher.setFactory and use ViewSwitcher.getNextView and View.findViewById to find and set your components accordingly.
A ViewSwitcher is also a subclass of ViewAnimator so you can set the in/out animations and use showNext and showPrevious as you are already familiar with.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Detect a mail link and when pressed, mail the address in app How can I detect when a mailto link is pressed in a UIWebView, and when it is pressed, open a window in the app to send the mail.
A: implement below method
- (BOOL)webView:(UIWebView *)webView1 shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSURL *requestURL = [request URL];
NSString *str_url = [requestURL absoluteString];
if([str_url isEqualToString:@"about:blank"]){
return YES;
} else {
//you can write mailComposeController methods over here
}
}
A: you can set the webview to recognize the links as
webView.dataDetectorTypes=UIDataDetectorTypeLink;
here is a link which will be of help I guess...
http://www.iphonedevsdk.com/forum/iphone-sdk-development/21630-open-email-editor-href-link-uiwebview.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: TreeVIew icons not displaying in MMC Snap-in on Windows XP We have developed a User Interface as an MMC snap-in but we’re having issues displaying icons inside a Treeview on Windows XP.
Basically, icons (.ico) added to ImageLists of a TreeView are simply not visible on Windows XP. We researched on the internet and received some pointers. , like these –
*
*http://www.pcreview.co.uk/forums/re-mmc-3-0-and-xp-icons-t2611897.html
This suggest drawing a Bitmap using the ico file.
*http://msdn.microsoft.com/en-us/library/aa965205(VS.85).aspx
This is an MSDN resource that suggests a few points to note in this regard.
*http://msdn.microsoft.com/en-us/library/system.windows.forms.treeview.imagelist.aspx
This MSDN resource has a note that requires us to add Application.EnableVisualStyles() and Application.DoEvents() just before InitializeComponents() - but since we are building an MMC snap-in, I cannot understand where to use these.
This link - http://msdn.microsoft.com/en-us/library/windows/desktop/bb773175(v=vs.85).aspx#mmc
has some information about this but it is for VC++ whereas our entire code is in C#
Any clue?
A: This is a workaround - Populate the SmallImageList in the constructor and you should get this working.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Secure Browsing don't show different content for Fans/Non-Fans on a Facebook Page I use the following Code on my Facebook page to check if user is FAN or NOT FAN. After this the users get different contents. It works fine but if I use Secure Browsing in Facebook I always see just: "You don't like this page yet."
I'm using the SSL-Proxy from my webhoster. Do you've any idea why it doesn't works while secure browsing?
<?php
require_once 'facebook-php-sdk/src/facebook.php';
// Create our Application instance.
$facebook = new Facebook(array(
'appId' => 'X',
'secret' => 'X',
'cookie' => true,
));
$signed_request = $facebook->getSignedRequest();
$like_status = $signed_request["page"]["liked"];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>zukundo</title>
<link rel="stylesheet" href="css/blueprint/screen.css" type="text/css" media="screen, projection">
</head>
<body>
<?php
if ($like_status) {
echo "You like this page.";
} else {
echo "You like this page not yet.";
}
?>
</body>
</html>
A: I assume your application is a tab application, not a canvas one.
Here is how it works:
*
*The facebook page will load your application in a iframe, with a POST parameter "signed_request" that contains an encrypted JSON Object, which is decrypted using your app secret.
*This JSON object contains the info if the current user is fan or not of this page.
If you're using an SSL proxy, it's possible that this proxy is receiving the POST parameter, but not propagating it to your application afterward.
In this case, your app wouldn't be able to receive any info from facebook, so you wouldn't be able to know if the user is fan or not (at least, not until he has granted you the permission to access his data, so you could check using the API)
To fix that, you'll need to buy and install an SSL certificate for your domain. Godaddy.com seems to be the cheapest offer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OpenCV - Random Forest Example Does anyone have some example using Random Forests with the 2.3.1 API Mat and not the cvMat?
Basically I have a Matrix Mat data that consists of 1000 rows with 16x16x3 elements and a Matrix Mat responses a 1000x1 matrix that holds which class each row belongs to. I would like to run the random forest algorithm on this.
A: You've already got the data in the right format; all that's left is to instantiate a CvRTrees object and perform your prediction.
The documentation for Random Trees v2.3 can be found here. You'll also want to look at the CvStatModel::train() documentation, which actually has the description of most of the parameters for CvRTree::train. Tom referenced a good complete example in comments that you should use.
Along with your data, you'll need a Mat to specify the type of each of your attributes. This Mat has one row for each input attribute, and one additional row for the output type (so 16x16x3 + 1 rows, in your case).
Optionally, you can use a CvRTParams object to specify parameters like number of trees, max depth, etc. I use the defaults in the example below.
If you like, you can pass in valIdx and sampleIdx Mats that specify which attributes and which data rows, respectively, to use for training. This could be useful for selection training/validation data without doing a bunch of gymnastics to get them in separate Mats.
Here's a quick example:
#define ATTRIBUTES_PER_SAMPLE (16*16*3)
// Assumes training data (1000, 16x16x3) are in training_data
// Assumes training classifications (1000, 1) are in training_classifications
// All inputs are numerical. You can change this to reflect your data
Mat var_type = Mat(ATTRIBUTES_PER_SAMPLE + 1, 1, CV_8U );
var_type.setTo(Scalar(CV_VAR_NUMERICAL) ); // all inputs are numerical
// Output is a category; this is classification, not regression
var_type.at<uchar>(ATTRIBUTES_PER_SAMPLE, 0) = CV_VAR_CATEGORICAL;
// Train the classifier
CvRTrees* rtree = new CvRTrees;
rtree->train(training_data, CV_ROW_SAMPLE, training_classifications,
Mat(), Mat(), var_type);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7609150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.