text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Perl multi-dimensional table with headers I'm trying to implement a multi-dimensional table with headers.
Here's an example for 2D:
< dimension1 >
/\ 'column0' 'column1'
dimension0 'row0' data00 data10
\/ 'row1' data01 data11
The headers for rows and columns are text, and the data is anything. I want to be able to do something like this (syntax can be different, I'm beginner in Perl):
my $table = new table(2); # 2 is the number of dimensions
# the following line creates a new row/column if it didn't exist previously
$table['row0']['column0'] = data00;
$table['row0']['column1'] = data01;
$table['row1']['column0'] = data10;
$table['row1']['column1'] = data11;
# the following line returns the headers of the specified dimension
$table->headers(0);
=> ('row0', 'row1')
First question: Is there something like this already done in CPAN? (before you ask I did search for a significant amount of time and I didn't find anything like it)
Second question: Here's my try, I know it's ugly and probably wrong. Any Perl expert out there care to review my code?
package table;
sub new {
my $class = shift;
my $dimensions = shift;
my $self = bless({}, $class);
$self->{dimensions} = $dimensions;
$self->{data} = [];
$self->{headers} = [];
return $self;
}
sub get_dimensions {
my $self = shift;
return $self->{dimensions};
}
# This function creates a header or return its index if it already existed.
# Headers are encoded as an array of hashes so that this is O(1) amortized.
sub header {
my $self = shift;
my $dimension = shift;
my $header = shift;
my $headers = $self->{headers}[$dimension];
if(!defined($headers)) {
$headers = $self->{headers}[$dimension] = {};
}
if(!defined($headers->{$header})) {
$headers->{$header} = scalar keys %$headers;
}
return $headers->{$header};
}
# This function returns the list of headers. Because the headers are
# stored as a hash (`header=>index`), I need to retrieve the keys
# and sort them by value.
sub get_headers {
my $self = shift;
my $dimension = shift;
my $headers = $self->{headers}[$dimension];
return [sort { $headers->{$a} cmp $headers->{$b} } keys %$headers];
}
# This last function stores/retrieves data from the table.
sub data {
my $self = shift;
my $data = $self->{data};
my $dimensions = $self->{dimensions};
for(my $i = 0; $i < $dimensions-1; ++$i) {
my $index = $self->header($i, shift);
if(!defined($data->[$index])) {
$data->[$index] = [];
}
$data = $data->[$index];
}
my $index = $self->header($dimensions-1, shift);
my $value = shift;
if(defined($value)) {
$data->[$index] = $value;
}
return $data->[$index];
}
A: You want a structure for an "N" dimensional table. I doubt there's a CPAN module that can do this because it's just not that common a situation.
The problem is that the data structure grows quite rapidly and so does the complexity.
You can store an N dimensional table in a single list by using a bit of mathematics to transform the N dimensional array into a single dimension. Let's say that X represents the X dimension and X' represents the length of that dimension. For a two dimensional table, you could get the value by doing:
X * Y` + Y.
For a 3 dimensional table X, Y, Z, the answer would be:
X * (Y' * Z') + Y * Z' + Z
For a 4 dimensional table W, X, Y, Z, the answer would be:
W * (X' * Y' * Z') + X * (Y' + Z') + Y * Z' + Z'
(I hope the math is right).
Therefore, I can imagine a structure like this for an N dimensional table. It would involve two different classes: One represents the dimensional information and the other represents the actual data (including all of the dimensions).
*
*Dimension (Class)
*
*Heading (alphanumeric string)
*Size of Dimension (integer)
*N-Table (Class)
*
*Array of Dimension (Dimension Class Objects)
*Array of Data (Alphanumeric strings)
You can get the number of dimensions by looking at:
my $numOfDimensions = scalar @{$ntable->{DIMENSIONS}};
And, you can get the heading of dimension $x by looking at:
my xDimensionHeading = $ntable->{DIMENSION}->[$x]->{HEADING};
And, the size of that dimension by looking at:
my xDimensionSize = $ntable->{DIMENSION}->[$x]->{SIZE};
Of course, you'd do this with true object oriented calls, and not bare references, but this gives you an idea how the structure would work.
Now, you need a way of transforming a list of integers that would represent a cell's location into a cell's location along a single dimensional array, and you'll have a way of getting and retrieving your data.
Would this be what you're looking for?
EDIT
Close to it, but I actually resize the table dimensions a lot (I can't determine their size in advance) and if I understood your solution doesn't accomodate for this.
This adds a lot of complication...
We need to throw out the Size in the Dimension class. And, we can't use a single dimensional array to store our data.
I hope you don't change the table dimensionality.
We could do something like this:
*
*N-Table (Class)
*
*List of Dimension Headings {DIMENSION}->[]
*List to Data {DATA}->[] (This could be a link to other lists)
The {DATA} list is a link of lists depending on the depth of the table. For example:
my data_3D = $table_3D->{DATA}->[$x]->[$y]->[$z];
my data_2D = $table_2D->{DATA}->[$x]->[$y];
The number of dimensions is scalar @{$table->{DIMENSION}}.
The question is how do I access the data in a way that's dimensional neutral. I could require 2, 3, 4, or more dimensions, and I have to have someway of structuring my address to pull it out.
We could have some sort of looping mechanism. We get a list of coordinates in @coordinates, and then look at each coordinate. The last will point to data. The rest will simply be another reference to another array.
my $data = pop @coordinates; #First Coordinate
$data = $table->[$data]; #Could be data if 1D table, could be a reference
foreach my $coordinate (@coordinates) {
die qq(Not enough coordinates) if ref $data ne 'ARRAY';
$data = $data->[$coordinate]; #Could be data, could be a reference
}
# Cell value is in $data
It also may be possible to build a list of coordinates, and then evaluating it. Again completely untested:
$coordinates = "[" . join ("]->[" => @coordinates . "]";
If there were three coordinates, this would be
$coordinates = "[$x]->[$y]->[$z]";
I'm not sure how a 1 dimensional array would work...
From there, you could build a statement and use eval on it and get the data.
You'll have to have several methods.
*
*Set the dimensions
*Set a cell
*Retrieve a cell
*Verify table is completeness (I have no idea how this would work.
This is more a brain dump, but it I think this might work. You don't have any set table dimensions and it might work for any N-dimensional table.
A: You may be able to use Text::TabularDisplay to do this. Here's a quick trial I did with your example.
use strict;
use warnings;
use Text::TabularDisplay;
my $t = Text::TabularDisplay->new(('', 'column0', 'column1'));
$t->add('row0', 'data00', 'data10');
$t->add('row1', 'data01', 'data11');
print $t->render;
shows:
+------+---------+---------+
| | column0 | column1 |
+------+---------+---------+
| row0 | data00 | data10 |
| row1 | data01 | data11 |
+------+---------+---------+
I'm not sure if this is exactly what you were looking for. You do have to fudge with the header by leaving the first column blank.
A: Text::Table might be useful here. I am showing a simple example below: You can play with the various options the module provides to create something close what you describe.
#!/usr/bin/perl
use warnings;
use strict;
use Text::Table;
my $inner_table = Text::Table->new(qw(column0 column1));
$inner_table->load(
[ qw(row0 data00 data01) ],
[ qw(row1 data10 data11) ],
);
my $outer_table = Text::Table->new(' ', 'dimension1');
$outer_table->load(
['dimension0', $inner_table->stringify ],
);
print $outer_table;
Output
C:\Temp> t
dimension1
dimension0 column0 column1
row0 data00
row1 data10
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: About messages from UITapGestureRecognizer The following is from documentation :
Although taps are discrete gestures, they are discrete for each state of the gesture recognizer; thus the associated action message is sent when the gesture begins and is sent for each intermediate state until (and including) the ending state of the gesture.
The above passage seems to indicate that more than one message is sent. The messages would include a "begin" message and an "end" message. But somehow I just get the "gesture end" message. Is there any way I can get both the tap begin and end message ? (What I wish to track is - "begin" : the moment the user touches the screen and "end" : the moment the user lifts his finger away from the screen.)
Hope that somebody who is knowledgable on this could help ...
http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UITapGestureRecognizer_Class/Reference/Reference.html#//apple_ref/occ/cl/UITapGestureRecognizer
A: - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
NSDate *date1 = [NSDate date]; //user touches the screen
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
NSDate *date2 = [NSDate date]; //user lifts his finger away from the screen
}
A: The UITapGestureRecognizer only fires when the gesture state is UIGestureRecognizerStateEnded
If you want to use a gesture recogniser to detect the start and end of a press, use the UILongPressGestureRecognizer, with the minumumPressDuration set to 0
A: Why don't you use - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event method ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: .load() does not work on IE I am trying to have a little dynamics work in this website http://peps.sqps.nl
Everything seems to work well untill I test the website in IE, it just doesnt give any content back.
The js I use is as following:
$(document).ready(function(){
$('li.navItem a').click(function(){
var url = $(this).attr('href');
$('article').load(url + ' article', function(){
$('article').fadeTo(1200, 1);
});
return false;
});
});
the html of the dynamic part is as following, where the <article></article> part is supposed to act dynamicly.
<section id="content">
<div id="article">
<article>
content is in here
</article>
</div>
</section>
The solution given here on similar problems didnt fix the bug
Anyone has any ideas?
Thnx!
A: Your URL looks like it would be badly formed.
url = "http://site.com/path/to/page"
load_url = url + ' article'
alert(load_url); // Displays "http://site.com/path/to/page article"
Is this what you really want?
A: Probably the IE is making cache of your code.
See this post: jQuery's .load() not working in IE - but fine in Firefox, Chrome and Safari
A: Add .each(function(){...}); after .load , it should works in IE and Chrome.
$('#<%=image1.ClientID %>').load(function () {
//things to do
}).each(function () {
if (this.complete) $(this).load();
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python: parsing binary stl file I'm having some difficulties while parsing a binary STL file with Python (2.7.1 32-bit and Windows 7 64). The file is a about 450k in size, but my parser suddenly stops working after parsing 244 triangles out of ~8600 with en exception of struct.unpack:
Exception unpack requires a string argument of length 12
The cursor position in the file is line 33, row 929. But the line contains about 3400 characters. So it doesn't seem to be newline problem.
This is the code:
import struct
normals = []
points = []
triangles = []
bytecount = []
fb = [] # debug list
def unpack (f, sig, l):
s = f.read (l)
fb.append(s)
return struct.unpack(sig, s)
def read_triangle(f):
n = unpack(f,"<3f", 12)
p1 = unpack(f,"<3f", 12)
p2 = unpack(f,"<3f", 12)
p3 = unpack(f,"<3f", 12)
b = unpack(f,"<h", 2)
normals.append(n)
l = len(points)
points.append(p1)
points.append(p2)
points.append(p3)
triangles.append((l, l+1, l+2))
bytecount.append(b[0])
def read_length(f):
length = struct.unpack("@i", f.read(4))
return length[0]
def read_header(f):
f.seek(f.tell()+80)
def write_as_ascii(outfilename):
f = open(outfilename, "w")
f.write ("solid "+outfilename+"\n")
for n in range(len(triangles)):
f.write ("facet normal {} {} {}\n".format(normals[n][0],normals[n][1],normals[n][2]))
f.write ("outer loop\n")
f.write ("vertex {} {} {}\n".format(points[triangles[n][0]][0],points[triangles[n][0]][1],points[triangles[n][0]][2]))
f.write ("vertex {} {} {}\n".format(points[triangles[n][1]][0],points[triangles[n][1]][1],points[triangles[n][1]][2]))
f.write ("vertex {} {} {}\n".format(points[triangles[n][2]][0],points[triangles[n][2]][1],points[triangles[n][2]][2]))
f.write ("endloop\n")
f.write ("endfacet\n")
f.write ("endsolid "+outfilename+"\n")
f.close()
def main():
infilename = r"cupHemis46_28.stl"
outfilename = r"cupHemis46_28_ascii_test.stl"
try:
f = open ( infilename, "r")
read_header(f)
l = read_length(f)
try:
while True:
read_triangle(f)
except Exception, e:
print "Exception",e[0]
print len(normals), len(points), len(triangles), l
write_as_ascii(outfilename)
except Exception, e:
print e
if __name__ == '__main__':
main()
The unpack function (not from struct) collects all the strings which will be written to a file. When I compare both file they seem equal, up to the file position where unpack stops working. I opened the binary file with Notepad++, the next character is a "SUB".
Are there any restrictions of unpack that I'm not aware of regarding file size or limitation in characters or something? Is there something wrong with my code? Thanks in advance.
A: Your unpack function calls f.read twice. I suspect you've walked off the end of the file.
You'll also have trouble with reading the file in text mode on Windows. Any incidental occurrences of \r\n will be read in as \n. Make the following change to avoid this problem.
f = open(infilename, "rb")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Read data from google docs spreadsheets In my app I have to show the details of a google docs spreadsheet.
In this spreadsheet I have 2 sheets. Each sheet details I have to show in 2 different activities.
Can anyone help me out to implement this functionality. What all things are required for this? I found one jar named jxl.jar. Should I use that?
A: For:
programmatically access and manipulate user data stored with Google
Documents
there is the Google Documents List API.
If you want to create/edit spreadsheets, you'll need to use the Google Spreadsheets API.
Both those APIs are part of the gData-API. The Java-client library s (.jar-files which can be used with your Android Project) can be downloaded here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Could not load file or assembly 'Ajax' or one of its dependencies. The system cannot find the file specified The additional error message with it is:
I have been facing this error where as i have also included ajax library in my website. Also web.config also has important tags regarding ajaxtoolkit.
Please keep in view that I have recently switched this website from ASP.NET 3.5 to 4.0
Please help on this....
Also here is Stack Trace:
Assembly Load Trace: The following information can be helpful to determine why the assembly 'Ajax' could not be loaded.
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
A: I just ran into this issue when trying to upgrade an old app to ASP.NET 4.0. I know - still old but this is what the client wanted. Went around and around as to why this was happening. And then I found it. The app was using the ASP.NET 4.0 Classic app pool in IIS. When I switched to ASP.NET 4.0 Integrated the error went away. Hope this helps someone else with this issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get the difference between two SELECT statements I am trying to get the difference between 2 select statements.
Here is the first select:
SELECT 1
SELECT *
FROM h_log_material
LEFT JOIN h_log_stkpnl
ON h_log_stkpnl.MODULE_UNIQUE_ID = h_log_material.MODULE_UNIQUE_ID
where
h_log_material.WO_ID='E11TMB7M05'
and h_log_material.mtrl_type='BL'
Output is 4917
SELECT 2
Here is second select:
SELECT *
FROM h_log_material
LEFT JOIN h_log_stkpnl
ON h_log_stkpnl.MODULE_UNIQUE_ID = h_log_material.MODULE_UNIQUE_ID
where
h_log_material.WO_ID='E11TMB7M05'
and h_log_material.mtrl_type='BL'
and h_log_stkpnl.op_id like '%STOCK-IN%'
Output is 4870
I would like to get the difference SELECT 1 - SELECT 2
As output I need rows which are not in select 2.
I tried this but it returns 0.
SELECT *
FROM h_log_material
LEFT JOIN h_log_stkpnl
ON h_log_stkpnl.MODULE_UNIQUE_ID = h_log_material.MODULE_UNIQUE_ID
where
h_log_material.WO_ID='E11TMB7M05'
and h_log_material.mtrl_type='BL'
and not exists
(SELECT *
FROM h_log_material
LEFT JOIN h_log_stkpnl
ON h_log_stkpnl.MODULE_UNIQUE_ID = h_log_material.MODULE_UNIQUE_ID
where
h_log_material.WO_ID='E11TMB7M05'
and h_log_material.mtrl_type='BL'
and h_log_stkpnl.op_id like '%STOCK-IN%')
A: The 2nd SELECT looks like a subset of the first so you can do
SELECT COUNT(*) - COUNT(CASE
WHEN h_log_stkpnl.op_id LIKE '%STOCK-IN%' THEN 1
END)
FROM h_log_material
LEFT JOIN h_log_stkpnl
ON h_log_stkpnl.MODULE_UNIQUE_ID = h_log_material.MODULE_UNIQUE_ID
WHERE h_log_material.WO_ID = 'E11TMB7M05'
AND h_log_material.mtrl_type = 'BL'
Edit
Following your clarification that you need columns not COUNT try this one out
SELECT *
FROM h_log_material
LEFT JOIN h_log_stkpnl
ON h_log_stkpnl.MODULE_UNIQUE_ID = h_log_material.MODULE_UNIQUE_ID
AND h_log_stkpnl.op_id LIKE '%STOCK-IN%'
WHERE h_log_material.WO_ID = 'E11TMB7M05'
AND h_log_material.mtrl_type = 'BL'
AND h_log_material.MODULE_UNIQUE_ID IS NULL
Your first query is doing a LEFT JOIN but the WHERE clause on the second one converts it into an inner join effectively. So the difference between the queries should be those rows where either there is no match in h_log_stkpnl or the match isn't LIKE '%STOCK-IN%' (I think!)
A: Have you tried
and h_log_stkpnl.op_id not like '%STOCK-IN%'
Unless there are null values (and those can be compensated for) that should be the difference.
A: You don't specify your platform but if you're running SQL 2008 you can use EXCEPT and INTERSECT to compare the results of two queries.
A: try it
SELECT h_log_material.field1,h_log_material.field2
FROM h_log_material
LEFT JOIN h_log_stkpnl
ON h_log_stkpnl.MODULE_UNIQUE_ID = h_log_material.MODULE_UNIQUE_ID
where
h_log_material.WO_ID='E11TMB7M05'
and h_log_material.mtrl_type='BL'
minus
SELECT h_log_material.field1,h_log_material.field2
FROM h_log_material
LEFT JOIN h_log_stkpnl
ON h_log_stkpnl.MODULE_UNIQUE_ID = h_log_material.MODULE_UNIQUE_ID
where
h_log_material.WO_ID='E11TMB7M05'
and h_log_material.mtrl_type='BL'
and h_log_stkpnl.op_id like '%STOCK-IN%'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to edit a hardcoded string in compiled DLL? I have a single compiled dll which i need to change a little. It was written by me half a year ago, but I've lost the source code. There's one single hardcoded string in it (it's a filename)
I need to change it from TestPage.html to TestPage1.html (it's not much longer)
How to do that? The string is anonymous, the corresponding piece of code is:
... + folder + "TestPage.html"
There's no variable it's assigned to.
Thanks in advance.
EDIT: I do not want to recompile c# code after extracting it with Reflector-like tools!
A: Use Reflector (or other similar tool) to decompile IL into C# (or another CLR language), and then - edit and compile it again.
A: You can use the free tool ILSpy to decompile the code and ressources from a .NET-dll file.
A: You could use CFF Explorer, which provides a very raw view on .NET assemblies. It also provides the possibility to view and even modify the UserString-stream (find it under .NET Directory > MetaData Streams > #US).
The UserString-stream stores string literals as the one you described. You should be able to find your particular string with the find-function and modify it. However, there is a limitation: You cannot use a string with a different length (shorter or longer). This would mess up the indices of all strings that would follow later on in the UserString-stream and all the offsets of the other sections. So, unfortunately I think changing it to TestPage1.html will not work, as it is one character longer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: wait for an link to appear which is already in the page in selenium Hi i am using selenium with testng.
I have created a code in which i will login to a website and then after that their is a operation that happens and it collects the name of all the ip addresses range given and after scanning their is a link that appears called SCAN COMPLETE. Now i have to wait for such link and after that i will logout.I use
selenium.waitforElemenPresent("link=SCAN COMPLETED");
Since on page this element is already present but hidden so it doesn't works. So i need to wait for such link to appear on the screen and after that i logout.
Any suggestions.
A: I assume you are using Selenium RC. One option is to wait for the element using XPath. This way you can also check for the display attribute.
So say the link looks something like this (notice the display attribute):
<a href="#" style="display: none">SCAN COMPLETE</a>
You can wait for it to be visible with:
selenium.waitForElementPresent("//a[text()='SCAN COMPLETE' and not(contains(@style, 'display: none'))]");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mapping same entity to itself as a collection Ok, say i have a "Person" entity which needs to have "Person"s as property (say, friends)
Since this is a many to many connection, If i'd create this schema using SQL (Which i'm not, i'm using the hbm.ddl.auto to do it for me) i'd probably make another table containing 2 columns with 2 ids (1 for each friend)
However, i'm not sure how to annotate this in hibernate, i did this:
class PersonEntity {
.
.
@ElementCollection
private List<PersonEntity> friends ;
.
.
}
Problem is, i'm not sure it's the best way.. for instance, i'm "thinking" that whenever i add a friend to the list and persist it will be inserted as the next row in the table, and since i can't seem to index this field i'm imagining the data retrieval will be inefficient.
Can you suggest better ways to solve this problem?
A: You're looking for @ManyToMany and @JoinTable.
The api doc of ElementCollection says:
Defines a collection of instances of a basic type or embeddable class
You have a collection of entity instances. See http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#eentity-mapping-association-collection-manytomany for how to use those annotations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to restrict users from creating a python object? I have a domain object User. I am looking for some way to restrict other python classes form creating any objects of `user' type.
A: You can use closures to hide the object away from the code but please accept that doing it in Python is considered very unpythonic and is pretty much against the philosophy of the language. You are supposed to document proper behavior, not guard against your users.
class KittenFactory(object):
def __create_teh_secret_objectz(self):
class Kitten(object):
i_can_haz_invisible = True
return Kitten()
Willing programmers will still be able to either copy() it or get its type() and instantiate it manually.
In other words: don't go there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How to persist sessions with Jetty 7 and jetty-maven-plugin? I'd like to configure Jetty to persist sessions on disk, so that restarting Jetty would not lose the sessions, but by reading the documentation I haven't yet got it working.
I'm running Jetty using Jetty Maven plugin (org.mortbay.jetty:jetty-maven-plugin 7.4.3.v20110701).
Enabling Persistence for the Maven Jetty Plugin tells to set up the HashSessionManager in the sessionHandler configuration section of the plugin, but the example there seems to be for the old maven-jetty-plugin, not the new jetty-maven-plugin.
I tried fixing the class names there like this (I also had to add a dependency to jetty-server jar, otherwise I got ClassNotFoundExceptions):
<webAppConfig implementation="org.mortbay.jetty.plugin.JettyWebAppContext">
<defaultsDescriptor>${project.build.outputDirectory}/META-INF/webdefault.xml</defaultsDescriptor>
<contextPath>${jetty.contextRoot}</contextPath>
<sessionHandler implementation="org.eclipse.jetty.server.session.SessionHandler">
<sessionManager implementation="org.eclipse.jetty.server.session.HashSessionManager">
<storeDirectory>${basedir}/target/jetty-sessions</storeDirectory>
</sessionManager>
</sessionHandler>
</webAppConfig>
Directory target/jetty-sessions gets created when server is run, but nothing is written there and the sessions don't persist as far as I can tell.
So, what am I missing?
A: The documentation lists the wrong class names. Use this snippet:
<sessionHandler implementation="org.eclipse.jetty.server.session.SessionHandler">
<sessionManager implementation="org.eclipse.jetty.server.session.HashSessionManager">
<storeDirectory>${basedir}/target/sessions</storeDirectory>
<idleSavePeriod>1</idleSavePeriod>
</sessionManager>
</sessionHandler>
I don't have an Eclipse login to fix it on their wiki. Maybe you can grab one and fix it there too to help others.
Update: I added idleSavePeriod to the configuration. I first thought you just copied the typo from Eclipse wiki.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ext.net script error in IE8 that doesn't occur in other browsers (including IE9) I use ext.net controls in ASP.NET WebForms application.
It works fine in Chrome 13-14, Opera 11, FF 6 but not in IE8.
It throws JavaScript errors such as:
Invalid argument
And:
BaseMainContent_MainContent_ctlContent_txtFax_txtCountryCode' is undefined
If it's enough information, how can I resolve it?
A code example
<div>
<ext:TextField runat="server" MsgTarget="Side" ID="LoginTxt" IsRemoteValidation="true">
<RemoteValidation OnValidation="ValidateLogin" ShowBusy="true" />
</ext:TextField>
</div>
<br />
<div>
<div>
<ext:TextField ID="PasswordTxt1" runat="server" InputType="Password"></ext:TextField>
<ext:TextField runat="server" ID="PasswordTxt2" Vtype="password" FieldLabel="Повторите пароль"
InputType="Password" MsgTarget="Side" IsRemoteValidation="true">
<RemoteValidation OnValidation="ValidatePasswords" ShowBusy="true" />
</ext:TextField>
</div>
</div>
<div>
<ext:ComboBox Width="200" runat="server" ID="LocaleCmb" Editable="false"
SelectedIndex="0">
<Items>
<ext:ListItem Text="Русский" Value="ru-RU" />
<ext:ListItem Text="English" Value="en-US" />
</Items>
</ext:ComboBox>
</div>
<div>
<ext:TextField runat="server" ID="LastNameTxt" />
</div>
<ext:TextField runat="server" ID="EmailTxt" MsgTarget="Side" FieldLabel="Email" Vtype="email"
IsRemoteValidation="true">
<RemoteValidation OnValidation="ValidateEmail" ShowBusy="true" />
</ext:TextField>
<div>
<uc:PhoneTextBox2 ID="PhoneUc" runat="server"/>
</div>
<div>
<uc:PhoneTextBox2 ID="FaxUc" runat="server" />
</div>
<br />
<div>
<uc:Address2 Title="Адрес" ID="AddressUc" CoordinatesVisible="false" runat="server" />
</div>
<div>
<div id="RecaptchaDiv" runat="server" class="x-form-invalid-icon" style="left: 350px; top: 0px;
position: relative; visibility: visible;">
</div>
<recaptcha:RecaptchaControl ID="Recaptcha" runat="server" />
</div>
<ext:Button runat="server" ID="SubmitTxt" Text="Register me">
<DirectEvents>
<Click OnEvent="SubmitBtnClick">
<EventMask ShowMask="true"></EventMask>
</Click>
</DirectEvents>
</ext:Button>
<uc:BackLinkButton ID="lnkPreviousPage" runat="server" />
In this case the error is
SCRIPT87: Invalid argument.
ext.axd?v=21945, line 7 character 31283
UPDATE:
a screenshot
UPDATE2:
I forgot to say I works good in IE9.
Here is the source of the uc:PhoneTextBox2
<style>
.invalidPhoneBox
{
border-color: #C30;
background: url('/extjs/resources/images/default/grid/invalid_line-gif/ext.axd') repeat-x scroll center bottom white;
}
</style>
<ext:CompositeField runat="server" ID="eCompositeField" CombineErrors="false" AutoWidth="true"
MsgTarget="Title">
<Items>
<ext:DisplayField runat="server" Text="(" />
<ext:NumberField ID="txtCountryCode" Width="29" AllowNegative="false" AllowDecimals="false"
MaxLength="3" runat="server" />
<ext:DisplayField runat="server" Text=")" />
<ext:NumberField runat="server" ID="txtCityCode" Width="58" AllowNegative="false" AllowDecimals="false"
MaxLength="7" />
<ext:TextField runat="server" ID="txtMainPhoneNumber" Width="60" MaxLength="7" AllowNegative="false"
AllowDecimals="false" />
<ext:TextField runat="server" ID="txtExtraPhoneNumber" Width="44" AllowBlank="false" MaxLength="5"
AllowNegative="false" AllowDecimals="false" MsgTarget="Side" />
</Items>
</ext:CompositeField>
code behind
public partial class PhoneTextBox2 : System.Web.UI.UserControl {
public bool EnableEmptyValues { get; set; }
public string Title { get; set; }
protected void Page_Init(object sender, EventArgs e) {
txtCountryCode.AllowBlank = EnableEmptyValues;
txtCityCode.AllowBlank = EnableEmptyValues;
txtMainPhoneNumber.AllowBlank = EnableEmptyValues;
}
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) {
eCompositeField.FieldLabel = Title;
// eCompositeField.LabelWidth = Title.Length*5;
if (!string.IsNullOrWhiteSpace(DataSource)) {
string[] phoneNumberArray = DataSource.Split('-');
if (phoneNumberArray.Length >= _standartDimension) {
txtCountryCode.Text = phoneNumberArray[0];
if (txtCountryCode.Text[0] == _plus) {
txtCountryCode.Text = txtCountryCode.Text.Remove(0, 1);
}
txtCityCode.Text = phoneNumberArray[1];
txtMainPhoneNumber.Text = phoneNumberArray[2];
if (phoneNumberArray.Length >= _extraDimension) {
txtExtraPhoneNumber.Text = phoneNumberArray[3];
}
}
}
}
}
public string DataSource { get; set; }
private const string _phoneNumberMask = "+{0}-{1}-{2}-{3}";
private const char _plus = '+';
private const int _standartDimension = 3;
private const int _extraDimension = 4;
public string Number {
get {
if (!string.IsNullOrWhiteSpace(txtCountryCode.Text) &&
!string.IsNullOrWhiteSpace(txtCityCode.Text) &&
!string.IsNullOrWhiteSpace(txtMainPhoneNumber.Text)) {
if (!string.IsNullOrWhiteSpace(txtExtraPhoneNumber.Text))
return string.Format(_phoneNumberMask, txtCountryCode.Text, txtCityCode.Text, txtMainPhoneNumber.Text, txtExtraPhoneNumber.Text);
string phoneNumber = string.Format(_phoneNumberMask, txtCountryCode.Text, txtCityCode.Text, txtMainPhoneNumber.Text, string.Empty);
return phoneNumber.Remove(phoneNumber.Length - 1);
}
return string.Empty;
}
}
public bool IsEmpty {
get {
return (string.IsNullOrWhiteSpace(txtCountryCode.Text) &&
string.IsNullOrWhiteSpace(txtCityCode.Text) &&
string.IsNullOrWhiteSpace(txtMainPhoneNumber.Text) &&
string.IsNullOrWhiteSpace(txtMainPhoneNumber.Text));
}
}
/// <summary>
/// Validate
/// </summary>
public void Validate() {
if (EnableEmptyValues) {
if (!IsEmpty && Number == string.Empty)
MarkInvalid();
else
MarkValid();
}
else {
if (IsEmpty)
MarkInvalid();
else {
if (Number == string.Empty)
MarkInvalid();
else
MarkValid();
}
}
}
private const string InvalidFormatNumberMessage = "InvalidFormatNumberMessage";
private const string EmptyNumberMessage = "EmptyNumberMessage";
private const string InvalidCls = "invalidPhoneBox";
public void MarkInvalid(string msg = null) {
// eCompositeField.AddLabelCls(InvalidCls);
txtCountryCode.MarkInvalid(msg);
txtCityCode.MarkInvalid(msg);
txtMainPhoneNumber.MarkInvalid(msg);
txtExtraPhoneNumber.MarkInvalid(msg);
}
public void MarkValid() {
//eCompositeField.RemoveLabelCls(InvalidCls);
//eCompositeField.MarkAsValid();
txtCountryCode.MarkAsValid();
txtCityCode.MarkAsValid();
txtMainPhoneNumber.MarkAsValid();
txtExtraPhoneNumber.MarkAsValid();
}
public const string InvalidCheckBoxCssStyle = "border-color:#C30; background: url('/extjs/resources/images/default/grid/invalid_line-gif/ext.axd') repeat-x scroll center bottom white; width: 40px !important;";
public const string ValidCheckBoxCssStyle = "border-color:#000; background: none repeat scroll 0 0 transparent;";
}
A: I had this exact error and while I can't reproduce your case exactly I can hopefully give you a good idea on how to fix it. The problem is that somehow an invalid width is getting assigned to one of the controls on the page. This can happen because of some incorrect configuration in the markup, or possibly a bug of some sort in Ext.NET. To determine which control is at fault:
*
*Load your page in IE8 and allow the built-in script debugger to halt execution at the point shown in your screenshot.
*In the right hand section of the developer pane click the "Watch" tab button and add a watch for H. Expand the tree until you can see the ID property. This will give you the ClientID of the control causing the problem.
*Locate the control in your .ascx markup and make sure that you've got the width configuration correct. The correct configuration may depend on the layout used for the parent container. Try diffent methods of setting the width to see if any resolve the issue.
Hopefully these steps can help you to narrow down the control causing the error and rectify it. In my case I had used AutoWidth="True". Changing to AnchorHorizontal="100%" fixed the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Setting Java Environment (Apache Tomcat) to encode UTF-8
I want to know how to set-up the Java Environment to encode in UTF-8.
Basically I have JSP pages displayed with some Arabic text but they don't seem to be encoding right.
When I run the pages in the IDE it works fine but on the server where they are host it simple displays it as question marks. I just want to know how to set the java environment or apache tomcat to encode the UTF-8.
Any help will be appreciated.
A: You must to edit the /config/web.xml
uncomment this filter: setCharacterEncodingFilter
<!-- A filter that sets character encoding that is used to decode -->
<!-- parameters in a POST request -->
<filter>
<filter-name>setCharacterEncodingFilter</filter-name>
<filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<!-- The mapping for the Set Character Encoding Filter -->
<filter-mapping>
<filter-name>setCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
A: You have a few general settings with different impact levels:
(1) Configure your JSP page to display content in utf-8 (place on top of jsp page)
<%@page pageEncoding="utf-8" %>
(2) Set default character encoding to utf-8 (java system property)
-Dfile.encoding="utf-8"
(3) Configure your application server to encode request parameters in utf-8 (in conf/server.xml)
<connector .... URIEncoding="utf-8" />
(4) Tell browser content is in utf-8 (place in html HEAD section)
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
A: In within your project directory:
You must have a folder named 'font' in this foler copy the arabic fonts , this will carry your path to characters on server too....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Why does a spring-security ACL have an identifier? I'm trying to set up our custom version of spring-security but I can't quite understand why an ACL has an identifier that is even supposed to be a primary key if, as I understand it, an ACL itself is never persisted directly in any way but is rather a view on a subset of ACL_Entrys.
As far as I understand it, an ACL is an access control list. Meaning a list of SIDs having Permissions for OIDs. Right?
The underlying datastructure used by spring-security defines an SID and an OID (in combination with a Class identifier). Those two together with a permission and the granting flag are called an access control entry or ACE and get persisted inside the acl_entry entity.
Inside the application I ask spring-security(or rather my own implementations of their interfaces) to get me all permission settings for a set of OIDs and SIDs and the result is a list contrived of SID-OID-permission-granting entries (aces) and thus called access control list. Now really I don't see how or why any kind of id comes into play here.
Am I missing something importand?! Please help me understand!
Is it maybe that one SID has a number of OID+permission+granting entries and thus is owner of its ACL? Or one OID has its SIDs and their permissions assigned to grouped into one ACL?
Also: What's all this hierarchy and parent stuff supposed to do? I guess it has to do with my identifier question, but I don't really see how acls can ber hierarchycal, if an acl is just a temporary subset. And why would I want to have a hierarchy betweens acls anyway?
Edit:
Appearently the solution to half my question is: An ACL is identified via the OID's primary key as one ACL always shows how that Object can be accessed.
However I still wonder why I would need a hierarchy or an owner for that matter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566863",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Problem in reading XML Hello Guys can you help me solving my problem in reading xml.
I'm just new in xml. Here's the sample xml.
<Org>
<Org ID="1">
<OrgNum>1</OrgNum>
<OrgName>sample1</OrgName>
</Org>
<Org ID="2">
<OrgNum>2</OrgNum>
<OrgName>sample2</OrgName>
</Org>
</Org>
I want to get only the OrgName with an Org ID = 2.
Here's my sample code but it's read all the text.
Help me plz..Tnx
string xml = Application.StartupPath + "\\OrgName.xml";
XmlDocument xmlDoc = new XmlDocument();
if (System.IO.File.Exists(xml))
{
XmlTextReader textReader = new XmlTextReader(xml);
textReader.Read();
while (textReader.Read())
{
XmlNodeType nType = textReader.NodeType;
if (nType == XmlNodeType.Text)
{
MessageBox.Show(textReader.Value);
}
}
}
A: Maybe your life gets a lot easier if you start using tools like xdocument, xmldocument and xpath
A: If you want to use the classic .net Xml object model, you could try this:
string xml = Application.StartupPath + "\\OrgName.xml";
XmlDocument xmlDoc = new XmlDocument();
if (System.IO.File.Exists(xml))
{
xmlDoc.Load(xml);
XmlElement root = xmlDoc.DocumentElement;
string orgName = root.SelectSingleNode(@"descendant::Org[@ID='1']/OrgName").InnerText;
MessageBox.Show(orgName);
}
A: A simple way to do it with linq:
var doc = XDocument.Load(Application.StartupPath + "\\OrgName.xml");
var result = doc.Root.Elements("Org").Where(x=>x.Attribute("id").ToString()=="2");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ajax URL property with API variable All I want to do is to be able to specify a User ID and API Key in the URL of an Ajax call:
Currently doing:
$.ajax({
url: "https://www.googleapis.com/plus/v1/people/115332174513505898112?key=AIzaFrCzbKLawSPG8C0tjZDozO1bSWx49mJm13s",
context: document.body,
dataType: 'jsonp',
success: function(data){
//blah...
}
});
However I want to be able to set the UserID and API Key dynamically so want there values in the URL: to be dynamic:
E.g.
var userId = 115332174513505898112;
var apiKey = AIzaSyCzbKLawSPG8C0tjZDozO1bSWx49mJm13s;
url: "https://www.googleapis.com/plus/v1/people/" + userId + "?key=" + apiKey,
However, as soon as a define the variables inside the $.ajax({ function the JavaScript stops working and I get an error of:
missing : after property id
[Break On This Error] var userId = 115332174513505898112;
What am I doing wrong, I'm sure I've done this before?
A: This should do it:
var userId = "115332174513505898112";
var apiKey = "AIzaSyCzbKLawSPG8C0tjZDozO1bSWx49mJm13s";
$.ajax({
url: "https://www.googleapis.com/plus/v1/people/" + userId + "?key=" + apiKey,
context: document.body,
dataType: 'jsonp',
success: function(data){
//blah...
}
});
Items to note:
*
*Quotes around the values of the userId and apiKey. (You may not need them around the userId value; you absolutely do around the apiKey.)
*You define those outside of the actual ajax function call.
I'm assuming the code is already inside a function, e.g:
function foo() {
var userId = "115332174513505898112";
var apiKey = "AIzaSyCzbKLawSPG8C0tjZDozO1bSWx49mJm13s";
$.ajax({
url: "https://www.googleapis.com/plus/v1/people/" + userId + "?key=" + apiKey,
context: document.body,
dataType: 'jsonp',
success: function(data){
//blah...
}
});
}
If not, put it in one to avoid creating global variables with those var statements.
A: You should put that values of your variables in quotes...
Additionally, you can not write any javascript code within objects - you need to declare your variables outside the object, and refer to them inside - like this:
var userId = "115332174513505898112";
var apiKey = "AIzaSyCzbKLawSPG8C0tjZDozO1bSWx49mJm13s";
$.ajax({
url: "https://www.googleapis.com/plus/v1/people/" + userId + "?key=" + apiKey,
context: document.body,
dataType: 'jsonp',
success: function(data){
//blah...
}
});
A: Use this code. Strings have to be contained within " (quotation marks). Also, you cannot define variables using var within { ... } (object, not to be confused with markers of a function/loop/condition body).
var userId = "115332174513505898112";
var apiKey = "AIzaSyCzbKLawSPG8C0tjZDozO1bSWx49mJm13s";
$.ajax({
url: "https://www.googleapis.com/plus/v1/people/"+userId+"?key="+api,
context: document.body,
dataType: 'jsonp',
success: function(data){
//blah...
}
});
A: You have to define the variables (the var statements) outside the object {} and the function call $.ajax().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Any way of parametrizing whether or not to append inner elements in ant? I am writing an ant file for compiling a flex project (but this question may apply to non-flex ant scripts as well).
I had several targets there that look like this:
<target name="first">
<mxmlc file="${src.dir}/FirstClass.as" output="${output.dir}/First.swf" ...identical_compiler_attributes...>
...identical_compiler_inner_elements...
<compiler.define name="AN_ATTRIBUTE" value="A_VALUE" />
</mxmlc>
</target>
<target name="second">
<mxmlc file="${src.dir}/SecondClass.as" output="${output.dir}/Second.swf" ...identical_compiler_attributes...>
...identical_compiler_inner_elements...
<!-- no additional compiler.define calls needed -->
</mxmlc>
</target>
I wanted to avoid duplication of common mxmlc attributes and inner element by using the <antcall> ant task, so I came up with something like this:
<target name="first">
<antcall target="helper_target">
<param name="src.file" value="FirstClass.as"/>
<param name="output.file" value="First.swf"/>
</antcall>
</target>
<target name="second">
<antcall target="helper_target">
<param name="src.file" value="SecondClass.as"/>
<param name="output.file" value="Second.swf"/>
</antcall>
</target>
<target name="helper_target">
<mxmlc file="${src.dir}/${src.file}" output="${output.dir}/${output.file}" ...identical_compiler_attributes...>
...identical_compiler_inner_elements...
<!-- WHAT DO I DO ABOUT THE compiler.define?? -->
</mxmlc>
</target>
This solves most duplication nicely. But what do I do about the <compiler.define> and other inner elements that differ between the mxmlc calls? The builtin if mechanism of ant doesn't help me here - i can't invoke a target in the middle of an mxmlc element....
Any ideas? (I know ant-contrib has some kind of if mechanism. Would rather have a pure-ant solution, and not even sure if ant-contrib's if will help here).
A: This sounds like a candidate for an Ant presetdef task. The manual describes the task thus:
The preset definition generates a new definition based on a current definition with some attributes or elements preset.
I can't provide an example for mxmlc as I don't have Flex here. But here's an example using an exec task:
<presetdef name="exec.preset">
<exec executable="sh" dir=".">
<arg value="-c" />
<arg value="echo" />
</exec>
</presetdef>
<exec.preset>
<arg value="hello world" />
</exec.preset>
If you run this using ant -verbose you'll see
exec.preset] Executing 'sh' with arguments:
[exec.preset] '-c'
[exec.preset] 'echo'
[exec.preset] 'hello world'
[exec.preset]
The extra arg provided in the preset call is added to the exec.preset - which is just what you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to get current NSView in Cocoa? I'm changing my content View from applicaiton
[window setContentView:otherView];
[window setContentView:otherView2]; //etc
What I need, to be able to get always my current Content View, how I can do that?Something like this
[window myCurrentContentView]; or window.view , I couldn't find it. Thanks.
A: [window contentView];
should do the trick.
NSWindow documentation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: want to find a encode format to improve performance of websocket for web game I use json as the serialize format that runs on websocket in my web game at first.
But there are so much redundancy in json. So I want to find a more effective format to serialize my object.
And then I found protojs(https://github.com/sirikata/protojs) which implements protobuf in javascript. But its encoding performance is so poor (about 20+ times of json) since javascript dose not support type cast and it has to do a lot math operations to convert the primary data type (such as double) to bytes to do the protobuf encoding. The result turns out to be that request in protojs is much slower than in json.
Is there any good idea to improve the efficiency of data communication on websocket in web game?
A: I recently attended onGameStart (write-up here) and Rob Hawkes of Mozilla and Rawkets fame mentioned BSON (Binary JSON). However, he did say that he wasn't 100% sure if it improved efficiency.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android Multiple Buttons with different Actions I create buttons dynamically based on the size of an array list that i get from another object. For each entry of the arraylist i need to create three buttons each one with different action.
Like this i need to create 3 times the sizes of arraylist number of buttons. If i had only one set of buttons I can write onClick()-method which takes the id of the button but here i have 3 buttons for each entry and need to write 3 different actions for those three buttons.
How could this be done?
A: Similar thing I have done when i needed a textview for each of my array item.it was like-
String[] arrayName={"abc","def","ghi"};
for(int i=0;i<arrayName.length;i++)
{
TextView tv=new TextView(context);
tv.setPadding(20, 5, 40, 5);
tv.setText(arrayName[i]);
tv.setTextSize(1, 12);
tv.setLayoutParams(new Gallery.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tv.setTextColor(Color.parseColor("#2554C7"));
tv.setClickable(true);
tv.setId(i);
layout.addView(tv);
}
In same way,you can add button in similar way. and in click event of each of them,you can code for their actions separately.(I have not tried this).So in each iteration,you will have 3 buttons for each of the array item.
Edit - 1:
You can differentiate ids like:
mButton1.setId(Integer.parseInt(i+"1"));
mButton2.setId(Integer.parseInt(i+"2"));
mButton3.setId(Integer.parseInt(i+"3"));
Then you can set click listener on each of the button like mButton1.setOnClickListener... and so on.
A: Declare a list of buttons:
private List<Button> buttons = new ArrayList<Button>();
Then add each button to this list:
buttons.add(0, (Button) findViewById(id in ur layout));
Inside a for loop give click listener:
Button element = buttons.get(i);
element.setOnClickListener(dc);
where dc is ur object name for your inner class that implements OnClickListener.
To access each button you can give:
Button myBtn;
@Override
public void onClick(View v) {
myBtn = (Button) v;
// do operations related to the button
}
A: Create the Common Listener class for your button action event and set the used into the setOnClickListener() method
Now set the unique id for the buttons.
Now suppose your class look like this :
class MyAction implements onClickListener{
public void onClick(View view){
// get the id from this view and set into the if...else or in switch
int id = view.getId();
switch(id){
case 1:
case 2:
/// and so on...
}
//// do operation here ...
}
}
set this listener in button like this way.
Button b1 = new Button(context);
b1.setId(1);
b1.setOnClickListenr(new MyAction());
Button b2 = new Button(context);
b2.setId(2);
b2.setOnClickListener(new MyAction());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Finding overlaping date ranges in an array I have an array of date ranges like this:
[0] => Array
(
[start_time] => 2011-10-01 00:00:00
[end_time] => 2011-10-05 00:00:00
[name] => Apples
)
[1] => Array
(
[start_time] => 2011-10-04 00:00:00
[end_time] => 2011-10-10 00:23:00
[name] => Oranges
)
[2] => Array
(
[start_time] => 2011-10-15 00:00:00
[end_time] => 2011-10-20 00:23:00
[name] => Bananas
)
I'm trying to calculate the overlap between each event and 'split' this overlap into a separate item in the array, then adjust the start_time and end_time of the intersecting events accordingly, so they no longer overlap. For example, in the array above 'Apples' intersects with Oranges by one day, so I'd like to end up with an array that looks like this.
[0] => Array
(
[start_time] => 2011-10-01 00:00:00
[end_time] => 2011-10-04 00:00:00
[name] => Apples
)
[1] => Array
(
[start_time] => 2011-10-04 00:00:00
[end_time] => 2011-10-05 00:00:00
[name] => Apples Oranges
)
[2] => Array
(
[start_time] => 2011-10-05 00:00:00
[end_time] => 2011-10-10 00:23:00
[name] => Oranges
)
[3] => Array
(
[start_time] => 2011-10-15 00:00:00
[end_time] => 2011-10-20 00:23:00
[name] => Bananas
)
A: To get reasonably efficient code, I guess that you will have to order the dates by beginning time. After that, it should be fairly easy to get the intersections by walking over the end-dates.
As you said that you were new to PHP, you might want to read up on the function http://php.net/manual/en/function.strtotime.php This converts your formatted dates into unix timestamps, thus making them comparable.
For sorting your above data structure, have a look at the different sorting functions for arrays: http://de3.php.net/manual/en/array.sorting.php
Especially uasort might be interesting for you.
As the others said, SO is not here to write your code, so have a look at set theory to get an idea for even better performing solutions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Change URL NextGEN Gallery Plugin We are using the NextGen Gallery plugin to generate a slideshow in a Wordpress site. I needed to change the site URL to a a different subdomain, and this seems to have broken the links. The plugin-generated javascript still passes the old URL to swfobject.embedSWF.
Does anyone know how to fix this? I already updated the Wordpress "General Settings" with the new WordPress address and Site address (which are the same), and the plugin does not seem to pick up that change. Thanks!
A: Found it. It's in the string-encoded ngg_options entry in the wp_options table. The specific field is "irURL".
Why they chose to capture the site URL independently, instead of reading it from the Wordpress site configuration, is beyond me.
A: Could it be that NextGen has hardcoded those values somewhere in its database tables?
It could be a matter of running a bunch of SQL update queries to replace any instances of http://old.domain for http://new.domain
And now I'll state the obvious, recommending you to backup the full DB before you attempt any of this.
A: I had the same problem (unchanged absolute CSS/JS files' paths) after domain changing although I changed every single old domain's occurrence in database (even in serialized arrays/objects in options).
I found solution on http://www.nextgen-gallery.com/galleries-opening-lightbox/ - I didn't have time to do an investigation where they store these paths or in which format. :P
For me it is extremely stupid in Wordpress that it stores absolute paths (with one and the same domain) in so many places but that's another matter. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adding border to GridBagLayout rows I have a condition where, when ever i create a new row in GridBagLayout, then i have to add an bottom border to that row. How can i achieve this?
A: 1) use JSeparator
2) set/remove Border for JComponent at last line
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: simple dropdown list i did not found simple dropdown list .
i'm new in mvc3
this part create and fill : ListMonitoringLicenseModelList = new List();
i fill this objectsList in another part and use it to fill MonitoringLicenseModelList
objectsList = new List(...fill objectsList...);
List<MonitoringLicenseModel>MonitoringLicenseModelList = new List<MonitoringLicenseModel>();
foreach (object o in objectsList)
{
string[] tmpString = o.ToString().Split('@');
int i = 0;
monitoringLicenseModel = new MonitoringLicenseModel();
monitoringLicenseModel.MonitoringID =Convert.ToInt32(tmpString[i++]);
monitoringLicenseModel.LicenseUI = tmpString[i++];
MonitoringLicenseModelList.Add(monitoringLicenseModel);
}
public ActionResult SchedulesIndex()
{
return View(MonitoringLicenseModelList);
}
how can i write dropdownlist to show this
name value
MonitoringID = LicenseUI
A: @model List<MonitoringLicenseModel>
...
@Html.DropDownList(
"SelectedMotoringID",
new SelectList(Model, "MonitoringID", "LicenseUI")
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Testing Battery Usage I want to test how my application effects the battery of a phone/tablet.
Are there any testing tools which will allow me to do so?
For example, I want to test which modules of my application are consuming the most amount of battery, etc.
A: The question that you have asked is a research topic right now.
There is some on going research on tracing fine grained power usage i.e tracing power usage on thread or subroutine basis.\
eprof is one tool developed by some university grads.
you can find some papers on this topic here : http://web.ics.purdue.edu/~pathaka/pubs.html
I am working on the same thing, I will surely notify you if anything usable comes for normal users.
A: There is a new tool which comes with Android 5.0.
You can run
adb shell dumpsys batterystats > dump.txt
To get the full battery dump of you device. You also can add some options like --unplugged (only output data since last unplugged) or --charged (only output data since last charged). You can also add a packagename to get informations for this package/app only:
adb shell dumpsys batterystats --unplugged your.package.name > dump.txt
The part > dump.txt put everything into a file (maybe just works on Windows, not sure. But you can just leave it away, the dump will be printed right in the console where you can copy it and put it in a file).
This works just if you have a device with Android 5.x.
If you have a device with a lower level you can try to use
adb shell bugreport > bugreport.txt
But this file will be very very big. (~8mb+)
After creating this file you can use the Historian Tool of Google
To use it you have to install Python 2.7.9 and run following command
python /path/to/historian.py dump.txt > battery.html
This will create a battery.html file where you can see the data in a more usefull formatting.
Last thing: If you want to reset the stats of the battery dump just call
adb shell dumpsys batterystats --reset
(just works with Android 5.x)
A: In practice, I believe most apps that have power problems, also have 'CPU' problems. That is, a profile of your application's CPU usage is probably a good approximation of your battery consumption. There are caveats and exceptions if, for example, your app is doing something expensive with the GPU, the wireless network, storage, etc, and that expensive operation isn't taking much CPU time.
Here's an interesting blog about a "Power Tutor" app that provides a more precise measurement on a running system than the built-in battery app:
http://gigaom.com/mobile/android-power-consumption-app/. I haven't tried it.
For another level of detail, here is a paper that breaks down which components of a phone suck the most juice (note the paper is from 2010): http://www.usenix.org/event/usenix10/tech/full_papers/Carroll.pdf
(Just skip to section 5 to read their results). They say the screen brightness is the biggest culprit.
If the screen brightness is the biggest culprit, be sure to set that to a fixed level if you are measuring your own application's usage.
If you're really interested in measuring power consumption, you can follow their methodology (which invovles opening the phone and physically attaching measuring devices.)
A: As of Android 2.3.3 the system has a native Battery monitor.
Settings -> About Phone -> Battery use
A: I would say that there is no real tool to test it since it can't be precisely mesured. If you take an iPhone, you will see the battery count go from 40% to 30%, then stay there for a while, go down to 20%, lower to 15%, go up to 25%, Go back to 20% ECT.
What you could do is charge your phone for an extended period of time, to make sure it is fully charged, and then use your app until the phone closes, and note the amount of time it took.
Now do this with another version and see the result.
Basicly you'll have to play the MasterMind game with it if you want to do the less tests as possible.
Also, if the change isn't easy to see, it is probably not very important.
A: We performed similar testing to know how my application is responsible for battery consumption of Nexus5 phone .
But unfortunately we could not get help from any tool but it was mostly based on manual testing .
We identified some modules in app which were suspected for more battery consumption.
*
*Location awareness module which uses GPS .
*Upload module which uses network connection runs a background operation for long time.
*Video creation module which also make CPU busy due to background operation.
and so on...
Finally after 3-4 round of testing we had some trend in data and we were able to identify the module which was big culprit for battery consumption.
Basically there will be more battery consumption if something is keeping CPU busy more time. So we can think of module which have background operations, network related operations.
As of now I can not find any tool which could tell above testing result in a particular app.
Hope my experience would be beneficial for requirement statement in original question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "70"
}
|
Q: GWT History JavaScript Not Working in Internet Explorer I am having trouble getting the Google Web Toolkit's History class to work in Internet Explorer, even though it works in Chrome, FF.
I created an app using GWT 2.0 about 12 months ago, and noticed it stopped working sometime. I stripped it back to just the very first class and it seems any time I call History.addValueChangeHandler, Internet Explorer crashes.
Here is the code:
package com.js.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.History;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class Test implements EntryPoint, ValueChangeHandler<String>
{
/**
* This is the entry point method.
*/
public void onModuleLoad() {
History.addValueChangeHandler(this);
History.fireCurrentHistoryState();
}
public void onValueChange(ValueChangeEvent<String> event) {
Label loading = new Label( "Loading..." );
RootPanel.get().add( loading );
}
}
It's hard to believe this could crash, but here is the error:
18:50:52.407 [ERROR] [test] Unable to load module entry point class com.js.client.Test (see associated exception for details)
com.google.gwt.core.client.JavaScriptException: (Error): Access is denied.
description: Access is denied.
number: -2147024891
at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:195)
at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:120)
at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:507)
at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:264)
at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
at com.google.gwt.user.client.impl.HistoryImplIE6.getTokenElement(HistoryImplIE6.java)
at com.google.gwt.user.client.impl.HistoryImplIE6.init(HistoryImplIE6.java:80)
at com.google.gwt.user.client.History.<clinit>(History.java:63)
at com.js.client.Test.onModuleLoad(Test.java:24)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.google.gwt.dev.shell.ModuleSpace.onLoad(ModuleSpace.java:369)
at com.google.gwt.dev.shell.OophmSessionHandler.loadModule(OophmSessionHandler.java:185)
at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:380)
at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:222)
at java.lang.Thread.run(Unknown Source)
Any help would be appreciated. Thanks!
A: Is this IE7? Are you using a JSP/Servlet to render your home page? If yes ensure your servlet generates the history iframe/script code with double quotes and not single quotes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there any equivalent of ProxyPassReverse/ProxyPass for Jboss Is there any equivalent of Apache ProxyPassReverse/ProxyPass for Jboss AS?
A: I'm not sure if JBoss supports anything like this, but it doesn't seem that it should be the role of an application server to also handle all of the numerous and complex features of a dedicated HTTP server like Apache HTTP Server.
Just like it is very common to front something like Apache Tomcat with Apache HTTP Server, couldn't you do the same with JBoss? If not, please further detail your need so that we can provide a better answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WPF UI detach(pin out) functionality Am looking to implement a detach and popup UI behaviour in my applcation.
It basically means that I will be displaying say, a stackpanel with lot elements on the right side of my page. And on a button click, I want the stackpanel part to popup(removing its allocated space in the UI) and should be able to move it above the underlying wpf UI.
What am trying to do is that remove the stackpanel from its parent grid on button click and add it as the child of wpf popup control. But I am facing some issues doing this way. However I just want to know whether I am doing it in the correct way or do anyone have a good alternative for implementing this pin out functionality am specified here?
Thanks,
Vinsdeon
A: How about using this kinda nice control, AvalonDock, which is simulating Visual Studio's dockable components behaviors?
http://avalondock.codeplex.com/
It will spare you the pain of developing such a specific functionality, and will have a great reusability anyway
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Windows Phone 7 SDK C or C++ Is there any way to use C or C++ on Windows Phone 7? Also i need access to OpenGL from C/C++ and some kind of adapter to C from, for example, C#.
A: Short answer: you cannot. You have to use C# and XNA.
Long answer:
*
*There is no OpenGL API on WP7. You have to use XNA for 3D graphics.
*You cannot use C++, only managed (.Net) languages. I'm not an expert but I believe officially supported languages are C#, VB.net and F# at the moment. However, you may be able to use other languages as long as you manage to compile those into valid MSIL assembly.
*Support for non-managed, native languages such as C++ is not coming anytime soon AFAIK.
A: On Windows Phone 8, you finally can.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Powershell - Form can I continuous update the form using Start-Sleep I am new in Powershell but not to programing
I have created a form to monitor web server availablility
I used Primalforms 2011 which is quite good.
The script works fine and the result is as expected.
The next step is to continuously check the webservers at a 10 minute interval.
My question is how can I achieve this from within yhe Powershell form.
I can create a another script to call the script every 10 minutes but that is not a smart way(IMHO).
What I would like is to call the Webcheck function every 10 minutes from withing the form, check the pages and update the status accodingly.
Is there some documentation on how the Poweshell form intenals work or is it trial and error?
It is per se possible.
A: Look at the asynchronous event handling in PSH2: the help for Register-ObjectEvent includes an example with a timer.
(A web search might be able to find a fuller example of PowerShell + GUI + Timer. Eg. http://www.sapien.com/blog/2011/08/09/primalforms-2011-spotlight-on-the-timer-control/)
A: Not an answer per se but personally I prefer a monitoring solution to be more than a GUI running on a machine. Of course it depends on the requirements\SLA of what you are monitoring and a GUI only solution has many advantages.
Having some form of scheduling software running a script that updates a datafile or database and then have a GUI read that would be my preferred way.
You could do it on a simple level with windows scheduled tasks. If you don't want to use a database you could use Export\Import-CliXML for very quick and easy data storage. Have the GUI check for a new\updated file every X minute(s) and load it if it's new.
Something I've done when using Sapien is to write all my functional code in PowerShell modules and have the GUI call the modules cmdlets. I like the idea of keeping the display different from the functionality - like MVC in web dev. It's very useful if you want to reuse the function from a script.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: not able to navigate using RedirectToAction I am notable to naviagate to another page using Redirect ie when result is false, then i would like to navigate to exception page which is not happening.
public ActionResult IsLoginExsit(CustomerDO loginData)
{
if (!string.IsNullOrEmpty(loginData.UserName) && !string.IsNullOrEmpty(loginData.Password))
{
bool result = Businesss.Factory.BusinessFactory.GetRegistrations().IsLoginExist(loginData.UserName, loginData.Password);
if (result)
{
CustomerDO custInfo = new CustomerDO();
JsonResult jsonResult = new JsonResult();
jsonResult.Data = loginData;
custInfo = Businesss.Factory.BusinessFactory.GetRegistrations().GetCustInfoByUserName(loginData.UserName);
SessionWrapper.SetInSession("CustomerID", custInfo.Id);
SessionWrapper.SetInSession("CustomerFirstName", custInfo.FirstName);
SessionWrapper.SetInSession("CustomerLastName", custInfo.LastName);
return jsonResult;
}
else
{
return RedirectToAction("UnAuthorized", "Exceptions");
}
}
return View();
}
A: You seem to be invoking this action using AJAX. If you want to redirect this should be done on the client side in the success callback of this AJAX call using window.location.href. So for example you could adapt your action so that in case of error it returns a JSON object containing the url to redirect to:
else
{
return Json(new { errorUrl = Url.Action("UnAuthorized", "Exceptions") });
}
and then inside your AJAX success callback:
success: function(result) {
if (result.errorUrl) {
window.location.href = result.errorUrl;
} else {
...
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to insert image along with text in MySql? I am trying to prepare a sample question paper preparation app.
I am using tinyMCE editor and ajax-file-uploader plugin with it - as some questions may need images along with text.
How do I store my questions that have both image and text into MySql using PhP?
A: I would suggest storing the image on some sort of NAS or some other location, and store the path to the image in the database along with the other data in respective fields.
You can store the image in the DB but it is not good idea to retrieve and present the image from the database to the user (It doesn't perform that great either). There might be a performance hit
A: MySQL handles images very well. You insert them in BLOBs. On the other hand you could store the image file name and path or a link, as text in your DB.
Which solution is the best depends on the requirements of your application. In general if you have a huge amount of images, your database will become huge and backing up will be slow. There might be a similar impact on your file system in order to store a huge amount of images.
Here is the interesting Microsoft To BLOB or not to BLOB paper, that will give you more information on the topic and even some metrics.
A: I would echo the answers already given by @harigm and @Costis Aivalis but if you really wanted to go "all out" and store both the HTML content and the images in the same BLOB why not have a look at RFC 2557 which allows you to place binary data (like images) in the document itself using the url scheme data:. To make this work you will need to parse your HTML once it gets back to your server and base64 encode all the images to be placed in the HTML, quite a lot of work for what would probably turn out to be little reward.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to save and load the contents of a multiline textbox to XML? I have a multiline textbox, and I use databinding to bind its Text property to a string. This appears to work, but upon loading the string from XML, the returns (new lines) get lost. When I inspect the XML, the returns are there, but once the string is loaded from XML they are lost. Does anybody know why this is happening and how to do this right.
(I am not bound to use either a multiline textbox, or a string property for binding, I just a maintainable, (and preferably elegant) solution. )
Edit: Basically, I use the XmlSerializer class:
loading:
using (StreamReader streamReader = new StreamReader(fileName))
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
return (T)xmlSerializer.Deserialize(streamReader);
}
saving:
using (StreamWriter streamWriter = new StreamWriter(fileName))
{
Type t = typeof(T);
XmlSerializer xmlSerializer = new XmlSerializer(t);
xmlSerializer.Serialize(streamWriter, data);
}
When looking inside the XML, it saves multiline textbox data like this:
<OverriddenComponent>
<overrideInformation>
<Comments>first rule
second rule
third rule</Comments>
</overrideInformation>
</OverriddenComponent>
But those breaks no longer get displayed after the data is loaded.
A: What are the actual codes for new lines ? 0x0A or 0x0D or both? I stumbled on a similar problem before. The characters from a string "got lost" because textbox "converted" them on its own (or didn't understand them). Basicly, your xml file may be encoded one way, and your textbox uses other encoding, or it is lost during reading from, or writing to, the file itself (your string may be "messed up" also during reading from/writing to file). So there are 3 places your string may be tampered with, without your knowledge:
*
*During writing to the file (take notice what encoding you use)
*During reading from the file
*When displaying your string in textbox.
My advice is that you should assign the text that you read from the file to another string (not bound) before you assign it to the bound one and use a debugger to check how it changes. This http://home2.paulschou.net/tools/xlate/ is a useful tool to check what exactly is in your strings.
When I encountered this problem in my application, I ended up using binary/hex values of characters to write/read, and then converting them back when I needed to display. But I had to use a lot of strange ASCII codes. Maybe there's an easier solution for you out there.
EDIT: or it may be just some xml-related thing. Maybe you should use some other character to replace line break when writing it to xml?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CakePHP Model Associations Here's the deal, i have 2 models: Rus and Audios. I want to use records from Audios in Rus controller, so i go and type in associations like this:
<?
class Rus extends AppModel
{
var $name = 'Ru';
var $hasMany = 'Audio';
}
?>
and
<?
class Audios extends AppModel
{
var $name = 'Audio';
var $belongsTo = 'Ru';
}
?>
when i use scaffol feature nothing works. help please.
A: Try the following.
ru.php:
<?
class Ru extends AppModel
{
var $name = 'Ru';
var $hasMany = 'Audio';
}
?>
audio.php
<?
class Audio extends AppModel
{
var $name = 'Audio';
var $belongsTo = 'Ru';
}
?>
Your model names should be singular.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Exception capturing and Error logging I have got a utility class, called ErrorLog, which basically does some basic error logging kinda stuff, recording error messages, stacktraces, etc.
So in my main c# app, I almost always chuck this piece of code, ErrorLog el = new ErrorLog() into the catch(Exception e) part, and then start calling its methods to do logging.
For example, here is 1 of the methods in ErrorLog class
public void logErrorTraceToFile(string fname, string errorMsg, string errorStackTrace)
{
//code here
}
Anyway, I am just wondering if it's a good approach to log errors in this way? It seems to me that this solution is a bit clumsy. (considering in each catch block you create el object and call its method, repeatedly.)
Also, in terms of storing error log files, where it the best / most reasonable location to save them? Currently, I just hard-coded the directory, C:\ErrorLogs\, as I am still testing a few things. But I do want to get it right before I forget.
So any ideas or suggestions?
Thanks.
A: Look at ELMAH This is very efficient in handling and catching errors in the application.
The errors get logged in the database.
A: Usually I'm using the Singleton pattern to have one application wide Logger.
public class Logger
{
protected static Logger _logger;
protected Logger()
{
// init
}
public void Log(string message)
{
// log
}
public static Logger GetLogger()
{
return _logger ?? _logger = new Logger();
}
}
As a place to store data I would use the application data or user data directory, only there you can be sure to have write access.
Edit: That's how you would use the Logger from any place in your code:
Logger.GetLogger().Log("test");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Convert WSDL1.1 To WSDL2.0 i am asking how can we convert a WSDL1.1 File that contains some WS-SecurityPolicy to a WSDL2.0 file.
I have tried to use the apache woden framework to do so using this tutorial : http://ssagara.blogspot.com/2009/01/converting-wsdl11-to-wsdl20-using-woden.html, but i'am encountering this problem :
java.lang.IllegalArgumentException: Encountered unknown extension element '{http://schemas.xmlsoap.org/ws/2004/09/policy}Policy', as a child of a javax.wsdl.Binding.
coudl any one have a solution for this kind of convertion please ?
A: It cannot be difficult - since the policy is independent from WSDL. Better remove the security policy from the WSDL 1.1 and convert it to 2.0. Then separately add the policy to the wsdl.
A: Woden converter tool based on XSL templates and not support for any extension processing such as WS-Policy. As Prabath mentioned first you need to remove those security policy from WSDL 1.1.
BTW once you add policy to the WSDL 2.0 document Woden can parse them through it's Extensions handling mechanism. please refer this post http://ssagara.blogspot.com/2009/03/parsing-wsdl-20-extensions-with-woden.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make a reference to a struct in C# in my application I have a LineShape control and a custom control (essentially a PictureBox with Label).
I want the LineShape to change one of its points coordinates, according to location of the custom control.
I had an idea to set a reference to a LineShape point inside the custom control and add location change event handler that changes referenced point coordinates.
However built in Point is a struct which is a value type, so that won't work. Does anyone have idea, how to make a reference to a structure or maybe someone knows a workaround for my problem?
I tried the solution regarding usage of the nullable type but it still doesn't work. Here's the way I define the field in my custom control (DeviceControl):
private Point? mConnectionPoint;
And implementation of the location change event handler:
private void DeviceControl_LocationChanged(object sender, EventArgs e)
{
if (mConnectionPoint != null)
{
DeviceControl control = (DeviceControl)sender;
Point centerPoint= new Point();
centerPoint.X = control.Location.X + control.Width / 2;
centerPoint.Y = control.Location.Y + control.Height / 2;
mConnectionPoint = centerPoint;
}
}
A: You can pass value types by reference by adding 'ref' before it when passing in a method.
like this:
void method(ref MyStruct param)
{
}
A: Your method does not really require 'reference' access to the mConnectionPoint member; You can assign the location values directly to the referenced Point, as a member of your class:
private void DeviceControl_LocationChanged(object sender, EventArgs e)
{
if (mConnectionPoint != null)
{
DeviceControl control = (DeviceControl)sender;
mConnectionPoint.X = control.Location.X + control.Width / 2;
mConnectionPoint.Y = control.Location.Y + control.Height / 2;
}
}
However, if the reason for this code is to move the LineShape control, then you should go straight to the source. The best way to change the properties of a control is just to change the properties on the control:
DeviceControl control = (DeviceControl)sender;
line1.StartPoint = [calculate point1 coordinates];
line1.EndPoint = [calculate point2 coordinates];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Accessing embedded Solr instance over HTTP I'm running an embedded Solr instance inside a webapp. What is the best way to provide direct (or proxied via the webapp) HTTP access to the Solr instance?
A: Direct access through http for the embedded solr is not an option.
you would need to route the queries to Embedded Solr through your web application, which would query on the solr instance an return back the results.
Using Embedded Solr forever is not much recommended. If you hosting a webapp why not very well host solr as well ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Weird stuff happening while importing modules I hate to give the question this heading but I actually don't know whats happening so here it goes.
I was doing another project in which I wanted to use logging module. The code is distributed among few files & instead of creating separate logger objects for seperate files, I thought of creating a logs.py with contents
import sys, logging
class Logger:
def __init__(self):
formatter = logging.Formatter('%(filename)s:%(lineno)s %(levelname)s:%(message)s')
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(formatter)
self.logger=logging.getLogger('')
self.logger.addHandler(stdout_handler)
self.logger.setLevel(logging.DEBUG)
def debug(self, message):
self.logger.debug(message)
and use this class like (in different files.)
import logs
b = logs.Logger()
b.debug("Hi from a.py")
*
*I stripped down the whole problem to ask the question here. Now, I have 3 files, a.py, b.py & main.py. All 3 files instantiate the logs.Logger class and prints a debug message.
*a.py & b.py imports "logs" and prints their debug message.
*main.py imports logs, a & b; and prints it own debug message.
The file contents are like this: http://i.imgur.com/XoKVf.png
Why is debug message from b.py printed 2 times & from main.py 3 times?
A: logging.getLogger('') will return exactly the same object each time you call it. So each time you instantiate a Logger (why use old-style classes here?) you are attaching one more handler resulting in printing to one more target. As all your targets pointing to the same thing, the last call to .debug() will print to each of the three StreamHandler objects pointing to sys.stdout resulting in three lines being printed.
A: Specify a name for the logger, otherwise you always use root logger.
import sys, logging
class Logger:
def __init__(self, name):
formatter = logging.Formatter('%(filename)s:%(lineno)s %(levelname)s:%(message)s')
stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setFormatter(formatter)
self.logger=logging.getLogger(name)
self.logger.addHandler(stdout_handler)
self.logger.setLevel(logging.DEBUG)
def debug(self, message):
self.logger.debug(message)
http://docs.python.org/howto/logging.html#advanced-logging-tutorial :
A good convention to use when naming loggers is to use a module-level
logger, in each module which uses logging, named as follows:
logger = logging.getLogger(__name__)
A: First. Don't create your own class of Logger.
Just configure the existing logger classes with exising logging configuration tools.
Second. Each time you create your own class of Logger you also create new handlers and then attach the new (duplicating) handler to the root logger. This leads to duplication of messages.
If you have several modules that must (1) run stand-alone and (2) also run as part of a larger, composite, application, you need to do this. This will assure that logging configuration is done only once.
import logging
logger= logging.getLogger( __file__ ) # Unique logger for a, b or main
if __name__ == "__main__":
logging.basicConfig( stream=sys.stdout, level=logging.DEBUG, format='%(filename)s:%(lineno)s %(levelname)s:%(message)s' )
# From this point forward, you can use the `logger` object.
logger.info( "Hi" )
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: actual difference between - (IBAction)pushClear:(id)sender and - (IBAction)pushClear:(NSButton)sender When I link buttons to the source code (.h file in this case) and select NSButton as type it Xcode will write:
- (IBAction)pushClear:(id)sender;
as far as I understand it should be
- (IBAction)pushClear:(NSButton)sender;
am I right, or just somewhat confused? If I link s.th. from within the iOS Interface Builder, everything seems to do what it should.
so will I have to fix these things by hand? Or is it ok the way it is (in the end, every things working fine. Just don't want to step into problems down the road.
EDIT:
Is there some sort of performance issue by just using?
- (IBAction)pushClear:(id)sender;
A: You can set type like this:
- (IBAction)pushClear:(NSButton *)sender;
if you are sure, that only NSButton objects will send this actions.
If you are not sure, than you may leave:
- (IBAction)pushClear:(id)sender;
and inside of this method check that sender is kind of class NSButton.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery get response from php file after posting I'm posting some data to a php file with jquery. The PHP file just saves the data and prints the success of fail message. I would like to get the message generated by php file and embed in a div. I'm unable to figure out how i can return the message from PHP file.
Here is my code:
jQuery:
$(document).ready(function(){
$('#submit').click(function() {
$.ajax({
type : 'POST',
url : 'post.php',
data: {
email : $('#email').val(),
url : $('#url').val(),
name : $('#name').val()
},
});
});
});
PHP:
<?php
//save data
$message = "saved successfully"
?>
A: Try -
$(document).ready(function(){
$('#submit').click(function() {
$.ajax({
type : 'POST',
url : 'post.php',
data: {
email : $('#email').val(),
url : $('#url').val(),
name : $('#name').val()
},
success:function (data) {
$("#yourdiv").append(data);
}
});
});
});
This uses the success callback of the ajax function to return your data back to the page within the data parameter. The callback function then appends your data to a div on the page.
You'll also need to -
echo $message
In your php page to give jQuery some data to work with.
A: Did you look at the properties of the ajax method yet?
From the jQuery site:
$.ajax({
url: 'ajax/test.html',
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
Of course, your PHP need to echo something (a JSON object preferably) that returns to the script.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: MYSQL: Procedure with if statement I'm trying to make a routine that first checks a users password, if it's correct it shall return some values from a different table or change some values in a row.
Is this even possible without making two queries that you handle in PHP? First call for the password, check if its correct then allow the user to make the name change.
Here an example of getting the Rows in User with email and password.
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `get_user_info`(
IN in_Email VARCHAR(45),
IN in_Pass VARCHAR(45)
)
BEGIN
SELECT * FROM User WHERE Email = in_Email AND Pass = in_Pass;
END
And this is what Ive got so far:
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `change_pass`(
in_Email VARCHAR(45),
in_PassOld VARCHAR(45),
in_PassNew VARCHAR(45)
)
BEGIN
SET @PassOld = (SELECT Pass From User WHERE Email = in_Email);
IF(@PassOld = in_PassOld) THEN
UPDATE User SET Pass = in_PassNew WHERE Email = in_Email;
END IF;
ENDND IF;
END
Thanks for all the help!
A: You should really hash those passwords, use the following code
DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `change_pass`(
in_Email VARCHAR(45),
in_PassOld VARCHAR(45),
in_PassNew VARCHAR(45)
)
BEGIN
DECLARE KnowsOldPassword INTEGER;
SELECT count(*) INTO KnowsOldPassword
FROM User
WHERE Email = in_Email AND passhash = SHA2(CONCAT(salt, in_PassOld),512);
IF (KnowsOldPassword > 0) THEN
UPDATE User
SET Passhash = SHA2(CONCAT(salt, inPassNew),512)
WHERE Email = in_Email;
END IF;
END $$
DELIMITER ;
The salt is an extra field in table user that is more or less random, but does not need to be secret. It serves to defeat rainbow tables.
You can set salt to a short string char(10) or randomish data. e.g.
salt = ROUND(RAND(unix_timestamp(now())*9999999999);
You don't need to update the salt, just generate it once and then store it.
For more on this issue see:
Salting my hashes with PHP and MySQL
How should I ethically approach user password storage for later plaintext retrieval?
A comment on your code
IF(@PassOld == in_PassOld) THEN //incorrect
IF(@PassOld = in_PassOld) THEN //correct, SQL <> PHP :-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: QSql module and multithreaded application I'm troubled by how the Sql module works with multithreaded application in Qt.
http://doc.qt.io/qt-5/threads-modules.html#threads-and-the-sql-module clearly states
that "A connection can only be used from within the thread that created it".
However this piece of code I wrote works :
#include <QCoreApplication>
#include <QSqlQuery>
#include <QtConcurrentRun>
void req()
{
QSqlQuery q("INSERT INTO users (username) VALUES (\"test\")");
}
void db()
{
QSqlDatabase _db;
_db = QSqlDatabase::addDatabase("QMYSQL");
_db.setDatabaseName("dbname");
_db.setHostName("host");
_db.setUserName("username");
_db.setPassword("password");
if (_db.open())
std::cout << "Ok" << std::endl;
else
std::cout << "Error" << std::endl;
}
int main(int ac, char **av)
{
QCoreApplication app(ac, av);
QtConcurrent::run(db);
sleep(1);
QtConcurrent::run(req);
return app.exec();
}
My application design requires multiple threads to interact with a database. Thoses threads
are spawned and managed by QtConcurrent::run().
So, since this piece of code works should I go for it or will I run into
troubles doing that ?
Any help, documentation or explanation is welcome !
Thank you.
A: The above code is fine because QSqlQuery creates its own QSqlDatabase. It would be a problem if it referenced _db as created by db(). The down side is that it doesn't actually do anything.
QSqlDatabase is not a QObject but it has-a driver which is a QObject and therefore has thread affinity.
If creating loads of QSqlDatabases is prohibitive, create worker threads which maintains their own connection. Then dispatch queries to these threads rather than creating new threads and therefore new connections.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Extjs Tree editor - disable single click to edit I am using tree editor. I need the tree node to become editable only when it is double clicked. So far I have done this
var tree = new Ext.tree.TreePanel({
root: this.getChildren(),
height: 300,
loader: new Ext.tree.TreeLoader(),
useArrows: true,
autoScroll: true,
listeners: {
dblclick: onTreeNodeDblClick
}
});
var treeEditor = new Ext.tree.TreeEditor(tree, {}, {
cancelOnEsc: true,
completeOnEnter: true,
selectOnFocus: true,
allowBlank: false,
listeners: {
complete: onTreeEditComplete
}
});
onTreeNodeDblClick: function (n) {
treeEditor.editNode = n;
treeEditor.startEdit(n.ui.textNode);
}
onTreeEditComplete: function (treeEditor, o, n) {}
I have searched the api to find something like "clicksToEdit" which we use in editor grid but cant find anything. Is there any way to do this?
A: Ext.tree.TreeEditor adds two event listeners (beforeclick, dblclick) to tree
so you may unsubscribe its from tree
tree.on('afterrender', function() {
tree.un('beforeclick', treeEditor.beforeNodeClick, treeEditor);
tree.un('dblclick', treeEditor.onNodeDblClick, treeEditor);
})
A: From API of Ext.tree.TreePanel:
beforeclick : ( Node node, Ext.EventObject e )
Fires before click processing on a node. Return false to cancel the default action.
So you could do this:
var tree = new Ext.tree.TreePanel({
root: this.getChildren(),
height: 300,
loader: new Ext.tree.TreeLoader(),
useArrows: true,
autoScroll: true,
listeners: {
dblclick: onTreeNodeDblClick,
beforeclick: function() { return false;}
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why code in any unit finalization section of a package is not executed at shut down? I have an application that uses statically-linked runtime packages as well as designtime packages that use them. For some reason the code in any unit finalization section is not being run at runtime (I can't tell when this started happening).
finalization
ShowMessage('Goodbye');
end.
Shutting Delphi down shows the message, but not when my application shuts down. It gets weirder in that if I put a breakpoint on ShowMessage, it breaks there but does not execute the line. If there are multiple lines in the finalization, the debugger stops on the first line, does not execute it and then jumps to the end.
procedure ProcOne;
begin
SomeObject.Free; // Debugger does not enter or stop here
SomeObject := nil;
end;
finalization
ProcOne; // Debugger stops here, doesn't execute, jumps to "end."
ProcTwo; // Every line has a blue dot
ShowMessage('Bye');
end.
The call stack on ProcOne breakpoint shows @Halt0 => FinalizeUnits => MyPackage.MyUnit.Finalization.
If I include the unit in an application that doesn't use packages, everything executes properly.
Does anyone have an idea what could be causing this?
EDIT:
Thanks to Allen Bauer's comment pointing in the right direction, I have managed to isolate the problem. It seems the problem arises if an application is built with a runtime package, then dynamically loads another package that also references that package and unit.
I have created a test project that demonstrates the problem: TestFinalization
Does anyone know the reason for this and/or a workaround? You normally might not notice that your finalization is not being run until you notice that external resources are not being cleaned up.
A: Make sure you're calling UnloadPackage for each dynamically loaded package before shutdown. If you're simply calling UnloadLibrary (or simply relying on the OS to unload them), then the finalizations for that the units in that package and all the units from other packages aren't being called. Initializations and finalizations are done using a reference counting system because in the face of dyanmically loaded packages, there is no way to know what units will be initialized and when. Only when you've balanced the finalization calls with the initialization calls will the last finalization call actually execute the code block in the finalization section. Likewise only the first call to the initialization section will actually execute the code block.
Initializations/finalizations are done using a compiler-generated table for a given module. When you build an exe or dll linked with packages, this table contains references to all the units that are actually used, even those from the linked packages. Note that only the units actually referenced are actually initialized. IOW, if you have 100 units in PackageA and the exe only references one of them, then only that unit and any units it uses will be initialized.
For dynamically loaded packages, there is really no way to know what units will actually be used, so the compiler generates the init/finit table as if every unit were initialized. This table is not processed upon loading of the package during the call to LoadLibrary, but rather is handled by calling a special export called Initialize(). The LoadPackage function ensures that this function is called. This table only ensures that all the units in the loading package are initialized. Only the units actually touched in any other package are initialized, similar to the exe/dll case I mentioned above. UnloadPackge does the reverse, and calls special export Finalize() before calling UnloadLibrary().
Finally, if you've made changes to uses lists of any packaged units and only rebuild the package, you can run into confusing cases where initializations/finalizations may not get called even though your units within a given package properly "use" each other. This is because the init/finit is controlled by the loading module and not from within itself. Only in the case where a package is explicitly loaded using LoadPackage will every unit in that package (and that package only) be initialized/finalized.
A: For anyone in the same situation as me, in light of Allen Bauer's answer:
I have a number of units which use initialization/finalization to self-register. In the spirit of Raymond Chen's advice I only run deregistration when it matters:
initialization
RegisterUnit();
finalization
//In debug mode we track memory leaks so properly deregister
//In release mode the app is shutting down; do not waste time
//freeing memory that's going to be freed anyway
{$IFDEF DEBUG}
UnloadUnit();
{$ENDIF}
I moved a bunch of these into packages but this broke core package finalization, as the question describes.
From Allen Bauer's answer it follows that you must call UnloadPackage() for all dynamically loaded packages, or you will not get proper finalization calls in the core.
But then I cannot use that optimization anymore. I have to painfully deregister every package on finalization because once I unload the package DLL the objects it registered in the core are going to be zombies.
This feels like a wasted effort. Unloading should be quick. I'd like to leave all dynamically loaded packages hanging until everything is simply destroyed.
What you can do instead is call FinalizePackage() on all dynamically loaded packages! This evens out the reference counters while leaving the packages loaded.
If a package employs this "skip deinit" trick its objects are going to remain alive until the process destruction. (It's the job of the package to make sure anything that can be called on them does not break). If it doesn't, it's fully deinitialized and what remains is an inert DLL.
This wouldn't work with packages that you plan on unloading truly dynamically of course.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Why the following JQuery does not work on IE browser when I put it in my website? I am using DDCharts JQuery plugin to put some charts in my website. I downloaded the plugin and the original files and examples work fine in Internet Explorer 8+ but when I included in my website, it did work on IE but it worked well on Firefox and I don't know why??!!!!
This is my code:
PSI - Dashboard
<!-- **************************************************** -->
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link type="text/css" href="http://jqueryui.com/themeroller/css/parseTheme.css.php?ffDefault=Verdana%2CArial%2Csans-serif&fwDefault=normal&fsDefault=1.1em&cornerRadius=5px&bgColorHeader=2191c0&bgTextureHeader=12_gloss_wave.png&bgImgOpacityHeader=75&borderColorHeader=4297d7&fcHeader=eaf5f7&iconColorHeader=d8e7f3&bgColorContent=fcfdfd&bgTextureContent=06_inset_hard.png&bgImgOpacityContent=100&borderColorContent=a6c9e2&fcContent=222222&iconColorContent=0078ae&bgColorDefault=0078ae&bgTextureDefault=02_glass.png&bgImgOpacityDefault=45&borderColorDefault=77d5f7&fcDefault=ffffff&iconColorDefault=e0fdff&bgColorHover=79c9ec&bgTextureHover=02_glass.png&bgImgOpacityHover=75&borderColorHover=448dae&fcHover=026890&iconColorHover=056b93&bgColorActive=6eac2c&bgTextureActive=12_gloss_wave.png&bgImgOpacityActive=50&borderColorActive=acdd4a&fcActive=ffffff&iconColorActive=f5e175&bgColorHighlight=f8da4e&bgTextureHighlight=02_glass.png&bgImgOpacityHighlight=55&borderColorHighlight=fcd113&fcHighlight=915608&iconColorHighlight=f7a50d&bgColorError=e14f1c&bgTextureError=12_gloss_wave.png&bgImgOpacityError=45&borderColorError=cd0a0a&fcError=ffffff&iconColorError=fcd113&bgColorOverlay=aaaaaa&bgTextureOverlay=01_flat.png&bgImgOpacityOverlay=75&opacityOverlay=30&bgColorShadow=999999&bgTextureShadow=01_flat.png&bgImgOpacityShadow=55&opacityShadow=45&thicknessShadow=0px&offsetTopShadow=5px&offsetLeftShadow=5px&cornerRadiusShadow=5px" rel="stylesheet" />
<link type="text/css" href="Style/ddchart.css" rel="stylesheet" />
<script language="javascript" src="http://jqueryui.com/js/jquery.js" ></script>
<script language="javascript" src="http://jqueryui.com/themeroller/themeswitchertool/" ></script>
<script language="javascript" src="JavaScript/jquery.tooltip.js" ></script>
<script language="javascript" src="JavaScript/jquery.ddchart.js"></script>
<script language="javascript">
$(document).ready(function(){
$('#switcher').themeswitcher();
});
</script>
<style type="text/css">
.chart_loading {
position:absolute;
bottom:0%;
left:0%;
height:10%;
width:10%;
padding:0;
margin:0;
z-index:1000;
text-align:center;}
</style>
<script type="text/javascript">
$(function() {
$("#chart_div_static").ddBarChart({
chartDataLink: "javascript/Static_Data.js?1=10",
action: 'init',
xOddClass: "ui-state-active",
xEvenClass: "ui-state-default",
yOddClass: "ui-state-active",
yEvenClass: "ui-state-default",
xWrapperClass: "ui-widget-content",
chartWrapperClass: "ui-widget-content",
chartBarClass: "ui-state-focus ui-corner-top",
chartBarHoverClass: "ui-state-highlight",
callBeforeLoad: function (){$('#loading-Notification_static').fadeIn(500);},
callAfterLoad: function (){$('#loading-Notification_static').stop().fadeOut(0);},
tooltipSettings: {extraClass: "ui-widget ui-widget-content ui-corner-all"}
});
});
</script>
<!-- **************************************************** -->
<div class="page">
<div id="header" >
<div class="HeadTop">
<h2 style="color:Red"> TEST System</h2>
</div>
</div>
<div id="main">
TEST - Dashboard
<!-- *********************************************************************************************** -->
<!-- For the Charts -->
<div id="switcher" style="position:relative; height:5%; width:100%;"></div>
<div style="position:relative; width:100%;height:95%;">
<div id="chart_div_static" style="position:relative; height:95%; width:100%;"></div>
<div id="loading-Notification_static" class="chart_loading ui-widget ui-widget-content ui-state-error">Loading...</div>
</div>
<div class="ui-widget-header ui-state-active" style="padding:7px 0 7px 10px">
Source
<button class="ui-button ui-state-default ui-corner-all" style="float:right; padding:2px;" onClick="window.open('Source/DDChart_Source.zip','_blank');">Download</button>
</div>
<!-- *********************************************************************************************** -->
</div>
</div>
A: Try putting your javascript at the end of the page instead of the start. IE has problems when you try and run scripts on elements that haven't loaded yet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CakePhp: Url based internationalization I've a small problem with my internationalization:
I want to have some url looking like this: http://mywebsite/eng/controller/action/params...
I found this http://nuts-and-bolts-of-cakephp.com/2008/11/28/cakephp-url-based-language-switching-for-i18n-and-l10n-internationalization-and-localization/
This is working nice most of time. But I've one case where this hasn't the expected result.
When I'm using $this->Html->link with named parameters, I don't get my nice structure, but something like http://mywebsite/controller/action/paramX:aaa/paramxY:bbb/language:eng
I think this is a routing problem, but I can't figure what is going wrong?
Thank you very much
A: This is because cakephp doens't find a route in routes.php that corresponds to this link. In other words, you'll have to define this route in the routes.php file
Router::connect('/:language/:controller/:action/:paramX/:paramY');
Once this set, $this->Html->link will output a nice url
A: I finally did this:
I created a custom CakeRoute, in this cakeRoute, I override the "match" url and the _writeUrl method.
Now every thing is working like a charm :)
For those which are interessted by the route class:
<?php
class I18nRoute extends CakeRoute {
/**
* Constructor for a Route
* Add a regex condition on the lang param to be sure it matches the available langs
*
* @param string $template Template string with parameter placeholders
* @param array $defaults Array of defaults for the route.
* @param string $params Array of parameters and additional options for the Route
* @return void
* @access public
*/
public function __construct($template, $defaults = array(), $options = array()) {
//$defaults['language'] = Configure::read('Config.language');
$options = array_merge((array)$options, array(
'language' => join('|', Configure::read('Config.languages'))
));
parent::__construct($template, $defaults, $options);
}
/**
* Attempt to match a url array. If the url matches the route parameters + settings, then
* return a generated string url. If the url doesn't match the route parameters false will be returned.
* This method handles the reverse routing or conversion of url arrays into string urls.
*
* @param array $url An array of parameters to check matching with.
* @return mixed Either a string url for the parameters if they match or false.
* @access public
*/
public function match($url) {
if (empty($url['language'])) {
$url['language'] = Configure::read('Config.language');
}
if (!$this->compiled()) {
$this->compile();
}
$defaults = $this->defaults;
if (isset($defaults['prefix'])) {
$url['prefix'] = $defaults['prefix'];
}
//check that all the key names are in the url
$keyNames = array_flip($this->keys);
if (array_intersect_key($keyNames, $url) != $keyNames) {
return false;
}
$diffUnfiltered = Set::diff($url, $defaults);
$diff = array();
foreach ($diffUnfiltered as $key => $var) {
if ($var === 0 || $var === '0' || !empty($var)) {
$diff[$key] = $var;
}
}
//if a not a greedy route, no extra params are allowed.
if (!$this->_greedy && array_diff_key($diff, $keyNames) != array()) {
return false;
}
//remove defaults that are also keys. They can cause match failures
foreach ($this->keys as $key) {
unset($defaults[$key]);
}
$filteredDefaults = array_filter($defaults);
//if the difference between the url diff and defaults contains keys from defaults its not a match
if (array_intersect_key($filteredDefaults, $diffUnfiltered) !== array()) {
return false;
}
$passedArgsAndParams = array_diff_key($diff, $filteredDefaults, $keyNames);
list($named, $params) = Router::getNamedElements($passedArgsAndParams, $url['controller'], $url['action']);
//remove any pass params, they have numeric indexes, skip any params that are in the defaults
$pass = array();
$i = 0;
while (isset($url[$i])) {
if (!isset($diff[$i])) {
$i++;
continue;
}
$pass[] = $url[$i];
unset($url[$i], $params[$i]);
$i++;
}
/*
//still some left over parameters that weren't named or passed args, bail.
//We don't want this behavior, we use most of args for the matching, and if we have more, we just allow them as parameters
if (!empty($params)) {
return false;
}*/
//check patterns for routed params
if (!empty($this->options)) {
foreach ($this->options as $key => $pattern) {
if (array_key_exists($key, $url) && !preg_match('#^' . $pattern . '$#', $url[$key])) {
return false;
}
}
}
return $this->_writeUrl(array_merge($url, compact('pass', 'named')));
}
function _writeUrl($params) {
if (isset($params['prefix'], $params['action'])) {
$params['action'] = str_replace($params['prefix'] . '_', '', $params['action']);
unset($params['prefix']);
}
if (is_array($params['pass'])) {
$params['pass'] = implode('/', $params['pass']);
}
$instance =& Router::getInstance();
$separator = $instance->named['separator'];
if (!empty($params['named']) && is_array($params['named'])) {
$named = array();
foreach ($params['named'] as $key => $value) {
$named[] = $key . $separator . $value;
}
$params['pass'] = $params['pass'] . '/' . implode('/', $named);
}
$out = $this->template;
$search = $replace = array();
foreach ($this->keys as $key) {
$string = null;
if (isset($params[$key])) {
$string = $params[$key];
} elseif (strpos($out, $key) != strlen($out) - strlen($key)) {
$key .= '/';
}
$search[] = ':' . $key;
$replace[] = $string;
}
$out = str_replace($search, $replace, $out);
if (strpos($this->template, '*')) {
$out = str_replace('*', $params['pass'], $out);
}
$out = str_replace('//', '/', $out);
//Modified part: allows us to print unused parameters
foreach($params as $key => $value){
$found = false;
foreach($replace as $repValue){
if($value==$repValue){
$found=true;
break;
}
}
if(!$found && !empty($value)){
$out.="/$key:$value";
}
}
return $out;
}
}
And you can set the route like this:
Router::connect('/:language/:controller/*', array(), array('routeClass' => 'I18nRoute'));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: django model filter question I have a model which I need to filter based on different conditions. I want to avoid having to write complicated nested conditions and fitting a model filter onto every situation.
Is there anyway to concatenate or combine the filter() arguments into a variable and then put that variable as a set of filter arguments like this?:
db_table.objects.filter(variable_of_arguments)
being equal to:
db_table.objects.filter(
(Q(first_name__icontains=search) |
Q(last_name__icontains=search)),
foo = True)
A: I'm not sure, but may be you can do it with 2 parameters:
param1 = Q(first_name__icontains=search) | Q(last_name__icontains=search))
param2 = {'foo', False}
db_table.objects.filter(param1, **param2)
A: You can build up a variable number of arguments and pass them in as follows:
q = Q(first_name__icontains=search) | Q(last_name__icontains=search)
p = Q(first_in_line=True) | Q(last_in_line=True)
args = [q, p]
kwargs = {
'foo': True
'bar': False
}
db_table.objects.filter(*args, **kwargs)
# Equivalent to:
#
# db_table.objects.filter(
# Q(first_name__icontains=search) | Q(last_name__icontains=search),
# Q(first_in_line=True) | Q(last_in_line=True),
# foo=True,
# bar=False
# )
Now you can use whatever logic you want to build up args and kwargs and the call to filter() will always be the same.
A: Here's a snippet that's been around for a while that might help: http://djangosnippets.org/snippets/1679/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ASP.NET web application taking a lot of time to Debug Actually i have an web application where i have a form which takes data from MYSQL database where i have written an Sp to get the data from DataBase(compares 100.000 records and gives 40,000 of records as output) and bind it to Gridview. At the very first time it takes 15 mins to debug and den for second time(reload) it takes approx.1-2 hours(while i call the same SP in MYSQL DB it takes ~8 mins) Can any one please help me.
A: You are not going to show 40,000 records at once. You need to implement SP level pagination.
CREATE PROCEDURE OrdersByStatus(
IN orderStatus VARCHAR(25),
IN start INT, IN size, OUT total INT)
BEGIN
SELECT count(orderNumber)
INTO total
FROM orders
WHERE status = orderStatus;
SELECT *
FROM orders
WHERE status = orderStatus
LIMIT start, (start + size);
END$$
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Facebook oauth dialog redirect after login problem on mobile touch site We redirect users to below URL on mobile phones for application authorisation:
https://m.facebook.com/dialog/oauth?client_id=XXXXXX&redirect_uri=http://www.server.com/callback.php&scope=offline_access,user_likes,publish_stream,publish_checkins,user_checkins&display=wap
If the user is logged in to Facebook on his/her phone, no problem, Facebook automatically redirects to oauth dialog page.
If user is not logged in, Facebook asks them to login first.
On wap site(A Nokia phone), it redirects to oauth dialog without any problem after login.
But on touch site(An iPhone), it add hastags to URL, redirects user to his/her Facebook homepage.
Even display=wap parameter on URL doesn't help on this issue.
Any ideas on how to solve this problem?
Thank you
A: Actually, here's a cleaner solution. (I hadn't seen the API for getLoginUrl at the time of my previous post. http://developers.facebook.com/docs/reference/php/facebook-getLoginUrl)
require_once("facebook.php");
$config = array(
"appId" => APP_ID,
"secret" => APP_SECRET
);
$facebook = new Facebook($config);
$params = array(
"scope" => "offline_access,user_likes,publish_stream,publish_checkins,user_checkins",
"redirect_uri" => "http://www.server.com/callback.php",
"display" => "touch"
);
$url = $facebook->getLoginUrl($params);
header("Location: $url");
A: I experienced the same problem and had troubles isolating it since it worked in Chrome on the desktop but not while using the iPhone's Safari browser.
I did a urlencode around the redirect_url parameter and set display to touch. So to use your link above as an example, I'd try this:
https://m.facebook.com/dialog/oauth?client_id=XXXXXX&redirect_uri=http%3A%2F%2Fwww.server.com%2Fcallback.php&scope=offline_access,user_likes,publish_stream,publish_checkins,user_checkins&display=touch
I sincerely hope that works for you. It seemed to have brought me luck.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566970",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jQuery ajax working on local file but not working from a remote url? I am currently trying to get data from a remote url using jQuery ajax calls.
I am just using a basic jquery function to do this. When using a local file the functions works correctly but it does not get a remote file.
I'm using the local files using Mamp on my local pc.
$.ajax({
url: "URL",
success: function(data) {
$('#notification').html(data);
}
});
Any ideas why this may not be work would be a great help?
Thanks,
Kane
A: Sounds like Same origin policy. You might need to use JSONP.
A: when you say 'remote file' do you mean like from another domain? coz browsers typically don't allow that.
See this JQuery external Ajax call not working in IE
A: Cross domain ajax request is not allowed typically. You can take a look to these answers:
jQuery AJAX cross domain
problem with cross-domain ajax calls
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can Vim restore the state exactly after an undo? For example, if I'm in the end of a word and I type 'diwu', the cursor ends up at the start of the word.
Same applies if I have something selected in visual mode (after undo I'd like it to go back to the visual selection I had before the operation I've just undone).
Sorry if stackoverflow isn't the best place for this (seemed to be the best option looking around).
A: The closest I came:
the quick brown fox jumped over the lazy moon
cursor here ----- ^
Execute
madiwu`a
It requires you to explicitely save the location before the edit/undo so it is pretty useless unless you know beforehand that you are going to revert an edit
*
*ma (save current position in mark 'a')
*diw (delete inner word, 'jumped ')
*u (undo that change, cursor ends up at 'j' of 'jumped')
*`a (jump to 'a' marker)
A: I'm not sure it can/should be automated with a mapping but in your first case I would create a mark with ma then do the deletion/undo, then type `a to position the cursor at the mark.
In the second case, gv reselects the previous visual selection.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Webdriver/FXDriver utils.js causing 'unresponsive script' error in Firefox I've got some browser tests that run using Watir webdriver and FXDriver and things are generally working ok. However there is one test that loads a lightbox that contains a lot of HTML, and when the tests open this lightbox, Firefox shows a popup complaining that Utils.js line 432 from FXDriver has become an 'unresponsive script' and the test times out. I would rather fix the problem properly than extend the dom.max_script_run_time value, so I looked at the line in question...
goog.string.canonicalizeNewlines = function(a) {
return a.replace(/(\r\n|\r|\n)/g, "\n")
};
It's pretty obvious why this is making Firefox hang, the question is how to stop it. This function gets called from many places, and because it gets called by Watir in a firebug-less Firefox instance it is pretty tricky to debug. How can I stop this from happening?
Editing the file, extending the timeout and reducing the amount of HTML it has to deal with are not options.
A: Start Watir-WebDriver with Firebug enabled.
First download the Firebug XPI file, then:
profile = Selenium::WebDriver::Firefox::Profile.new
profile.add_extension "../path/to/firebug.xpi"
b = Watir::Browser.new :firefox, :profile => profile
see: http://watirwebdriver.com/firefox/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: T-SQL: CASE statement in WHERE? I have the following WHERE clause in my SQL query currently:
WHERE c.Town LIKE '%' + @Town + '%'
What I want do is make the first '%' optional - so if the user has selected to just filter by records that just start with the given text, the WHERE would be
WHERE c.Town LIKE @Town + '%'
I assumed the simplest way to do this would be CASE statements, but I'm having no joy as it seems the syntax is incorrect. Can I get any pointers? Here's the CASE statement I was trying:
WHERE c.Town LIKE (CASE WHEN @FilterOptions = 1 THEN '%' ELSE '') + @Town + '%'
A: You missed the END:
WHERE c.Town LIKE (CASE WHEN @FilterOptions = 1 THEN '%' ELSE '' END) + @Town + '%'
A: A CASE must end with an END. Try
WHERE c.Town LIKE (CASE WHEN @FilterOptions = 1 THEN '%' ELSE '' END) + @Town + '%'
A: Case should have end.
I think the below statement can help you.
WHERE c.Town LIKE (CASE WHEN @FilterOptions = 1 THEN '%' ELSE '' END) + @Town + '%
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ® gets converted to ® in Python while parsing XML My RSS feed ontains:
<title><![ CDATA[HBO Wins 19 Emmy® Awards, The Most of Any Network This Year]]></title>
Now I am parsing RSS and then assigning the title to title as below:
for item in XML.ElementFromURL(feed).xpath('//item',namespaces=NEWS_NS):
title = item.find('title').text
Log("Title :"+title)
and when I am checking the out put or the log file then I see the title as below:
HBO Wins 19 Emmy® Awards, The Most of Any Network This Year.
® gets converted to ® . Any I tried using HTML parser but no use.
A: You state that the encoding of the feed is ISO-8859-1.
In that case, if the bytes that you say should be interpreted as ® are in fact C2 AE, then the text really, truly is Emmy® Awards, and everything is working as it should. If the sender intended different text, they would have sent different data or set the encoding differently.
If the encoding of the feed were UTF-8, and the bytes sent over the wire were still C2 AE, then the text would be Emmy® Awards.
If the encoding of the feed were ISO-8859-1, and the bytes sent over the wire were simply AE, with no C2, then the text would be Emmy® Awards.
To be sure what the bytes are, use the od -x command in Unix or the d command in debug.exe for Windows. Don't trust Notepad in situations like this. It lies.
A: You've received some text encoded using UTF-8, but at some point those bytes are being incorrectly interpreted as ISO-8859-1 or another encoding instead.
Without more context, it's difficult to tell exactly where the mistake is taking place. You should first check the encoding being used to read your log file.
A: I tried the following and worked:
title = item.find('title').text
title = title.encode('iso-8859-1')
When I am getting the string converted to UTF-8(® to ® ) and I am converting it back to iso-8859-1(® to ® ) and getting the correct output
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to call a method with argment in an input component? I want to call a method with parameter that return a string.
public String MyMethod(Integer param) {
String xx=......;
return xx;
}
And I want to display this result in <p:inputText>. How can I do this? I'm using primefaces.
A: Let's say you have the following:
private String someField;
public String getSomeField() {
return someField;
}
public String setSomeField(String input) {
someField = input;
}
Then you can access this property in your .xhtml file which contains the <p:inputText> like this:
<p:inputText value="#{nameOfYourManagedBean.someField}" />
Alright? I'd still recommend you to read a book or something, since this is very basic stuff.
A: Thank you for your answers,
my classBean contain a reference of anotherClass like this
bean user
{....
Profils idProfil}
So when I've tried to call beanUser.selectedProfil.nameProfil in p:inputText, it works fine.
Thank's
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Force all axis labels to show In ASP.NET Column Chart, when the chart size is small some axis labels are not shown.
Question: How can I force all the label to show even if they have to overlap?
A: Set the Interval property for the Axis to 1, this will enforce it to display all the available labels irrespective of the space limitation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: Merge Crystal reports .NET 4 C# Good day,
I'm not sure if this is possible but I want to merge 3 Simila reports into 1 at runtime in report viewer. I have 3 reports that are very similar and need to all run at the same time, currently I have to show the viewer 3 times to show all the reports. I would idealy like to set it up so page 1 is report 1,page 2 is report2, page 3 is report 3...they are all longer than a page but I am using this as an example.
Any help here would be greatly appreciated
A: I suppose it's impossible put 3 reports inside 1 reportviewer.
I suggest an easy way to solve your problem:
create a new blank report then insert as subreports the 3 reports.
Be careful, subreports can't contain others subreports inside.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Save output of CGI script under different filename than the script name I have a Python CGI script script.py running on a server. It produces a CSV file as output.
I want computer-inexperienced people that don't know about file extensions to be able to just save the file to their hard drive and use it by double-clicking.
The problem: If they now click "OK" in the save dialog of the browser, the saved file's name is script.py, instead of script.csv.
How can I set some sort of "default filename" from within the CGI? Maybe some HTTP header trickery?
I don't have access to the server configuration.
A: You need to set a Content-Disposition header, with a filename attribute. See an earlier question for some discussion.
Yours would look like:
Content-Disposition: attachment; filename=script.csv
As well as setting the filename, this will tell the browser to save the file, rather than to open it inline.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to adjust component's size according to the screen ( or display ) size? I tested my application in another mobile phone , a htc mobile phone , and it has a very large screen size. So I was very surprised when I saw the arrangement of the components ! Here is the captured image of the screen from the camera of another phone :
So how to make the components be sized and placed well according to the screen display size of any device ?
A: AFAIF LWUIT components automatically resized based on resolution. I think you are using setMargin or setPadding for those components. So you need to handle them based on resolution. Get the resolution for the mobile and change the component margin and padding. use this code for get resolutions,
int screen_width = Display.getInstance().getDisplayWidth();
int screen_height = Display.getInstance().getDisplayHeight();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to set all post data in ModelMap in Spring MVC? I have many input fields in a form to post data to server side.
And in controller, I want to get all attributes in ModelMap like this:
public String save(ModelMap model) {
....
}
I don't want to use @RequestParam since there are so many fields to be sent. I think the data in a form will be posted and saved in ModelMap automatically, but its not working
Could anyone help me?
Thanks.
A: You should use a @ModelAttribute in the form handler
@RequestMapping(value="/submitform", method = RequestMethod.POST)
public String save(@ModelAttribute("mydata") MyData myData) {
//do something with
//myData.getField1();
//myData.getFiled2();
}
and this is how you will send the page to the form
@RequestMapping("/fillform")
public String loadForm(ModelMap model) {
//you could also fill MyData, to do autofill on the html form
model.put("mydata", new MyData());
return "fillform"; //[jsp]view resolver will pick up fillform.jsp
}
A: I am trying to make the same thing. The problem with previous answer is taht the UI is dynamically build by iterating on Map<String, Object>.
So it is not possible to pre define the MyData.class.
I am solving this issue using next approach:
@RequestMapping(value = "/secure/filled", method = RequestMethod.POST)
public String saveFilledData(HttpServletRequest request, ModelMap model) {
request.getParameter("nameOfTheParameter");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery fullcalendar: JSON data not loading in any browser except FF3 I've got a fullcalendar set up on the following url: http://www.forumtheatrebillingham.co.uk/show-calendar.html
It had been working fine, but now something has gone wrong and the data returned by my JSON feed isn't being displayed in the calendar in any browser except FF3.
There are no javascript errors being displayed and monitoring the ajax requests in a console shows them being correctly fetched when the next/last month buttons are pressed.
I'm at a loss to explain why it's not working, can anyone suggest anything?
A: Your JSON is not valid. If you run your response through JSONLint.com, you'll see an error on all of your objects
{
"title" : "",
"start" : "2011-10-23",
"end" : "1970-01-01",
"pagetitle" : "Songs from the Movie Sister Act",
"url" : "songs-from-the-movie-sister-act.html",
"description" : "Mother Superior and the Sisters give an energetic must-see performance. All the hit songs from the two Sister Act movies are included in this show!",
"image" : "/assets/components/phpthumbof/cache/assets_images_shows_Sister Act Artwork.pdf.cdb9fc59e31e0ea8b7440e2a0a1de8e8.jpeg",
"dates" : "23rd Oct 2011",
"color": "green",
} ,
Since color is the last item in the list, it should not be followed by a comma.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JavaScript Closures use global setting object or pass it to each function another question concerning javascricpt closures. I have a global "settings object". Is it better to use it from within functions in global scope or pass the object every time a function needs to access the object?
For a better understanding a little mockup of the situation here
Please ignore that "baz()" also gets the passed object within "foobar()" from the global scope within the closure. You see that both versions work fine.
The thing is that I am passing whatever object the function needs to work to every function and EVERY time (unneccesary overhead?), which might be nice and easy to read/understand but I am seriously thinking about changing this. Disadvantage would be that I have to keep the "this" scope wherever it gets deeper right?
Thanks for your advice!
A: Your settings object isn't global, it's defined within a closure.
As the intent is that it be accessed by other function within the closure, I'd say you were 100% fine to just access that object directly and not pass it as a parameter.
FWIW, even if you did pass it as a parameter the overhead is negligible because only a reference to the object is passed, not a copy of the whole object.
A: So you have basically three options:
*
*You want to expose settings as a global variable, and have it accessed by your functions,
*You want to hide settings as an implementation detail and have it accessed by your functions,
*You want to give a possibility to supply different settings objects to different functions.
Global variable approach
Well, I guess it's a little bit like with any global variable. If settings is a singleton (for example it describes your application) and you can't see any benefit in having a possibility to call the same function with different settings objects, then I don't see why it couldn't be a global variable.
That said, because of all the naming conflicts, in Javascript it's good to "namespace" all the global variables. So instead of global variables foo and bar you should rather have one global variable MyGlobalNamespace which is an objects having attributes: MyGlobalNamespace.foo and MyGlobalNamespace.bar.
Private variable approach
Having a private variable accessed by a closure is a good pattern for hiding implementation details. If the settings object is something you don't want to expose as an API, this is probably the right choice.
Additional function parameter approach
Basically if you see a gain in having a possibility of supplying different settings to different function calls. Or perhaps if you can picture such gain in the future. Obvious choice if you have many instances of settings in your application.
EDIT
As to the question from the comments:
Example 1)
var blah = 123;
function fizbuzz() {
console.log(blah); // <-- This is an example of a closure accessing
// a variable
console.log(this.blah); // <-- Most likely makes no sense. It might work,
// because by default this will be set to a global
// object named window, but this is probably not
// what you want. In other situations this might
// point to another object.
}
Example 2)
var obj = {
blah: 123,
fizbuzz: function() {
console.log(this.blah); // <-- This is *NOT* an example of a closure
// accessing a private variable. It's rather the
// closest Javascript can get to accessing an
// instance variable by a method, though this
// terminology shouldn't be used.
console.log(blah); // <-- This MAKES NO SENSE, there is no variable blah
// accessible from here.
}
};
In a nutshell, I'd encourage you to read some good book on the fundamental concepts of Javascript. It has its paculiarities and it's good to know them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to integrate spring social in Spring Roo What's the simple procedures (step-by-step) to integrate Spring Social in Spring Roo? I am currently using STS. Any help would be appreciated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Using Python, how do I close a file in use by another user over a network? I have a program that creates a bunch of movie files. I runs as a cron job and every time it runs the movies from the previous iteration are moved to a 'previous' folder so that there is always a previous version to look at.
These movie files are accessed across a network by various users and that's where I'm running into a problem.
When the script runs and tries to move the files it throws a resource busy error because the files are open by various users. Is there a way in Python to force close these files before I attempt to move them?
Further clarification:
JMax is correct when he mentions it is server level problem. I can access our windows server through Administrative Tools > Computer Management > Shared Folders > Open Files and manually close the files there, but I am wondering whether there is a Python equivalent which will achieve the same result.
something like this:
try:
shutil.move(src, dst)
except OSError:
# Close src file on all machines that are currently accessing it and try again.
A: This question has nothing to do with Python, and everything to do with the particular operating system and file system you're using. Could you please provide these details?
At least in Windows you can use Sysinternals Handle to force a particular handle to a file to be closed. Especially as this file is opened by another user over a network this operation is extremely destabilising and will probably render the network connection subsequently useless. You're looking for the "-c" command-line argument, where the documentation reads:
Closes the specified handle (interpreted as a hexadecimal number). You
must specify the process by its PID.
WARNING: Closing handles can cause application or system instability.
And if you're force-closing a file mounted over Samba in Linux, speaking from experience this is an excruciating experience in futility. However, others have tried with mixed success; see Force a Samba process to close a file.
A: As far as I know you have to end the processes which access the file. At least on Windows
A: The .close() method doesn't work on your object file?
See dive into Python for more information on file objects
[EDIT] I've re-read your question. Your problem is that users do open the same file from the network and you want them to close the file? But can you access to their OS?
[EDIT2] The problem is more on a server level to disconnect the user that access the file. See this example for Windows servers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Boost message_queue: just the constructor lets me configure it, no other member functions available This is a classic Boost message_queue example:
#include <boost/interprocess/ipc/message_queue.hpp>
using namespace boost::interprocess;
struct Data { ... };
int main() {
Data data1;
message_queue::remove("message_queue");
message_queue mq(create_only, "message_queue", 100, sizeof(Data));
mq.send(&data1, sizeof(Data), 0);
}
Now I would like to put the mq message_queue object inside a class as a member variable, with the lifetime of this class' object:
#include <boost/interprocess/ipc/message_queue.hpp>
using namespace boost::interprocess;
struct Data { ... };
class DataManager
{
message_queue mq;
public:
DataManager()
: mq(create_only, "message_queue", 100, sizeof(Data)) // ok
{
mq.Open(create_only, "message_queue", 100, sizeof(Data)); // Open does not exist
}
};
It seems I can only initialise the mq object in the member initialisation list, since message_queue does not provide the member functions to set its parameters at a later time.
Am I wrong? Is there another way to do it?
I would like to be able, e.g., to let an object use a message queue whose name is passed as a parameter to one of its member functions.
Thank you.
A: How about this :
class QueueManager
{
boost::scoped_ptr<message_queue> mq;
// ctor
QueueManager(string msgqname)
{
mq.reset(new message_queue(create_only, msgqname, 100, sizeof(Data));
}
};
Just to give you an idea that at least some parameters can be passed to class constructor.
Since message queue uses shared memory underneath, I think most parameters can not be changed after construction.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Issue with running a migration on heroku This is a follow up to this post Rails, data structure and performance, where I have attempted to create a Counter Cache on Rails. To not have it to default 0, I have also added updating the column to the existing count value in the database.
Running rake db:migrate on development works fine, even though it took a few hours to run.
But running the migration with heroku is giving me the following error :
== AddVotesCount: migrating ==================================================
-- add_column(:options, :votes_count, :integer, {:default=>0})
-> 0.0196s
/Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/net/http.rb:644:in `initialize': Operation timed out - connect(2) (Errno::ETIMEDOUT)
from /Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/net/http.rb:644:in `open'
from /Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/net/http.rb:644:in `block in connect'
from /Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/timeout.rb:44:in `timeout'
from /Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/timeout.rb:87:in `timeout'
from /Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/net/http.rb:644:in `connect'
from /Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/net/http.rb:637:in `do_start'
from /Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/net/http.rb:626:in `start'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/rest-client-1.6.7/lib/restclient/request.rb:172:in `transmit'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/rest-client-1.6.7/lib/restclient/request.rb:64:in `execute'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/rest-client-1.6.7/lib/restclient/request.rb:33:in `execute'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/rest-client-1.6.7/lib/restclient/resource.rb:51:in `get'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/heroku-2.8.4/lib/heroku/client.rb:554:in `process'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/heroku-2.8.4/lib/heroku/client.rb:532:in `get'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/heroku-2.8.4/lib/heroku/client.rb:290:in `read'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/heroku-2.8.4/lib/heroku/client.rb:311:in `each'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/heroku-2.8.4/lib/heroku/command/run.rb:50:in `rake'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/heroku-2.8.4/lib/heroku/command.rb:114:in `run'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/heroku-2.8.4/bin/heroku:14:in `<top (required)>'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/bin/heroku:19:in `load'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/bin/heroku:19:in `<main>'
I have tried a few different things but seem lost at this point, any help appreciated ! The strange thing is that the error message does not always come up instantly, sometimes it takes 10/20 minutes as if the migration was running.
Thanks
Update : here is the content of my migration file :
class AddVotesCount < ActiveRecord::Migration
def self.up
add_column :options, :votes_count, :integer, :default => 0
Option.all.each do |option|
option.votes_count = option.votes.count
option.save!
end
end
def self.down
remove_column :options, :votes_count
end
end
Update 2 : This works in staging environment with heroku... but not in production
After a few modifications, the migration code is now :
def self.up
add_column :options, :votes_count, :integer, :default => 0
Option.reset_column_information
Option.find_each do |option|
Option.reset_counters option.id, :votes
end
and the error is :
== AddVotesCount: migrating ==================================================
-- add_column(:options, :votes_count, :integer, {:default=>0})
-> 0.0224s
/Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/net/http.rb:644:in `initialize': getaddrinfo: nodename nor servname provided, or not known (SocketError)
from /Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/net/http.rb:644:in `open'
from /Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/net/http.rb:644:in `block in connect'
from /Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/timeout.rb:44:in `timeout'
from /Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/timeout.rb:87:in `timeout'
from /Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/net/http.rb:644:in `connect'
from /Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/net/http.rb:637:in `do_start'
from /Users/ebellity/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/net/http.rb:626:in `start'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/rest-client-1.6.7/lib/restclient/request.rb:172:in `transmit'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/rest-client-1.6.7/lib/restclient/request.rb:64:in `execute'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/rest-client-1.6.7/lib/restclient/request.rb:33:in `execute'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/rest-client-1.6.7/lib/restclient/resource.rb:51:in `get'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/heroku-2.8.4/lib/heroku/client.rb:554:in `process'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/heroku-2.8.4/lib/heroku/client.rb:532:in `get'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/heroku-2.8.4/lib/heroku/client.rb:290:in `read'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/heroku-2.8.4/lib/heroku/client.rb:311:in `each'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/heroku-2.8.4/lib/heroku/command/run.rb:50:in `rake'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/heroku-2.8.4/lib/heroku/command.rb:114:in `run'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/gems/heroku-2.8.4/bin/heroku:14:in `<top (required)>'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/bin/heroku:19:in `load'
from /Users/ebellity/.rvm/gems/ruby-1.9.2-p136/bin/heroku:19:in `<main>'
A: For those who might face the same error, I got in touch with heroku and they told me to run the migration with this:
$ heroku run bash --app appname
then
$ rake db:migrate
For some reason, it worked...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Prevent duplicate records when I save the values into the ComboBox - C# I have been saving into the ComboBox a value out of the selected column in datagridview with below code.
My question is:How can I prevent duplicate records when I save the values into the ComboBox? How can I do that?
Code:
int ColumnIndex = dgUretimListesi.CurrentCell.ColumnIndex;
CmbAra.Text = "";
for (int i = 0; i < dgUretimListesi.Rows.Count; i++)
{
CmbAra.Items.Add(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString());
}
A: Please try this
private void dgvServerList_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
try
{
if (e.ColumnIndex == 1)
{
string id = dgvServerList[e.ColumnIndex, e.RowIndex].Value.ToString();
int duplicaterow = 0;
for (int row = 0; row < dgvServerList.Rows.Count; row++)
{
if (row != e.RowIndex && id == dgvServerList[e.ColumnIndex, row].Value.ToString())
{
duplicaterow = row + 1;
MessageBox.Show("Duplicate found in the row: " + duplicaterow);
this.dgvServerList[e.ColumnIndex, e.RowIndex].Value = "";
break;
}
}
}
}
catch
{
}
}
A: Use a set:
int ColumnIndex = dgUretimListesi.CurrentCell.ColumnIndex;
CmbAra.Text = "";
HashSet<string> set = new HashSet<string>();
for (int i = 0; i < dgUretimListesi.Rows.Count; i++)
{
string s = dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString();
if(!set.Contains(s)) {
CmbAra.Items.Add(s);
set.Add(s);
}
}
A: by using the following check and then determine to add or not
if(CmbAra.Items.Contains(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString()))
A: you could first transfer your datagridview items to a dictionary (which guarantees uniqueness) and then transfer that dictionary content to the combobox. or you could check for uniqueness yourself using a 'Contains' method on the combobox. you could even tie the dictionary to the combobox as a source for the combobox items.
Dictionary<string,bool> d = new Dictionary<string,bool>();
int ColumnIndex = dgUretimListesi.CurrentCell.ColumnIndex;
CmbAra.Text = "";
for (int i = 0; i < dgUretimListesi.Rows.Count; i++)
{
d[dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString()] = true;
}
CmbAra.Items.AddRange(d.Keys);
A: You can use the following code part.
if(!(CmbAra.Items.Contains(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString())))
{
CmbAra.Items.Add(dgUretimListesi.Rows.Cells[ColumnIndex].Value.ToString());
}
else
{
MessageBox.Show("Value Already exists , not added");
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Parameters of AMDeviceInstallApplication function() Can anyone tell me the parameters of AMDeviceInstallApplication function() in iTunesMobileDevice.dll?
A: AMDeviceInstallApplication(IntPtr sockInstallProxy, IntPtr cfStrPath, IntPtr opts, CallBack callback, IntPtr unknow);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NSThread stop / pause I have created a NSThread instance in my app. After some point I want to pause it. Is there any way how to do that. I tried doing,
if(![myThread isFinished]) {
myThread = nil;
}
but still i m not able to stop that thread.
A: [NSThread sleepForTimeInterval:TIME_TO_PAUSE_THREAD];
OR
YOu have to use NSOperation queue for same
Following link may be usefull to you
http://developer.apple.com/library/ios/#samplecode/ThreadedCoreData/Listings/Classes_ParseOperation_h.html#//apple_ref/doc/uid/DTS40010723-Classes_ParseOperation_h-DontLinkElementID_5
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: VS2010 takes long time to show a project properties I have Visual Studio 2010 Ultimate installed on my super machine (8 Xeon Processors, 12GB Ram, ...). My problem is that VS2010 takes a long time to open any project properties!!
Does any one knows a fix to this problem?!
Thanks in advance.
A: I found the solution!! You just need to delete the solution *.suo files, it seems they got corrupt!!
After I did that everything returned to normal again, even the solution build process is now several times faster!! :D
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Wrap large text in PHP I want to break a line after certain number of characters like after some 20 characters it should break line after nearest full stop(.) in PHP.
I have a text like this:
A Paragraph follows like "Our Customer service dept. will help you
with any issue you might have. Buyer is responsible for return
shipping. We offer free UPS or USPS ground shipping to the continental
U.S. We ship within 1 business day of payment. All other shipping
rates apply (see auction of item purchased for details). All orders
get a UPS or USPS tracking number.
This is what I've tried so far:
$desc = $listings['Item']['Description'];
echo wordwrap($desc,250,"<br />\n");
A: Use wordwrap() to wrap your string before a given number of characters. If you want to split by dot (.), you can do something with explode() and implode().
A: I think regex is the easiest way to give you what you want. Considering this question, I'm pretty positive you either never heard of it or don't know how it works, at all.
Because it's pretty complicated, I'm willing to help you out until you manage it to work exactly the way you want.
I have ran some tests and this works for me.
echo preg_replace('/(\.{20}?|.{10,20}?\. )/', '$1<br />', $desc);
This single line of code puts break tags either when 20 characters is reached or when there's a dot followed by a space if there are more than 10 characters before to avoid single word lines.
The example text you gave would go from:
A Paragraph follows like "Our Customer service dept. will help you with any issue you might have. Buyer is responsible for return shipping. We offer free UPS or USPS ground shipping to the continental U.S. We ship within 1 business day of payment. All other shipping rates apply (see auction of item purchased for details). All orders get a UPS or USPS tracking number.
to:
A Paragraph follows like "Our Customer service dept.<br />
will help you with any issue you might have.<br />
Buyer is responsible for return shipping.<br />
We offer free UPS or USPS ground shipping to the continental U.S.<br />
We ship within 1 business day of payment.<br />
All other shipping rates apply (see auction of item purchased for details).<br />
All orders get a UPS or USPS tracking number.
Let me know if this is the way you want it!
A: <?php
$text = "Our Customer service dept. will help you with any issue you might have. Buyer is responsible for return shipping. We offer free UPS or USPS ground shipping to the continental U.S. We ship within 1 business day of payment. All other shipping rates apply (see auction of item purchased for details). All orders get a UPS or USPS tracking number.";
$textTrimmed = substr($text, 20) // The number of chars
echo $textTrimmed
?>
or you can use a function
function trimTextAfter($text, $numberOfChar){
echo substr($text,$numberOfChar);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Some space between divs in line I want to build 'rubber' interface, so I use div with width in %, but when I try to fill 100% of width with several divs, they not intermix on line, but in suome they have 100%. If use table then all fine. Here are examples:
<div style='white-space:nowrap;'>
<div style='width:50%;border: 1px solid #4e5e6e;display:inline-table;'>A1</div>
<div style='width:50%;border: 1px solid #a2f2d4;display:inline-table;'>A2</div>
</div>
<div style='white-space:nowrap;'>
<div style='width:10%;border: 1px solid #4e5e6e;float:left'>A1</div>
<div style='width:40%;border: 1px solid #a2f2d4;float:left'>A2</div>
<div style='width:40%;border: 1px solid #4e5e6e;float:left'>A3</div>
<div style='width:10%;border: 1px solid #a2f2d4;float:left'>A4</div>
</div>
<table style='width:100%'><tr style="width:100%";>
<td style='width:10%;border: 1px solid #4e5e6e;'>A1</td>
<td style='width:40%;border: 1px solid #4e5e6e;'>A1</td>
<td style='width:40%;border: 1px solid #4e5e6e;'>A1</td>
<td style='width:10%;border: 1px solid #4e5e6e;'>A1</td>
</td></table>
If size of you window is enough, they all will appear right, but if you make it smaller, someone jump off their line.
If I do not clearly expressed, I want to display div in a single line in not depending on the width.
A: The 1px border adds to the width of the boxes. So your boxes will have a width of 50%+1px, 10%+1px and so on.
A: the solution would be to remove the pixel from the border and put a div inside the % width div with a border
A: What lucassp said.
A solution would be to add a negative margin to anything you gave a border:
<td style='width:10%;border: 1px solid #4e5e6e; margin: -1px;'>A1</td>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DebugBreak in Unix/ Linux? Do we have similar windows API of DebugBreak in Unix/ Linux. I want to debug a daemon process which should open NetBeans when DebugBreak statement is executed. Thanks in advance.
A: there is __builtin_trap() GCC intrinsic.
A: Whav! this is what I am looking for Embedded break points in C http://mainisusuallyafunction.blogspot.in/2012/01/embedding-gdb-breakpoints-in-c-source.html and to get sample program have a look in to https://github.com/kmcallister/embedded-breakpoints
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Reading text from an external applications textbox I am trying to extend some features of a external programm that is not able to use plugins or something. So I have to write my own app that reads the text from a textbox from this external application and trigger some own actions.
By using the FindWindow API in user32.dll I allready catched up the handle for the external application. But now I am kind of stuck. By using Spy++ from the Visual Studio Tools I got the information that the class name from the control I would like to read from is "WindowsForms10.EDIT.app.0.218f99c", but there are several of them. Additionally every time the external app starts it creates a new control id for the textbox I want to read.
How can I get it managed to identify a certain textbox and read the value of it? Can anybody give me a hint or kind of advice?
A: The Code in C#
public static class ModApi
{
[DllImport("user32.dll", EntryPoint = "FindWindowA", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll", EntryPoint = "SendMessageTimeout", SetLastError = true, CharSet = CharSet.Auto)]
public static extern uint SendMessageTimeoutText(IntPtr hWnd, int Msg, int countOfChars, StringBuilder text, uint flags, uint uTImeoutj, uint result);
[DllImport("user32.dll", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
static internal extern bool EnumChildWindows(IntPtr hWndParent, funcCallBackChild funcCallBack, IntPtr lParam);
public delegate bool funcCallBackChild(IntPtr hWnd, IntPtr lParam);
public static ArrayList TextBoxStrings = new ArrayList();
public static void ParseWindowControls(string WindowTitle)
{
IntPtr hWnd = FindWindow(null, WindowTitle);
TextBoxStrings.Clear();
funcCallBackChild MyCallBack = EnumChildWindowsProc;
EnumChildWindows(hWnd, MyCallBack, IntPtr.Zero);
}
private static bool EnumChildWindowsProc(IntPtr hWndParent, IntPtr lParam)
{
var buffer = new StringBuilder(256);
long Retval = GetClassName(hWndParent, buffer, buffer.Capacity);
if (buffer.ToString() == "Edit" || buffer.ToString() == "Static")
{
TextBoxStrings.Add(GetText(hWndParent));
}
return true;
}
private static string GetText(IntPtr hwnd)
{
var text = new StringBuilder(1024);
if (SendMessageTimeoutText(hwnd, 0xd, 1024, text, 0x2, 1000, 0) != 0)
{
return text.ToString();
}
return "";
}
}
A: After stumbling through several pages I found the solution how to retrieve the contents from a textbox from an external application. I think this code could be usefull for others too, so here is the result:
Module modApi
Private Declare Function FindWindow Lib "user32.dll" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As IntPtr
Private Declare Function GetClassName Lib "user32.dll" Alias "GetClassNameA" (ByVal hwnd As IntPtr, ByVal lpClassName As String, ByVal nMaxCount As Long) As Long
Private Declare Function SendMessageTimeoutString Lib "user32.dll" Alias "SendMessageTimeoutA" (ByVal hwnd As IntPtr, ByVal msg As Long, ByVal wParam As Long, ByVal lParam As String, ByVal fuFlags As Long, ByVal uTimeout As Long, ByVal lpdwResult As Long) As Long
Friend Declare Function EnumChildWindows Lib "user32.dll" (ByVal hWndParent As IntPtr, ByVal funcCallBack As funcCallBackChild, ByVal lParam As IntPtr) As Boolean
Public Delegate Function funcCallBackChild(ByVal hWnd As IntPtr, ByVal lParam As IntPtr) As Boolean
Public TextBoxStrings As ArrayList = New ArrayList
Public Sub ParseWindowControls(ByVal WindowTitle As String)
Dim hWnd As IntPtr = FindWindow(vbNullString, WindowTitle)
TextBoxStrings.Clear()
If hWnd Then
Dim MyCallBack As New funcCallBackChild(AddressOf EnumChildWindowsProc)
EnumChildWindows(hWnd, MyCallBack, IntPtr.Zero)
Else
MsgBox("Could not find window!", vbOKOnly + vbExclamation, "Error")
End If
End Sub
Private Function EnumChildWindowsProc(ByVal hWndParent As IntPtr, ByVal lParam As IntPtr) As Boolean
Dim Buffer As String = Space(256)
Dim Retval As Long = GetClassName(hWndParent, Buffer, Len(Buffer))
If Left(Buffer, Retval) = "WindowsForms10.EDIT.app.0.218f99c" Then
TextBoxStrings.Add(GetText(hWndParent))
End If
EnumChildWindowsProc = True
End Function
Private Function GetText(ByVal hwnd As IntPtr) As String
Dim sText As String = Space(1024)
If SendMessageTimeoutString(hwnd, &HD, 1024, sText, &H2, 1000, 0) <> 0 Then
GetText = Left(sText, InStr(sText, vbNullChar) - 1)
Exit Function
End If
GetText = ""
End Function
End Module
You can pass a window title to the sub ParseWindowControls(). The sub tries to find the requested window. If the window is found it begins to gather all controls found in this application. The callback examines the found control if it meets my specifications (textbox) and stores the text in a arraylist. Later you just have to know the index of your requestet textbox and get it out of the arraylist. That's it. Hope this helps others too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: LINQ CSV Database - Quick way for except I have a pair CSV Files.
CSV1 :
Option Number , Product Number , Product Name
CSV2 :
Product Number , Product Details , Product Details
The number of records is very high , number of files (pairs generated weekly) is also very high.
CSV2 will have some of the Product details , manually the Product Details are entered.
How can I :
1.Re Generate CSV1 to have only those Product Number (and Option and Name) for those Products whose details do not exist in CSV2
Tried LINQ to CSV from code project , able to read / write fine
but the EXCEPT part takes a lot of time.
var query =
from c in dc.Customers
where !(from o in dc.Orders
select o.CustomerID)
.Contains(c.CustomerID)
select c;
This is the equivalent , but still too slow.
How can I trim all the fields retrieved using the query.
If I am to set the type to int - Product Number.
That should help. Please provide your feedback. I can provide the code.
But it is mostly based on LINQTOCSV from codeproject.
A: You could load the product numbers from CSV2 in a hashset and then your where clause could become:
where !hashSet.Contains(productID)
which performance should be better (O(1))
A: Products from both files select to dictionaries, where key is product number and then compare, it will be faster.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I capture the post parameters from a server file using ajax in jquery? I have
datestring ="name=one"
$.ajax({
type: "POST", url: 'url.com', data:datastring,
complete: function(data){
alert(data);
} ,
success:function() { alert("success"); },
})
});
I use ajax to send the datastring to url.com. However url.com redirects the page to the initial one together with some post parameters..How can I retrieve those parameters using ajax ?
A: You have an error in your code, because e forgot to put the semicolon ';':
$.ajax({
type: "POST",
url: 'url.com',
data:{
name: 'one'
},
complete: function(data){
alert(data);
},
success:function() {
alert("success");
},
});
Other think, it's about the data, the above example method it's better.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Calendar with Outlook like functionality I am trying to do the following for managing appointments.
When the user opens the app, show him a calendar control which will fetch his schedule from the sql server database. If the user is scheduled to meet Mr. A,X and Z on 15th, then the calendar control should display three links in that calendar for that particular day. Clicking on these links will take the user to the details of the person he is supposed to meet. Similarly do for other dates too.
I can use ASP.NET, AJAX, jQuery anything. Are you aware of any existing project or code that exists for the same?
A: a fully existing project you will not find no,
but you can however use jquery and its vast plugin database for some of your front end functionalities.
however this would just be a small help, as you would still need to do many manual coding,
this just shows a calendar with data. if you provide the data of course.
all server side code would still be your work and possibly the custom front end stuff too, login system, clicking the link opening the calendar on the right spot. etc etc.
if you are interested in doing it this way,
here is a hand full of calendar plugins you could use
*
*ical calendars
*Plans
*FullCalendar
these are just a few, you can find many more on the net
if you choose not to take this path, there are probably serverside controls you could use,
like telerik's rad Calendar, of course this option comes with a price. i have no knowledge of free alternatives (and defenately not whether those are as flexible as previously mentioned solutions)
A: telerik.com RadScheduler. I use it alot and its pretty good an flexible. You can do your links scenario with either their Appointment Template or the new jQuery templates.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Replace text using sed i am having trouble replacing the modified date in my script via sed.
I am getting the last modified date like this:
olddate=`grep -m1 "Built " script.sh | cut -c 22-29`
I get the current date with:
newdate=`date +%d/%m/%y`
Basically i want to replace old date with new date
sed -i "" "s/$olddate/$newdate/g" script.sh
But this doesn't work as the date contains slashes. I've looked around and i can't find the way to escape them properly. Any help would be appreciated.
A: You can use separators other than slashes, for instance ";"
sed -i "" "s;$olddate;$newdate;g" script.sh
A: Use , instead of / !
sed -i "" "s,$olddate,$newdate,g" script.sh
In fact you can use almost any char as separators.
A: use sed "s#$olddate#$newdate#g"
that should work
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Alignment one cell in h:panelGrid How to align a particular cell inside a h:panelGrid in jsf 2.0. I am able to align whole table by adding style in the h:panelGrid. But I need only one cell to be aligned center.
Thanks
Brajesh
A: If you want to say that you need only one column (through the word cell) to be aligned center, use columnClasses
<h:panelGrid columns="3" columnClasses="basicStyle, centerStyle, basicStyle"
CSS
.basicStyle {
/*text-align: inherit; optinal*/
}
.centerStyle{
text-align: center;
}
Edit: Align only one cell
Declare a new grid just for the cell you want to align:
<h:panelGrid columns="2" width="800px">
<h:outputText value="#test" />
<h:outputText value="#test" />
<h:panelGrid columnClasses="centerStyle" width="100px">
<h:outputText value="#test" />
</h:panelGrid>
<h:outputText value="#test" />
<h:outputText value="#test" />
<h:outputText value="#test" />
</h:panelGrid>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Plain JS countdown with repeat and delay I keep running into several issues when creating a countdown script
*
*it does not run smoothly
*hard to make it repeat (closure)
*hard to delay the start and to delay the repeat (closure)
Can someone please help me FIX this code which should work in my opinion but doesn't
the processing I need is
a. counter starts delay number of seconds after the page loads,
b. when counter reaches 0, the countdown RE-starts after delay number of seconds
Here is my Fiddle
Issues:
*
*when it starts, the counter seems to wait an additional second before counting down
*it does not pause
*the repeat starts after the counter has continued
.
// more accurate timer - https://gist.github.com/1185904
function interval(duration, fn){
this.baseline = undefined
this.run = function(){
if(this.baseline === undefined){
this.baseline = new Date().getTime()
}
fn()
var end = new Date().getTime()
this.baseline += duration
var nextTick = duration - (end - this.baseline)
if(nextTick<0){
nextTick = 0
}
(function(i){
i.timer = setTimeout(function(){
i.run(end)
}, nextTick)
}(this))
}
this.stop = function(){
clearTimeout(this.timer)
}
}
window.onload=function() {
var cnt1 = 10;
var delay1 = 5;
var timer1 = new interval(1000, function(){
document.getElementById('out1').innerHTML=cnt1--
if (cnt1 <= 0) { // trying to reset
timer1.stop(); // does not work
cnt1 = 10;
setTimeout(function() { timer1.run()},delay1*1000)
}
})
setTimeout(function() { timer1.run()},delay1*1000)
}
A: I've rewritten your code to produce the desired results. Your previous code was very inefficient. See my script comments for usage.
Fiddle: http://jsfiddle.net/RVBDQ/1/
/*
@name timer
@param number startFrom Starts counting down from this number
@param number delay Seconds to wait before repeating the counter
@param number intervalDelay Milliseconds between countdown
@param number runTimes Optional; Limit of counting. The function stops when it has run <runTimes> times. Default 1 (=one countdown)
@param Boolean noFirstRun Optional; If false, the counter starts off immediately. Default false
*/
function timer(startFrom, delay, intervalDelay, runTimes, notFirstRun){
if(typeof runTimes == "undefined") runTimes = 1;
if(runTimes-- < 0) return;
setTimeout(function(){
var ctn = startFrom;
var timer1 = window.setInterval(function(){
document.getElementById('out1').innerHTML = ctn--;
if(ctn <= 0){
clearInterval(timer1);
timer(startFrom, delay, intervalDelay, runTimes, true);
}
}, intervalDelay);
}, notFirstRun?delay*1000:0);
}
window.onload=function() {
timer(10, 5, 1000, 2);
//Runs two times, starts counting from 10 to 1, delays 5 seconds between counters.
}
A: Object exposing start([delay]) and stop().
http://jsfiddle.net/RVBDQ/3/
function interval(duration, fn, delay){
this.timer = null;
this.duration = duration;
this.fn = fn;
this.start(delay);
}
interval.prototype.start = function(delay){
if (this.timer) {return;}
var self=this;
this.timer = setTimeout(function(){ self.run(); }, delay||0);
};
interval.prototype.run = function(called){
var self = this,
nextTick = called ? this.duration - (new Date - called) : 0;
this.timer = setTimeout(function(){
self.fn();
self.run(new Date);
}, nextTick<0 ? 0 : nextTick);
};
interval.prototype.stop = function(){
clearTimeout(this.timer);
this.timer = null;
};
window.onload = function() {
var cnt1 = 10;
var delay1 = 5;
window.timer1 = new interval(1000, function(){
document.getElementById('out1').innerHTML=cnt1;
cnt1 = cnt1 === 1 ? 10 : cnt1-1;
}, delay1*1000);
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Need help with zend framework paginator I wanted to generate a table with dymanic columns and rows
Example if i have a array of
1.1, 1.2, 1.3, 1.4
2.1, 2.2, 2.3, 2.4
3.1, 3.2, 3.3, 3.4
Currently is displaying 1.1 1.2 1.3 1.4
then 2.1 2.2 2.3 2.4 ...etc
but I wanted to display 1.1 ,2.1, 3.1
then 1.2 2.2 2.3 ... etc
Rather then display all the row values for that particular row. I wanted to display all the column values at once.
In c++ i know you have to use nested for loop in order to achieve this
for (int i=0; i< col_size; i++)
{
for (int j=0; j < row_size; j++)
{
cout << a[i][j];
}
}
But how can it be done using Zend framework plus im also using zend paginator
Is there any method I can use to determine the column size?
My Current code is
<div class ="outcome">
<?php
foreach($this->paginator as $row){
$this->providerSearchResults($row); // using custom helper
}
echo '</ul>';
$params = array('location' => $this->location,'industryType' => $this->industryType); // used to pass to the paginationcontrol
echo $this->paginationControl($this->paginator,'Sliding','paginationcontrol.phtml',$params);
</div>
My custom helper
public function providerSearchResults($row)
{
echo $row['businessName']
echo $row['cpuPrice']
echo $row['hdPrice'];
.....
echo $row['ramPrice];
}
Thanks so much!
A: You Can Use A Nested for loop in Php As well How ever You have an option of vprintf, printf or fprintf as well.. wheich u can use inside a forloop like
forloop
printf("%d%d%d",i)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Flex MX:HTML handling errors and loading problems I have a simple mx:html that load a page.. I'd like to show a popup when there is a problem loading the page...
How can I handle this event? I have not find anything useful on the web :(
A: mx:html is based on htmlloader, and unfortunately you cannot read HTTP headers using this object, so you cannot read the HTTP status. Several workarounds are:
a)use an urloader before the htmlloader and check the HTTP status
b)you can read the html page content with yourhtmlcontrol.htmlloader.window.document. If it's a known page you can detect if the page content corresponds with some status.
I think that a) is more reliable than b).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is adding a tickbox that does nothing !ifempty bad or clever? I have a very bespoke system that we will use internally to track payments.
I have an input box, and if the user leaves it blank (Does not know X), it inserts "Awaiting X" into a database instead of the X.
The idea i have to stop the user fill in either variations of NONE or N/A or some random string of text all the time is that they click a tick box "Not known yet?" and it addes 0.4 opacity to it with jQuery or something - therefore leaving it blank.
Is this bad practice or clever mini-validation?
I welcome any clever ideas for this..
A: On the database side
It is good practice to use null (not the string 'null', but the database concept null). Into a database to signal the fact that there is no data.
So I would advice not to use 'awaiting this or that', but just use null.
In a database you can select these rows like so:
SELECT * FROM table1 WHERE name IS NULL
On the UI side
I like your idea.
Do do hope that if and when I select the editbox, I can just fill something in without having to untick the checkbox by hand.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ThreadLocal<> and memory leak .Net 4. ThreadLocal<> implements IDisposable. But it seems that calling Dispose() doesn't actually release references to thread local objects being held.
This code reproduces the problem:
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
namespace ConsoleApplication2
{
class Program
{
class ThreadLocalData
{
// Allocate object in LOH
public int[] data = new int[10 * 1024 * 1024];
};
static void Main(string[] args)
{
// Stores references to all thread local object that have been created
var threadLocalInstances = new List<ThreadLocalData>();
ThreadLocal<ThreadLocalData> threadLocal = new ThreadLocal<ThreadLocalData>(() =>
{
var ret = new ThreadLocalData();
lock (threadLocalInstances)
threadLocalInstances.Add(ret);
return ret;
});
// Do some multithreaded stuff
int sum = Enumerable.Range(0, 100).AsParallel().Select(
i => threadLocal.Value.data.Sum() + i).Sum();
Console.WriteLine("Sum: {0}", sum);
Console.WriteLine("Thread local instances: {0}", threadLocalInstances.Count);
// Do our best to release ThreadLocal<> object
threadLocal.Dispose();
threadLocal = null;
Console.Write("Press R to release memory blocks manually or another key to proceed: ");
if (char.ToUpper(Console.ReadKey().KeyChar) == 'R')
{
foreach (var i in threadLocalInstances)
i.data = null;
}
// Make sure we don't keep the references to LOH objects
threadLocalInstances = null;
Console.WriteLine();
// Collect the garbage
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
Console.WriteLine("Garbage collected. Open Task Manager to see memory consumption.");
Console.Write("Press any key to exit.");
Console.ReadKey();
}
}
}
Thread local data stores a reference to a large object. GC doesn't collect these large objects if references are not nulled manually. I used Task Manager to observe memory consumption. I also run memory profiler. I made a snapshot after garbage was collected. The profiler showed that leaked object is rooted by GCHandle and was allocated with here:
mscorlib!System.Threading.ThreadLocal<T>.GenericHolder<U,V,W>.get_Boxed()
mscorlib!System.Threading.ThreadLocal<T>.get_Value()
ConsoleApplication2!ConsoleApplication2.Program.<>c__DisplayClass3.<Main>b__2( int ) Program.cs
That seems to be a flaw in ThreadLocal<> design. The trick with storing all allocated objects for further cleanup is ugly. Any ideas on how to work around that?
A: The memory has probably been garbage collected but the CLR process hasn't let go of it yet. It tends to hold onto allocated memory for a bit in case it needs it later so it doesn't have to do an expensive memory allocation.
A: Running on .Net 4.5 DP, I don't see any difference between pressing R or not in your application. If there actually was a memory leak in 4.0, it seems it was fixed.
(4.5 is a in-place update, so I can't test 4.0 on the same computer, sorry.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: How to learn the link between C++ code and the generated assembly code? My question is specifically for Windows C++ compilers and Visual Studio, but I got offered to interview for a job in finance where they wanted somebody very technical to write real-time multi-threaded code who could analyse at assembly level the code generated by a C++ compiler.
What are the methods one can apply to learn the link between C++ code and the generated assembly and achieve this level of proficiency ?
A: The simple answer to this is., To compile code and look at it in the debugger.
Debuggers will show you connection between the two in a very harsh way. The next step is to understand compiler theory and then look at the source code of compilers to understand what they try and do.
I think the person interviewing you may have been trying to see if you can understand what kind of effort is involved - rather than actually knowing how to do it.
A: The first thing to do would be to learn the assembler and machine code.
There is some very good documentation of the machine code available at
the Intel site (although it may be more detailed than you need). There
are two common assembler formats in widespread use: the one used by
Microsoft is based on the original Intel assembler, where as g++ uses
something completely different (based on the original Unix assembler for
PDP-11), so you'll have to choose one (although the assembler syntax
itself is rarely a real problem—knowing what the individual
instructions do is more important).
Once you have some idea of how to read assembler: most compilers
have options to output assembler: for VC++, use /Fa (and /c as well,
if you don't want to actually link the results); for g++, -S (which
causes the compiler to stop once it has generated the assembler. In the
case of VC++, the assembler will be in a file xxx.asm (where xxx.cpp
was the name of the file being compiled), for g++, xxx.s. Try
compiling some code, with different levels of optimization, and then
look at the assembler in an editor.
Finally, if the question is asked, it's probably because the interviewer
is concerned about performance issues; what he's really interested in is
whether you know the relative cost of various operations (or the risks
involved when multithreading; e.g. what operations are atomic, etc.) In
which case, it probably wouldn't hurt to point out that issues like
locality (which determines the percent of cache hits) are often more
important that the individual operations.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Json.net serialization of custom collection implementing IEnumerable I have a collection class that implements IEnumerable and I am having trouble deserializing a serialized version of the same. I am using Json.net v 4.0.2.13623
Here is a simplier version of my collection class that illustrates my issue
public class MyType
{
public int Number { get; private set; }
public MyType(int number)
{
this.Number = number;
}
}
public class MyTypes : IEnumerable<MyType>
{
private readonly Dictionary<int, MyType> c_index;
public MyTypes(IEnumerable<MyType> seed)
{
this.c_index = seed.ToDictionary(item => item.Number);
}
public IEnumerator<MyType> GetEnumerator()
{
return this.c_index.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
public int CustomMethod()
{
return 1; // Just for illustration
}
}
When I serialize it i get the following json
[
{
"Number": 1
},
{
"Number": 2
}
]
But then when i try to deserialize i get the following exception
System.Exception: Cannot create and populate list type MyTypes
Have also tried using serialization hints but have had no success
These are the test function i have used
public void RoundTrip()
{
var _myTypes1 = new MyTypes(new[] { new MyType(1), new MyType(2) });
var _jsonContent = JsonConvert.SerializeObject(_myTypes1, Formatting.Indented);
var _myTypes2 = JsonConvert.DeserializeObject<MyTypes>(_jsonContent);
}
public void RoundTripWithSettings()
{
var _myTypes1 = new MyTypes(new[] { new MyType(1), new MyType(2) });
var _serializationSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Arrays };
var _jsonContent = JsonConvert.SerializeObject(_myTypes1, Formatting.Indented, _serializationSettings);
var _myTypes2 = JsonConvert.DeserializeObject<MyTypes>(_jsonContent, _serializationSettings);
}
Has anybody managed to serialize their own collection objects ?
Thanks in advance
Pat
A: I believe JSON .NET depends on having a parameterless constructor for the types it deserializes to. From a deserialization point of view it has no idea what to provide to the constrcutor.
As for your collection, again how is it supposed to know how to populate an implementation of IEnumerable<T> which only defines how to enumerate the collection not how to populate it. You should instead deserialize directly to some standard IEnumerable<MyType> (or directly to IEnumerable<MyType> which I believe JSON.NET supports) and then pass it to your constructor.
I believe all of the following should work in this case:
var _myTypes2 = new MyTypes(JsonConvert.DeserializeObject<MyTypes[]>(_jsonContent));
var _myTypes2 = new MyTypes(JsonConvert.DeserializeObject<List<MyTypes>>(_jsonContent));
var _myTypes2 = new MyTypes(JsonConvert.DeserializeObject<IEnumerable<MyTypes>>(_jsonContent));
Alternatively, though more work, if you need to deserialized directly you can implement something like IList on your collection which should allow JSON.NET to use the IList methods to populate your collection.
A: As of Json.NET 6.0 Release 3 and later (I tested on 8.0.3), this works automatically as long as the custom class implementing IEnumerable<MyType> has a constructor that takes an IEnumerable<MyType> input argument. From the release notes:
To all future creators of immutable .NET collections: If your collection of T has a constructor that takes IEnumerable then Json.NET will automatically work when deserializing to your collection, otherwise you're all out of luck.
Since the MyTypes class in the question has just such a constructor, this now just works. Demonstration fiddle: https://dotnetfiddle.net/LRJHbd.
Absent such a constructor, one would need to add a parameterless constructor and implement ICollection<MyType> (instead of just IEnumerable<MyType>) with a working Add(MyType item) method. Json.NET can then construct and populate the collection. Or deserialize to an intermediate collection as in the original answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: Javascript Regular Expression Problem str = 'autocomplete=\\\"off\\\" name=\\\"composer_session_id\\\" value=\\\"1557423901\\\" \\\/>\\u003cinput type=\\\"hidden\\\" autocomplete=\\\"off\\\" name=\\\"is_explicit_place\\\" id=\\\"u436754_5\\\"';
or use this string
session_id\":1557423901,\"include_source\":\"web_composer\",\"allow_cities\":true},\"bootstrapEndpoint\":\"\\\/ajax\\\/places\\\/typeahead.php\"});},\"j4e8191ff7ff1878042874292\":function(){return new Typeahead(JSCC.get('j4e8191ff7ff1878042874291'), {node_id: \"u436754_1\",
i want that str.match() return value of composer_session_id which is "1557423901" and also the id of is_explicit_plac which is "u436754_5".
How to get "1557423901" and "u436754_5" using JavaScript regex.match() or split or else?
Note: It's guaranteed that name will precede value in each case.
A: Since JavaScript doesn't have lookbehinds, I wrote this snippet that matches 'attribute=\\\"value\\\"' then removes the 'attribute=\\\" and \\\" parts.
var matches = str.match(/(?:name|id|value)=\\".*?\\"/g);
for (var key in matches)
matches[key]=matches[key].replace(/.*?\\"(.*?)\\"/,"$1");
Enjoy!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: TabGroupActivity startChildActivity - pause currentActivity Extending TabGroupActivity, when I start a new childActivity:
public void startChildActivity(String Id, Intent intent) {
Window window = getLocalActivityManager().startActivity(Id,
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
activityIdList.add(Id);
setContentView(window.getDecorView());
}
}
How can I put the current activity into the pause state?
Because after I start a child activity in this way, when I restart it, then the on create method is run. How can I avoid this?
Found one solution is to use another flag:
Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
but not sure if it is the best solution
P.P.S
Another solution is to add an boolean intent to the startChildActivity method:
public void startChildActivity(String Id, Intent intent) {
intent.addExtra("resume", true);
Window window = getLocalActivityManager().startActivity(Id,
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
activityIdList.add(Id);
setContentView(window.getDecorView());
}
}
and then retrieve it from the child activity and check if the activity is restarted or not
A: Try putting this in activity tag in the manifest file
android:launchMode="singleTask"
It should look something like this
<activity android:name=".dashboard.DashboardActivity" android:screenOrientation="portrait"
android:launchMode="singleTask"/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Recommendation for Optimum Template Engine for Python Web Dev in a Particular Use Case For Python Web Development, there is a large selection of template engines. My work is limited to a fairly narrow/specific set of use cases. A description of these might suggest to someone who has a working knowledge with many/most of them, that one of them is better suited for my particular use cases. In other words, there might be one among this group that was optimized against a spec close to my own use case, if so i would like to know what it is.
Here are the criteria that describe those uses cases:
*
*server-side language is python, but i hope that i don't need a lot
of python expressions in my templates
*i will use it with the python web servers CherryPy and (likely)
Twisted
*jQuery is is the language in which the data display
libraries/plug-ins are written
*the templates describe abstract web pages used for data display
(BI Dashboard, is a fair description) once the server delivers the data to the
template (in response to form selections submitted on an antecedent
page) i just want to display the data in a grid, e.g., the jQuery
plug-in jqgrid, or in a plot, e.g., one of the standard types in
Flot
*performance is critical, but the scope is very narrow--only for a
data handling and rendering--i expect grids will often be populated
with several thousand data rows (though the grid itself will be
paginated); likewise, the plots could easily have a thousand or so
data points, though again, the pre-processing and computation will be
done elsewhere
*very little need for a rich syntax (no need for complex multi-way
branching, etc.)--i prefer to do any processiong/computation on the
server (and again, data filtering will almost always be done by the
jQuery plugin i use to render the data)
*likewise, the user's interaction with the displayed data is through
native elements supplied by the jQuery plug-in (e.g., page up/down,
sort, etc.)
*a "designer-friendly" template is not really important (not because i
don't like designers, but because the design effort required should
be low enough so that i even i can do it.
A: If your templating requirements are really simple, then I suggest you to use Python's builtin String Formatting engine...
A: You may want to take a look at Jinja2. It offers precompilation of templates, allows familiar Python syntax and is framework-agnostic.
A: Mako, Jinja2, Cheetah and the Django template engine all do this. For that matter, anything on this list will work, also: http://wiki.python.org/moin/Templating
None of the requirements is particularly interesting. They don't point to any product because they're very general.
Except this, which doesn't belong.
likewise, the user's interaction with the displayed data is through native elements supplied by the jQuery plug-in (e.g., page up/down, sort, etc.)
This is irrelevant. No user can ever interact with the template. They interact with a web page that provides data to the template.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Session variable fetched into a local var changes when operating on the local one i noticed a strange behaviour when interacting with session variables in Django.
In one of my app i created a middleware.py file containing a function that copy a session variable that stores an object into a local one and then i change an attribute of the object from the local var. It happens that the changes i make to the local variable are applied also to the session variable. It seems that the local var is only a reference to the session. Is this behaviour correct?
Here's the code:
class CloudMiddleware(object):
user = request.session['user']
user.email = 'myemail'
When i do
user = request.session['user']
email = user.email
The value of email is equal to 'myemail'.
I always thought i had to save my object back in the session if i want to store it. Could someone explain me how it really works?
A: user is a mutable object, so it's passed by reference. Anything is correct.
A: This is nothing to do with sessions, but a simple consequence of how Python mutable objects work. When you do user = request.session['user'] you are getting a reference to the object, exactly as you would with any other mutable object stored in a standard dictionary. So yes, when you change one of its attributes, that change is referenced in any other reference you have to it.
Note that for sessions, this change will only be persisted in the lifetime of the current request. That's because Django can't know the session object has changed, so won't save it unless you specifically tell it to - see the documentation for details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: read pdf from itext I had made a table in pdf using text in java web application.
PDF Generated is:
Gender | Column 1 | Column 2 | Column 3
Male | 1845 | 645 | 254
Female | 214 | 457 | 142
On reading pdf i used following code:
ArrayList allrows = firstable.getRows();
for (PdfPRow currentrow:allrows) {
PdfPCell[] allcells = currentrow.getCells();
System.out.println("CurrentRow ->"+currentrow.getCells());
for(PdfPCell currentcell : allcells){
ArrayList<Element> element = (ArrayList<Element>) currentcell.getCompositeElements();
System.out.println("Element->"+element.toString());
}
}
How to read text from pdf columns and pass to int variables?
A: Why don't you generate the Column of the pdf as fields, so that reading will be much easier
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I edit a submit button in Wordpress? I want to add an onclick attribute to the submit button of the media.php section in wordpress adminpanel. Where can I edit this button in Wordpress? It only writes out <?php submit_button( __( 'Update Media' ), 'primary', 'save' ); ?> and I can't find a way to just edit the HTML to add my onclick.
A: The function submit_button($text, $type, $name, $wrap, $other_attributes) is located in the /wp-admin/includes/template.php file on line 2169
submit_button(..) It then does a call on get_submit_button($text, $type, $name, $wrap, $other_attributes) which is located in the same file on line 2190.
Unfortunately there is no apply_filters to modify the output of the WordPress. In that case you have to make changes in the WordPress core files. I do not suggest you make any change in the WordPress core files, because on next update you will lose that changes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Delete cookies UIWebView How to delete cookies in UIWebView? This code:
NSArray* cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
for (NSHTTPCookie *cookie in cookies) {
[cookies deleteCookie:cookie];
}
deletes cookies but when I restart my application, there are same cookies in NSHTTPCookieStorage. Sometimes this code works, but i want to make it work everytime.How to solve this problem?
A: Try something like this:
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* facebookCookies = [cookies cookiesForURL:
[NSURL URLWithString:@"http://login.facebook.com"]];
for (NSHTTPCookie* cookie in facebookCookies) {
[cookies deleteCookie:cookie];
}
A: This worked for me:
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *allCookies = [cookies cookies];
for(NSHTTPCookie *cookie in allCookies) {
if([[cookie domain] rangeOfString:@"facebook.com"].location != NSNotFound) {
[cookies deleteCookie:cookie];
}
}
A: deleting a single cookie does not always work for some odd reason. To truly get a cookie deleted you will need to store the not specific cookie and then reload them and then iterate through all cookies and delete them such as this
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies];
if (cookies != nil && cookies.count > 0) {
for (NSHTTPCookie *cookie in cookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
[[NSUserDefaults standardUserDefaults] synchronize];
}
A: Make sure to call:
[[NSUserDefaults standardUserDefaults] synchronize];
in the end... Works like a charm...
A: The similar for previous one but simplier:
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray *allCookies = [cookies cookies];
for(NSHTTPCookie *cookie in allCookies) {
if([[cookie domain] contains:@"facebook.com"]) {
[cookies deleteCookie:cookie];
}
}
The "best answer" is bad because it allows to delete cookies for the specified concrete URLs. So for example you delete cookie for "login.facebook.com" but you may miss "www.login.facebook.com"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Change the font color and size of UISegment Control I want to change the font color and font size of uisegment control. is is possible ?
if any one has do this and any one has solution please tell me or share any helpful link
Thanks.
A: As some other answers mention, you can also use setTitleTextAttributes:forState:
UIFont *font = [UIFont boldSystemFontOfSize:12.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
forKey:UITextAttributeFont];
[segmentedControl setTitleTextAttributes:attributes
forState:UIControlStateNormal];
A: better use image for the same
- (void)insertSegmentWithImage:(UIImage *)image atIndex:(NSUInteger)segment animated:(BOOL)animated;
A: Check This
NSArray *ary=[sgmntControl subviews];
NSInteger intCount=0;
for (id seg in ary)
for (id label in [seg subviews])
if ([label isKindOfClass:[UILabel class]])
{
if(intCount==1)
{
[label setTextColor:[UIColor blackColor]];
[label setShadowColor:[UIColor whiteColor]];
}
else {
[label setTextColor:[UIColor whiteColor]];
[label setShadowColor:[UIColor blackColor]];
}
[label setFont:[UIFont boldSystemFontOfSize:16]];
[label setShadowOffset:CGSizeMake(0,1)];
}
Thanks
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: $("#slider_range").slider is not a function Ok, I have included the google api libraries for Jquery UI, like so:
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js' ></script>
Now I have a script that updates some spans and a hidden input on document slide and not only, on document ready:
<script type="text/javascript">
$(document).ready(function()
{
var slider=$('#slider_range').slider({
range:true,
min:0,
max:5,
step:1,
values:[0,3],
slide:function(event,ui)
{
$('#level').val(ui.values[0]+'-'+ui.values[1]);
$('#low').html(ui.values[0]);
$('#high').html(ui.values[1]);
}
});
var s=slider;
if(s.slider("values",0)==s.slider("values",1))
{
$('#level').val(s.slider("values",0));
$('#low').html(s.slider("values",0));
$('#high').html(s.slider("values",0));
}
else
{
$('#level').val(s.slider("values",0)+'-'+s.slider("values",1));
$('#low').html(s.slider("values",0));
$('#high').html(s.slider("values",1));
}
});
</script>
The ideea is that on a page it shows the slider and on another not.
The error message I get from Firebug is this:
$("#slider_range").slider is not a function
And points to the line
slide:function(event,ui)
What could be causing this? Why on a page the slider can be seen and on another (which uses the same template that loads the above) can`t?
Please help!
A: I just had the same error while i used the foundation framework from zurb along with jquery ui slider.
Problem #1:
the foundation framework 3.2.4 already delivers jquery 1.8.1 and i tried to include my own copy of jquery 1.9 just before the foundation files. (= duplicate jquery inclusion)
Problem #2:
the order of my inclusions. jquery ui needs to be included AFTER the foundation framework files.
A: There were two differing jquery libraries included on the second page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Beginners Moq question on Verifying I'm just playing around with Moq and I cannot work out how to get a call to Verify to work as expected. My problem seems to be that the method I'm calling on the SUT is not being called. Here's my code to test:
public class ImageHandler : BaseHttpHandler
{
public override void ProcessRequest(HttpContextBase context)
{
var person = new Person();
this.DoPerson(person);
context.Response.ContentType = "image/jpeg";
if (context.Request.RawUrl.ToLower().Contains("jellyfish.jpg"))
{
context.Response.TransmitFile(@"C:\Temp\jf.jpg");
}
else if (context.Request.RawUrl.ToLower().Contains("koala.jpg"))
{
context.Response.TransmitFile(@"C:\Temp\k.jpg");
}
else
{
context.Response.Write("File not found.");
}
}
public virtual void DoPerson(Person person)
{
}
}
Here is my MSpec test:
[Subject("Process")]
public class When_Given_Person
{
private static Mock<HttpContextBase> httpContext;
private static Mock<HttpRequestBase> httpRequest;
private static Mock<HttpResponseBase> httpResponse;
private static Mock<ImageHandler> mockSut;
private static BaseHttpHandler sut;
private Establish context = () =>
{
httpContext = new Mock<HttpContextBase>();
httpResponse = new Mock<HttpResponseBase>();
httpRequest = new Mock<HttpRequestBase>();
mockSut = new Mock<ImageHandler>();
httpContext.SetupGet(context => context.Response).Returns(httpResponse.Object);
httpContext.SetupGet(context => context.Request).Returns(httpRequest.Object);
httpRequest.SetupGet(r => r.RawUrl).Returns("http://logicsoftware/unkown.jpg");
sut = mockSut.Object;
};
private Because of = () => sut.ProcessRequest(httpContext.Object);
private It should_call_person_with_expected_age = () =>
{
mockSut.Verify(s => s.DoPerson(Moq.It.IsAny<Person>()),Times.AtLeastOnce());
};
}
This is really basic stuff, nothing too fancy. Now, when I run the test I get:
Expected invocation on the mock at least once, but was never
performed: s => s.DoPerson(It.IsAny()) No setups configured.
I believe this is due to the fact that sut.ProcessRequest() is not actually called - I have a breakpoint at the start of ProcessRequest(), but it's never hit. Can someone show me how to setup my mockSut so that ProcessRequest() is called.
Cheers.
Jas.
A: When you make a Mock of an object with Moq, it will mock the whole object and set it up to return defaults or do nothing on every method and property. So sut.ProcessRequest, won't actually do anything: DoPerson will never be called.
You'll only want to mock out dependencies to the classes you want to test, never the class itself.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to fix this generic problem within the repository pattern? I have a type converter which converts a string into an object and vice versa, the type converter takes the local into account. To implement easily several type converters, e.g. for BigDecimal, Point, and so on I decided to make this interface generic.
public interface TypeConverter<T extends Object>
{
convertToString(Locale locale, T object);
}
This is great to implement as you can be sure you only get the desired T and don't have to cast or something else.
convertToString(Locale locale, BigDecimal bigDecimal) { ... }
To retrieve the correct converter, I build up a type converter repository where you can access a specific type converter
typeConverterRepository.getTypeConverter(sourceValue.getType())
The type converter repository than gives us the correct type converter.
Now we want to call this converter:
TypeConverter typeConverter = typeConverterRepository.get( ....)
typeConverter.convertToString(context.getLocale(), sourceValue.getValue());
This leads into an eclipse warning:
The method convertToString(Locale, capture#2-of ?) in the type TypeConverter<capture#2-of ?> is not applicable for the arguments (Locale, Object)
How can this be fixed without using the @SupressWarning annotation? Thank you!
A: I think the problem lies within your typeConverterRepository pattern.
Do a typeconverter that looks like the following
public class TypeConverterRepository {
public <T> void registerTypeConverter(Class <T> type, TypeConverter<T> typeConverter);
public <T> TypeConverter<T> getTypeConverter(Class <T> type);
}
Then you can safley do a
TypeConverter<MyClass> typeConverter = typeConverterRepository.getTypeConverter(MyClass.class);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: java : get values from matrix for each time I do an action on y , get values 0 and 1 from table.
String[][] columns = {{"col1" , "col2"}};
int[] values = new int[columns.length];
String[] y = { "TEST", "BUG" };
for (int j = 0; j < y.length; j++)
{
//do some actions
//bellow I need to get at the same time col1 and col2
table.getVal(0, columns [0][j])) ?
}
I need to get value of col1, col2 on y1 and on y2 ? how could I use columns in the getVal to have the expected values ?
thanks,
A: class MatrixExampleDemo {
public static void main(String[] args) {
int array[][] = { { 1, 3, 5 }, { 2, 4, 6 } };
System.out.println("Row size= " + array.length);
System.out.println("Column size = " + array[1].length);
outputArray(array);
}
public static void outputArray(int[][] array) {
int rowSize = array.length;
int columnSize = array[0].length;
for (int i = 0; i <= 1; i++) {
System.out.print("[");
for (int j = 0; j <= 2; j++) {
System.out.print(" " + array[i][j]);
}
System.out.println(" ]");
}
System.out.println();
}
}
Check this also...................
import java.lang.reflect.Array;
import static java.lang.System.out;
public class CreateMatrix {
public static void main(String... args) {
Object matrix = Array.newInstance(int.class, 2, 2);
Object row0 = Array.get(matrix, 0);
Object row1 = Array.get(matrix, 1);
Array.setInt(row0, 0, 1);
Array.setInt(row0, 1, 2);
Array.setInt(row1, 0, 3);
Array.setInt(row1, 1, 4);
for (int i = 0; i < 2; i++)
for (int j = 0; j < 2; j++)
out.format("matrix[%d][%d] = %d%n", i, j, ((int[][])matrix)[i][j]);
}
}
A: I don't quite see the logic in your code, but general matrix operations would be:
String[][] matrix = new String[10][10];
matrix[0][0] = "1.1";
matrix[0][1] = "1.2";
matrix[1][0] = "2.1";
matrix[2][1] = "2.2";
int x = 0; // col
int y = 1; // row
String val = matrix[y][x]; // 1.2
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7567137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.