text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: How do I grab an image retrieved from a camera via web browser? I have an IP camera that hands me a snapshot of what it is seeing when I enter a specific url which the manual provides. The manual also states that the http response is:
HTTP Code: 200 OK
Content-Type: image/jpeg
Content-Length: <image size>
Body:<JPEG image data>
Looking at the page on Firefox, I can see nothing but the image. I cannot even view its page source. I am hoping this indicates a very simple format to grab with C++.
What I want to do is to write a C++ program that autograbs images from this camera at some time interval (and perhaps even do stuff on the image while it's at it).
What do I need to know to make this happen?
(Note that I have to use C++ EDIT: and linux )
A: The easiest solution is probably curl. It's even got an example which lacks just the for (;;) { grab(); sleep(60000); } loop.
A: Provided that you mention "I have to use C++", if Windows is in question then you can use WinHTTP API. You create session and connection to the IP camera web server, then you send HTTP request with URL to get JPEG snapshot, and read back your JPEG image data.
A: That HTTP statement is an image its self. Except the image data is encoded, and the image has a few textual headers above it. Otherwise it is the equivelent of an image found in a local image file. To grab the file, open a connection to the server, read in the contents and interpret the HTTP request. [It'll tell you about bad requests, the size of the image, etc]
For information on how to grab the resource see this question.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Sencha Touch tabPanel tabbar dynamic images In my application i am having a tabPanel. The title and icons of the tabs need to be dynamic. I am getting this data from the server. But i couldn't find any way which can load icons from a external source URL. I used the iconCls property with my custom class as .tab{-webkit-mask-box-image: url("SomeHttpURL")} but this is also static. How do i make SomeHttpURL a placeholder which replaces with the URL i am getting from server at the runtime?
Tarun Sharma.
A: In your css:
.x-tab img.your_icon_name .x-button img.x-icon-mask.your_icon_name{
-webkit-mask-image:url("SomeHttpURL");
}
In your panel code:
iconCls: 'your_icon_name',
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Creating a Task scheduler for Database status change In my application a registered user's profile should expire after 3 months from the registration date. I need to check and set the status of users to expired in DB every day at midnight. How can I achieve this. I think this may be done by creating a windows service and a scheduler and timer.
A: You don't need windows service for this. A scheduled task would do this nicely. Just launch taskschd.msc and create new task.
Depending on what you are using for DB, another option for you might be a DB mainenance task. This is easy to do in SQL Server, many other enterprise level databases can do that too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: bind with INADDR_ANY If I bind a socket to INADDR_ANY I know that it will accept incoming connections on any of IPs configured on the server. Lets say I have 1 IP configured when I make the bind() call and then a new IP gets configured. Will be bind() accept connections initiated to the newly configured IP also or does it work only for the IPs that were existing when bind() was called ?
A: Yes it will accept connections on newly created or newly configured interfaces.
You can try it yourself, by creating a dummy interface:
/sbin/ifconfig dummy0 172.17.42.99 netmask 255.255.255.255
Or something; then try to connect to that IP.
A: On Linux when you bind to INADDR_ANY then the socket stays bound to 0.0.0.0 and will accept connection to any local IP address no matter how that changes. Only when a TCP connection is established then the single connection is bound to the IP address it was received on. Other connections may still be received on any address.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: sizeof(long) in 64-bit C++ I have downloaded MinGW-64, so I can now compile 64-bit programs for Windows 7, using g++ 4.7.0 (experimental). But the following line:
cout << sizeof(long) << " " << sizeof(void*) << endl ;
prints 4 8, not 8 8. The documentation for g++ 4.6.0 says:
The 64-bit environment sets int to 32 bits and long and pointer to 64 bits
Does anybody know why sizeof(long) is not 8?
Edited to add: The source of my confusion was that g++ 4.7.0 for 64-bit Windows is not (yet) an official part of the GNU Compiler Collection. And it's the first 64-bit version with a 32-bit long, so the documentation simply doesn't apply to it. Indeed, if you go to the relevant web page, the full entry for IA-32/x86-64 consists of this:
...
A: MinGW is designed to build Windows applications, and the Microsoft platform ABI specifies that int and long have the same size of 32 bits. If MinGW defined long differently from MSVC, most existing Windows apps that use long would break when compiled using MinGW.
Having said that, Cygwin x86_64 does follow the LP64 convention on Windows, just like on Linux (source).
So you can use that to build a Windows app where the size of long is 8 bytes :)
Test case:
#include <stdio.h>
#include <windows.h>
int CALLBACK WinMain(HINSTANCE a, HINSTANCE b, LPSTR c, int d)
{
char buf[100];
snprintf(buf, sizeof(buf),
"sizeof(int)=%d, sizeof(long)=%d, sizeof(long long)=%d\n",
sizeof(int), sizeof(long), sizeof(long long));
MessageBox(NULL, buf, "Cygwin Test", MB_OK);
return 0;
}
Compile with: C:\cygwin64\bin\gcc.exe -mwindows -m64 cygwin-test.c -o cygwin-test
Output:
A: MinGW is designed to build a WIN32 application and WIN32 headers/libraries assumes the long(or LONG) type to be 32 bits wide even on a 64bit Windows.
Microsoft decided that otherwise so much of the existing Windows source codes should be changed. For example, the following structure uses LONG types.
typedef struct tagBITMAPINFOHEADER {
...
LONG biWidth;
LONG biHeight;
...
} BITMAPINFOHEADER
;
A: Because it doesn't have to be. The C++ standard only requires that it is (if memory serves) at least 32 bits wide, and at least as big as int.
MSVC (and the ABI used by Windows) defines long to be 32 bits wide, and MingW follows suit because well, the compiler is a lot more useful when it agrees with the host OS
A: On the microsoft windows OS you have LLP64 so the size of long is 32 bit. (see the table below)
Quote from wikipedia:
In 32-bit programs, pointers and data types such as integers generally have the same length; this is not necessarily true on 64-bit machines.
Mixing data types in programming languages such as C and its descendants such as C++ and Objective-C may thus function on 32-bit implementations but not on 64-bit implementations.
In many programming environments for C and C-derived languages on 64-bit machines, "int" variables are still 32 bits wide, but long integers and pointers are 64 bits wide.
These are described as having an LP64 data model. Another alternative is the ILP64 data model in which all three data types are 64 bits wide, and even SILP64 where "short" integers are also 64 bits wide.
However, in most cases the modifications required are relatively minor and straightforward, and many well-written programs can simply be recompiled for the new environment without changes.
Another alternative is the LLP64 model, which maintains compatibility with 32-bit code by leaving both int and long as 32-bit. "LL" refers to the "long long integer" type, which is at least 64 bits on all platforms, including 32-bit environments.
Type ILP64 LP64 LLP64
char 8 8 8
short 16 16 16
int 64 32 32
long 64 64 32
long long 64 64 64
pointer 64 64 64
A: It's OS specific. Windows still has size of long equal 32 bits
A: Most of Windows applications are written with the expectation that for all intents and purposes int=long=32 bits. I'm guessing MinGW is just making sure it's still the case and there're no surprises.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
}
|
Q: Restoring a Google Doc from Trash using Zend GData I am creating a filemanger that uses Google Docs for storage, but I am having difficulty working out how to restore a file that has been sent to the trash. I can send to trash by using this code:
$resourceId = "file:12345";
$link = "https://docs.google.com/feeds/default/private/full/";
$file = $docs->getDocumentListEntry($link.$resourceId);
$file->delete();
I can then view all trashed documents using:
$docs = new Zend_Gdata_Docs($client);
$docs->setMajorProtocolVersion(3);
$feed = $docs->getDocumentListFeed($link."-/trashed");
foreach($feed->entries as $entry) {
...
}
My question is how can I then restore one of these files back to location it was before it was deleted as you can in Google Docs proper?
A: Ok, so I worked out how to restore trashed files in my Google Docs App. Code is as follows:
$service = Zend_Gdata_Docs::AUTH_SERVICE_NAME;
$client = Zend_Gdata_ClientLogin::getHttpClient($gUser, $gPass, $service);
$client->setHeaders('If-Match: *');
$gdocs = new Zend_GData_Docs($client);
$gdocs->setMajorProtocolVersion(3);
$slug = array('If-Match'=>'*');
$link = "https://docs.google.com/feeds/default/private/full/".$resourceId;
$entry = $gdocs->getDocumentListEntry($link);
$xml = $entry->getXML();
$feed = str_replace('label="trashed"', 'label=""',$xml);
$entryResult = $gdocs->updateEntry($feed, $entry->getEditLink()->href,null,$slug);
This will also work for unstarring a document and with other category elements. So for example:
Replace:
$feed = str_replace('label="trashed"', 'label=""',$xml);
With:
$feed = str_replace('label="starred"', 'label=""',$xml);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: change svn file property on the fly with svnkit I need to change the value of a versioned custom property of a file in an svn repository on the fly.
I do not want to alter any content, just change the value of the property of the already existing file.
I am using svnkit in java.
How would i go about it?
example:
http:://svnserver.com/example/directorya/file1.txt ... has svn property: myproperty = abc
after the operation:
http:://svnserver.com/example/directorya/file1.txt ... has svn property: myproperty = def
This is what i tried, but it doesnt work. Instead of changing the file property it adds a commit to the whole repo, without touching the file file1.txt.
SVNRepository repository = SVNRepositoryFactory.create(url);
ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(user,password);
repository.setAuthenticationManager(authManager);
ISVNEditor editor = repository.getCommitEditor("comment" , null);
editor.openRoot(-1);
editor.openFile("file1.txt", -1);
editor.changeFileProperty("file1.txt", "mypropertyname", SVNPropertyValue.create("myvalue"));
editor.closeEdit();
A: i had not called closeFile(), and i needed an "/" before the filename, now it works
SVNRepository repository = SVNRepositoryFactory.create(url);
ISVNAuthenticationManager authManager = SVNWCUtil.createDefaultAuthenticationManager(user,password);
repository.setAuthenticationManager(authManager);
ISVNEditor editor = repository.getCommitEditor("comment" , null);
editor.openRoot(-1);
editor.openFile("/file1.txt", -1);
editor.changeFileProperty("/file1.txt", "mypropertyname", SVNPropertyValue.create("myvalue"));
editor.closeFile("/file1.txt",null);
editor.closeEdit();
A: We can use
SVNDeltaGenerator and use sendDelta method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how can i implement cross reference attacks with using jquery? i am using jQuery in my asp.net mvc site. How can i make sure the use is secure in the sense of protecting against cross site scripting / sql injection attacks?
A: jQuery doesn't play much role in protecting against those kind of attacks. It's the server side code. For example to protect against SQL injection attacks make sure to always use parametrized queries when querying your database. To protect against XSS make sure you always HTML encode any value that you are outputting in a view.
As far as jQuery is concerned, when sending AJAX requests always use the data hash to pass parameters and avoid string concatenations:
$.get('/foo', { id: $('#id').val() });
instead of:
$.get('/foo?id=' + $('#id').val());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to replace the number with the "image width" in vote page <form action="/votes/vote" method="post">
<% for option in @vote.options %>
<%= option.name %>
<%= option.quantity %>
<input type="checkbox" name="op[]" value="<%= option.id %>" /><br />
<% end %>
<input type="hidden" value="<%= @vote.id %>" name="id"/>
<input type="submit" value="Submit" />
</form>
<%= option.quantity%> is the number of the vote; I want to replace it with an image more visual. How?
option1.quantity=15; =>: =====15px(columnar image)======
option1.quantity=30; =>: =============30px(columnar image)===============
A: I don't know if I understand your question, but if you want something "more visual", what about creating DIV like a color bar:
%div{:style => "background-color: green; height: 20px; width: #{option.quantity}px;"}
= option.quantity
you can replace color with some background columnar image of course:
%div{:style => "background-image: url('some_columnar_image_path'); height: 20px; width: #{option.quantity}px;"}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607534",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: convert php array to array Lets say I'm having the following php array
Array(
[0]=>a,b,c
)
how can I convert it to get as result another array, what should look like
Array(
[0]=>a
[1]=>b
[2]=>c
)
A: // $a = array('a,b,c');
$b = explode(',', $a[0])
A: You can simple use php explode() function for that.explode(",", $somearray[0]);.
A: This is the way to create index array if you want to give first index of your array whatever you want rather than 0.
Array(
[0]=>'a','b','c'
)
So if you want to start you first index from 10 than.
Array(
[10]=>'a','b','c'
)
will result like this
Array(
[10]=>'a',
[11]=>'b',
[12]=>'c'
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How to use logrotate with cluster? How to use logrotate with cluster node.js module ? What kind of signal logrotate must send to cluster process for reopening log files ?
A: This is not possible yet, it's one of the first issues of cluster:
https://github.com/LearnBoost/cluster/issues/5
A: After trying it out by myself this is definitely the answer on your question: https://npmjs.org/package/log4node
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Issue with custom tableviewcell imageview and accessory view I'm using customized tableviewcell and adding image view to the cell. When I'm trying to add accessory discloser indicator to that cell, the accessory view's background is changing to gray color(which is default).
Please see this image
Can any one tell the solution for this??
A: Set the background colour of the cell in tableView:willDisplayCell:forRowAtIndexPath:, e.g.:
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
cell.backgroundColor = [UIColor blueColor];
}
A: You can set the default color or any color you want:
cell.backgroundColor=[UIColor clearColor];
(or)
cell.backgroundColor=[UIColor blueColor];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: scanf() skip variable In C, using scanf() with the parameters, scanf("%d %*d", &a, &b) acts differently. It enters value for just one variable not two!
Please explain this!
scanf("%d %*d", &a, &b);
A: The * basically means the specifier is ignored (integer is read, but not assigned).
Quotation from man scanf:
* Suppresses assignment. The conversion that follows occurs as
usual, but no pointer is used; the result of the conversion is
simply discarded.
A: http://en.wikipedia.org/wiki/Scanf#Format_string_specifications
An optional asterisk (*) right after the percent symbol denotes that the datum read by this format specifier is not to be stored in a variable.
A: Asterisk (*) means that the value for format will be read but won't be written into variable. scanf doesn't expect variable pointer in its parameter list for this value. You should write:
scanf("%d %*d",&a);
A: The key here is to clear the buffer, so scanf will not think that it already has some input, and so it will not get skipped!
#include <stdio.h>
#include<stdlib.h>
void main() {
char operator;
double n1, n2;
printf("Enter two operands: ");
scanf("%lf %lf",&n1, &n2);
fflush(stdin); //do this between two scanf
printf("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
}
fflush(stdin); //this clears the scanf for new input so it does not ignore any input taking line becuase it has
some charater already stored in its memory
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: GDB: debugging a child process after many fork()s I'm debugging a program which repeats the typical procedure of using fork() where the child process does some delegated task as the parent calls waitpid() to wait for the child to finish and then continues. For example:
while (!finished) {
pid_t p = fork();
if (p < 0) {
perror("fork");
exit(EXIT_FAILURE);
}
else if (p == 0) {
/* Do something. For example: */
if (/* some (rare) condition */)
raise(SIGSEGV);
exit(EXIT_SUCCESS);
}
else {
int status;
pid_t w = waitpid(p, &status, 0);
if (w < 0) {
perror("waitpid");
exit(EXIT_FAILURE);
}
/* Do something. */
}
}
I'd like to run the program inside GDB and debug a child process that receives a signal, no matter how many other child processes successfully finished and vanished before it.
Of course, I need set follow-fork-mode child, because otherwise GDB won't look into the child processes. But this alone will detach the parent, lead GDB to the first child, and finish debugging upon its exit.
Therefore, I also need set detach-on-fork off to prevent the parent from being detached. However, this causes GDB to stop and give me a prompt, with the parent being suspended, when the first child exits. I could use inferior to choose the parent and issue continue, but I need to do this for every child. If the 1000th child is the one that receives the signal and that I want to look into, I need to repeat this process 999 times.
So I'm wondering if there is a way to, kind of, do this automatically and let GDB follow what the CPU would be executing, e.g. parent → child1 → parent → child2 → … , without stopping and prompting me, and stop at the first childN that receives a signal.
A: If the signal you'd like to debug is SIGSEGV (or one of the other signals that causes the program to core dump), the easiest solution might be to just let the child dump core, and do post-mortem debugging.
Otherwise, you might want to catch the signal, print a message along the lines of child 23435 caught signal 2; execute gdb /proc/23435 23435 and then suspend the child with e.g.
while(1) sleep(1);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Why isn't this code working? C++ This code should ask the user for a their name and then split it at the space.
It should put the firstname in the variable first, and the last name in de variable lastname
#include <iostream>
using namespace std;
int main()
{
char string[80];
char first[20];
char lastname[20];
bool f = true;
int c = 0;
cout << "Whats your Name? \n";
gets(string);
for(int i =0; i < strlen(string); i++){
if(string[i] == ' ') {
f = false;
c = 0;
}
if(f) {
first[c] = string[i];
} else if(!f) {
lastname[c] = string[i];
}
c++;
}
for(int i = 0; i < strlen(first); i++) {
cout << first[i] << "\n";
}
for(int i = 0; i < strlen(lastname); i++) {
cout << lastname[i]<< "\n";
}
return 0;
}
A: Unless you really need to write this using only C functions, it would be much easier to use C++ strings.
Something like (this is untested):
std::string input;
std::string first;
std::string lastname;
// prompt the user
std::cout << "What's your name? ";
// get a line of input
std::getline(std::cin, input);
// find a space in the string
size_t space = input.find_first_of(" ");
// was the space found?
if (space != std::string::npos)
{
// copy out the first and last names
first = input.substr(0, space);
lastname = input.substr(space + 1);
// output them to stdout
std::cout << first << std::endl << lastname << std::endl;
}
This means you don't have to worry about null-terminating strings or string lengths or anything like that. As flolo said, your code doesn't do that and thus will definitely run into problems. The memory layout of a C string is an array of characters with a null byte on the end, which is how things like strlen() know where the end of the string is. Also, your code's going to have a horrible time the moment somebody enters a name with more than 20 characters in it, which isn't particularly implausible.
A: You dont say how your program does behave wrong. But one error I see is due to the fact that c-strings are 0-terminated. You must add in your "if ...==" a first[c]=0; (before you reset c to 0) and after the the loop a lastname[c]=0.
A: Talk about doing things the hard way. It would be easier using
std::string, but if you insist on using char[], don't use gets
(which is irremdially broken), but fgets, and second, find the end of
the string once and for all. So either (preferred:
std::string line;
std::getline( std::cin, line );
if ( ! std::cin )
// Something when wrong...
typedef std::string::const_iterator Iter;
Iter begin = line.begin();
Iter end = line.end();
or:
char line[80];
if (fgets( line, stdin ) == NULL )
// Something went wrong...
typedef char const* Iter;
Iter begin = line;
Iter end = line + strlen( line );
if ( end != begin && *(end - 1) == '\n' )
--end;
Then find the first space:
Iter pivot = std::find( begin, end, ' ' );
Then create the two strings first and last, either:
std::string first( begin, pivot );
std::string last( pivot == end ? end : pivot + 1 );
or
char first[80] = { '\0' }; // nul fill to ensure trailing '\0'
std::copy( begin, pivot, first );
char last[80] = { '\0' };
std::copy( pivot == end ? end : pivot + 1, end, last );
Then output:
std::cout << first << std::endl;
std::cout << last << std::endl;
Of course, if you're using std::string, you don't even need to create
the variables first and last; you can output a temporary:
std::cout << std::string( begin, pivot ) << std::endl;
std::cout << std::string( pivot == end ? end : pivot + 1, end ) << std::endl;
A: Some minor issues not mentioned from the others:
if(f) {
first[c] = string[i];
} else if(!f) { // <- this "if" statement looks like you did not understand "if .. else"
lastname[c] = string[i];
}
So better write:
if(f) {
first[c] = string[i];
} else {
lastname[c] = string[i];
}
And the part
if(string[i] == ' ') {
f = false;
c = 0;
}
should be better
if(string[i] == ' ') {
f = false;
c = 0;
continue;
}
because otherwise your lastname will always contain a leading space.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WCF XmlSerializerFormat and OperationContract: nested soap parameters serialization After reading the post XmlSerializer with specified pattern not working I try to implement such a service : OperationContract with the XmlSerializerFormat. But my Soap message contains an additional tag that is the operation parameter. How can I remove that tag ?
Here is my service sample
[System.ServiceModel.ServiceContractAttribute(Namespace = "http://mynamespace.com/", ConfigurationName = "ConfigName")]
public interface MyInterfacePort
{
[System.ServiceModel.OperationContractAttribute(Action = "http://mynamespace.com/opName", ReplyAction = "*")]
[System.ServiceModel.FaultContractAttribute(typeof(MyError), Action = "http://mynamespace.com/opName", Name = "opErr")]
[System.ServiceModel.XmlSerializerFormatAttribute()]
opResponse opName(opRequest request);
Then the serialized request:
[System.Serializable]
public partial class opRequest
{
public string myProperty;
generated soap message:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<opName xmlns="http://mynamespace.com/">
<request>
<myProperty>262157</myProperty>
</request>
</opName>
</s:Body>
</s:Envelope>
My service doesn't handle the additional <request> tag
Thank's for your help.
A: You can use an unwrapped [MessageContract] class if you want to remove the additional element in the XML request. The code below shows your example with such contract.
public class StackOverflow_7607564
{
[System.ServiceModel.ServiceContractAttribute(Namespace = "http://mynamespace.com/", ConfigurationName = "ConfigName")]
public interface MyInterfacePort
{
[System.ServiceModel.OperationContractAttribute(Action = "http://mynamespace.com/opName", ReplyAction = "*")]
[System.ServiceModel.FaultContractAttribute(typeof(MyError), Action = "http://mynamespace.com/opName", Name = "opErr")]
[System.ServiceModel.XmlSerializerFormatAttribute()]
opNameResponse opName(opNameRequest request);
}
public class MyError { }
[MessageContract(IsWrapped = false)]
public class opNameRequest
{
[MessageBodyMember(Name = "opName")]
public opRequest request;
}
[MessageContract(IsWrapped = false)]
public class opNameResponse
{
[MessageBodyMember(Name = "opNameResponse")]
public opResponse response;
}
[System.Serializable]
public partial class opRequest
{
public string myProperty;
}
[System.Serializable]
public partial class opResponse
{
public string myProperty;
}
public class Service : MyInterfacePort
{
public opNameResponse opName(opNameRequest request)
{
return new opNameResponse { response = new opResponse { myProperty = request.request.myProperty } };
}
}
public static void Test()
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(MyInterfacePort), new BasicHttpBinding(), "");
host.Open();
Console.WriteLine("Host opened");
var factory = new ChannelFactory<MyInterfacePort>(new BasicHttpBinding(), new EndpointAddress(baseAddress));
var proxy = factory.CreateChannel();
Console.WriteLine(proxy.opName(new opNameRequest { request = new opRequest { myProperty = "hello world" } }).response.myProperty);
((IClientChannel)proxy).Close();
factory.Close();
Console.Write("Press ENTER to close the host");
Console.ReadLine();
host.Close();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Send and receive from Socket in Android Java Hi All I have a small question.
*
*I have server client application Where the client will be sending data asynchronously.
*The server will receive message and parse.
*If server receives a wrong data it will send and error message to the client.
Now my Problem is in client I will be sending data continuously with out caring about acknowledgement example:
*
*Suppose I am sending some 1000 messages from client. The client sends all the data in the socket.
*If error occurs server will also put error message in the socket.
*But either one can happen: send data from client or send message from the server.
What is the best way to handle the case?
If any error occurs and client receives the error message from the server then the client has to resend the data. One way is to send the data and wait for acknowledgement. I don't want client to wait for servers ack because chances of error are very less. Can any one tell me some good solution to this?
A: Have the error message include the 'index' the client should restart sending at.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Edge detection in Javascript I have a matrix (here's the plot: http://i.imgur.com/GNIWp.png) and I'd like find out, where the edges are.
Here's a picture of the same plot with lines which indicate the edges: http://i.imgur.com/yffGh.png
Is there any algorithm to detect these edges?
A: There are plenty of fairly simple edge detection algorithms that aren't too hard to implement, such as the Canny edge detector. Bear in mind that a lot of these algorithms have different strengths and weaknesses, so I'd suggest you read up on the different approaches and decide based on what you're trying to do.
Alternatively, if you only want the functionality and aren't interested in actually implementing it, you can use the Pixtastic image processing library.
Also, possible duplicate question here (though that question is more to do with background removal).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Hadoop: what should be mapped and what should be reduced? This is my first time using map/reduce. I want to write a program that processes a large log file. For example, if I was processing a log file that had records consisting of {Student, College, and GPA}, and wanted to sort all students by college, what would be the 'map' part and what would be the 'reduce' part? I am having some difficulty with the concept, despite having gone over a number of tutorials and examples.
Thanks!
A: Technically speaking, Hadoop MapReduce treats everything as key-value pairs; you just need to define what the keys are and what the values are. The signatures of map and reduce are
map: (K1 x V1) -> (K2 x V2) list
reduce: (K2 x V2) list -> (K3 x V3) list
with sorting taking place on K2 values in the intermediate shuffle phase between map and reduce.
If your inputs are of the form
Student x (College x GPA)
Then your mapper should do nothing more than get the College values to the key:
map: (s, c, g) -> [(c, s, g)]
with college as the new key, Hadoop will sort by college for you. Your reducer then, is just a plain old "identity reducer."
If you are carrying out a sorting operation in practice (that is, this isn't a homework problem), then check out Hive, or Pig. These systems drastically simplify these kinds of tasks. Sorting on a particular column becomes quite trivial. However, it is always educational to write, say, a hadoop streaming job for tasks like the one you identified here, to give you a better understanding of mappers and reducers.
A: Yahoo has sorted Peta and Tera Bytes of data. Others (including Google) do it on a regular basis, you can search for the sort benchmarks on the internet. Yahoo has published a paper on how they have done it.
Ray's approach has to be modified a bit to get the final output sorted. The input data has to be sampled and a custom partition written to send a key range to a particular reducer. Then the output of the N reducers just need to be concatenated. The Yahoo paper explains this is more detail.
The 'org.apache.hadoop.examples.terasort' package has sample code for sorting data.
If you are new to MapReduce I suggest watching the following videos. They are a bit lengthy, but are worth.
http://www.youtube.com/watch?v=yjPBkvYh-ss
http://www.youtube.com/watch?v=-vD6PUdf3Js
http://www.youtube.com/watch?v=5Eib_H_zCEY
http://www.youtube.com/watch?v=1ZDybXl212Q
http://www.youtube.com/watch?v=BT-piFBP4fE
Edit: Found some more information at the Cloudera blog here. There are some built-in classes to make sorting easier.
Total order partitions HADOOP-3019. As a spin-off from the TeraSort record, Hadoop now has library classes for efficiently producing a globally sorted output. InputSampler is used to sample a subset of the input data, and then TotalOrderPartitioner is used to partition the map outputs into approximately equal-sized partitions. Very neat stuff — well worth a look, even if you don’t need to use it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is heroku console secure? When doing and running commands in heroku console, via heroku run console. Is this a secure connection?
For example, if I am editing a user's password. Will the information from my computer to the heroku console be secure / encrypted?
A: Yes, heroku console works over SSH. That's why you have to generate an encryption keypair to use Heroku. Your traffic is encrypted.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I remove an invitation request notification? I'm using FB.ui({method: 'apprequests', ... }) to invite a user but when the user accepts and logs into the app, the app icon still has a little red 1 on it. How do I remove this notification or even get a list of notifications? I've tried querying the graph explorer with manage_notifications permissions but I always end up with an empty data array.
I'd like to do as much as possible using the graph API and php if that's an option.
A: This is covered thoroughily in the requests documentation. You would just need to issue a HTTP DELETE command to https://graph.facebook.com/requestID?access_token=... The id's come as part of the querystring when the user clicks on the notification: https://apps.facebook.com/[app_name]/?request_ids=[request_ids]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rebasing to new versions in upstream git (GitHub) with losing all local changes I want to have the following version structure:
(my private changes to 0.1.0) - A - B - C - ...
/
(upstream repo) - 0.1.0 - 0.2.0 - ...
\
(my private changes to 0.2.0) - D - E - F - ...
I don't want to merge my changes with changes in upstream, because the upstream is developed rapidly and usually there are zillions of hard to resolve conflicts, because upstream code was significantly redesigned. When 0.3.0 is out, I'm going just to create an exact copy of it forgetting my private changes and then re-apply my private fixes one by one. But I don't want my old changes to disappear completely - I want them to sit somewhere still (on a separate branch?).
git rebase is not what I want. According to Pro git book, rebasing will try to re-apply A-B-C patches to 0.2.0. Here is an example situation between upstream 0.1.0 and 0.2.0 release dates:
(upstream) - 0.1.0 - (my master) - A - B - C
Now 0.2.0 is out:
(my master) - A - B - C
/
(upstream) - 0.1.0 - 0.2.0
I don't want to rebase my A - B - C changes because of too many conflicts. I want to label my A - B - C branch as 'my-0.1.0' and start a 'new' master branch from 0.2.0:
(my-0.1.0) - A - B - C
/
(upstream) - 0.1.0 - 0.2.0 - (my new master)
I want my new master branch to be a clean copy of upstream 0.2.0, without any attempts to re-apply my old A-B-C changesets to it. So later I can cherry-pick A-B-C changes one by one if I need them in post-0.2.0 world.
How do I put the my-0.1.0 label? Is it a label, a tag, a branch? How do I start an empty master branch off 0.2.0? Note that there are two different repos: my repo and upstream repo. Do I need to copy upstream branch from upstream repo to my repo? How I ensure that 0.2.0 is pulled after 0.1.0, and not after C? If I just do a pull request after
(upstream) - 0.1.0 - (my master) - A - B - C
I get
(upstream) - 0.1.0 - (my master) - A - B - C - "0.2.0 merged with ABC"
which is not what I want.
Also sometimes I want to push certain change (e.g. E) back to upstream. Is it possible to create a pull request for E change only? In darcs this is possible. If it's not possible with Git/GitHub, then I will need to create a separate branch, reapply the changes in E manually. How should I proceed?
A: git rebase is your friend.
Tag the old version if you want and rebase your private branches on the latest upstream version.
To create a pull request for E only, you can either:
*
*Create new branch and git cherry-pick E to it (the old branch will have the old version of E).
*git rebase -i the branch and reorder the commits to put E first. Than you can tag E and create a pull request from that tag. When the upstream applies it, rebasing should correctly apply the remaining commits
In either case if the rebase does not realize E is merged when upstream finally does it (which happens if they modified it), just use the interactive rebase to drop your obsolete version of it.
Darcs actually does the same thing, but darcs rebases automatically if it can do it without conflicts (and refuses to do it altogether if it can't), while in git you rebase explicitly and if there are conflicts (E turns out to depend on D), it spits out the conflict and lets you deal with it anyway you want.
Edit: Ah, you just want to put A, B and C aside and start with clean 0.2.0. You can use either branch (on master, do):
git branch -m my-0.1
git checkout -b master 0.2.0
or tag (on master, do):
git tag my-0.1
git reset --keep 0.2.0
The branch will keep it's reflog around, you will be able to check it out and modify it. The tag will not have reflog and you won't be able to check it out (checkout will put you in the "detached HEAD" state unless you give it a branch to create).
A: You might want to look at git rebase --onto which will let you apply a set of changes onto a different base than they are currently on
A: Note that since git1.7.2rc2, the git reset --keep 0.2.0 option mentioned by Jan Hudec in his answer can also be written:
git checkout -B master 0.2.0
The announce mentions:
git checkout -B <current branch> <elsewhere>"
is a more intuitive way to spell "git reset --keep <elsewhere>".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: UIWebView content resize issue in iPad I have a UIWebview in iPad. I have attached a screens shot. Please see its coordinates and the masking of its position (The web view is added to xib in portrait mode). However when I load that in portrait mode or landscape mode the content is fit to the size of the web view. Issue arise when I turn the iPad to a different orientation. That means even though the UIWebView resizes properly the content doesnt resize properly. As a work around seen in many places I used the following meta tag in the head section of the web page Im loading.
However also used the "webView.scalesPageToFit = YES". Still no luck. Please help me to solve this problem.
Thank you
A: How about:
-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)
fromInterfaceOrientation
{
[webView reload];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What is the scope of function within anonymous namespace in VC++? If CPP file defines
namespace
{
void Function() { ... }
}
what is the scope of Function?
A: File Scope. In this case Function is accessible only within the file it is defined in.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What to use to store in postgresql a string with no specific upper limit? On the postgresql manual page:
If you desire to store long strings with no specific upper limit, use text or character varying without a length specifier.
My question is: when to use which ? Or it doesn't matter ?
A: They are the same. Use what you prefer :)
Although text is not SQL standard I prefer it because is sorter.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Throw exception from one-way operation Assume that you have the following operation:
void AddCustomer(Customer)
(i.e. a Customer object as input and no output)
Complying to WS-I BP 1.1 you are not allowed to define fault messages for one-way operations [1]. However, you may want to throw an exception in case, for example, the customer is a duplicate. How would you achieve this? Defining the operation as a request/response with an empty response signaling that the operation succeeded? Not that pretty in my opinion... Maybe you know another way? I mean: within a java/.net program you still want to be able to throw exceptions also for void-methods...
Example:
<operation name="AddCustomer">
<input message="tns:AddCustomerRequest"/>
<output message="tns:AddCustomerResponse"/>
<fault name="DuplicateCustomer" message="tns:DuplicateFault"/>
</operation>
where AddCustomerResponse would be an empty sequence.
[1] http://www.w3.org/TR/wsdl#_porttypes
A: According to the wsdl 1 specification there is no solution for this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607582",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to check if a URL is valid or not in Windows batch script I am a newbie in Windows batch scripting. I have a question though.
In Windows batch scripting, how will I know if a variable is a valid URL or not?
Example:
Valid URL:
url=https://stackoverflow.com/questions/ask
Invalid URL:
url=not a valid url
A: You might use FINDSTR to validate your URL by matching it against a regular expression. See the answers to this Stack Overflow question Regular expressions in findstr
Basically you'll have to understand
*
*how to use FINDSTR and its /R switch. See HELP FINDSTR
*how to code a regex for matching and validating URLs. Google for regex tutorial.
Hint: (http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?
*and how to interpret FINDSTR results in a batch file. See HELP FOR
A: This is simple and should work in most cases:
setlocal enableextensions enabledelayedexpansion
set URL=url to test
if not x%URL:http://=%==x%URL% goto http
if not x%URL:https://=%==x%URL% goto http
if not x%URL:ftp://=%==x%URL% goto ftp
REM else
echo invalid url!
A: Don't bother. Whatever you use won't be identical to whatever rules the program you're about to run uses. Just let the program decide.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do protocols in Objective C work?
Possible Duplicate:
Objective-c - Purpose of categories and protocols
Can anyone justify @protocol mechanism of Objective C in simple words.
Like,
*
*Defining protocol
*Implementing protocol
*Other alternatives of protocol
A: You can find a good introduction on protocols at Apple's developer site, as well as on WikiBooks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How to autocomplete path to include file with solid prefix? in Netbeans, when I start writing absolute path to file I get autocomplete for path. e.g. when write:
require_once "D:/www/"
and I get autocomplete for path to file e.g.:
..
project1/
project2/
file1.php
file2.php
But when I use constant or variable prefix to path, e.g.:
class Tools{
// const
const PATH_TO_PROJECT = 'D:/www/project1/';
// or variable
public $pathToProject = 'D:/www/project1/';
}
and write:
require_once Tools::PATH_TO_PROJECT . '';
// or
$tools = new Tools();
require_once $tools->pathToProject . '';
I don't get autocomplete.
Is there any way how to achieve autocomplete for this style of includes? Or is there more elegant way to do this?
And what about Auto including Classes. Is there some good library for this: I prefer something more modular.
Thank's for help and excuse my basic English.
With the wishes of a beautiful day
Radek
A: You can set include_path the code should be something like:
ini_set('include_path', ini_get('include_path').PATH_SEPARATOR.'D:/www/project1/');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607588",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ASP.NET remote COM port access I'm building a website in ASP.NET with backend functionality in C#. The idea is that you can connect a device to your own serial port, then go to the website to send the received data from your serial port to the website.
I made a simple page which can access a serial port but after some thinking I realized I was only accessing the serial port of the computer the server runs on. I'm sure I'll be able to solve this by using two seperate applications, a client and a server. The client will then send the received data through TCP to the server. The problem is that I don't want two seperate applications, I want only one application, the website.
I'm not sure if this is possible, so my question is: Is this possible and how can it be done? Thanks in advance!
A: The only way you could do it is to build a custom browser plug-in, such as an ActiveX control. But, that limits you to using Internet Explorer. Even then, i think IE now has too many protections to allow it so people running Vista or Windows 7 would not be able to run your control without disabling browser security.
A: No, it's not possible, since the browser cannot access serial devices connected to the PC (and that's a good thing).
One workaround would be to create a browser plugin which does have the rights to access the serial device, but then, again, you'd have two applications.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: 400 Bad Request when updating DueDate or creating new task with DueDate I am trying to update dueDate for task:
Task updatedTask = service.tasks.get(gTask.getTaskListGuid(), gTask.getGuid()).execute();
updatedTask.setTitle(gTask.getTitle());
updatedTask.setNotes(gTask.getDescription());
updatedTask.setDue(gTask.getDueDate());
service.tasks.update(gTask.getTaskListGuid(), gTask.getGuid(), updatedTask).execute();
But api returns me:
10:49:40,323 ERROR GTasksServiceProcessor.[main]processUpdatedTasks:81 - Can't update task: com.google.api.client.http.HttpResponseException: 400 Bad Request
com.google.api.client.http.HttpResponseException: 400 Bad Request
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:708)
at com.google.api.services.tasks.Tasks$RemoteRequest.execute(Tasks.java:1574)
at com.google.api.services.tasks.Tasks$TasksOperations$Update.executeUnparsed(Tasks.java:870)
at com.google.api.services.tasks.Tasks$TasksOperations$Update.execute(Tasks.java:855)
at ua.com.stormlabs.gap.gtasks.GTasksManager.updateTask(GTasksManager.java:120)
at ua.com.stormlabs.gap.gtasks.GTasksServiceProcessor.processUpdatedTasks(GTasksServiceProcessor.java:78)
at ua.com.stormlabs.gap.gtasks.GTasksServiceProcessor.start(GTasksServiceProcessor.java:51)
at ua.com.stormlabs.gap.gtasks.GTasksGapApp.main(GTasksGapApp.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Where is a problem?
I have same exception when trying to create new task with dueDate.
Also I found thread:
http://groups.google.com/group/google-tasks-api/browse_thread/thread/1753df5bbc8e3cb8/ab66b5e675f06e6a?lnk=gst&q=problem+changing#ab66b5e675f06e6a
But it doesn't help me.
A: This fixed it for me: https://groups.google.com/d/msg/google-tasks-api/F1PfW7yOPLg/3Awlcivpb1oJ
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607590",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: MVC: Replace A ID Value (of a Foreign Key) In A View By Its Value Assume we have these two tables, binded by foreign key CAT_ID:
Category[CAT_ID,CAT_NAME]
cat_id = 1, cat_name= Classical
cat_id = 2, cat_name = Jazz
...
MusicAlbums[ALBUM_ID, ALBUM_NAME, CAT_ID]
album_id = 1, album_name = Wagner - Parsifal, cat_id=1
album_id = 2, album_name = "Davis Miles - Kind of Blue, cat_id = 2
How can I display on MVC View instead of CAT_ID its value(that is : CAT_NAME) ? like this:---------
Music
1 | Wagner - Parsifal | Classical
2 | Davis Miles - Kind of Blue | Jazz
---------
Thank you
A: You want the Foreign Key feature (Its marked as new so may not have been available when you first looked):
http://demos.telerik.com/aspnet-mvc/grid/foreignkeycolumn
(View code (from their site, slightly cleaned up))
Html.Telerik().Grid<ClientEditableOrder>()
.Name("Grid")
.Columns(columns =>
{
columns.Bound(o => o.OrderID).Width(100);
columns.ForeignKey(o => o.EmployeeID, (IEnumerable<employee>)ViewData["employees"],
"ID", "Name").Width(230);
columns.Bound(o => o.OrderDate).Width(150);
columns.Bound(o => o.Freight).Width(220);
})
//..etc..
.Render();
ViewData is set in the initial controller action:
public ActionResult Edit() {
var r = _userService.GetAllemployees().ToList();
ViewData["employees"] = r;
return View();
}
Their 'AjaxEdit' controller action does some funky stuff with explicitly listed foreign key ids in the parameters. But as my object exposed the FK fields I found in worked as expected without the need for any tricky business..
Bonus points to anyone who can provide an example of filtering/sorting on the displayed value on these columns as these features apply themselves to the underlying 'id' value rather than the displayed string (annoying!)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: php get string from binary file I have JPG image with XMP meta data inside.
I'd like to read this data, but how?
$content = file_get_contents($fileName);
var_dump($content);
displays real number of bytes 553700
but
$len = strlen($content);
var_dump($len);
displays 373821
So, I can't simple do
$xmpStart = strpos($content, '<x:xmpmeta');
because I get wrong offset.
So, the question is, how to find and read string from binary file in PHP?
(I have mb_string option ON in php.ini)
UPD1:
I have some binary file. How can I check in PHP, this file contains several strings or not?
A: Getid3 is a PHP package that claims to be able to read XMP Metadata.
A: Essentially, it doesn't matter what kind of data you are reading - strlen() et al. should always work.
What I think is happening here is that on your server, strlen() is internally overridden by mb_strlen() and the internal character encoding is set to UTF-8.
UTF-8 is a multi-byte encoding, so some of the characters in your (wildly arbitrary) byte stream get interpreated as multi-byte characters - resulting in a shortened length of 373821 instead of 553700.
I can't think of a better workaround than always explicitly specifying a single-byte encoding like iso-8859-1:
$pos = strpos($content, '<x:xmpmeta', 0, 'iso-8859-1');
this forces strpos() (or rather, mb_strpos()) to count every single byte in the data.
This will always work; I do not know whether there is a more elegant way to force the use of a single-byte encoding.
A: The exif_read_data() PHP function could help the XMP meta data
More info here: http://php.net/manual/en/function.exif-read-data.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: copy elision method From the standard definition of copy elision method:
In C++ computer programming, copy elision refers to a compiler optimization technique that eliminates unnecessary copying of objects.
Let us consider following code:
#include <cstdlib>
#include <iostream>
using namespace std;
int n=0;
struct C
{
C (int) {}
C(const C&) {++n;}
};
int main(int argc, char *argv[])
{
C c1(42);
C c2=42;
return n;
}
This line "return n" will returns either 0 or 1, depending on whether the copy was elided.
Also consider this code:
#include <iostream>
struct C {
C() {}
C(const C&) { std::cout << "Hello World!\n"; }
};
void f() {
C c;
throw c; // copying the named object c into the exception object.
} // It is unclear whether this copy may be elided.
int main() {
try {
f();
}
catch(C c) {
}
}
It says that
// copying the exception object into the temporary in the exception declaration.
//It is also unclear whether this copy may be elided.
So my question is how useful is implement such optimization method, if sometimes results are undefined? And in general how often it is used?
A: The important bit is that the standard explicitly allows for this, and that means that you cannot assume that the side effects of a copy constructor will be executed as the copies might be elided. The standard requires that the implementation of a copy-constructor has copy-constructor semantics, that is, has as whole purpose the generation of a second object semantically equivalent in your domain to the original object. If your program complies with that, then the optimization will not affect the program.
It is true, on the other hand, that this is the only situation I can think where the standard allows for different visible outcomes from the same program depending on what the compiler does, but you have been advised that you should not have side effects in your copy constructor (or rather, you cannot depend on the exact number of copies performed).
As to whether it is worth it, yes it is. In many cases copies are quite expensive (I am intentionally ignoring move-constructors in C++11 from the discussion). Consider a function that returns a vector<int>, if the copy is not elided, then another dynamic allocation is required, copy of all of the vector contents and then release of the original block of memory all three operations can be expensive.
Alternatively, you could force users to change their code to create an empty object and pass it by reference, but that will make code harder to read.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607598",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: MVC or MVP architecture for winform applications using Entity Framework as ORM I am going to develop a winform project of considerable size. I am planning to use Entity Framework as ORM tool. Now I am searching for an architecture(MVC/MVP/MVVM etc..) to implement all these. Firstly there are few choices for n-layered architecture for windows forms and most those I get are written prior to EF came into market. I got a framework called Rocket Framework from codeplex(http://rocketframework.codeplex.com)
I have looked around it but am skeptical that it will accommodate a wide range of requirements. If anyone has already discovered the wheel already, please guide me through.
Also if the existing architectures prior EF4 can accommodate it than also I can give it a try.
Ideas please!
A: Well your choices is influenced by the technology you're using. Some technologies make a certain pattern natural to do and thus if you (and every developer) don't explicitely design and care about this you'll end up with what feels most natural. On WinForms the most natural pattern is MVP. You have your view that you can layout in the designer and your code-behind file becomes the presenter, essentially combining view and presenter in one class (it's a 1:1 relationship anyway). For web applications on the other hand MVC is a natural pattern since your web server already acts as a controller. Finally MVVM is supported very well in WPF, although you could fall towards MVP there as well if you start using the code behind file a lot. But relying on DataBinding instead can make you forget to use the code behind file. A good article I read about this is here. Of course you can realize MVVM with WinForms, read this link for a good example.
From the point of testability MVVM is perceived as the best pattern since your view model (and therefor the behavior of your view) can be tested without an actual GUI. MVP however is easy to understand and realize, doesn't require complex bindings and gives you most control over what is happening (e.g. event suppression).
A: WinForms applications are mostly developed with MVP pattern. The original MVC is not used very much - only its Model-2 variant (for example ASP.NET MVC) for web applications. MVVM is used primarily with WPF and Silverlight.
Neither of these patterns affects how you use Entity framework - they are not data access related patterns.
A: After a lot of R&D and extensive study I finally settled here:
https://github.com/geersch/ModelViewPresenter
It is an MVP architecture written by Christophe Geers. It supports all I needed- Architecture for winform, web portability support, Entity Framework. Really nice and easy to use.
Additional reading:
http://www.cerquit.com/blogs/post/MVP-Part-I-e28093-Building-it-from-Scratch.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Does Content Security Policy block bookmarklets? Does Mozillas CSP block to execute Javascript from a bookmark by default?
Can it be configured to do so?
A: The behavior is specified in mozillas wiki.
CSP should not interfere with the operation of user-supplied scripts (such as browser add-ons and bookmarklets).
Have a look here:
https://wiki.mozilla.org/Security/CSP/Specification#Non-Normative_Client-Side_Considerations
A: Yes, the CSP blocks bookmarklets in Mozilla Firefox. There is a bug about it.
However, you can get around this restriction by injecting the JS code into an external CSS stylesheet, like my Top News Feed bookmarklet does:
External CSS:
#topnewsfeed { font-family: '(function(){/*payload*/})()'; }
Bookmarklet JS:
(function() {
var a = document.createElement("link");
a.rel = "stylesheet";
a.href = "//niutech.github.io/topnewsfeed/topnewsfeed.css";
a.onload = function() {
var a = b.currentStyle ? b.currentStyle.fontFamily : document.defaultView.getComputedStyle(b, null).fontFamily;
eval(a.replace(/^["']|\\|["']$/g, ""));
};
document.body.appendChild(a);
var b = document.createElement("div");
b.id = "topnewsfeed";
document.body.appendChild(b);
})()
The bookmarklet loads a CSS file containing JS code, adds an element styled by this CSS, reads the element style attribute and eval the code.
A: As of 2017, the answer is still a definitive "maybe" - just like when this answer was originally posted in 2011. The specification clearly says:
Policy enforced on a resource SHOULD NOT interfere with the operation of user-agent features like addons, extensions, or bookmarklets.
And this is indeed the behavior I see in Chrome 61: a bookmarklet will run on https://addons.mozilla.org/, a site that has a strict content security policy without script-src: 'unsafe-inline'. Yet in Firefox 56 bookmarklets won't run on this website and a CSP violation is being reported.
There is a very long discussion on this issue in the Firefox bug report, in particular linking to a similar discussion on the W3C spec. So as of now, you cannot really rely on bookmarklets being unaffected by CSP. You can always disable CSP altogether, but that's one important protection layer less for you.
A: I have created a work-around "fix" for this issue using a Greasemonkey userscript (in Firefox). You can now have bookmarklets on all CSP and https:// sites, plus have your bookmarklets in a nice, easily-editable library file instead of being individually squished into a bookmark.
See: https://groups.google.com/d/msg/greasemonkey-users/mw61Ynw5ORc/Gl_BNUhtSq0J
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
}
|
Q: Error in Update query [Using String.Format] I am trying to write an update statement for inserting data from asp.net gridview to sql server 2005 database.but it is showing me an error, Please tell me how to solve.
cmdUpdate.CommandText = String.Format("Update Products SET ProductName=
{0},UnitsInStock={1},UnitsOnOrder={2},ReorderLevel={3} WHERE ProductID={4} AND
SupplierID={5}", "productname.Text, unitsinstock.Text, unitsonorder.Text,
recorderlevel.Text, employeeid.Text, supplierid.Text");
Error is-
Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
A: Your syntax for string.Format is incorrect - each parameter after the string template should be on their own, without the double quotes surrounding them all...
This will work (notice I've removed the double quotes from just before 'productname.Text' and after 'supplierid.Text'):
String.Format("Update Products SET ProductName={0}, UnitsInStock={1}, UnitsOnOrder={2}, ReorderLevel={3} WHERE ProductID={4} AND SupplierID={5}",
productname.Text, unitsinstock.Text, unitsonorder.Text,
recorderlevel.Text, employeeid.Text, supplierid.Text);
A: You missed the arguments,
For instance,
str=String.Format("{0} {1}",arg1,arg2);
Do not use hard-coded sql strings. Try to learn/use parameterized queries.
EDIT:
string ConnectionString = "put_connection_string";
using (SqlConnection con = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
string sql = "Update Products SET
ProductName=@ProductName,
UnitsInStock=@UnitsInStock,
UnitsOnOrder=@UnitsOnOrder,
ReorderLevel=ReorderLevel
WHERE ProductID=ProductID AND SupplierID=@SupplierID";
cmd.CommandText = sql;
cmd.Connection = con;
cmd.Parameters.Add("@ProductName", System.Data.SqlDbType.VarChar, 50).Value =productname.Text;
cmd.Parameters.Add("@UnitsInStock", System.Data.SqlDbType.Int).Value =unitsinstock.Text;
cmd.Parameters.Add("@UnitsOnOrder", System.Data.SqlDbType.Int).Value =unitsonorder.Text;
cmd.Parameters.Add("@ReorderLevel ", System.Data.SqlDbType.Int).Value =recorderlevel.Text;
cmd.Parameters.Add("@ProductID", System.Data.SqlDbType.Int).Value =producteid.Text;
cmd.Parameters.Add("@SupplierID", System.Data.SqlDbType.Int).Value =supplierid.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
EDIT: What is C# using block?
*
*If the type implements IDisposable, it automatically disposes it
*Provides a convenient syntax that ensures the correct use of IDisposable objects.
*Avoiding Problems with the Using Statement
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Convert a binary number to Base 64 I know this is a pretty silly question, but I don't know what to do.
I have an arbitrary binary number, say,
1001000000110010000000100100000010000011000000010001000001011000110000110000011100011100000011000000010010011000100000000000000100100000010110001100001000000111
I want to convert it to Base 64 using PHP - and every way I try gives me a different result. Even different online converters convert it differently:
http://home2.paulschou.net/tools/xlate/
http://convertxy.com/index.php/numberbases/
PHP's base_convert only works up to base36, and base64_encode expects a string.
What do I do?
UPDATE: I implemented the solution functions suggested by @binaryLV, and it did work well.
However, I compared the results to PHP's built-in base_convert. It turned out that base_convert to base36 returns shorter values that the custom base64 function! (And yes, I did prepend a '1' to all the binary numbers to ensure leading zeros aren't lost).
I have noticed, too, that base_convert is quite innacurate with large numbers. So I need is a function which works like base_convert, but accurately and, preferably, up to base 64.
A: Length of a string in example is 160. It makes me think that it holds info about 160/8 characters. So,
*
*split string into parts, each part holds 8 binary digits and describes single character
*convert each part into a decimal integer
*build a string from characters, that are made from ASCII codes from 2nd step
This will work with strings with size n*8. For other strings (e.g., 12 binary digits) it will give unexpected results.
Code:
function bin2base64($bin) {
$arr = str_split($bin, 8);
$str = '';
foreach ( $arr as $binNumber ) {
$str .= chr(bindec($binNumber));
}
return base64_encode($str);
}
$bin = '1001000000110010000000100100000010000011000000010001000001011000110000110000011100011100000011000000010010011000100000000000000100100000010110001100001000000111';
echo bin2base64($bin);
Result:
kDICQIMBEFjDBxwMBJiAASBYwgc=
Here's also function for decoding it back to string of binary digits:
function base64bin($str) {
$result = '';
$str = base64_decode($str);
$len = strlen($str);
for ( $n = 0; $n < $len; $n++ ) {
$result .= str_pad(decbin(ord($str[$n])), 8, '0', STR_PAD_LEFT);
}
return $result;
}
var_dump(base64bin(bin2base64($bin)) === $bin);
Result:
boolean true
A: PHP has a built in base 64 encoding function, see documentation here. If you want the decimal value of the binary string first use bin2dec, there are similar functions for hexadecimals by the way. The documentation is your friend here.
[EDIT]
I might have misunderstood your question, if you want to convert between actual bases (base 2 and 64) use base_convert
A: To convert a binary number (2 base) to a 64 base use the base_convert function.
$number = 1001000000110010000000100100000010000011000000010001000001011000110000110000011100011100000011000000010010011000100000000000000100100000010110001100001000000111;
base_convert ($number , 2, 64);
A: $number = 1001000000110010000000100100000010000011000000010001000001011000110000110000011100011100000011000000010010011000100000000000000100100000010110001100001000000111;
echo base64_encode ($number);
This is if you want the exact string be converted into Base 64.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: JScrollPane doesn't appear in my JTextArea This class is the layout and implementation for the first tab in my program, the CreatePanel. I am trying to implement a JScrollPane in my JTextArea. However, the scroll bar never appears, although the program compiles correctly. I've looked all over for solutions and have tried a couple of variations, but nothing is seeming to work.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class CreatePanel extends JPanel
{
private Vector flightList;
private SelectPanel sPanel;
private JButton createButton;
private JLabel airName, flightNumber, departCity, departDay, departTime, arriveCity, arriveDay, arriveTime, price;
private JLabel notify, blank;
private JTextField l1, l2, l3, l4, l5, l6, l7, l8, l9;
private JTextArea flightInfo;
private JScrollPane scroll;
String air, num, dC, dD, dT, aC, aD, aT, prc;
//Constructor initializes components and organize them using certain layouts
public CreatePanel(Vector flightList, SelectPanel sPanel)
{
this.flightList = flightList;
this.sPanel = sPanel;
// organize components here
// creates all labels and textfields for Flight Creation tab
notify = new JLabel("");
blank = new JLabel("");
airName = new JLabel("Enter a name of Airlines");
flightNumber = new JLabel("Enter a flight number");
departCity = new JLabel("Enter a departure city");
departDay = new JLabel("Enter a departure day");
departTime = new JLabel("Enter a departure time");
arriveCity = new JLabel("Enter an arrival city");
arriveDay = new JLabel("Enter an arrival day");
arriveTime = new JLabel("Enter an arrival time");
price = new JLabel("Price");
l1 = new JTextField("");
l2 = new JTextField("");
l3 = new JTextField("");
l4 = new JTextField("");
l5 = new JTextField("");
l6 = new JTextField("");
l7 = new JTextField("");
l8 = new JTextField("");
l9 = new JTextField("");
createButton = new JButton("Create a flight");
createButton.addActionListener(new ButtonListener());
flightInfo = new JTextArea("No flight");
flightInfo.setEditable(false);
// the user-entered information panel
JPanel panelUser = new JPanel();
panelUser.setLayout(new GridLayout(10, 2));
panelUser.add(notify);
panelUser.add(blank);
panelUser.add(airName);
panelUser.add(l1);
panelUser.add(flightNumber);
panelUser.add(l2);
panelUser.add(departCity);
panelUser.add(l3);
panelUser.add(departDay);
panelUser.add(l4);
panelUser.add(departTime);
panelUser.add(l5);
panelUser.add(arriveCity);
panelUser.add(l6);
panelUser.add(arriveDay);
panelUser.add(l7);
panelUser.add(arriveTime);
panelUser.add(l8);
panelUser.add(price);
panelUser.add(l9);
// panel for the button
JPanel panelButton = new JPanel();
panelButton.add(createButton);
// the leftside panel of CreatePanel
JPanel panelLeft = new JPanel();
panelLeft.setLayout(new BorderLayout());
panelLeft.add(panelUser, BorderLayout.CENTER);
panelLeft.add(panelButton, BorderLayout.SOUTH);
// the rightside panel of CreatePanel
JPanel panelInfo = new JPanel();
scroll = new JScrollPane(flightInfo);
scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scroll.setVisible(true);
panelInfo.setLayout(new GridLayout(1, 1));
panelInfo.add(flightInfo);
// WHY WONT YOU WORK?
// layout for CreatePanel
setLayout(new GridLayout(1, 2));
add(panelLeft);
add(panelInfo);
}
}
What am I doing wrong when adding the JScrollPane??
A: You use scrollbar as needed, so the bar will only be visible when you reach the limit of the textarea (overflow, more text than the size :D)
Edit: Additionally, you must add the scroll to the panel and not the flight info
A: You have been trying to add the wrong Panel.
Replace panelInfo.add(flightInfo); with panelInfo.add(scroll) and you should see your JScrollPane appear (you may need to set the scrollbar policies to "ALWAYS" to demonstrate this).
While I'm at it, may I suggest that you try to make a minimum failing example when you post a question? Apologies if I sound pedantic, but it really makes it easier for others to help you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery, how to use multiple ajax requests? i have this situation inside xxx.php:
<form id="s">
<input id="q"/>
<input type="submit" href="Search!"/>
</form>
<div id="r"></div>
inside the foo.php i have another form:
<form id="ss">
<input id="qq"/>
<input type="submit" href="Search!"/>
</form>
<div id="rr"></div>
and inside the yyy.php i have another form:
<form id="sss">
<input id="qqq"/>
<input type="submit" href="Search!"/>
</form>
<div id="rrr"></div>
inside javascript.js i have :
$('#s').submit(function(evt) {
evt.preventDefault();
$.ajax({
url: 'foo.php',
data: {
query: $('#q').val()
},
success: function(data) {
$('#r').html(data);
}
});
return false;
});
$('#ss').submit(function(evt) {
evt.preventDefault();
$.ajax({
url: 'yyy.php',
data: {
query: $('#qq').val()
},
success: function(data) {
$('#rr').html(data);
}
});
return false;
});
what happens is that when i submit the first form the second one load in, so now i have 2 forms (as expected) but when i submit the second form the third one doesn't load using ajax, but it redirects to it by refreshing.
so basically i need to do as many ajax loads as i can
any ideas?
thanks
A: You should use .live because you are adding data dynamically
$('#ss').live('submit', function(evt) {
evt.preventDefault();
$.ajax({
url: 'yyy.php',
data: {
query: $('#qq').val()
},
success: function(data) {
$('#rr').html(data);
}
});
return false;
});
A: You need to use Live events for things you dynamically load in so in your case:
$("#ss").live('submit', function (e) {
// Code here
});
You only need to use live events for things that are not always in the DOM. If you request pages through ajax and then intent to use them you will need to use live events.
See : http://api.jquery.com/live/
For a little more detail
A: try handling newly loaded form $('#sss').submit(function(evt) {});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Replace for-switch loop with a Linq query I have a Message object which wraps a message format I do not have control over. The format is a simple list of Key/Value pairs. I want to extract a list of Users from a given Message. For example given the following message...
1. 200->....
2. 300->....
3. ....
4. 405->....
5. 001->first_user_name
6. 002->first_user_phone
7. 003->first_user_fax
8. 001->second_user_name
9. 001->third_user_name
10. 002->third_user_phone
11. 003->third_user_fax
12. 004->third_user_address
13. .....
14. 001->last_user_name
15. 003->last_user_fax
I want to extract four Users with the provided properties set. The initial keys 200/300....405 represent fields I don't need and can skip to get to the User data.
Each users data is in consecutive fields but the number of fields varies depending on how much information is known about a user. The following method does what I'm looking for. It uses an enumeration of possible key types and a method to find the index of the first field with user data.
private List<User> ParseUsers( Message message )
{
List<User> users = new List<User>( );
User user = null; String val = String.Empty;
for( Int32 i = message.IndexOfFirst( Keys.Name ); i < message.Count; i++ )
{
val = message[ i ].Val;
switch( message[ i ].Key )
{
case Keys.Name:
user = new User( val );
users.Add( user );
break;
case Keys.Phone:
user.Phone = val;
break;
case Keys.Fax:
user.Fax = val;
break;
case Keys.Address:
user.Address = val;
break;
default:
break;
}
}
return users;
}
I'm wondering if its possible to replace the method with a Linq query. I'm having trouble telling Linq to select a new user and populate its fields with all matching data until you find the start of the next user entry.
Note: Relative key numbers are random (not 1,2,3,4) in the real message format.
A: I don't see the benefit in changing your code to a LINQ query, but it's definitely possible:
private List<User> ParseUsers(Message message)
{
return Enumerable
.Range(0, message.Count)
.Select(i => message[i])
.SkipWhile(x => x.Key != Keys.Name)
.GroupAdjacent((g, x) => x.Key != Keys.Name)
.Select(g => g.ToDictionary(x => x.Key, x => x.Val))
.Select(d => new User(d[Keys.Name])
{
Phone = d.ContainsKey(Keys.Phone) ? d[Keys.Phone] : null,
Fax = d.ContainsKey(Keys.Fax) ? d[Keys.Fax] : null,
Address = d.ContainsKey(Keys.Address) ? d[Keys.Address] : null,
})
.ToList();
}
using
static IEnumerable<IEnumerable<T>> GroupAdjacent<T>(
this IEnumerable<T> source, Func<IEnumerable<T>, T, bool> adjacent)
{
var g = new List<T>();
foreach (var x in source)
{
if (g.Count != 0 && !adjacent(g, x))
{
yield return g;
g = new List<T>();
}
g.Add(x);
}
yield return g;
}
A: How about splitting message into a List<List<KeyValuePait<int, string>>> where each List<KeyValuePair<int, string>> represents a single user. You could then do something like:
// SplitToUserLists would need a sensible implementation.
List<List<KeyValuePair<int,string>>> splitMessage = message.SplitToUserLists();
IEnumerable<User> users = splitMessage.Select(ConstructUser);
With
private User ConstructUser(List<KeyValuePair<int, string>> userList)
{
return userList.Aggregate(new User(), (user, keyValuePair) => user[keyValuePair.Key] = keyValuePair.Val);
}
A: No, and the reason being, in general, most LINQ functions, in the same way as SQL queries, deal with unordered data, i.e. they don't make assumptions about the order of the incoming data. That gives them flexibility to be parallelized, etc. Your data has intrinsic order, so doesn't fit the model of querying.
A: I don't think there is any performance benefit, but it increases readability a lot in my opinion.
A possible solution could look like this:
var data = File.ReadAllLines("data.txt")
.Select(line => line.Split(new[] {"->"}, StringSplitOptions.RemoveEmptyEntries))
.GroupByOrder(ele => ele[0]);
The real magic is happening behind GroupByOrder, which is an extension method.
public static IEnumerable<IEnumerable<T>> GroupByOrder<T, K>(this IEnumerable<T> source, Func<T, K> keySelector) where K : IComparable {
var prevKey = keySelector(source.First());
var captured = new List<T>();
foreach (var curr in source) {
if (keySelector(curr).CompareTo(prevKey) <= 0) {
yield return captured;
captured = new List<T>();
}
captured.Add(curr);
}
yield return captured;
}
(Disclaimer: idea stolen from Tomas Petricek)
Your sample data yields the following groups, which now just have to be parsed into your User object.
User:
first_user_name
first_user_phone
first_user_fax
User:
second_user_name
User:
third_user_name
third_user_phone
third_user_fax
third_user_address
User:
last_user_name
last_user_fax
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: writing select clause with times I would like to write a sql clause like:
SELECT * FROM table WHERE orderdate < {orderdate three years after};
I tried some dateadd function, but I didn't find an example to fit just my needs. Any help?
A: If you are using SQL Server:
... WHERE orderdate < DATEADD(year, 3, orderdate)
Documentation and examples here:
http://msdn.microsoft.com/en-us/library/ms186819.aspx
Maybe I've not understood your question correctly but that seems to be a pointless query, as Konerak commented.
A: In MySQL
select * from table
where orderdate < DATEADD(NOW(),INTERVAL 3 YEARS)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CouchDB not updating view for upcoming and past events I have the following view on couchdb that will only return docs with a date greater than the current date like:
function (doc) {
var eventDay = new Date(new Date(doc.start).toDateString()),
currentDay = new Date(new Date().toDateString());
if (eventDay > currentDay) {
emit();
}
}
So in this case the view will always show future(upcoming) events only. I also have the same inverted view to show only past events. But the problem is that apparently the view is not being updated on the next day. So I have to update the view manually by adding few line breaks and so I guess this causes a ‘refresh’.
Any ideas on how I could make this work?
Thanks a lot
A: Don't forget that the map code per entry is executed on document creation/change, thus you will not have consistent values for what you regard as "currentDay".
Instead, you must build a view that allows you to add this information during the query. Here is an example:
funciton(doc){
//Extract from date object.
var year = ..;
var month = ..;
var day = ..;
//..
emit([year,month,day], null);
}
This will create an complex index, ordered by (year,month,day). You can now query for partial ranges, for instance all dates in the future, by using startkey/endkey. Please see the View API for details: http://wiki.apache.org/couchdb/HTTP_view_API
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why does IE not add to my dropDown? I'm running this sample script with IE:
var $select = $('#select');
var $button = $('#button');
$button.click(function() {
var $option = $('<option />');
$option.text('hello');
$option.appendTo($select);
});
var $tabs = $('#tabs');
$tabs.tabs();
It's pretty straight forward: when clicking on the button, an option should be added to my dropdown. This works great - the basic fct in IE either.
My problem:
just "open" the dropDown, and "close" it again. Now switch to tab "button" and hit the button. Now switch to tab "select" - a new option should be available.
This works great on every browser except IE ... (sometimes IE messes up after several tab-switches)
How can I fix my script?
A: There's a much simpler, and more cross-browser friendly, way to add options to select boxes than adding option DOM elements (live example):
$button.click(function() {
var option = new Option('hello');
$select[0].options.add(option);
});
Perhaps that would work more reliably for you. (Note that it's add, not push. The options object on select elements isn't really an array.)
Instead of options.add you can also do:
$button.click(function() {
var options = $select[0].options,
option = new Option('hello');
options[options.length] = option;
});
...which also adds to the end, in an array-like way. But add is reliable cross-browser.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to increment an auto-increment field with ADO.NET in C# I have a database table with three fields:
Product(ProdId, Name, Price)
Where ProdId is a auto-increment field. The auto-increment is with seed 1, starting from 0.
I perform operation on the database by using C# in an ASP.NET application.
If I use LINQ to INSERT a new record I just assign values to Name and Price fields and when I submit the changes the database is responsible to increment the ProdId.
How can I do it with the standard ADO.NET? If I write an INSERT statement
INSERT INTO Product (Name, Price) VALUES (@Name, @Price)
when I execute the command an exception is thrown;
Cannot insert NULL in ProdId.
Anybody has a solution? Thanks
A: I would start debugging in this order:
*
*Make sure in your SQL you do have AUTO Increment on
Data Types can be numeric, money, decimal, float, bigint and int
*
*using the Studio Management tool, run the insert query manually
like:
DECLARE @Name nvarchar(100), @Price money
SET @Name = 'Bruno Alexandre';
SET @Price = 100.10;
INSERT INTO Product (Name, Price) VALUES (@Name, @Price)
or
INSERT INTO Product SELECT @Name, @Price
*
*Make SURE that you are pointing in your ADO Connection to the correct Database.
*If using EF, refresh your table using the Update Table Wizard on the .edmx file
A: How did you define the ProdId, try INT NOT NULL AUTO_INCREMENT ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get the Version Number for JBoss 7 from within a WAR? For older JBoss these mechanisms worked :
*
*Check for Class org.jboss.mx.util.MBeanServerLocator
*Then use JSR77: Look for a JMX MBean with *:j2eeType=J2EEServer,* and get the attribute serverVersion
or
*
*Check for an MBean with name jboss.system:type=Server and get the value of attribute Version
But for JBoss 7 neither MBean exists (nor any suitable class to check, with the WAR sitting in its OSGi cage). All I can do is for searching the JMX domain jboss.modules: if it exists infer that this is a Jboss 7.
Is there a way to get the exact version number from within a WAR's init() ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Convert ArrayList fetched from HashMap to an Array How can i do this ?
When i stored my fields in HashMap , i did it like simple Objects
HashMap map = new HashMap();
map.put ("Autorul",numelePrenumeleAutorului);
map.put ("Denumirea cartii",denumireaCartii);
map.put ("Culoarea cartii",culoareaCartii);
map.put ("Genul cartii",gen);
map.put ("Limba",limba);
map.put ("Numarul de copii",numarulDeCopii);
map.put ("Numarul de pagini",numarulDePagini);
map.put ("Pretul cartii",pretulCartii);
ArrayList arl=new ArrayList();
for (int i = 0;i<numarulDeCopii;i++) {
arl.add(coeficientUzura[i]);
}
map.put ("Coeficientii de Uzura",arl);
I access values from HashMap (look for the last lines)
Carte (String caleSpreFisier) {
HashMap map = new HashMap();
File file = new File(caleSpreFisier);
try {
FileInputStream f = new FileInputStream(file);
ObjectInputStream s = new ObjectInputStream(f);
map = (HashMap)s.readObject();
s.close();
} catch(Exception e){
System.out.println("An exception has occured : "+e);
}
for (Object key :map.keySet()) {
if (key.equals("Autorul")) {
numelePrenumeleAutorului = (String)map.get(key);
}
if (key.equals("Denumirea cartii")) {
denumireaCartii = (String) map.get(key);
}
if (key.equals("Culoarea cartii")) {
culoareaCartii = (String)map.get(key);
}
if (key.equals("Genul cartii")) {
gen = (String) map.get(key);
}
if (key.equals("Limba")) {
limba = (String) map.get(key);
}
if (key.equals("Numarul de copii")) {
numarulDeCopii = (Integer) map.get(key);
}
if (key.equals("Numarul de pagini")) {
numarulDePagini = (Integer) map.get(key);
}
if (key.equals("Pretul cartii")) {
pretulCartii = (Double) map.get(key);
}
if (key.equals("Coeficientii de Uzura")) {
ArrayList temp = new ArrayList();
Object me = map.get(key);
System.out.println(me);
//temp = (ArrayList) map.get(key);
}
}
A: Object[] array = ((ArrayList) map.get(key)).toArray();
A: First of: you're in object denial. Your HashMap should really be a proper class that you wrote with the real properties to hold your different fields.
That way you also don't have to do that ugly "name of the property"-to-local-variable mapping.
Next: if what you put into the map is an ArrayList, then you can just cast what you get out to that type again:
ArrayList temp = (ArrayList) map.get(key);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Change the color of an image in php? How can i change the color of a clipart in a image ,this image has red color heart in it http://www.tutorialpark.com/wp-content/uploads/3/Heart-Blending.jpg i want to change from red to blue in php Thanks. Mostly my images will be in png format.
A: In PHP5 you could use the imagefilter function with the filter, called "IMG_FILTER_COLORIZE". If you dont have PHP5 you could do it manually.
A user, called Bartman did the following solution, which works as far as I tested it: http://www.php.net/manual/en/function.imagecolorset.php#93134
A: To change the color of the image you can use imagefill() or imagefilltoborder ().
Check this.
http://www.tuxradar.com/practicalphp/11/2/8
A: You can use my script if you have installed Imagick Library in your server. You can invoke it with:
./replacecolor -i "{what color shold be replaced}" -o "{to what color}" -f 40 -g 50 {path to img} {path to new image}
example:
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: TinyMCE editor fixed size with no scrollers? At the moment I have this:
tinyMCE.init({
// General options
mode : "exact",
elements : "fkField, lkField, ukcField, khField",
theme : "advanced",
plugins : "table",
width : "300",
height: "185",
// Theme options
theme_advanced_buttons1 : "fontsizeselect, bold,italic,underline,bullist, cleanup, |,justifyleft,justifycenter,justifyright",
theme_advanced_buttons2 : "tablecontrols",
theme_advanced_buttons3 : "",
theme_advanced_buttons4 : "",
theme_advanced_toolbar_location : "bottom",
theme_advanced_toolbar_align : "center",
theme_advanced_resizing : false
});
This gives me a editor with the size of 300x185.
Now in this editor, I would like to do so you can only write until the editor is full. (without the scroller)
So you are unable to enter more text, and the scroller should not appear (disable scrolling)
Right now you can at the bottom of inside the editor just make new line and it will add the scroller <- which i do not want to happen
How can i do this? Is this unpossible? I have made research for some time now, but maybe it's just me searching wrong..
Thanks
A: add in a ccs file the following code
.mceContentBody{
overflow-y:hidden!important;
}
and add the path of css file in content_css attribut of tinymce
content_css : /path/to/css/file.ss
A: You will need to write an own plugin. Check the editor height on each Keystroke (you may use the built in tinymce event onKeyUp). If the heigth changes remove the last inserted code.
EDIT: Howto get the current editor iframe heigth
var currentfr=document.getElementById(editor.id + '_ifr');
if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) { //ns6 syntax
currentfr.height = currentfr.contentDocument.body.offsetHeight + 26;
}
else if (currentfr.Document && currentfr.Document.body.scrollHeight) { //ie5+ syntax
currentfr.height = currentfr.Document.body.scrollHeight;
}
A: I got it to work by adding this to my extra tinyMCE CSS file:
IFRAME {overflow:hidden;}
Previously, the scrollbars were only off in Firefox. This fixes it for Chrome as well. However, it does add a gray bar the side of a scrollbar at the bottom, so I need to enlarge the height of my text editor.
A: for me it worked by just adding rules to a regular stylesheet, it wasn't needed to add a css file to content_css attribute (example is in scss)
.my-tinymce-container {
width: 200px;
.mce-edit-area {
height: 200px;
overflow-y: hidden;
}
}
A: A lot simpler and easy solution would be:
tinymce.init({
selector: '#container',
},
init_instance_callback: function (ed) {
tinymce.activeEditor.getBody().style.overflow = 'hidden'
},
});
Explanation:
In Init callback get the body for TinyMCE and change style as required.
In this case to remove scrollbar overflow = 'hidden'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: unable to get log4net to use WebServiceAppender from crm 2011 I have attempted to use a log4net webserviceappender from within a crm 2011 plugin (sandboxed), log4net apparently gets installed along with the plugin correctly (exception if log4net config file is malformed), but apparently the appender doesn't get called. I can call the webservice directly from within the plugin, so that part is working, but can't figure out what might be wrong with log4net.
Does anyone know of a step by step for using log4net with crm and/or have a good idea as to why the webserviceappender doesn't get called?
Thanks
EDIT: Including log4net.config file upon request.
<!-- WebService parameters. -->
<param name="Url" value="http://my-internal-server/errorlog/ErrorHandler.asmx" />
<param name="TimeoutSeconds" value="60" />
<!-- Proxy parameters. -->
<param name="UseProxy" value="false" />
<param name="ProxyUrl" value="http://myproxy:3128" />
<param name="ProxyBypassOnLocal" value="true" />
<param name="ProxyUseDefaultCredentials" value="true" />
<param name="ProxyCredentialsDomain" value="OFFICE" />
<param name="ProxyCredentialsUserName" value="MyUser" />
<param name="ProxyCredentialsPassword" value="MyPassword" />
</appender>
<root>
<level value="Info" />
<appender-ref ref="WebServiceAppender" />
</root>
A: It looks like you have deployed the configuration file on disk. This is not the ideal place as you have to deal with different requirements for the different modules.
To simplify the deployment of plugins, which need additional configuration, you have the possibility to pass configuration values to the plugin constructor. You should pass the configuration and configure log4net at runtime. See how to write the plugin constructor.
Another option is to use the webressources of Dynamics CRM 2011. See this blog article which describes all available options.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607664",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Code contracts and ASP.Net Validators Imagine I have a method having a contract :
public void Do(string value)
{
Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(value));
MyBusiness.Handle(value);
}
This method is called from an asp.net 2.0 web site, and value is grabbed from a textbox, mandatory :
<asp:TextBox ID="txtValue" runat="server" />
<asp:RequiredFieldValidator runat="server" ControlToValidate="txtValue" ErrorMessage="boom" />
<asp:Button ID="btnDo" OnClick="btnDo_Click" Text="Do" />
The code behind is classic :
protected void btnDo_Click(object source, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
Do(txtDo.Text);
}
}
This code is working, but throw code contracts warnings : Requires unproven (!string.IsNullOrEmpty(value)), which let me think (not surprisingly though) that the static checker is not smart enough to see the Page.IsValid (this would probably far more complex for the static checker to have such intelligence).
What are my options in this case ?
The option option I see is to help the static check with assume :
protected void btnDo_Click(object source, EventArgs e)
{
Page.Validate();
if(Page.IsValid)
{
Contract.Assume(!string.IsNullOrEmpty(value));
Do(txtDo.Text);
}
}
This has the merit to works as expected, but the client side is noised by a lot of Contract.Assume on large project.
Any idea/suggestion ?
A: I think that Contract.Assume() is the right choice here. Yes it's noisy, but I don't know any better way that wouldn't complicate the issue.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Pretty urls (friendly_id gem) with dots Many solutions are available for rails 2 but none for rails 3.1 because the map object has been removed.
Any solution for this problem in the latest rails?
A: I have had to do this recently on a project. Luckily, it's simple to override the slug-generating method on a per-model basis.
please refer to
https://github.com/norman/friendly_id/blob/master/lib/friendly_id/slugged.rb#L113-116
and
https://github.com/norman/friendly_id/blob/master/lib/friendly_id/slugged.rb#L227-231
you should be able to define this on the model:
# Use default slug, but upper case and with underscores
def normalize_friendly_id(string)
super.upcase.gsub("-", ".")
end
Hope this helps.
Note: This method is available in FriendlyId 3.x as well. It's great for defining a custom regex for generating slug strings.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Proving Fibonacci recursive algorithm time complexity I am trying to understand a proof by induction in my algorithms text book. Here's the author is proving using induction that the T(n) will always be greater than 2^(n/2) (This is for calculating the nth fibonacci number using the recursive algorithm):
What I don't understand is the very last step, where he is manipulating the equation. How does he go from:
> 2^(n-1)/2 + 2^(n-2)/2 +1
to
> 2^(n-2)/2 + 2^(n-2)/2 +1
He just randomly changes 2^(n-1)/2 to 2^(n-2)/2. Is this a mistake?
Thanks.
A: It's deliberate, if you look closely it's an inequation and he uses it do finish the induction step.
Note the typo, it should say "We must show that T(n) > 2^(n/2)" and not <.
A: I believe that particular step runs off the assumption that:
T(n-1) > T(n-2)
Therefore, we can form an algebraic inequality:
T(n-1) + T(n-2) + 1 > T(n-2) + T(n-2) + 1
We can lop off the + 1 from the right side (because the inequality will still hold true for anything subtracted away on the LESSER side):
T(n-1) + T(n-2) + 1 > T(n-2) + T(n-2)
From this, substitute our T(m) = 2^(m/2) (for anything less than n and > 2, which n-1 and n-2 both qualify):
2^(n-1)/2 + 2^(n-2)/2 + 1 > 2^(n-2)/2 + 2^(n-2)/2
That gets you that particular step. It's done this way deliberately as the poster above me stated, to get to 2^(n/2).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: HTML5 WebSQL: how to know when a db transaction finishes? I've the following code that gets a json recordset and insert some data in three different tables on the client Web Sql storage.
How can I intercept the end of databaseSync() function?
What I want to do is display an alert or better an ajax spinner gif in order to inform the user when the sync is complete.
Many thanks for your help,
ciao!
function databaseSync() {
// table one
$.getJSON("http://192.168.1.40:8888/iOS/mobilesrv/index.php?ACT=one", function(json) {
$.each(json.results, function(i, res) {
db.transaction(function(tx) {
tx.executeSql("INSERT INTO table1 (A, B, C, D) VALUES (?,?,?,?) ", [res.A, res.B, res.C, res.D], onSuccess, onError);
});
});
});
// table two
$.getJSON("http://192.168.1.40:8888/iOS/mobilesrv/index.php?ACT=two", function(json) {
$.each(json.results, function(i, res) {
db.transaction(function(tx) {
tx.executeSql("INSERT INTO table1 (A, B, C, D) VALUES (?,?,?,?) ", [res.A, res.B, res.C, res.D], onSuccess, onError);
});
});
});
// table three
$.getJSON("http://192.168.1.40:8888/iOS/mobilesrv/index.php?ACT=three", function(json) {
$.each(json.results, function(i, res) {
db.transaction(function(tx) {
tx.executeSql("INSERT INTO table1 (A, B, C, D) VALUES (?,?,?,?) ", [res.A, res.B, res.C, res.D], onSuccess, onError);
});
});
});
}
A: Ok, this is my fifth revision, but I liked this question and I keep coming up with better ideas. This one uses jquery deferred objects and I think it finally covers all cases and works the way it should.
function tableInsert(url) {
var dfd = $.Deferred();
var arr = [];
$.getJSON(url, function(json) {
$.each(json.results, function(i, res) {
var dfd = $.Deferred();
arr.push(dfd.promise());
db.transaction(function(tx) {
tx.executeSql(
"INSERT INTO table1 (A, B, C, D) VALUES (?,?,?,?) ",
[res.A, res.B, res.C, res.D],
function(){
onSuccess(dfd.resolve);
},
function(){
onError(dfd.resolve);
}
);
});
});
$.when.apply(this, arr).then(dfd.resolve);
});
return dfd.promise();
}
function databaseSync() {
$.when( tableInsert("http://192.168.1.40:8888/iOS/mobilesrv/index.php?ACT=one"),
tableInsert("http://192.168.1.40:8888/iOS/mobilesrv/index.php?ACT=two"),
tableInsert("http://192.168.1.40:8888/iOS/mobilesrv/index.php?ACT=three"))
.then(function(){
console.log( 'All processing complete' );
});
}
For this to work you'll need to change onSuccess and onError to execute the resolve function as a callback function after doing whatever else it is they do and then this should work for you. I hope you find this useful.
A: Alternately, you can use one transaction for the bulk insert and use callback function to get notified about completion of the transaction
function doSync(){
databaseSync(function(){
console.log('database sync is completed')
});
}
function databaseSync(onTrxSuccess) {
db.transaction(function(tx) {
// table one
$.getJSON("http://192.168.1.40:8888/iOS/mobilesrv/index.php?ACT=one", function(json) {
$.each(json.results, function(i, res) {
tx.executeSql("INSERT INTO table1 (A, B, C, D) VALUES (?,?,?,?) ", [res.A, res.B, res.C, res.D], onSuccess, onError);
});
});
// table two
$.getJSON("http://192.168.1.40:8888/iOS/mobilesrv/index.php?ACT=two", function(json) {
$.each(json.results, function(i, res) {
tx.executeSql("INSERT INTO table1 (A, B, C, D) VALUES (?,?,?,?) ", [res.A, res.B, res.C, res.D], onSuccess, onError);
});
});
// table three
$.getJSON("http://192.168.1.40:8888/iOS/mobilesrv/index.php?ACT=three", function(json) {
$.each(json.results, function(i, res) {
tx.executeSql("INSERT INTO table1 (A, B, C, D) VALUES (?,?,?,?) ", [res.A, res.B, res.C, res.D], onSuccess, onError);
});
});
}, null, onTrxSuccess);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Pen input in Android tablet I want to use pen in android tablet . I use pen and want to write text with pen. How can I develop the android application to be accept only pen input in EditText . Can I use pen in emulator ? Is there any usable API for this .?
A: As far as I know, only HTC supports a pen on some their android tablets (please someone correct me if I'm wrong, I may not be up-to-date on these things). Their pen can be used concurrently while you're touching the device because their screen can tell the difference between your finger and their special pen.
Here is a link to their pen api
http://www.htcdev.com/devcenter/tablet-pen
(free registration with their site is required I believe)
I believe they have an HTC SDK you can download with the AVD manager, but I just don't know if it comes with a special emulator for their pen api -- I haven't tried it yet.
Also other android tablets/phones can be used with pens, even if they're technically not made to support pens (but those pens are just special styluses that emulate the capacitive touch of your finger), so with those devices, the screen can not tell the difference between your fingers and that pen (so you can not assign them different functions which is definitely not as good).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting user specified information from URL in Objective C iOS Currently I am working with a UIWebview which shows web content provided from a user. In this content there will be links to other web content and I need to decide whether to open links in safari or in the UIWebview.
My current solution is to add a queryString to the URL in the html e.g. <a href=http://www.w3schools.com?StayInApp target=_blank>Visit W3Schools</a>
When the user presses the link the following method in the UIViewController decides how to open the link.
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
NSLog(@"%@",url);
NSLog(@"%@",[url scheme]);
NSLog(@"%@",[url user]);
NSLog(@"%@",[url query]);
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
if ([[url query]isEqualToString:@"OutOfAppApp"]) {
NSLog(@"go out");
[[UIApplication sharedApplication] openURL:url];
return NO;
}
else if([[url query]isEqualToString:@"StayInApp"])
{
return YES;
}
}
return YES;
}
I do not have very much experience within web development and can therefore not see the consequences of using this approach. Is this a valid approach or should I use another way?
Regards
EDIT:
I have now come up with another approach using custom URL schemes, but I would still like comments on whether this is a valid solution :)
I have added a prefix to the links such as <a href=InAPP:http://www.w3schools.com target=_blank>Visit W3Schools</a>
When a user presses a link the app examines the prefix and decides whether to launch the rest of the url in the app or in safari. This is done with the following methods:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSURL *url = [request URL];
if (navigationType == UIWebViewNavigationTypeLinkClicked) {
if ([[url scheme]isEqualToString:@"InAPP"]) {
NSLog(@"go in");
NSURLRequest *req=[NSURLRequest requestWithURL:[self removeExtensionFromURL:url]];
[[self browserView] loadRequest:req];
return NO;
}
else if([[url scheme]isEqualToString:@"OutAPP"])
{
NSLog(@"go out");
[[UIApplication sharedApplication] openURL:[self removeExtensionFromURL:url]];
return NO;
}
}
return YES;
}
-(NSURL*)removeExtensionFromURL:(NSURL*)url
{
NSMutableString *urlString=[NSString stringWithFormat:@"%@",url];
NSString *newURLString;
if ([[url scheme]isEqualToString:@"InAPP"]) {
newURLString = [urlString stringByReplacingOccurrencesOfString:@"InAPP:" withString:@""];
}
else if([[url scheme]isEqualToString:@"OutAPP"])
{
newURLString = [urlString stringByReplacingOccurrencesOfString:@"OutAPP:" withString:@""];
}
return [NSURL URLWithString:newURLString];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is using JPA/ORM to generate a db schema a bad idea? Salve!
Part of another question/answer on SO (as well as other statements claiming the same):
if you are updating your database schema by JPA (generally not a good practice though)
Is it true that you should not use a JPA implementation to generate your db schema?
I have to model the entities and relationships ony my own anyways. I need to define constraints such as notnull, primary and foreign keys, data types and sizes as well.
Assuming that the JPA implementation in use does not have any flaws in its DDL schema creation code and also assuming that I do specify all JPA constraints, relations etc. correctly, the db schema created by the JPA implementation should be exactly the same -if not better- as a schema handcrafted by myself, right?
This does not include "special cases" such as (business-logic-) specific INSERT triggers etc., because these can not be generated by the JPA implementation at all (as far as I know, correct me if I'm wrong).
What's your view on this?
I do currently handcraft my db schema first, then setup the JPA constraints, relations etc. and let the JPA implementation create a db schema as well. I then compare the two schemata to see whether I've done the setup correctly. This does of course mean that I also have to specify the same column names etc. as I did for my handcrafted schema.
To make my question more precise; I do not blindly trust on the ORM framework to generate a schema for me. I rather have an idea of how the schema looks in my mind and then configure the framework to match it.
I guess you could create more/most efficient schemata only by hand, but after all I need (or rather want to) use them with an ORM framework. So while I should not do so, I need to keep the limitations of ORM frameworks in mind when creating a db schema anyways.
So since I use an ORM framework in order not to have to care about RDBMS specifics, what's the point of having my application create the schema using RDBMS specific DDL?
If I have to use some existing and exotic schema I do not need to (re-)create the schema anways as well as I might not be able to use such a generic tool as an ORM framework.
A: I usually let JPA create the schema initially only. After, I fine-tune it and maintain it by hand.
There are several reasons I prefer maintaining the schema by hand:
*
*it allows putting comments in the SQL code
*it allows adding comments/descriptions for the tables and columns
*it allows specifying table spaces and other things that are not possible with JPA annotations
*it allows splitting the schema creation between several SQL files (one per table + one for the constraints, for example)
*it lets me reuse some parts of the schema creation script in my schema migration script. For example, if version 2 of my app introduces 3 new tables, I need an alter script that can reuse the three SQL files creating the three new tables
*I sometimes need to use synonyms for sequences, rather than concrete ones
*it lets me choose names for primary key constraints
*probably some other reasons I've forgotten
A: I usualy do the opposite, i.e. create the DB schema manually, then I use my IDE to export the JPA entity structure from it. Afterwards, I refine the JPA entities again manualy.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How can i create a my own custom button without using interface builder? I want to create my own custom button without using any interface builder.
Actually i wants to set all my properties/attribute(Like frame,color,size,label etc.) separate in a NSObject class.Then from my UIView class i want to draw them .
How can i do it as i am never use NSObject class?
Any sample application or example to do this?
A: Actually, you can subclass UIButton - for an example, have a look at Fun With UIButtons and Core Animation Layers. Is this is too much, you can simply create a new UIButton and set it's properties:
UIButton *btn = [[UIButton alloc] initWithFrame:yourFrame]
btn.backgroundColor = [UIColor redColor];
...
[btn release;]
A: Check this Code:
UIButton *btn=[[UIButton alloc] initWithFrame:CGRectMake(152,0,150,128)];
[btn setBackgroundColor:[UIColor clearColor]];
[btn setImage:actualImage forState:UIControlStateNormal];
[btn setTag:1];
[btn addTarget:self action:@selector(btnTouched:)forControlEvents:UIControlEventTouchDown];
[self addSubview:btn];
[btn release];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Selenium Script For IE I got this error , while running selenium script for Internet Explorer 9.
Exception in thread "main" org.openqa.selenium.WebDriverException: Unexpected error launching Internet Explorer. Protected Mode must be set to the same value (enabled or disabled) for all zones. (WARNING: The server did not provide any stacktrace information); duration or timeout: 193 milliseconds
A: There is a bug report discussing this issue: http://code.google.com/p/selenium/issues/detail?id=1795
If you turn ON protected mode in ALL Internet Explorer Zones (Security Tab in IE settings) I believe the issue is resolved.
A: DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(
InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,
true
);
WebDriver dr = new InternetExplorerDriver(ieCapabilities);
A: Don't do it through code here is why
http://jimevansmusic.blogspot.com/2012/08/youre-doing-it-wrong-protected-mode-and.html
A: WebDriver driver = null;
@BeforeSuite
public void suiteSetup() {
System.setProperty("webdriver.chrome.driver", "D:\\drivers\\chromedriver.exe");
driver = new ChromeDriver();
}
//Simply create some blank annotations over here for validation purpose
@BeforeTest
public void testSetup() {
}
@BeforeMethod
public void methodSetup() {
}
@Test
public void testMethod1() throws IOException {
FileInputStream file = new FileInputStream("C:\\Users\\Desktop\\Leave_Details.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(file);// .xslx file
HSSFWorkbook wb = new HSSFWorkbook(file);- .xsl file
XSSFSheet sh = wb.getSheet("Sheet1");
HSSFSheet sh = wb.getSheet("Sheet1");// Sheet1 need to be replaced with actual tab name
System.out.println(sh.getRow(0).getCell(0).getStringCellValue()); // Gives the data. need to update the row and column numbers accordingly
driver.get("url");
//Get the title of the application
String strTitle = driver.getTitle();
System.out.println("Title of the page:"+strTitle);
//No of elements
List<WebElement> listElements = driver.findElements(By.xpath("")); // Use findelemet'S' not findelement
System.out.println(listElements.size());
}
@Parameters ({"Type","Name"}) // Add name of parameters added in testng.xml and give name over here and do the same naming in method
@Test
public void testMethod2(String strType, String strName) {
System.out.println(strType); //Gives the parameter value specified in testng.xml
}
@AfterTest
public void testTearDown() {
}
@AfterMethod
public void methodTearDown() {
}
@AfterSuite
public void suiteTearDown() {
driver.close();
}
A: File src=new File("filepath/excelsheetname.xlsx");
// load file
FileInputStream fis=new FileInputStream(src);
// Load workbook
XSSFWorkbook wb=new XSSFWorkbook(fis);
// Load sheet- Here we are loading first sheetonly
XSSFSheet sh1= wb.getSheetAt(0);
// getRow() specify which row we want to read.
// and getCell() specify which column to read.
// getStringCellValue() specify that we are reading String data.
System.out.println(sh1.getRow(0).getCell(0).getStringCellValue());
System.out.println(sh1.getRow(0).getCell(1).getStringCellValue());
System.out.println(sh1.getRow(1).getCell(0).getStringCellValue());
System.out.println(sh1.getRow(1).getCell(1).getStringCellValue());
System.out.println(sh1.getRow(2).getCell(0).getStringCellValue());
System.out.println(sh1.getRow(2).getCell(1).getStringCellValue());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: binary propery in EF4 with mysql -- datatype I am using mysql together with EF4 and VS2010. I am using model first and uses the Generate database from model function to create the database.
Problem is that the binary properties in the model is converted to varbinary(100). I need them to be converted to MEDIUMBLOB.
I know I can change this manually but it would be really great if this could be done automaticly.
A: Is one-time mapping change automatically enough? ;-)
You can do this in model designer, just select Table mappings from Entity RMB menu, .
EDIT:
That is weird, but it looks like actually Table Mappings does not allow to change mapping types.
Anyway, what you can do is to change T4 template to generate SQL. To do this, find file:
VS_BASE_DIR\Common7\IDE\Extensions\Microsoft\Entity Framework Tools\DBGenSSDLToSQL10.tt
and modify line 165 to return proper SQL Type name instead of the one returned by ToStoreType() extension method of EdmProperty. Unfortunately I didn't find a way to modify it directly.
Of Course this will modify settings for all further projects. If that is not desired, you can make a copy of original template and chose right one through EF Model Properties\DDL Generation Template in every project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't use "acts_as_url" in ruby on rails 3 I'm newb and I'm sorry because of my dumb question! Please, help me!!
I'm working with Rails 3, and this my problem:
I have a model name: Photo using gem 'mongoid'.
I want to make a permalinks which are readable url instead of unreadable '_id' generated from mongoid!
After searching in google, I found a gem called 'stringex'! I decided to use this gem, and put this line in my Gemfile:
gem 'stringex'
then ran "bundle install' to use it.
I just do everything following the guide in github Readme_rsl/stringex but the trouble occurs:
undefined method `acts_as_url' for Photo:Class
Is it because ROR 3 doesn't support this gem? Or I missed something?
Please, I need help!
A: This is probably not the answer you're looking for, but I think the answer is "you can't do that." At least not currently.
The gem you mention is intimately tied to ActiveRecord (see this issue ticket). If you look in the stringex source code in lib/stringex.rb, you can see that acts_as_url is only included on ActiveRecord and not on Mongoid.
What's happening is that you're using Mongoid on your model, and the nice acts_as_url methods are not attached to the Mongoid::Document. It MAY be as simple as just modifying lib/stringex.rb to also include acts_as_url on Mongoid, though I assume that if it were that simple it would already have been done.
So where does that leave you? There are other ways to generate slugs. I haven't used any of them, so I can't speak to which ones are good or not. Googling "mongoid slug generation" can hopefully point you in the right direction.
A: Your model needs to have a url attribute to store the nice url in the database for later use.
I don't know why the don't mention that on the README. I found that out after reading a couple of articles.
A: In my case restarting the rails server command helped.
A: This isn't difficult to write yourself. And it will help you to understand a few parts of rails and routes.
*
*Add a 'permalink' column to the db.
*Do a find_by_permalink(params[:id]) in the controller
*Add a def to_param method to the model and return the permalink
column
*Add a create_permalink before_validations method. Generate the
permalink however you like and store it in the db.
The only trick is ensuring uniqueness and handling name (and url) changes. stringex looks like it helps with uniqueness, not with name changes.
There are other gems to help with name changes (aliasing and redirecting if there's a new name) if you care about that. You can handle that in different ways.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: @WebServlet annotation and error 404 First of all: I use GlassFish 3.1 + Eclipse Java EE indigo.
I want to testing cache solutions with javaee so I made a dummy app. I have a big generated database and I list, search, modify, etc some data. To do that I wrote some basic servlet and I call with GET parameters. e.g.: /app/list?page=product&pageSize=100
The ListServlet is annotated with
@WebServlet({ "/ListServlet", "/list" })
and it works like a charm, I can use both urls.
So I need some additional servlet (for search, modify). I created them and annotated the same way.
But when I type the url http://localhost/app/modify or /app/search?id=1 I get error 404.
I tried to write a very dummy helloservlet which is print a hello world message but it didn't work: error 404. I restarted the glassfish server and the computer but not helped.
What's the problem? Did I miss something?
EDIT:
the servlets are the same package uses the same imports...
A: Are you sure your url patterns are correct? Try something like this:
@WebServlet( name="ListServlet", displayName="ListServlet", urlPatterns = {"/list","/modify", "/search"}, loadOnStartup=1)
If you want all the patterns go into the same servlet. If not, you would have to have a different servlets for each pattern, and those servlets should be named differently I guess.
Anyway, for this kind of behaviour I would recommend using for example Restlet routing.
EDITED:
I tested it. Here you have my servlets working like a charm:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(asyncSupported = false, name = "HelloServlet1", urlPatterns = {"/hello1"})
public class TestServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.write("<h2>Hello Servlet One </h2>");
out.close();
}
}
and the second one:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(asyncSupported = false, name = "HelloServlet2", urlPatterns = {"/hello2"})
public class TestServlet2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.write("<h2>Hello Servlet Two </h2>");
out.close();
}
}
I do call them like: http://localhost:8080/eetest/hello1 and http://localhost:8080/eetest/hello2 and they print 'Hello Servlet One' and 'Hello Servlet Two' respectivelly.
(tested on JBoss AS 7 - web profile)
A: I had this issue and the problem was a forgotten import statement in my servlet. Make sure your servlet is compiling correctly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How can I force Vaadin v8 to update the screen? I have a small Vaadin v8 application that has several input fields (comboboxes, selectgroups, etc...). The content of most of these is determined by the chosen content of the first ComboBox. However, when I select something in it, all the others stay blank until I click one, at which point they all update. This is not desired behaviour, but I assume it's being caused by the server-side being up to date but not updating the client side view. (Even when adding requestRepaint() in my first Combobox's ValueChangeListener)
There must be some method to force Vaadin to get the data I want it to display even if no other components are clicked?
EDIT
I'm not allowed to post answers to my own question so soon, so I'm putting it here temporarily:
I found that there's a javascript method that synchs client and server.
myComponent.getApplication().getMainWindow().executeJavaScript("javascript:vaadin.forceSync();");
The only problem I have now is that the ValueChangeListener on one of my comboboxes still only fires when I click another combobox (or the same one twice). It's the weirdest thing because the second combobox, when loaded, fires it's event perfectly.
A: I had the same problem, see below how it could be done in version 8.0.5 (from 2017):
@Push
public class WebUi extends UI {
public void fireComponentUpdated() {
getUI().push();
}
}
A: There is a hack you can use if you have set a datasource for your componets that forces vaadin to re-render them. I use this for updating tables that have dynamic data
yourcomponent.setContainerDataSource(yourcomponent.getContainerDataSource());
A: Did you requestRepaint on the correct components?
Keep in mind that requestRepaint marks the component as dirty but doesn't mean it will be repainted - a client can only be refreshed when it makes a request to the server.
See this thread https://vaadin.com/forum/-/message_boards/view_message/231271 for more information about your options (it deals with UI refreshes due to background thread processing).
A: Is the first ComboBox in "immediate" mode?
If not, it probably should be : component.setImmediate(true).
See https://vaadin.com/book/-/page/components.selection.html
A: In Vaadin 7 it is enough to put this line in main UI.init(VaadinRequest) method:
UI.getCurrent().setPollInterval( 1000 );
if you want to refresh your UI (in this case) every second. This way you instruct UI to poll server for changes in defined interval.
Beware, excessive server traffic might be a problem if you have lot of users that use your application at the same time.
In Vaadin 6 you will have to play with ProgressIndicator (which could be invisible if you want) and try to do the similar what UI.getCurrent().setPollInterval(int) in Vaadin 7 does.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
}
|
Q: How to make the JInternalFrame of the specified size? I have a JFrame.
I have added menu-bar to it.
I have set its size and location using following line.
frmMain.setBounds(0, 0, 1024, 768); // JFrame
Next I have added a JInternalFrame to the code for JInternalFrame as follows:
ifActivateProject=new JInternalFrame();
ifActivateProject.setBounds(450, 400, 300, 350);
ifActivateProject.add(pnlActivateProject);
ifActivteProject.setVisible(true);
ifActivateProject.setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
frmMain.getContentPane().add(ifActivateProject);
When I executes the program the Internal frame occupies all the remaining area in JFrame. As I have set the location and size of internal frame. It wont appear at that location and of the specified size.
I want to show Internal frame of different sizes depending on menu click means on one menu click one internal frame has shown. After closing that internal frame on another menu click another should be appear in my JFrame. All these internal frames are of different sizes. But the problem is the added internal frame as shown in above code snippet acquires all the space of JFrame.
What's wrong with above code?
A: A JInternalFrrame should be added to a JDesktopPane, not a JFrame.
See How to Use Internal Frames for more details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: WP7 (windows phone 7) How to zoom with the PhotoCamera? I'm using the PhotoCamera for an AR app and I was thinking that a zoom in/out function would be a nice one.
But I can't figure out how to do it. There is no zoom method in the PhotoCamera Class.
Does anyone have a lead on how to do it ?
A: I've trying to figure out the same problem. It seems, that there is no way to do any zooming with PhotoCamera class.
The only way to implement a zoom is digitally zooming by cropping the image and scaling it. One way to do this, is simply to scale the UI element (for example Rectangle) that the videobrush is set to. If you are processing the frames, you have to apply the same cropping and scaling to the preview buffer that you get from the camera class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Generate object model out of RelaxNG schema with RNGOM - how to start? I want to generate an object model out of an RelaxNG Schema.
Therefore I want to use the RNGOM Object Model/Parser (mainly because I could not find any alternative - although I don't even care about the language the parser is written in/generates). Now that I checked out the RNGOM source from SVN, I don't have ANY idea how to use RNGOM, since there is not any piece of information out there about the usage.
A useful hint how to start with RNGOM - a link, example, or any description which saves me from having to read understand the whole source code of RNGOM - will be awarded as an answer.
Even better would be a simple example how to use the parser to generate an Object model out of an RNG file.
More infos:
I want to generate Java classes out of the following RelaxNG Schema:
http://libvirt.org/git/?p=libvirt.git;a=tree;f=docs/schemas;hb=HEAD
I found out that the Glassfish guys are using rngom to generate the same object model I need, but I could not yet find out how they are using rngom.
A: A way to proceed could be to :
*
*use jing to convert from Relax NG to XML Schema (see here)
*use more common tools to generate classes (e.g. JaxB).
A: Hi I ran into mostly the same requirement except I am concentrating on the Compact Syntax. Here is one way of doing what you want but YMMV.
To give some context, my goal in 2 phases: (a) Trying to slurp RelaxNG Compact Syntax and traverse an object/tree to create Spring 4 POJOs usable in Spring 4 Rest Controller. (b) From there I want to develop a request validator that uses the RNG Compact and automatically validates the request before Spring de-serializes the request. Basically scaffolding JSON REST API development using RelaxNG Compact Syntax as both design/documentation and JSON schema definition/validation.
For the first objective I thought about annotating the CompactSyntax with JJTree but I am obviously not fluent in JavaCC so I decided to go a more programatic approach...
I analyzed and tested the code in several ways to determine if there was a tree implementation in binary, digested and/or nc packages but I don't think there is one (an om/tree) as such.
So my latest, actually successful approach, has been to build upon binary and extend SchemaBuilderImpl, implement the visitor interface, and passing my custom SchemaBuilderImpl to CompactSyntax using the long constructor: CompactSyntax(CompactParseable parseable, Reader r, String sourceUri, SchemaBuilder sb, ErrorHandler eh, String inheritedNs)
When you call CompactParseable.parse you will get structured events in the visitor interface and I think this is good enough to traverse the rng schema and from here you could easily create an OM or tree.
But I am not sure this is the best approach. Maybe I missed something and there is in fact an OM/Tree built by the rngom implementation (in my case CompactSyntax) that you can traverse to determine parent/child relationships more easily. Or maybe there are other approaches to this.
Anyway, this is one approach that seems to be working for what I want. Is mostly visitor pattern based and since the interfaces were there I decided to use them. Maybe it will work for you. Bottom line, I could not find an OM/AST that can be traversed implemented anywhere in the implementation packages (nc, binary, digested).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Can I reference an external JavaScript file in a PHP file? I cannot seem to get this to work. I have a small JS file that switches banners depending on the time of day, but it seems that doing an external reference in my PHP file does not work. It works fine in an HTML page.
This is the code in the JavaScript file.
function getStylesheet() {
var currentTime = new Date().getHours();
if (7 <= currentTime && currentTime < 19) {
document.write("<img src='images/banner_day.jpg'>");
} else {
document.write("<img src='images/banner_night.jpg'>");
}
}
getStylesheet();
And here is the reference code I used to call the JavaScript file. Its in a PHP file.
<script src="http://beta.website.com/wp-content/themes/theme/scripts/banner.js"></script>
Everything on the PHP page shows up in the browser, except for the banner that I tried to call with the script.
Here is the entire PHP file code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div id="main">
<div class="container">
<div id="header">
<div id="logo">
<a href="http://bifffffdggdch.com"><img src="http://beta.dfdfdf.com/wp-content/themes/asdafd/images/logo.png" /></a>
</div>
<div id="shadow2"></div>
<div id="shadow1"></div>
<ul id="menu">
<li><a href="">df</a></li>
<li><a href="">df</a></li>
<li><a href="">fd df df</a></li>
<li><a href="">The asfdssd asdfds</a></li>
<li><a href="">sf</a></li>
<li><a href="">df</a></li>
<li><a href="">dfd</a></li>
</ul>
<div id="slogan"><big>"fasfdsads2005."</big></div>
<div id="loginDiv">Login Panel Here</div>
</div>
<div id="banner">
<script src="http://beta.adsfasfasfd.com/wp-content/themes/adfadsf/scripts/banner.js"></script></div>
<div class="sidebar">
Sidebar Content<br />
<br /><br />
blah
blah
blah
</div>
<div class="content">
Main Content
<br />
<br />
<br />
<br />
<br />
<br />
</div>
<div id="footer">
<div class="container">
<div class="footer_column long">
<h3>Cadsfadsfafdfsd.com All Rights Reserved</h3>
<p>dsafasdfdffadffadsdafsdfsadafsdfsadfas</p>
</div>
<div class="footer_column2">
<h3>More Links</h3>
<ul>
<li><a href="http://aadfsdfsdfa.
com">asfsdfa</a></li>
<li><a href="http://ItsNotch.
com">ItsNotch</a></li>
<li><a href="http://adfasfsfaf.
com">adsfasf</a></li>
<li><a href="http://twitter.
com/safs">Twitter</a></li>
<li><a href="https://www.facebook.com/group.php?gid=10215yy20340498">Facebook Fan Page
</a></li>
</ul>
</div>
<div class="footer_column2">
<h3>RSS</h3>
<ul>
<li><a href="">RSS Feed</a></li>
<li><a href="">What is RSS?</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
A: Have you made sure that you've actually got the <script></script> in your head? I certainly can't see it there (unless it is in <?php wp_head();>?).
Having attempted to navigate to http://beta.website.com/wp-content/themes/theme/scripts/banner.js it returns a 404, you'll need to fix this issue first.
Remember that javascript is client side, and all you want to do with php is spit out the tags somewhere for the browser to deal with.
A: It might be path problem.
What is you images (full) path?
What is you page (full) path?
As it is now it looks for images directory beneath your current page. Is this correct?
A: Try changing your Javascript to this:
window.onload = function () {
// Uncomment this line to make sure the script is loading/running, then delete it
// alert('Hello, your Javascript is running');
// Declare variables
var currentTime, bannerDiv, newImg;
// Get currentTime
currentTime = new Date().getHours();
// Get 'banner' div
bannerDiv = document.getElementById('banner');
// Get create a new <img>
newImg = document.createElement('img');
// Assign a src="" attribute depending on the time
newImg.src = (currentTime > 7 && currentTime < 19) ? 'images/banner_day.jpg' : 'images/banner_night.jpg';
// add the new image to the document
bannerDiv.appendChild(newImg);
};
And put it in the <head> of the document, so change
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<!-- ....... -->
<div id="banner">
<script src="http://beta.adsfasfasfd.com/wp-content/themes/adfadsf/scripts/banner.js"></script>
</div>
<!-- ....... -->
...to:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://beta.adsfasfasfd.com/wp-content/themes/adfadsf/scripts/banner.js"></script>
</head>
<body>
<!-- ....... -->
<div id="banner"></div>
<!-- ....... -->
If it still doesn't work, one of two things is happening:
*
*Your javascript file is not actually at http://beta.adsfasfasfd.com/wp-content/themes/adfadsf/scripts/banner.js so the script cannot be loaded/run. Uncomment the first line to confirm that the script is running.
*Your banner images cannot be found at images/banner_night.jpg - make sure your relative paths are correct.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: XCreateGC function performance I've a problem with XCreateGC function performance. It seems that works normal(fast) in several cases, and very slow in other cases:). For more details, please look on this code:
void some_function(int dx, int dy, int sx, int sy, int w, int h,
Drawable src, Drawable mask, Drawable dest)
{
Display *dpy = QX11Info::display();
GC gc = XCreateGC(dpy, src, 0, 0);
XSetClipOrigin(dpy, gc, dx - sx, dy - sy);
XSetClipMask(dpy, gc, mask);
XCopyArea(dpy, src, dest, gc, sx, sy, w, h, dx, dy);
XFreeGC(dpy, gc);
}
Thanks in advance.
A: The key to Xlib performance is understanding when the library needs to block for a reply from the X server. In general, creating a resource (such as GC) does not require blocking; the resource ID is allocated on the client side, and the create request is simply queued up or sent, with no waiting for a reply. At the time when an Xlib call eventually needs a reply, it will have to suddenly stop and wait for ALL requests up to that point to complete, get replies for everything pending, and finally get the reply for the call at hand. This will make one Xlib function look like it's super slow, but really you're seeing the cost of a whole bunch of previous functions, potentially.
XCreateGC should not block for replies, though, as far as I know. It may be possible that it blocks due to a full send buffer? Perhaps you have a flood of requests and at some point your app stalls while it blocks on a full socket buffer, until the X server can catch up and read more requests.
Anyway since this question is old it's probably too late to ask for details, but I think the basic answer is that if you're using a profiler, an Xlib function call may be on the stack when Xlib is actually waiting for or experiencing the consequences of some earlier Xlib function call, or just the sheer number of X requests you are making. Most likely XCreateGC itself is not the problem.
Another esoteric reason to wait for the X server can be that another client has a server grab, which keeps the server from processing requests from anyone else.
The key strategies are often:
*
*reduce number of X requests
*do as much as possible before you block for a reply (rough rule of thumb, anything called XGetSomething will have to wait for all pending requests to complete, then gather all replies)
Those are usually the main issues, the exception is when you do some truly heavy operation such as moving lots of image data around, then a single operation can be more important than number of ops or round-trip blocking.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Delete GWT module development mode? I have a GWT application with several modules. I have deleted one that I don't need anymore (JasperReportTest) - I deleted JasperReportTest.gwt.xml file and classes referring to that module.
But when I try to run my application in development mode I get this in my console:
Loading modules
com.mycompany.myapp.JasperReportTest
[ERROR] Unable to find 'com/mycompany/myapp/JasperReportTest.gwt.xml' on
your classpath; could be a typo, or maybe you forgot to include a
classpath entry for source?
If I run compile everything works fine. How can I delete the module, so development mode won't try to load it? I searched project for string "JasperReportTest" and I didn't find it. Where is loading of this module written?
A: Solved - problem was that in Run configurations I had that module in startup command
A: Have a look at the Google → Web Toolkit in your project's properties.
A: I was getting the same behaviour, and the good place to remove the reference to the unwanted module is in "run configuration" dialog but in the "arguments" tab', not in GWT one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: .gitattributes not making a difference, trying to skip files when using git difftool I've read the Git Pro website and I've read multiple answers on StackOverflow, but sadly I am simply unable to make .gitattributes work for me.
Whenever I'm using git difftool, it will attempt to display the difference between binary files, such as image files (PNG).
I have tried a variety of combinations in my .gitattributes file, but whenever I run my git difftool command, it still attempt to compare the binary files.
In my repository's folder, I have:
.git
.gitattributes
[my project's files subdirectories]
I have tried many combinations of filters for my .gitattributes file. For example:
*.pbxproj binary
*.png binary
Or also:
*.pbxproj binary -diff
*.png binary -diff
Even:
*.pbxproj binary
*.png binary
*.pbxproj -diff -difftool
*.png -diff -difftool
Every time, I simply add my .gitattributes file to the index and commit it. However, after doing so, when I run my git difftool to examine my differences between two branches, this happens:
git difftool otherBranch HEAD
Viewing: 'MyApp.xcodeproj/project.pbxproj'
Hit return to launch 'diffmerge':
Viewing: 'MyApp/Background1.png'
Hit return to launch 'diffmerge':
How come it's doing this? How can I finally set my .gitattributes file properly so I do not have to view the diffs for these specific files?
To further investigate, I have used the git check-attr command as follows:
git check-attr binary MyApp/MainBackground.png
The output is MyApp/MainBackground.png: binary: set ... I wonder why git difftool still forces me to view the diff!
A: It looks like this is a deficiency in difftool. If you use the .gitattributes file as you have described then the output of 'git diff' is modified as intended so setting *.proj binary or *.proj -diff changes the git diff output for any .proj files to 'binary files differ'. However, difftool apears never to look at the attributes. I believe this is because difftool basically calls the same code as mergetool and merging of binary files is supported (if only by copying one over the other). The attached patch is a small change to the difftool-helper script that should cause it to skip files for which the binary attribute is set. It is probably something for the git mailing list.
--- git-difftool--helper 2011-06-03 21:48:08.000000000 +0100
+++ /opt/git/libexec/git-core/git-difftool--helper 2011-10-06 13:17:55.000000000 +0100
@@ -56,6 +56,10 @@
fi
}
+if test $(git check-attr diff "$1" | sed 's/.*diff: //') = 'unset'; then
+ echo skip binary file "\"$1\""
+else
+
if ! use_ext_cmd; then
if test -n "$GIT_DIFF_TOOL"; then
merge_tool="$GIT_DIFF_TOOL"
@@ -70,3 +74,4 @@
launch_merge_tool "$1" "$2" "$5"
shift 7
done
+fi
A: patthoyts's answer worked for me.
The trick for me was figuring out version of git-difftool--helper git was using (MacPorts had installed multiple versions)
I used (with the difftool open):
lsof | grep "git-difftool--helper"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Does Facebook actually support OAuth 2.0? I've already succesfully implemented LinkedIn and Twitter Oauth 2.0 authorization in my App with external libraries. But I have problems with Facebook. It seems like it has different authorization flow.
I need to have 3 endpoints to implement OAuth: request token url, access token url and authorize token url.
For LinkedIn and Twitter I have them:
REQ_TOKEN_URL="https://api.linkedin.com/uas/oauth/requestToken";
ACCESS_TOKEN_URL="https://api.linkedin.com/uas/oauth/accessToken";
AUTHORIZE_TOKEN_URL="https://api.linkedin.com/uas/oauth/authorize";
REQ_TOKEN_URL="https://api.twitter.com/oauth/request_token";
ACCESS_TOKEN_URL="https://api.twitter.com/oauth/access_token";
AUTHORIZE_TOKEN_URL="https://api.twitter.com/oauth/authorize";
But for Facebook instead of request token I have
OAUTH_FACEBOOK_DIALOG = "https://www.facebook.com/dialog/oauth";
And I'm not sure if it's equal. Probably not, since it doen's work the way it did with LinedIn and Twitter.
And in Facebook documentation they suggest to start with redirecting user to "https://www.facebook.com/dialog/oauth", but in classical OAuth 2.0 first I have to request the token from request_token_URL.
So the question is: is Facebook authorization flow actually not OAuth 2.0 and I have to use different approach?
A: Facebook does in fact fully support OAuth 2.0. Twitter currently does not support OAuth 2.0. LinkedIn OAuth 2.0 support I believe is still in beta. But yes, you will need to use a different approach for different versions of OAuth.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: What is the difference between Object-Graph and a class diagram? Is there a difference in the meaning of "class diagram" and "object graph"?
A: see this tutorial
http://www.cs.toronto.edu/~jm/340S/Slides6/ClassD.pdf
Object graph contains value of one instance of class see example View its a view of an object system at a particular point in time
while
class diagram as wiki
The class diagram is the main building block of object oriented modelling. It is used both for general conceptual modelling of the systematics of the application, and for detailed modelling translating the models into programming code. Class diagrams can also be used for data modeling.[1] The classes in a class diagram represent both the main objects and or interactions in the application and the objects to be programmed. In the class diagram these classes are represented with boxes which contain three parts: [2]
A class with three sections.
The upper part holds the name of the class
The middle part contains the attributes of the class
The bottom part gives the methods or operations the class can take or undertake
see further
A: I agree with the previous post but would like to add that a class diagram is based on UML which is an accredited language sponsored by the OMG and known by over 5 millions users. UML is therefore a standard based on a model from which you get views.
IN UML 2 the class diagram is fantastic if used with Java because it seems to me that the new specification has exactly the same structure as a java project. It include a project name, with packages including classifiers (e.g. Class, interface, enum) which includes attributes, methodes which includes properties.
If you have to use just one diagram I would say to use Class diagram. It is easy to create because you don't need to know UML and can reverse engineer your project into a model a get class diagram views. My class diagram is Just magic:-)
A: Class diagram represent class name,its attributes and behaviours whereas object diagram represent instance of class diagram,object diagram comes under class diagram
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do you make a subdomain route for every action in a Zend Framework controller? Using Zend Framework I want to use an account name (:account) as the subdomain that will call the basket controller. When using getParams() for the index action it does display the :account parameter but this does not work on any other actions in the basket controller.
This is the code I currently have in the bootstrap:
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$domain_name = 'domain.com';
$plainPathRoute = new Zend_Controller_Router_Route_Static('');
$hostnameRoute = new Zend_Controller_Router_Route_Hostname(
':account.' . $domain_name,
array(
'controller' => 'basket'
)
);
$router->addRoute('account', $hostnameRoute->chain($plainPathRoute));
Thanks in advance for your help and guidance.
A: You actually need two chained routes:
*
*Your subdomain route
*A route responsible for everything after your domain
I use this config to set up a route this (although I map all subdomains to modules, but i guess you can fix this ;):
'subdomain' => array(
'type' => 'Zend_Controller_Router_Route_Hostname',
'route' => ':module.localhost',
'chains' => array(
'index' => array(
'type' => 'Zend_Controller_Router_Route',
'route' => ':controller/:action/*'
)
)
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mysql From enum to tinyint problems I've got a table with
`terms_of_payment` enum('0','1') NOT NULL DEFAULT '0' COMMENT ''
I run
ALTER TABLE `customer`
CHANGE `terms_of_payment` `terms_of_payment` TINYINT( 1 )
NOT NULL DEFAULT 0 COMMENT '';
and I found all my customers (with '0' value) set to 1 when I'm waiting 0
Could you explain me, what's the trouble, please ?
Bye
A: Converting the ENUM to TINYINT might give unexpected results, as MySQL will actually already store your ENUM in the form of integers. To get the result you want, you should actually start by converting your column to a CHAR(1) and then go to TINYINT(1).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How do you modify IDEA IntelliJ v10.x code generators for getters and setters? IntelliJ generates the following getter/setter code for boolean fields:
private boolean isTest;
public boolean isTest() {
return isTest;
}
public void setTest(boolean test) {
isTest = test;
}
This too yields the same method signatures:
private boolean test;
public boolean isTest() {
return test;
}
public void setTest(boolean test) {
this.test = test;
}
Great! So far so good. IntelliJ is following JavaBean naming conventions for boolean.
But watch what happens when you use the object Boolean (instead of the primitive boolean):
private Boolean isTest;
public Boolean getTest() {
return isTest;
}
public void setTest(Boolean test) {
isTest = test;
}
Uh oh! Do you see it? It should be generating this instead (which Eclipse does):
private Boolean isTest;
public Boolean getIsTest() {
return isTest;
}
public void setIsTest(Boolean isTest) {
isTest = isTest;
}
This may seem like no big deal, but this little inconsistency caused a huge project nightmare. The reason is this: There are other layers and frameworks which expect to map variables EXACTLY to the Java class field names - otherwise it fails without custom mapping logic (painful and unnecessary).
Our team uses the is*Name* pattern for all Boolean objects. Even our boolean database columns are named is_name, which gets translated to "is*Name*" using JBoss Hibernate reverse engineering tools plugin for Eclipse.
Does anyone know how to fix this? Is there some type of code generation template we can configure? Any help is greatly appreciated.
A: It was reported that Eclipse generates get<Property> for Boolean while IDEA generated is<Property>. It is against the specification and users requested to fix it.
As a result of addressing this bug current IDEA version is working in accordance to the JavaBeans specification and uses such getters only for primitive boolean type and get<Property> for other types including Boolean.
Sorry, but there is no way to configure this behavior in IDEA.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to install XML::Twig for Windows XP I tried installing XML::Twig using ppm and also tried manually by adding twig.pm files in the perl/lib folder, also tried using Nmake but got an error
"NMAKE : fatal error U1073: don't know how to make 'C:\Documents' Stop."
How do I install it?
A: The best solution I've found, is to start off with Strawberry Perl, which includes pre-build XML::Twig and XML::LibXML
I know that isn't quite what you asked - but I found it a perpetual nuisance to get the XML library dependencies installed, so this is the approach I adopted.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607772",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Hide author bio I have to convert a PSD to (x)HTML for a client of mine witch in turn will use that theme for a client of him.
Now the question is, is there a way to protect my copyrights from within the page for copyrights like ?
In example, is there a way to leave somethink like that into the code and protected from removal;
<meta name="author" content="My name" />
Another and last question is, if I upload that project in my portfolio, will be that wrong from my side ? When I mean in my portfolio, I don't mean to represent that project as a full project developed by me, but as a PSD to (x)HTML Convertion project.
A:
is there a way to leave something like that into the code and protected from removal;
No. HTML is a completely open format; you can not protect it from being copied; you can also not prevent anybody with access to the HTML from removing the notice.
If this is about making sure you are identified as the author of the work, consider making a (written) agreement with your client saying that there will be an author notice in the HTML, and they are not allowed to remove it.
A: @Merianous; there is a new term called humans.txt which use by google also.
this also use by boilerplate in there project http://html5boilerplate.com/humans.txt
check this link http://humanstxt.org/
A: If this is really important to you, I'd recommend that you make it part of the contract between you and your designers. They provide you a PSD, you provide them XHTML on the condition that they don't remove your attribution links from the code.
Programmatic methods would be unreliable, so it's probably best to settle it with a gentleman's agreement.
A: The short answer: NO
The long answer: you can use many tricks to protect you bio in code, but this will only made harder to remove: it will be always possibile to steal your work with the necessary efforts.
A: You normally don't see those kinds of things directly in the HTML. You're more than welcome to add comments to the CSS:
/*
* Author : Adam Wexler
* Email : adam@wexcode.com
* All code (c) 2011 Wexcode
* All rights reserved
*/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: java/jsf strange error: WARNING: StandardWrapperValve PWC1406: Servlet.service() ... threw exception java.lang.NullPointerException I have simple jsf app with servlet for dynamic images and filter setting utf8 encoding. From time to time (1/10 requests) I get very strange error:
WARNING: StandardWrapperValve[com.webapp.servlet.ImageServlet]: PWC1406: Servlet.service() for servlet com.webapp.servlet.ImageServlet threw exception
java.lang.NullPointerException
at com.sun.enterprise.v3.services.impl.monitor.MonitorableSelectionKeyHandler$CloseHandler.notifyClosed(MonitorableSelectionKeyHandler.java:94)
at com.sun.enterprise.v3.services.impl.monitor.MonitorableSelectionKeyHandler$CloseHandler.remotlyClosed(MonitorableSelectionKeyHandler.java:90)
at com.sun.grizzly.BaseSelectionKeyHandler.notifyRemotlyClose(BaseSelectionKeyHandler.java:233)
at com.sun.grizzly.util.OutputWriter.notifyRemotelyClosed(OutputWriter.java:353)
at com.sun.grizzly.util.OutputWriter.flushChannel(OutputWriter.java:148)
at com.sun.grizzly.util.OutputWriter.flushChannel(OutputWriter.java:76)
at com.sun.grizzly.http.SocketChannelOutputBuffer.flushChannel(SocketChannelOutputBuffer.java:326)
at com.sun.grizzly.http.SocketChannelOutputBuffer.flushBuffer(SocketChannelOutputBuffer.java:398)
at com.sun.grizzly.http.SocketChannelOutputBuffer.flush(SocketChannelOutputBuffer.java:376)
at com.sun.grizzly.http.ProcessorTask.action(ProcessorTask.java:1247)
at com.sun.grizzly.tcp.Response.action(Response.java:268)
at org.apache.catalina.connector.OutputBuffer.doFlush(OutputBuffer.java:380)
at org.apache.catalina.connector.OutputBuffer.flush(OutputBuffer.java:353)
at org.apache.catalina.connector.CoyoteOutputStream.flush(CoyoteOutputStream.java:175)
* at com.webapp.servlet.ImageServlet.doGet(ImageServlet.java:35)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:734)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:343)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at com.ocpsoft.pretty.PrettyFilter.doFilter(PrettyFilter.java:118)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
* at com.webapp.filter.CharacterEncodingFilter.doFilter(CharacterEncodingFilter.java:32)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:217)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
Here's my servlet and filter, I marked with asterisks lines referencing to stacktrace:
@WebServlet(urlPatterns = "/images/*")
public class ImageServlet extends HttpServlet {
@Inject
private FileService fileService;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
byte[] img = fileService.getImage(request.getPathInfo());
if (img != null) {
response.setContentType("image/png");
response.addHeader("Content-Length", String.valueOf(img.length));
ServletOutputStream os = response.getOutputStream();
os.write(img);
* os.flush();
os.close();
} else {
response.sendRedirect(request.getContextPath() + "/error");
}
}
}
@WebFilter(urlPatterns = "/*")
public class CharacterEncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
* chain.doFilter(request, response);
}
@Override
public void destroy() {
}
}
I have completely no idea what's going on... I'm using Glassfish 3.1.1 web profile with jdk7
A: Flushing is already implicitly done when you close the stream. Closing is already implicitly done by the container itself. You actually do not need to do it yourself. However, most servlet developers do it to have early feedback for the case they overlooked that something else further in the request-response chain is writing to the output stream, e.g. a buggy filter or response wrapper or something. This would then result in an IOException on every call because the stream is closed.
In any case, you have 2 options to treat the flush() and close():
*
*Put them in a try-catch wherein you ignore the exception.
*Remove those 2 lines. The container does that for you anyway. It will also just ignore the exception.
This exception is just a sign that the client aborted the connection. E.g. pressed [Esc] or closed the window/tab or navigated away to a different page while the image is still streaming.
See also:
*
*Should I close the servlet outputstream?
A: at com.sun.grizzly.util.OutputWriter.notifyRemotelyClosed()
Somehow this looks to me as if the connection you are flushing the stream of has intermediately been closed by the remote peer (a web browser?).
Can you try response.flushBuffer() instead. Does this also throw the exception?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Better way to return the value from a property from a child object when the childobject can be null I try to explain this with an example:
public class Player
{
public string FirstName {get; set;}
public Team Team {get; set;}
}
public class Team
{
public string Name {get; set;}
}
Now I want to map a Player to a PlayerVM (ViewModel)
public class PlayerVM
{
public string PlayerFirstName {get; set;}
public string TeamName {get; set;}
}
So the code is something like:
public List<PlayerVM> GetPlayers()
{
// Lazy loading enabled,
// so the Team child objects (if present, will be retrieved)
var players = Database.GetPlayers();
var list = new List<PlayerVM>();
foreach (var player in players)
{
var vm = new PlayerVM();
vm.PlayerFirstName = player.FirstName;
if (player.Team != null)
{
vm.TeamName = player.Team.Name;
}
else
{
vm.TeamName = "-- no team --";
}
list.Add(vm);
}
return list;
}
I want to replace
if (player.Team != null)
{
vm.TeamName = player.Team.Name;
}
else
{
vm.TeamName = "-- no team --";
}
by something like:
vm.TeamName = Utils.GetProperty<Player>(p => p.Team.Name, "-- no team --");
is this possible using generic Lamba / Func expressions ?
<< Edit >>
Thanks for the answers, I know I can use oneliners, but I was actually looking for a generic way to access nested child objects. (The nesting could be X levels deep...)
string countryName = Utils.GetProperty<Player>(p => p.Team.Country.Name, "-- no country --");
How to do this ?
<< Edit 2 >>
A possible solution would to convert the Func Expression using this code
http://code.google.com/p/gim-projects/source/browse/presentations/CantDanceTheLambda/src/MemberNameParser.cs
to a string like "Team.Country.Name".
Then use reflection to access the properties.
A: What about
vm.TeamName = p.Team.Name != null ? p.Team.Name : "-- no team --";
No generics, no lambda, but if you want to replace the if/else block with a oneliner, this is the way to go.
So to clean up the entire mapping it will be
list.Add( new PlayerVM{
PlayerFirstName = player.FirstName,
TeamName = player.Team.Name != null ? player.Team.Name : "-- no team --"
});
A: I would create a property in the Player class:
public string TeamName {
get {
return this.Team != null ? this.Team.Name : "-- no team --";
}
}
A: A possible solution can be found here:
Get Nested Property value using reflection and Linq.Expression
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607782",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use foreign keys in SQL Buddy? I need to use foreign keys for update and cascade, etc.
ALTER TABLE topics
ADD FOREIGN KEY(topic_by) REFERENCES users(user_id)
ON DELETE RESTRICT ON UPDATE CASCADE;
but I am not able to make foreign keys in SQL Buddy.
Any way to do that?
A: did you try this :
ALTER TABLE topics
ADD CONSTRAINT topic_by FOREIGN KEY(user)
REFERENCES users(user_id) ON DELETE RESTRICT ON UPDATE CASCADE
A: Try this query:
ALTER TABLE topics
ADD CONSTRAINT topic_by
FOREIGN KEY (user_id) REFERENCES users(user_id);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Outlook 2003 VBA to detect selected account when sending Is it possible to detect which account an email is being sent via the Application_ItemSend VBA function of Outlook 2003? The accounts are POP3/SMTP on a standalone machine, and not MAPI or Exchange based.
I have tried using "Outlook Redemption" (http://www.dimastr.com/redemption/) but I just cannot find any property / method that will tell me which of the accounts the email is being sent through.
I don't need to be able to amend/select the account being sent from, just simply detect.
A: I have found a way of finding the account name, thanks to this link which provides the code for selecting a particular account.
Using this code as a base, I have create a simple GetAccountName function, which is doing exactly what I need it to do.
Edit: The below will only work if you're NOT using Word as the editor.
Private Function GetAccountName(ByVal Item As Outlook.MailItem) As String
Dim OLI As Outlook.Inspector
Const ID_ACCOUNTS = 31224
Dim CBP As Office.CommandBarPopup
Set OLI = Item.GetInspector
If Not OLI Is Nothing Then
Set CBP = OLI.CommandBars.FindControl(, ID_ACCOUNTS)
If Not CBP Is Nothing Then
If CBP.Controls.Count > 0 Then
GetAccountName = CBP.Controls(1).Caption
GoTo Exit_Function
End If
End If
End If
GetAccountName = ""
Exit_Function:
Set CBP = Nothing
Set OLI = Nothing
End Function
A: Here is a try:
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Msgbox(Item.SendUsingAccount.DisplayName)
End Sub
This will give you the display name of the current sending account.
If that's not enough, you can try the other properties of the Item.sendUsingAccount var.
A: In Outlook 2003, you need to use the RDOMail object in Redemption to access the Account property of a mail item. Here is some code that changes the SendAccount from the default account to another account in the OL Profile, for all items in the Outbox. It could be improved by coding an account selection subroutine that reads the accounts in the OL Profile and presents them as a list for the user to select from. In the code provided the new send account is hard-coded.
Sub ChangeSendAccountForAllItems()
On Error Resume Next
Dim oOutlook As Application
Dim olNS As Outlook.NameSpace
Dim sOrigSendAccount As String
Dim sNewSendAccount As String
Dim iNumItemsInFolder As Integer
Dim iNumItemsChanged As Integer
Dim i As Integer
Dim rRDOSession As Redemption.RDOSession
Dim rRDOFolderOutbox As Redemption.RDOFolder
Dim rRDOMail As Redemption.RDOMail
'Create instance of Outlook
Set oOutlook = CreateObject("Outlook.Application")
Set olNS = Application.GetNamespace("MAPI")
'Create instance of Redemption
Set rRDOSession = CreateObject("Redemption.RDOSession")
rRDOSession.Logon
'Set a new Send Account (using Redemption)
'Change this to any SendAccount in your Profile
sNewSendAccount = "ThePreferredSendAccountNameInTheProfile"
Set rRDOAccount = rRDOSession.Accounts(sNewSendAccount)
Response = MsgBox("New Send Account is: " & sNewSendAccount & vbCrLf & _
vbCrLf, _
vbOK + vbInformation, "Change SendAccount for All Items")
'Get items in Outbox folder (value=4) (using Redemption)
Set rRDOFolderOutbox = rRDOSession.GetDefaultFolder(olFolderOutbox)
Set rRDOMailItems = rRDOFolderOutbox.Items
iNumItemsInFolder = rRDOFolderOutbox.Items.Count
iNumItemsChanged = 0
'For all items in the folder, loop through changing Send Account (using Redemption)
For i = 1 To iNumItemsInFolder
Set rRDOItem = rRDOMailItems.Item(i)
rRDOItem.Account = rRDOAccount
rRDOItem.Save
iNumItemsChanged = iNumItemsChanged + 1
'3 lines below for debugging only
'Response = MsgBox("Item " & iNumItemsChanged & " of " & iNumItemsInFolder & " Subject: " & vbCrLf & _
' rRDOItem.Subject & vbCrLf, _
' vbOK + vbInformation, "Change SendAccount for All Items")
Next
Response = MsgBox(iNumItemsChanged & " of " & iNumItemsInFolder & " items " & _
"had the SendAccount changed to " & sNewSendAccount, _
vbOK + vbInformation, "Change SendAccount for All Items")
Set olNS = Nothing
Set rRDOFolderOutbox = Nothing
Set rRDOMailItems = Nothing
Set rRDOItem = Nothing
Set rRDOAccount = Nothing
Set rRDOSession = Nothing
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't create a PDF with iText and JSF I want to create a pdf using iText in my JSF + Spring web app.
When I click on a button the pdf should be generated. The method that is fired:
public void createPDF() {
log.debug("entered createPDF");
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "inline=filename=file.pdf");
try {
// Get the text that will be added to the PDF
String text = "test";
// step 1
Document document = new Document();
// step 2
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
// step 3
document.open();
// step 4
document.add(new Paragraph(text));
// step 5
document.close();
// setting some response headers
response.setHeader("Expires", "0");
response.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
// setting the content type
response.setContentType("application/pdf");
// the contentlength
response.setContentLength(baos.size());
// write ByteArrayOutputStream to the ServletOutputStream
OutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
os.close();
log.debug("flushed and closed the outputstream");
}
catch(DocumentException e) {
log.error("error: "+e);
}
catch (IOException e) {
log.error("error: "+e);
}
catch (Exception ex) {
log.debug("error: " + ex.getMessage());
}
context.responseComplete();
log.debug("context.responseComplete()");
}
this is the page with the button:
<!DOCTYPE composition PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:s="http://jboss.org/seam/faces"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:rich="http://richfaces.org/rich"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:c="http://java.sun.com/jsp/jstl/core"
template="/pages/layout/layout.xhtml">
<ui:define name="content">
<h:form>
<rich:panel style="width: 785px; height: 530px; ">
<a4j:commandButton value="Afdrukken" execute="@form"
action="#{huishoudinkomenAction.print}" style="float:right;" />
</rich:panel>
</h:form>
</ui:define>
I see the debug messages in the log but nothing happens to the web app. I don't see a pdf.
What am I doing wrong?
Regards,
Derk
EDIT:
When I changed the <a4j:commandButton /> to a <h:commandButton /> it worked.
A: I've never used RichFaces, but with Primefaces controls, you can set the attribute ajax="false".
<p:commandButton id="someid" value="Text for user" action="someConfiguredAction" ajax="false"/>
or
<h:commandButton id="someid" value="Text for user" action="someConfiguredAction"/>
A: When you use <a4j:commandButton> a new XmlHttpRequest will be created on your browser, and your serverside method will be called via JS. The output PDF will be written into the output stream, but the actual result will be read out of XmlHttpRequest, and interpreted by jsf.ajax.response() javascript function.
Since JSF ajax responses are always XML with a root of <partial-response>, you're basically sending junk back to the JSF ajax handler. (PDF != XML with <partial-response> root). Obviously this fails parsing so it appears that "nothing happens".
So you must use the <h:commandButton/> to do a real request. You need also to do:
response.setHeader("Content-disposition", "attachment; filename=mycool.pdf");
serverside in order to inform the browser that it receives a new file, and should download it, and not display it instead of the page.
This will have the end behavior of an "ajax" call, where you do a call, you receive the response (and save it), but your page content stays there.
A: You can't download files with ajax. Ajax is fired and handled by JavaScript code. However, JavaScript has for obvious security reasons no way to force a Save As dialogue with arbitrary content in a JavaScript variable (such as the response of an ajax request).
Make sure that the download button fires a synchronous (non-ajax) request. Use a normal command button or turn off ajax in the ajax command button.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jqgrid ui autocompletion : Disable Case sensitivity In my JQgrid i have a ui atocomplete column which are Case sensitive.
For example i have 2 Items in my grid: Ivan and ivan, if i type "i" autocomplete will return only ivan.
I have tryed to make a function inside of source: but i failed since my ajax call always return object Object instead of an item. Any ideas?
Code for autocomplete:
$(elem).autocomplete({
delay: 0,
minLength: 0,
source: function (req, response) {
alert(req);
$.ajax({
mtype: "post",
url: '@Url.Action("GetBrands")',
dataType: "json",
async: false,
cache: false,
data: { term: req },
success: function (data) {
alert(data);
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp("^" + re, "i");
response($.grep(data, function (item) { return matcher.test(item.value); }));
}
});
},
Controller side code:
public virtual JsonResult GetBrands(string term)
{
if (term == null) term = string.Empty;
var vendorId = _service.GetVendorIdByUsername(GetUserName());
var brands = _service.GetBrandsByVendor(vendorId);
var brand = new BrandsViewModel();
brand.BrandName = "Opret ny Brand...";
brands.Add(brand);
foreach (var brandsViewModel in brands)
{
if (brandsViewModel.BrandName == "Intet")
{
brandsViewModel.BrandName = "";
}
}
return Json((from item in brands
where item.BrandName.Contains(term)
select new
{
value = item.BrandName
//votes = item.Votes,
}).ToArray(),
JsonRequestBehavior.AllowGet);
}
A: convert it all to one case when compering:
public virtual JsonResult GetBrands(string term)
{
if (term == null) term = string.Empty;
term = term.ToLower();
var vendorId = _service.GetVendorIdByUsername(GetUserName());
var brands = _service.GetBrandsByVendor(vendorId);
var brand = new BrandsViewModel();
brand.BrandName = "Opret ny Brand...";
brands.Add(brand);
foreach (var brandsViewModel in brands)
{
if (brandsViewModel.BrandName == "Intet")
{
brandsViewModel.BrandName = "";
}
}
return Json((from item in brands
where item.BrandName.ToLower().Contains(term)
select new
{
value = item.BrandName
//votes = item.Votes,
}).ToArray(),
JsonRequestBehavior.AllowGet);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Redirect from old site and subsites to new domain - main page with htaccess I have the following rules in my .htaccess
rewritecond %{http_host} ^oldname.com [nc]
RewriteRule ^(.*)$ http://www.newname.com [r=301,nc]
rewritecond %{http_host} ^www.oldname.com [nc]
rewriterule ^(.*)$ http://www.newname.com [r=301,nc]
I am wondering how to merge does 2 rules in one. Beside that I would like to redirect if user comes to: www.oldname.com/?action=whatever to newname as well...
Thanks for response!
A: rewritecond %{http_host} ^(www\.)?oldname.com [nc]
RewriteRule ^(.*)$ http://www.newname.com [r=301,nc]
change the above code to that
rewritecond %{http_host} ^(www\.)?oldname.com [nc]
RewriteRule ^(.*)$ http://www.newname.com/$1 [r=301,nc]
If that not work tell me to give you another solution.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: EditText formatting Now I've got an EditText with TextWatcher which formats user input as a phone. For example if users input is 89011234567 it will be formatted as +7 (901) 123-45-67.
I wonder is there any way I can extend or implement some classes like CharSequence or Editableor any other like these to make EditText display the formatted output, but when I will call mEditText.getText().toString() it will return original users input?
A: You could create a class that extends the standard EditText, and then override the getText() method to return what you need.
public class MyEditText extends EditText {
//Implement the methods that need implementation. Calling the method in the super class should do the trick
@Override
public Editable getText() {
//return an Editable with the required text.
}
}
Then you just use the MyEditText instead of the normal EditText.
This solution will work, if you don't use the getText()-method other places (like your TextWatcher).
A: You could store the user's input into the tag property of your edittext, this way you could access it and it wouldn't be modified by using setText to display the formatted number !
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to pack OGG audio file to RIFF container? I have an ogg audio file and some information which is saved as sequence of bytes. I need to pack this audio and information in a single container such as RIFF or something else. I'm searching solutions which can be written under .NET.
A: Ogg is a container format. What you perhaps will want is either use some Ogg format tools to attach your data directly to existing file, or re-stream the data into different container format where you have tools to attach your data to.
The formats might be WAV/RIFF, Matroska, MP4. It also perhaps depends what is exactly this additional data, more like a thumbnail, or additional stream (user comments with timestamps etc).
A popular framework for such manipulation in .NET is DirectShow.NET library, but as you clarify your need, you might end up using a different tool.
See also a neighboring thread with a code snippet: Ogg to Riff/Wave encoding with acm
A: How to move Ogg file to Wav file with Ogg Vorbis data in C#
static void OggToWavWithOgg()
{
string fileName = @"e:\Down\fortuna.ogg";
using (DsReader dr = new DsReader(fileName))
{
if (dr.HasAudio)
{
short oggFormatTag = 26479;
IntPtr format = dr.ReadFormat();
WaveFormat waveFormat = AudioCompressionManager.GetWaveFormat(format);
IntPtr formatOgg = AudioCompressionManager.GetCompatibleFormat(format, oggFormatTag);
using (WaveWriter ww = new WaveWriter(File.Create(fileName + ".wav"),
AudioCompressionManager.FormatBytes(formatOgg)))
{
AudioCompressionManager.Convert(dr, ww, true);
}
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I get a ContentItem's content in Orchard? I have instance of ContentItem and I'd like to get the contents of it. How do I do this?
A: Say that your type is named Contact, has a BodyPart, and has a text field name Subject. If you are inside a content template like Content-Contact.cshtml, you can access the content item using Model.ContentItem. Casting it as dynamic will let Orchard give you some useful behavior to access its contents.
// necessary to access parts by name
@using Orchard.ContentManagement;
@{
// cast in order to have improved accessors
dynamic contentItem = Model.ContentItem;
// access each part by its name
string body = contentItem.BodyPart.Text;
// access fields using the default part
string subject = contentItem.Contact.Subject.Value;
}
A: That is extremely vague. I'll take an example at random:
contentItem.As<BodyPart>().Text
will get you the contents of the body part if it has one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Flash As2 Image snapshot Is there any approach to take the snapshot of a drawing created in pure AS2 flash coding ?
I tried to use Bitmapdata and bridge but bitmap works in as3 and bridge combines two swf together and communicate with them.
Is there a way of doing screenshot in as2 ?
A: Yes, it can be done in AS2, but it will be a lot slower than in AS3.
Here is an old pre-AS3 example:
http://www.flash-db.com/Tutorials/snapshot/index.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607805",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Multiple domains and subdomains on a single Pyramid instance I'm looking to have multiple domains and subdomains on a single Pyramid instance. However, I can't seem to find any documentation on it. The last question referred to a glossary with very little information and no examples. Do any of you have any examples or can direct me to better documentation?
A: Pyramid is just a WSGI application. This means it's dependent on the HTTP_HOST environ key (set by the Host header) to determine the host of the application. It's all relative. Point-being that Pyramid has no restrictions on what it can accept, thus the world is your oyster and you can set it up to limit content to various domains however you'd like. This of course starts with what hosts your webserver is configured to feed to your application.
Assuming you're using URL dispatch, you might want to design some custom route predicates that check the request.host value for whatever you'd like. Returning False from that predicate will prevent that route from ever matching a request to that host.
This is a large topic, so it might help if you give some more specifics. For example, since Pyramid is relative, any URL you may want to generate from 'example.com' to redirect someone to 'sub.example.com' will need to be done via a pregenerator.
def pregen(request, elements, kw):
kw['_app_url'] = 'http://sub.example.com'
return elements, kw
def req_sub(info, request):
return request.host.startswith('sub')
config.add_route('sub_only', '/',
custom_predicates=(req_sub,),
pregenerator=pregen)
config.add_route('foo', '/foo')
config.add_view(view, route_name-'foo')
def view(request):
# redirect the user to "http://sub.example.com", regardless of whether
# request.host is "example.com" or "sub.example.com"
return HTTPFound(request.route_url('sub_only'))
A: If you have control over your hosting environment, I would strongly suggest keeping the domain stuff out of pyramid and handling it with a proxy server such as apache mod proxy, routing to subdomains in pyramid. Then you can easily switch any of the domain name to view routing without having anything fragile (like domain names) in your pyramid code. Your app code will be much cleaner this way, and far easier to change later.
Here's an Apache example of two domains going to one pyramid app, assuming we are serving the pyramid app somehow or another on port 5001 (gunicorn or whatever you want).
<VirtualHost *:80>
ServerName domain_2.com
ProxyPreserveHost On
# send all request to our app at /app1/*
ProxyPass / http://127.0.0.1:5001/app_1/
ProxyPassReverse / http://127.0.0.1:5001/app_1/
</VirtualHost>
<VirtualHost *:80>
ServerName domain_2.com
ProxyPreserveHost On
# send all request to our app at /app2/*
ProxyPass / http://127.0.0.1:5001/app_2/
ProxyPassReverse / http://127.0.0.1:5001/app_2/
</VirtualHost>
And here's an example of one domain going to several pyramid instances:
<VirtualHost *:80>
ServerName mydomain.com
ProxyPreserveHost On
# admin go to manager app on 5001
ProxyPass /media/manager/ http://127.0.0.1:5001/ retry=5
ProxyPassReverse /media/manager/ http://127.0.0.1:5001/
# downloads from server app on 5002
ProxyPass /media/server/ http://127.0.0.1:5002/ retry=5
ProxyPassReverse /media/server/ http://127.0.0.1:5002/
</VirtualHost>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: jQuery UI, draggable child div larger than parent I have looked over several articles and tried all of the methods proposed and found no solutions as of yet.
I am attempting to create a map that is draggable, but will stop when it its own edge meets the edge of the parent's edge. The child is larger than the parent so I have tried all different types of methods to resolve this but have yet to find a solution.
The example below shows an example in which the black border should not have any white space within. I have tried containment in several different flavors but haven't figured out the math for it.
Example: http://jsfiddle.net/LQtCY/3/
Thanks
A: Have u tried this?
var parentPos = $('.mapshell').offset();
var childPos = $('.mapcontent_1').offset();
$(".mapcontent_1").draggable({
drag: function(event, ui) {
if (ui.position.top > parentPos.top) {
ui.position.top = parentPos.top;
}
if (ui.position.left > parentPos.left) {
ui.position.left = parentPos.left;
}
},
scroll: false
});
http://jsfiddle.net/LQtCY/6/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: mismatch in constructors/destructors count
Possible Duplicate:
C++ basic constructors/vectors problem (1 constructor, 2 destructors)
I have got the code:
#include <iostream>
class A
{
public:
A() { std::cout<<"A::A"<<std::endl; }
~A() { std::cout<<"A::~A"<<std::endl; }
};
class B : public A
{
public:
B(){ std::cout<<"B::B"<<std::endl; }
~B(){ std::cout<<"B::B"<<std::endl; }
};
void Func( A a ){}
int main()
{
B b;
Func(b);
}
in VS2010EE output will be:
A::A
B::B
A::~A //why twice? Once on gcc!
A::~A
B::~B
A::~A
But, when we have copy constructor, output is:
A::A
B::B
A::A(copy)
A::~A
B::~B
A::~A
A: That's a bit unfortunate. VS should avoid that second copy; are all optimizations on? Presumably, it's calling a copy constructor on the A portion of b to create the argument (ie slicing it), then copying that object onto the stack again for the function call. (In the first example, your constructor for A isn't being called because the generated copy constructor doesn't print output.) When you provide a copy constructor, it must create the copy directly on the stack.
A: You're not counting all the constructors. In the first case, the copy constructor is invoked to create a copy of the object when calling Func (because the function takes its parameter by value).
When you don't define a copy constructor yourself, the compiler will generate one for you. And the compiler-generated copy constructor doesn't print anything out, so it doesn't figure in your output.
A: If I understand correctly, you're effectively asking this:
Why does VS2010 create an additional temporary when I have no copy
constructor?
The only answer I have is 'because it's allowed to'. It seems that it gets optimised away when you're using gcc, and also gets optimised away when you provide a user-defined copy constructor.
The behaviour is a little odd, but it's perfectly compliant. If all C++ compilers performed identically, we'd only need one compiler...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Masking or hiding inaccurately entered data in SQL Server 2008 OK, so my subject line isn't very descriptive, but here's the scenario:
An end-user has a legal obligation to submit transaction data to a government agency. The transactions contain the name and address of various individuals and organizations. HOWEVER, end users frequently misspell the names of the reported individuals and organizations, or they badly mangle the address, etc.
The information submitted by the end user is a legal 'document', so it cannot be altered by the agency that received it. Also, the transactions can be viewed and searched by the public. When the government agency notices an obvious misspelling or bad address, they would like to 'hide' or 'mask' that bad value with a known good value. For example, if an end user entered 'Arnie Schwarzeger', the agency could replace that name with 'Arnold Schwarzenegger'. The public that viewed the data would see (and search for) the correct spelling, but could view the original data as entered by the end user after they found the data record in question.
Hopefully that explains the business case well enough...on to the SQL part! So to address this problem, we have tables that look like this:
CREATE TABLE [dbo].[SomeUserEnteredData](
[Id] [uniqueidentifier] NOT NULL,
[LastOrOrganizationName] [nvarchar](350) NOT NULL, // data as entered by end-user
[FirstName] [nvarchar](50) NULL, // data as entered by end-user
[FullName] AS ([dbo].[FullNameValue]([FirstName],[LastName])) PERSISTED, // data as entered by end-user
[MappedName] AS ([dbo].[MappedNameValue]([FirstName],[LastName]))) // this is the 'override' data from the agency
CREATE TABLE [dbo].[CorrectionsByAgency](
[Id] [uniqueidentifier] NOT NULL,
[ReplaceName] [nvarchar](400) NOT NULL,
[KeepName] [nvarchar](400) NOT NULL)
CREATE FUNCTION [dbo].[FullNameValue]
(
@FirstName as NVARCHAR(40),
@LastOrOrganizationName as NVARCHAR(350)
)
RETURNS NVARCHAR(400)
WITH SCHEMABINDING
AS
BEGIN
DECLARE @result NVARCHAR(400)
IF @FirstName = '' OR @FirstName is NULL
SET @result = @LastOrOrganizationName
ELSE
SET @result = @LastOrOrganizationName + ', ' + @FirstName
RETURN @result
END
CREATE FUNCTION [dbo].[MappedNameValue]
(
@FirstName as NVARCHAR(50),
@LastOrOrganizationName as NVARCHAR(350)
)
RETURNS NVARCHAR(400)
AS
BEGIN
DECLARE @result NVARCHAR(400)
DECLARE @FullName NVARCHAR(400)
SET @FullName = dbo.FullNameValue(@FirstName, @LastOrOrganizationName)
SELECT top 1 @result = KeepName from CorrectionsByAgency where ReplaceName = @FullName
if @result is null
SET @result = @FullName
RETURN @result
END
Hopefully, if my sample isn't TOO convoluted, you can see that if the agency enters a name correction, it will replace all occurrences of the misspelled name. From a business logic perspective, this works exactly right: the agency staff only enters a few corrections and the corrections can override everywhere there are misspelled names.
From a server performance standpoint, this solution STINKS. The calculated SomeUserEnteredData.MappedName column can't be indexed, and no view that reads from that column can be indexed either! There's no way this can work for our needs if we can't index the MappedName values.
The only alternative I've been able to see as a possibility is to create an additional linking table between the end-user created data and the agency created data -- when the agency enters a correction record, a record is created in the linking table for every occurrence of the bad column value. The down side to this seems to be the very real likelihood of creating/destroying many (hundreds of thousands) of those linking records for every correction entered by an agency user...
Do any of you SQL geniuses out there have great ideas about how to address this problem?
A: I'm not sure if this is answering your question directly, but I would try to simplify the whole thing: stop using functions, persist "calculated" values and use application logic (possibly in a stored procedure) to manage the data.
Assuming that one agency correction can be applied to many user-entered names, then you could have something like this:
create table dbo.UserEnteredData (
DocumentId uniqueidentifier not null primary key,
UserEnteredName nvarchar(1000) not null,
CorrectedNameId uniqueidentifier null,
constraint FK_CorrectedNames foreign key (CorrectedNameId)
references dbo.CorrectedNames (CorrectedNameId)
)
create table dbo.CorrectedNames (
CorrectedNameId uniqueidentifier not null primary key,
CorrectedName nvarchar(1000) not null
)
Now, you need to make sure your application logic can do something like this:
*
*External user enters dirty data
*Agency user reviews the dirty data and identifies both the incorrect name and the corrected name
*Application checks if the corrected name already exists
*If no, create a new row in dbo.CorrectedNames
*Create a new row in dbo.UserEnteredData, with the CorrectedNameId
I'm assuming that things are rather more complicated in reality and corrections are made based on addresses and other data as well as just names, but the basic relationship you describe seems simple enough. As you said, the functions add a lot of overhead and it's not clear (to me) what benefit they provide over just storing the data you need directly.
Finally, I don't understand your comment about creating/destroying linking records; it's up to your application logic to handle data changes correctly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Perl memory leak from match operator While investigating a long running perl program for memory leaks I tried to use Test::LeakTrace.
Looking at one of the leaks it reports I can narrow down the leaking code to just:
/$?/
So running: perl -MTest::LeakTrace::Script -e'/$?/' prints:
leaked SCALAR(0x10d3d48) from -e line 1.
Why is this, do I need to worry about it ?
Update: Also tried Devel::LeakTrace::Fast, it's not complaining about the same code.
A: Assuming you got a leak. Then this:
perl -e'/$?/ for 1..1E9'
should make your process grow in memory
ps -o rss,vsz <PID>
In my case it stays stable all the way. You should check it for your setup. It could be that leak your module detects is some late destruction. You could write a note to the module authors to help you figure out its output, you can help them to improve it...
BTW another thing confirming "no leak" for me is that on
perl -MTest::LeakTrace::Script -e'/$?/ for 1..1000'
I don't see multiple leaked scalars, just one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607831",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Android - Passing the main activity around I have a several activities in my app. The main activity (activity1) extends ActivityGroup (I need to support 2.2 and above, so I cant use fragments).
The main activity1 creates activity2, which in turn creates activity3. But when creating activity3 I want activity1 to create it, not activity2.
How do you pass the main activity around between activities?
Thanks
A: A better way is to use startActivityForResult() in avtivity1 to statrt activity2.
and when you want activity3 just finish activity2 and in activity1 override
onActivityResult() and start Activity3. passing activity instance is not better idea
since that Activity may get killed when at background and thus susceptible to throw an
Exception.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ASP.NET MVC 3 in-memory data store I have a project which provides users with a list of current tasks that need to be completed. Any user can complete any task, and so to ensure that only one user is working on a task at a time I need to be able to 'lock' it. I'm using SignalR for this, so a user requests a lock on a task, and if they are successful (ie. if noone else has locked it) then they will be able to access the further information that they need.
My problem is how to store the list of locked tasks. The original plan was simply to add an additional bit field 'IsLocked' to the Task table and update this when the user requested a lock and when the task was unlocked. We have about 300 concurrent users, however, and a task takes only about 3-4 minutes, meaning huge numbers of additional - and tiny - queries on the database. Therefore we were wondering about in-memory storage, simply storing a list of task ids in a 'lockedTasks' list.
I had considered using caching, but am unsure on the best ways to do this, or even if better alternatives exist. If anyone has any experience in this then some advice would be great thanks
A: I would avoid memory completely as IIS is not that great with it, if you found your self in the IIS need for refreshing the Application Pool for some sort of reason, your list is simply gone!
Maybe a MemCache system? If it does not loose things in the above way, but...
I would advice to be in the middle, IO File is fast that request data to a Database, specially if it's not in the same machine (witch for security reasons, it should never be), so... why not, and just to hold your list, you don't use one of the currently famous NoSQL database?
MongoDB is a document database that has a .NET Library and it's easy to use, it is not as fast as Memmory, but extremely quicker than Physical databases for what you want.
Normally the NoSQL Database will be hosted in the App_Data folder so it will be extremely fast to access and you can just hold there the task_id and user_id of all locked tasks.
A: Have you considered stateful filters?
Check out this links for more info:
*
*ASP.NET MVC Filters and Statefulness
*Brad Wilson: Advanced MVC
3 - (Video)
*Brad Wilson: Advanced MVC 3 - (PDF)
A: I'm sorry, but if your app can't handle a single query every 3-4 minutes x 300 users, then you're doing something very wrong. Just browsing a site typically generates orders of magnitude more queries than that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Exchange server search from android email I am trying to search exchange server mailbox by the following command from a android client.
<Search>
<Store>
<Name>Mailbox</Name>
<Query>
<And>
<Class>Email</Class>
<CollectionId>5</CollectionId>
<FreeText>a</FreeText>
</And>
</Query>
<Options>
<Range>0-4</Range>
</Options>
</Store>
But the response is a status error...
<Search>
<Status>1</Status>
<Response>
<Store>
<Status>2</Status>
.............
Any pointers?
Thanks in advance
A: How did get CollectionId ? You should use cmd = FolderSync to get server id.
let collectionId = server id
you could see this
Android mail search using Exchange Activesync
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP Update giving error if no data is edited Thanks for asking me to make my question clearer.
I have a form which is used to save content in a database.
The user is also allowed to update any content by editing the fields in the form and submitting it.
The update query looks something like this:-
$res = mysql_query("UPDATE freight SET .... WHERE id='$id'") or die ( mysql_error());
if(mysql_affected_rows() > 0){
//do some stuff
return true;
}
else{
return false;
}
Now my problem is this: If the user changes some field while updating the form, mysql_affected_rows() is > 0 so I am able to "//do some stuff".
But if the user does not change any field in the form and simply submits, mysql_affected_rows return 0 and I reach the false block.
I was under the impression that UPDATE should overwrite every time thereby mysql_affected_rows() should return 1 irrespective of whether any fields have been changed or not.
I use the return value to display an appropriate success or error message in the screen. Hence this is a serious bug.
Can you suggest whats the right way to achieve the correct functionality?
Thanks,
Vish
A: mysql_affected rows() -1 will be returned if the query itself can not be issued to the server, possibly because of syntax error AND if the last query was not either an INSERT or UPDATE statement.
When using UPDATE, MySQL will not update columns where the new value
is the same as the old value. This creates the possibility that
mysql_affected_rows() may not actually equal the number of rows
matched, only the number of rows that were literally affected by the
query.
so your solution can be achieved by below logic ( but this is not safe)
if(mysql_affected_rows()!=-1){
}
A: if( $_POST['message'] != '' ) {
// add the field to your query
} else { // this is optional
// don't add it to your query
}
// do the mysql update here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: sql nested select parsing Situation:
I have several SSRS reports of which I need the sql-code to be documented.
For this I need the code to be formatted in exactly the same way time and time again.
Problem:
In some of my reports I have structures like
select outer
from (
select outin
from (
select inner
from (
select innerMax
from
)z
where
)x
where dateadd(d,12,getdate())
)y
where
And I want the result to be
select outer
from (
select outin
from (
select inner
from (
select innerMax
from
)z
where
)x
where dateadd(d,12,getdate())
)y
where
But I have problems with indenting the nested select's
I'd really appreciate it if you can provide me with examples.
I've used splits, regex, substrings, ...
greetings
A: This is trickier than you might think: split, substring and regex will not be enough to reliably tackle this problem. Consider comments, or string literals inside your SQL code that might contain text that looks like SQL or contains parenthesis which will mess up your indentation levels.
A better way is to use an SQL parser. Here's a demo with python-sqlparse:
#!/usr/bin/env python
import sqlparse
sql = """
select outer
from (
select outin
from (
select inner
from (
select innerMax
from
)z
where
)x
where dateadd(d,12,getdate())
)y
where
"""
print sqlparse.format(sql, reindent=True)
which will print:
select outer
from
(select outin
from
(select inner
from
(select innerMax
from)z
where)x
where dateadd(d,12,getdate()))y
where
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to give priority to a jar file in eclipse classpath? There is a class file TagAttributeInfo which is under two of my jar files.
j2ee-6.1.jar,servlet-api-2.3.jar .
Now i need that class to be called from j2ee-6.1.jar but in runtime ,it is taking the class of servlet-api-2.3.jar,which i don't want.
Can anybody help me to prioritize the jar file in class path so that i will give first priority to j2ee-6.1.jar.
A: *
*Go into your Project Properties > Build Path.
*In the Order and Export tab, find j2ee-6.1.jar and press the Up button to move it higher up in the class path order. Keep pressing Up until it is above servlet-api-2.3.jar.
*Finally press OK.
A: The first jar that it finds on the classpath that has the class it's looking for will be used. So you can prioritize your class by putting its jar at the beginning of the classpath.
How exactly you would do this in Eclipse I'm not sure, but there's probably some list of project dependencies that correspond to the jars on the classpath, and hopefully you can order the elements on that list and put your jar on the top. Try looking for it in the project settings panel.
A: *
*remove servlet-api-2.3.jar, you don't need it.
*or move j2ee-6.1.jar higher up than servlet-api-2.3.jar in the lib list.
A: You move it up in the classpath order (right click on the project, select Build Path, followed by Configure Build Path and then Order and Export)
A: I don't know if it's part of the spec but placing the "higher" priority jar earlier on the classpath works when I've done this in the past.
A: Are you sure you need both jar files?
Anyway, in the Build Path dialog you can specify the order for jar files to be searched.
A: Only one of these jars should be in your classpath, to be able to compile your classes. But at runtime, the jar will be in your application server classpath, and you won't be able to replace it with the other one.
If your container is a JEE6 container, then it uses servlet 3.0 and the servlet-api-2.3.jar is obsolete and should not be in the classpath. If your container only supports servlet api 2.3, then you won't be able to use classes from the jee6 jar in this container.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Pascal's Triangle returning nonsense values This is a homework project I was assigned some time ago... I've been successful in getting this far on my own, and the only hiccup I have left is (I believe) an issue with data types and overflow.
I've tried changing over to unsigned and double, and the code complies and still accepts input in the terminal, but it seems to hang up after that... nothing is printed and it looks like it's caught in a loop.
Here is the code...
/* pascaltri.c
* A program that takes a single integer as input and returns the nth line of
* Pascal's Triangle. Uses factorial() function to help find items of
* individual entries on a given row.
*/
#include <stdio.h>
#include <stdlib.h>
long factorial(long i)
{
long fact = 1;
while(i > 1)
{
fact = fact * i;
i = i - 1;
}
return fact;
}
main(void)
{
long n;
long *nPtr;
nPtr = &n;
scanf(" %i", nPtr);
if (n >= 0)
{
long k;
long *kPtr;
kPtr = &k;
for(k = 0; k <= n; k++)
{
long ans;
long *ansPtr;
ansPtr = &ans;
ans = factorial(n) / (factorial(k) * factorial(n - k));
printf("\n %i", ans);
}
return 0;
}
return 0;
}
It's not perfect or pretty, but it works up to an input of 13 (that is, row 14) of the triangle. Beyond that I start getting gibberish and even negative values sprinkled throughout the returns... much larger values break the code and return nothing but an exit error message.
Any ideas on how I can correct this problem? I've been staring at the screen for much to long to really see anything myself. Also, it's not essential, but I would like to print my return values on one line, rather than having them separated by a newline character.
1 5 10 10 5 1
Would the easiest way be to load the values into an array as they are computed, and then print the array? Or is there a built-in way I can tell the print statement to occur on only one line?
A: For the garbage, you are most likely running into an integer overflow, that is, your calculated values become too large for the long data type. You should correct it by calculating your factorial function without explicitely calculating n!.
A: You are suffering from integer overflow. You may need to find a different approach to the algorithm to avoid having to calculate the large numbers.
In answer to your other point about the newline, you are explicitly printing the newline with the \n in your print statement. Remove it, and you will get answers printed on one line. You probably want to inlucde a final printf("\n"); at the end so the whole line is terminated in a newline.
Some other observations:
*
*You don't need the first return 0; - the control will drop out of
the bottom of the if block and on to the second (should be only)
return 0; and not cause any problems.
*You're declaring kPtr but not using it anywhere
*You don't need to declare a separate variable nPtr to pass to scanf; you can pass &n directly.
A: Change scanf(" %i", nPtr); to
scanf(" %ld", nPtr);
and printf("\n %i", ans); to
printf("\n %ld", ans);
to get printout on one line, use:
printf(" %ld", ans);
If you are using gcc, turn on warnings, i.e. use -Wall.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7607850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.