text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Highlighted color not cover all the table cell in Objective-c As the screenshot below, the highlighted color(blue) is not covered all the are of the cell, how can I make the highlighted color(blue) cover all the cell?
Thanks
A: Your subviews are covering the highlighting. You can try setting the highlighted color of all subviews in the cell to the same color. If its a UIImageView you would need to set the highlightedImage property to an image with a blue background, etc..
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get unique or distinct user comments? User has many Posts and many Comments. Posts has many Comments.
If I have @post, how do I get all unique user comments of this post?
For example. User Foo and user Bar have comments on @post. User Foo has 10 comments, while user Bar has 5 comments.
The result only needs to return Foo and Bar. How do I go about this?
I tried the following to no avail:
@post.comments.select('DISTINCT users.email').joins(:user)
Im using MySql by the way.
A: I'm assuming by "needs to return Foo and Bar" you mean the users Foo and Bar.
If an array will do, consider this:
@post.comments.collect(&:user).uniq
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error while trying to parse JSON using the json library I'm trying to parse JSON using the json library. I'm executing the chunk of code below, and I get the error:
Traceback (most recent call last):
File "test1.py", line 12, in <module>
parsedResponse = json.loads(data)
File "/usr/local/lib/python2.7/json/__init__.py", line 326, in loads
return _default_decoder.decode(s)
File "/usr/local/lib/python2.7/json/decoder.py", line 360, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/local/lib/python2.7/json/decoder.py", line 378, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
The code is:
import urllib, urllib2
from django.utils import simplejson
import json
opener = urllib2.build_opener()
requestURL = "http://api.shopstyle.com/action/apiSearch?pid=2254&fts=red+dress&min=0&count=10"
data = opener.open(requestURL).read().decode('utf8')
print data #this works
parsedResponse = json.loads(data)
I tried removing the read().decode('utf8') and passing that into json.load(), but that doesn't work either. I'd appreciate any help :)
Thanks.
A: When you printed your output, did it by any chance look like this?
<SearchResult>
<QueryDetails>
<Category>womens-clothes</Category>
<CategoryName>Clothing</CategoryName>
<ShowSizeFilter>false</ShowSizeFilter>
<ShowColorFilter>true</ShowColorFilter>
...
That's XML, not JSON.
A: is data null?
is data not proper JSON?
from your URL it seems that its outputting XML not JSON tho.
if you can post the output of data that would help
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using LINQ to SQL with custom business model? When using LINQ to SQL am I forced to live with objects structured the same as the database? Or can I use a different modelling structure for my business models?
If it's possible, how can I make this change?
A: You can create your own business model as DTO classes and copy the content to these DTO classes from your linq to sql objects. We used T3 templates (I don't remember where I got it...you can google it) to generate the DTOs to save the coding time and used Automapper initially to convert from L2S objects to DTOs, however, we started getting AutoMapperException randomly with no clues. So, for all our new code, we have created helper class to do the conversion. The advantage of this approach is that, now your service can be consumed by even non .NET clients as DTOs are platform generic.
A: Yes, LINQ to SQL always works directly with the database. It is always a one to one mapping.
This is one of many reasons to use Entity Framework, which allows you to program against an entity model which will not necessarily map one to one to the database structure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHP parse HTML rows based on class name How can I get all the rows with a specific class name such as:
<tr class="dailyeventtext" bgcolor="#cfcfcf" valign="top">
and then place each cell in that row into an array?
I used cURL to get the page off the client's server.
A: $matches = array();
$dom = new DOMDocument;
$dom->loadHTML($html);
foreach($dom->getElementsByTagName('tr') as $tr) {
if ( ! $tr->hasAttribute('class')) {
continue;
}
$class = explode(' ', $tr->getAttribute('class'));
if (in_array('dailyeventtext', $class)) {
$matches[] = $tr->getElementsByTagName('td');
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Animated Panel in Java how do applications get animated such as when you press a button, suddenly this whole panel would slide out then another panel would slide in with another set of option. is it playing with Thread.sleep(time) then change coordinates of the panel? or there's more than this algo?
A: This is somewhat general, but let me try. Yes, Thread.sleep(time) is relevant here(http://johnbokma.com/java/applet-animation.html). There is latency as you redraw. Java provides a lot of features in the javax.swing package for that kind of stuff : see here http://en.wikipedia.org/wiki/Swing_%28Java%29 . Also, see here http://download.oracle.com/javase/tutorial/uiswing/ .
for a simple slide-in/out animation, try this: http://www.java2s.com/Code/Java/GWT/SlideinandslideoutanimationSmartGWT.htm .
And Java 2D graphics is pretty broad, see here
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP: Extracting important keywords from a string I use the Google Images API to automatically generate thumbnails for my blog posts. I want to pick 3 or 4 important keywords from the post title and get a relevant image from Google Images. What's a good way to do this using PHP?
A: You could try the yahho term extraction api
http://developer.yahoo.com/search/content/V1/termExtraction.html
Or maybe tagthe.net
Both are accessible from php with the likes of cURL
A: There's not really a good way to automatically determine which keywords are "important". However, you could put in all words with at least a certain length, or the 3 longest words, or the words of at least a certain length that occur the most in the article.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Django (nonrel), App engine and asynchronous database calls When using Google App Engine with Django-nonrel, is there any way to take advantage of the Async Datastore API when I declare my model classes with the Django API?
A: Ok, I've investigated a bit more and found an alternative way to deal with having a Django Model (i.e.: all Django features there) and still having access to the async API...
Mainly, using the datastore directly:
from google.appengine.api import datastore
and I already had methods to convert all my models to/from a json dict, so, it was mostly a matter of discovering how Django-Nonrel did it behind the scenes:
E.g.:
Considering a 'Project' class with to_json and from_json methods (i.e.: create from a dictionary)
For doing a simple query (it seems Run() will do the work asynchronously, so, one could do the query.Run() and later start another query.Run() and both would work at the same time):
query = datastore.Query(Project._meta.db_table)
for p in query.Run():
p['id'] = c.key().id() #Convert from app engine key
print Project.from_json(p)
Now, using the API to get an object asynchronously:
from djangoappengine.db.compiler import create_key
async = datastore.GetAsync(create_key(Project._meta.db_table, project_id))
p = async.get_result()
p['id'] = c.key().id() #Convert from app engine key
print Project.from_json(p)
So, it's possible to retain the model with the Django structure and when needed some wrappers do the needed work asynchronously.
A: No. The Django framework provides its own interface to the datastore, and until it supports asynchronous calls directly, it's not possible to make asynchronous calls.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: android: ksoap2 org.xmlpull.v1.XmlPullParserException: expected: START_TAG exception I am trying to get a response from a web service. However I am getting some exception errors: mainly this one
org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope (position:START_TAG <html>@1:6 in java.io.InputStreamReader@40524b78)
Actually I am trying to access a method of a web-service and the webservice is supposed to return two strings (Lets say String1 and String2). Moreover, I have to provide or pass two parameters (lets say Parameter 1 and Parameter 2 where Parameter 1 should be integer and Parameter 2 should be String) Here is my code
public class MyWebService extends Activity {
private static final String SOAP_ACTION ="http://www.mywebsite.com/myMethod";
private static final String METHOD_NAME = "MyMethod";
private static final String NAMESPACE = "http://www.myNamespace/";
private static final String URL = "http://mysession.com/myservice.asmx?WSDL";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pi = new PropertyInfo();
pi.setName("Parameter 1");
pi.setValue(1);
pi.setType(pi.INTEGER_CLASS);
request.addProperty(pi);
PropertyInfo pi2 = new PropertyInfo();
pi2.setName("Parameter 2");
pi2.setValue("Any string");
pi2.setType(pi2.STRING_CLASS);
request.addProperty(pi2);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet=true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
//SoapObject result=(SoapObject)envelope.getResponse();
SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
String resultData = result.toString();
//String string1=result.getProperty(0).toString();
//String string2=result.getProperty(1).toString();
Log.v("WEBSERVICE","RESPONSE: "+resultData);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Can anyone tell me if I am doing something wrong here.. Another very important question:
Can anyone tell me that why I can't use getProperty(0) or getProperty(1) method with the result here. I am supposed to get two strings in response from webservice but I can't use getProperty(index) with SoapPrimitive..
All suggestions are appreciated
Thanks
A: I am not sure this is exact solution what you need but this works for me, I was getting same problem before, but There was 5 parameters needed and I just added 3 parameters using SoapObject, so it was giving this type of error, so please make sure that you have added all required parameters using request.addProperty("test","test") before call this webservice.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I reset the text visible with a jQuery Autocomplete combobox? Using a jQuery Autocomplete combobox like on the demo
http://jqueryui.com/demos/autocomplete/#combobox
How do I reset the visible user-entered text using jQuery?
(after the user has entered some text, made an autocomplete choice and caused, an unrelated, change)
Note: Changing the underlying select element does not cause any change in the autocomplete input field.
Note 2: This is one of many autocomplete comboboxes on the page in question (unlike demo)
A: I am able to reset the demo with the following code. One thing to note is that the select box is hidden but the values need to be maintained.
//clear each option if its selected
$('#combobox option').each(function() {
$(this).removeAttr('selected')
});
//set the first option as selected
$('#combobox option:first').attr('selected', 'selected');
//set the text of the input field to the text of the first option
$('input.ui-autocomplete-input').val($('#combobox option:first').text());
A: If you want to clear the text in a comboBox (comboChild) that depends on another combo box, you do this in the "select:" event (triggered when parent combo box is changed):
//Creation of the parent combo:
$comboParent.combobox({
select: function( event, ui ) {
clearComboBoxText($("#combo2"));
}
});
function clearComboBoxText(cmbBoxObj){
var inputsDelBox = cmbBoxObj.next().children(); //ref to the combo editable
inputsDelBox.val(""); // this clears the text
//inputsDelBox.css( "background-color", "green" ); //if you want to change color
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Use ManagementObject to restart remote service I want to restart a service on a remote machine and do not want to use ServiceController because the process to get all services on that machine took 21 seconds while the following ManagementObject returned in less than 2 seconds:
ConnectionOptions options = new ConnectionOptions();
ManagementScope scope = new ManagementScope("\\\\" + ConfigurationManager.AppSettings["remoteMachine"] + "\\root\\cimv2", options);
scope.Connect();
ObjectQuery query = new ObjectQuery("Select * from Win32_Service where DisplayName LIKE '%" + ConfigurationManager.AppSettings["likeSerices"] + "%'");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
ManagementObjectCollection queryCollection = searcher.Get();
List<ServiceObj> outList = new List<ServiceObj>();
foreach (ManagementObject m in queryCollection)
{
ServiceObj thisObject = new ServiceObj();
thisObject.DisplayName = m["DisplayName"].ToString();
thisObject.Name = m["Name"].ToString();
thisObject.Status = m["State"].ToString();
thisObject.StartMode = m["StartMode"].ToString();
outList.Add(thisObject);
}
I now tried:m.InvokeMethod("StopService", null); in the foreach block with no success. What am I doing worng?
Thank you
Jack
A: I don't know C# but this VBScript sample from here shouldn't be too bad to convert:
' VBScript Restart Service.vbs
' Sample script to Stop or Start a Service
' www.computerperformance.co.uk/
' Created by Guy Thomas December 2010 Version 2.4
' -------------------------------------------------------'
Option Explicit
Dim objWMIService, objItem, objService
Dim colListOfServices, strComputer, strService, intSleep
strComputer = "."
intSleep = 15000
WScript.Echo " Click OK, then wait " & intSleep & " milliseconds"
'On Error Resume Next
' NB strService is case sensitive.
strService = " 'Alerter' "
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
("Select * from Win32_Service Where Name ="_
& strService & " ")
For Each objService in colListOfServices
objService.StopService()
WSCript.Sleep intSleep
objService.StartService()
Next
WScript.Echo "Your "& strService & " service has Started"
WScript.Quit
' End of Example WMI script to Start / Stop services
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: sumproduct of List or Array using lambda expression I'm trying to get the sumproduct (values * index) of a List or Array.
for (int i = 0; i < myList.Count; i++)
{
sumproduct += myList[i] * i;
}
Can this be done using a lambda expression?
In general, can I access the index of a List or Array in lambda expressions?
Something with syntax similar to:
sumproduct = myList.Sum((value, index) => value * index);
A: sumproduct = myList.Select((i, j) => i*j).Sum();
This uses the second overload of Select() that includes index.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Given an array of ints, what is the most efficient way to split the array down the middle into two arrays of shorts? It struck me there must be a clever way to do this. This isn't for homework, or work or anything. I was just noodling around with a file format that has data interleaved.
So, in generic C/C++, (or whatever) given some array
int x[] = ...
is there a clever way of splitting it into two short arrays
short sa1[], sa2[]
such that the int array is split down the middle
x[i] = 1111111111111111 1111111111111111
sa1[i] sa2[i]
Edit: Sorry if this is not phrased well. For each i-th element of the int array, the left-most 16 bits become the i-th element of one array, and the right-most 16bits become the i-th element of a 2nd array.
so given
x[i] = 0001111111111111 1111111100011111
then
sa1[i] = 0001111111111111
sa2[i] = 1111111100011111
I'm looking for non-obvious answers that do not loop over each element and shift and mask each element. That's easy :)
A: There's a lot of ways to do this:
Assumptions:
*
*short is 16 bits.
*int is 32 bits.
Method 1: (A simple loop)
for (int i = 0; i < size; i++){
int tmp = x[i];
sa1[i] = (tmp ) & 0xffff;
sa2[i] = (tmp >> 16) & 0xffff;
}
Method 2: SSE2
for (int i = 0; i < size / 8; i++){
__m128i a0 = ((__m128i*)x)[2*i + 0];
__m128i a1 = ((__m128i*)x)[2*i + 1];
a0 = _mm_shufflelo_epi16(a0,216);
a1 = _mm_shufflelo_epi16(a1,216);
a0 = _mm_shufflehi_epi16(a0,216);
a1 = _mm_shufflehi_epi16(a1,216);
a0 = _mm_shuffle_epi32(a0,216);
a1 = _mm_shuffle_epi32(a1,216);
((__m128i*)sa1)[i] = _mm_unpacklo_epi64(a0,a1);
((__m128i*)sa2)[i] = _mm_unpackhi_epi64(a0,a1);
}
This last example is very fast if the loop is further unrolled. I won't be surprised if this can beat all byte-manipulation libraries.
However, it has the following restrictions:
*
*The data must be aligned to 16 bytes.
*The number of iterations must be divisible by 8.
*It requires SSE2.
The first two of these can be solved by cleanup code. It's messy, but if you really desire performance, it may be worth it.
EDIT:
Yes this violates strict-aliasing, but it's nearly impossible to use SSE intrinsics without doing so.
A: If int is exactly two shorts on your platform, you can just reinterpret_cast the int array into short array, then take even/odd elements.
Note however, that size of int versus short is not guaranteed (other than short cannot be larger than int). For example int may be equal to short or it may be more than 2 shorts. Even the absolute size of int is not guaranteed (typical sizes are 4 and 8 bytes).
For truly portable solution, you'll probably be better off mapping the exact format of the file you are trying to interpret into bit fields.
A: You will need to know the length of x, but you could do something similar to:
#include <stdio.h>
int main(int argc, char * argv[])
{
int x[] = {1, 2, 3, 4, 5, 6};
int xlen = 6;
short * a = &x[0];
short * b = &x[xlen/2];
printf("%d\n%d\n", a[0], b[0]);
}
a points to the beginning of the original int array, and allows you to index in short increments. Same deal with b, except it starts from the middle of the original int array.
I would call this clever, but you will get a warning from gcc about incompatible pointer types. This is the kind of thing I might do in an embedded environment, but I would make sure it doesn't cause any security issues in a less controlled environment.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Need help setting Neural Network parameters (learning rate, momentum, hidden layer size...) I have a standard feedforward backpropagation neural network that i would like to train to be able to recognize a blue ball. I have 30 images 20 of the ball and 10 without and my first question is whether or not this is enough im assuming its better to have more than less but it would be nice to know if there is a minimum of sorts. Each image is 96 pixels wide by 128 pixels high so thats 12,288 pixels in total times 3 for RGB which gives 36,864 perceptrons in my input layer. Since i only need to know if an image contains the blue ball or does not i have 1 output perceptron. All perceptrons in the network use the logistic activation function. In my hidden layer i've tried a whole bunch of different number of hidden units ranging from 100-3000 but none of them seem to work, the network either says that the MSE is low enough to stop after 1 iteration or the network never reaches the desired MSE and stops because of a training iteration limit and the output is always the same value no matter what the input is. Ive tried a range of learning rates and momentums all under 0.1 and the momentum is always less than the learning rate, my goal MSE right now is 0.0005. I've done object detection using a neural network before but instead of having an input layer i just had a hidden layer with 12,288 perceptrons (one for each pixel) and each perceptron had 24 inputs (8 bits per colour 3*8 = 24 bits) that received binary colour information from the image and then i had one output perceptron, all perceptrons used the logistic activation function and it worked. I thought id try using an input layer but so far the only thing i've been able to learn is the XOR problem.
So my questions are:
What would be optimal network topology for my problem? (How many layers, hidden units...)
Is there a range of learning rate and momentum values i should use?
Is 30 training samples enough?
And just as a side note in case it matters when my neural network is created the weights are initialized with values ranging from -0.3 - 0.3
A: In general, I think the big problem with neural nets is that you don't get good guarantees before hand, and you have a lot of freedom in the structure. Picking the right parameters is a matter of doing lots of experimenting and iterating a lot.
I don't think that anyone can you tell beforehand what will definitely work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why does read-sequence not return upon end of the console stream? I am opening a serial port with CLISP in Cygwin as an IO stream and found that reading character-by-character is too slow. For some reason, the stream is being classified as interactive which I believe is causing it to hang with a read smaller than the size of my sequence.
I am interacting with the debug port on a special system. I intended to spend just a little time to script some interactions, but ended up shaving a yak.
I see a few different ways to resolve this.
*
*Read 1 char at a time which allows for read-char-no-hang. This is too slow.
*Write a FFI to a serial library. I don't think I should have to do this.
*Find some way to determine the remaining length of the stream. Good solution.
*Figure out how to make the serial port non-interactive which may cause the read-sequence to return upon end of stream. This seems like the best solution to me.
(with-open-file (serial "/dev/ttyS3"
:direction :io
:external-format :unix
:if-exists :overwrite)
(read-sequence *data* serial)))
So, per the title, why does read-sequence not return upon the end of the console stream? Additionally, what is the best way to achieve that behavior? I'd prefer to stick with the basic CLISP.
A: First, check your definitions for READ-SEQUENCE.
Second, serial data doesn't always have an end-of-file marker (actually, usually doesn't). Maybe your data is getting cooked by the ttyS3 driver, but if this was a raw read, you should assume you have to write your own termination conditions (or implement the ones defined by your device).
Third, serial IO often winds up making you do yak shaving. It's pretty classic network coding, you have to think about packets, frames, speed synchronization and all the usual goodness with protocols. If you're really lucky, your application is simple and you can avoid that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to save/load progress? Suppose I have a program, with let's say - a dictionary, that the user updates, changes and stuff like that. Now, I want to save that dictionary in a file, so in the next time he runs the program, he can continue where he stopped.
What is the right way to/how would you accomplish that?
Thank you.
A: One option could be to serialize the Dictionary object itself to a file, in either a custom format, XML, or simply a binary representation and then deserialize it when the application loads, but this breaks down with multiple users.
One of the most common approaches to persisting data is in a database.
Apologies if this answer is vague, but the solution really depends on the needs of your application. Maybe a simple text file is sufficient, or maybe you do need something more robust, such as a database.
There are several free database options out there: SQL Server Express, MySQL, PostgreSQL, SQLite just to name a few.
A: I would just serialize the dictionary since that's what the app is using.
Assuming that you have a Dictionary<string, string> here the serialize method I'd use:
var entries =
dictionary
.Select(kvp =>
new XElement(
"entry",
new XAttribute("key", kvp.Key),
new XAttribute("value", kvp.Value)));
var xd = new XDocument(new XElement("dictionary", entries));
xd.Save(@"C:\filename.xml");
And then to bring it back from disk:
var dictionary =
XDocument
.Load(@"C:\filename.xml")
.Root
.Elements("entry")
.ToDictionary(
x => x.Attribute("key").Value,
x => x.Attribute("value").Value);
Pretty easy, huh?
A: So, a dictionary could be a pretty large thing and loading it all up in memory isn't probably the answer. I'd probably utilize some sort of DB to hold it - sqlite or something like that would work. It would be pretty straightforward to track the last thing the user used in a table entry and the dictionary entries as well. Particularly for a dictionary the DB solution works nicely because it allows for things like links to other entries, etc. Doing this in some flat file or even in XML is probably the wrong approach if it is of any appreciable size.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Zend Framework: Select with join and PDO name param binding I am using Zend Framework and have been trying to do a joined query and also use named param binding. Referencing from the two posts below. When I just do the join everything works. When I add the name binding then it gets this error:
Message: SQLSTATE[HY093]: Invalid parameter number: no parameters were
bound
How to do a joined query in the ZF tables interface?
Zend Framework: How to find a table row by the value of a specified column?
I have scaled it way down trying to remove any possible errors but it is still getting the error and no idea why.
$query = "country = :cc"; // changing :cc to 'US' everything works
$params = array(':cc' => 'US');
$db = $this->getDbTable();
$select = $db->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
$select->setIntegrityCheck(false)
->join(array("daytable"), 'weektable.showid = daytable.id')
->where($query, $params);
$rowset = $db->fetchAll($select);
A: Try this:
->where('country = ?', 'US')
Binding params with Zend_Db_Select
A: $query = "country = ?"; // changing :cc to 'US' everything works
$param = 'US';
$db = $this->getDbTable();
$select = $db->select(Zend_Db_Table::SELECT_WITH_FROM_PART);
$select->setIntegrityCheck(false)
->join(array("daytable"), 'weektable.showid = daytable.id')
->where($query, $param);
$rowset = $db->fetchAll($select);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting access token issue with twitter4j I am getting the following error. Any help ?
09-25 20:44:58.934: WARN/System.err(3741): oauth.signpost.exception.OAuthExpectationFailedException: Request token or token secret not set in server reply. The service provider you use is probably buggy.
09-25 20:44:58.934: WARN/System.err(3741): at oauth.signpost.AbstractOAuthProvider.retrieveToken(AbstractOAuthProvider.java:202)
09-25 20:44:58.934: WARN/System.err(3741): at oauth.signpost.AbstractOAuthProvider.retrieveAccessToken(AbstractOAuthProvider.java:97)
09-25 20:44:58.934: WARN/System.err(3741): at corp.encameo.app.TwitterApp$3.run(TwitterApp.java:145)
09-25 20:44:58.981: ERROR/TWITTER(3741): Error getting access token
At line 145 of TwitterApp.java
new Thread() {
@Override
public void run() {
int what = 1;
try {
(line 145) mHttpOauthprovider.retrieveAccessToken(mHttpOauthConsumer,
verifier);
mAccessToken = new AccessToken(
mHttpOauthConsumer.getToken(),
mHttpOauthConsumer.getTokenSecret());
configureToken();
User user = mTwitter.verifyCredentials();
mSession.storeAccessToken(mAccessToken, user.getName());
what = 0;
} catch (Exception e) {
e.printStackTrace();
}
mHandler.sendMessage(mHandler.obtainMessage(what, 2, 0));
}
}.start();
using the following libraries:
signpost-commonshttp4-1.2.1.1.jar ,
signpost-core-1.2.1.1.jar ,
signpost-jetty6-1.2.1.1.jar ,
twitter4j-core-2.1.6.jar .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Custom TableViewCell question I subclassed UITableViewCell and added a round rec button using IB.
Normally, the event will be handled on the class of my custom UITableViewCell.
But how do handle the event that the button is clicked on the viewController which has a UITableView that uses this UITableViewCell?
A: When creating the custom cell, make sure you are adding the view controller as the button action's target. So in your view controller's (assuming it is the datasource for the table view):
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// All your standard identifier & dequeueing stuff here
if (cell == nil)
{
// We are creating a new cell, let's setup up its button's target & action
cell = [[[CustomCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
[cell.yourButton addTarget:self action:@selector(yourAction:) forControlEvents:UIControlEventTouchUpInside];
}
return cell;
}
A: So its kinda akward the way u are doing it because what u really wanna do is create a subclass of uiview and then create that and add it to the contentView of the cell. But since u are doing it this way u should set the tag of the button to its index and then in the selector have the function say cancelButton: and then this should be ur cancelButton function decleration
-(void)cancelButton:(id)sender
{
UIButton pressed = (UIButton)sender;
//and then pass in the tag pf the button with pressed.tag
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Authenticating Heroku app with Google I'm trying to set up a Rails app on Heroku to access Google data. I'm new to the process but it looks like I need to register an authentication certificate with Google in order to use Google services (using either OAuth or AuthSub). End game: I need persistent access to Google calendar data.
Google's Manage Domain site provides a way to upload an X.509 certificate, but for development purposes I'm just using Heroku's Piggyback SSL to get access to the heroku.com certificate. Assuming I'm on the right path, how do I provide the Heroku certificate to Google so I can continue?
It's also quite possible that I've gone down a rabbit hole; if that's the case, any advice re: authenticating Heroku with Google would be much appreciated.
A: You're making it way too hard on yourself. Either use OAuth 1 with the HMAC-SHA1 signature method or use OAuth 2. Preferably OAuth 2, though I'm not sure if that's compatible with the old GData libraries that the current version of the Calendar API uses. But honestly, even if it's not compatible, the advantages of OAuth 2 might make it worth hacking something together. You can use Signet to do OAuth 2 — that's the Google-supported OAuth client for Ruby. Don't use AuthSub unless you've got a really good reason. There should be no certificates involved at all.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to instantiate a non-public final class using reflection? I have a non-public final class that looks like the following:
final class FragmentManagerImpl {
...
}
Note that it is not public and it has no declared constructors.
I would like to instantiate an instance of this class using reflection. However, both of the following code snippets result in IllegalAccessExceptions:
// BUG IllegalAccessException on calling newInstance
final Class c = Class.forName("android.support.v4.app.FragmentManagerImpl");
c.newInstance();
// BUG IllegalAccessException on calling newInstance
final Class c = Class.forName("android.support.v4.app.FragmentManagerImpl");
final Constructor constructor = c.getDeclaredConstructor();
constructor.setAccessible(true);
constructor.newInstance();
What is the correct way to instantiate this class from a package that is not android.support.v4.app?
A: According to JavaDocs, you can call getDeclaredConstructors() method and you'll get all the private constructors as well as the default constructor.
public Constructor[] getDeclaredConstructors()
throws SecurityException
Returns an array of Constructor objects reflecting all the
constructors declared by the class represented by this Class object.
These are public, protected, default (package) access, and private
constructors. The elements in the array returned are not sorted and
are not in any particular order. If the class has a default
constructor, it is included in the returned array. This method returns
an array of length 0 if this Class object represents an interface, a
primitive type, an array class, or void.
See The Java Language Specification, section 8.2.
It doesn't specify how exactly this getDeclaredConstructor(Class... parameterTypes) method, that you are using, will work though.
A: I'm guessing, but I think that it is complaining about the accessibility of the class not (just) the constructor.
Try calling setAccessible(true) on the Class object as well as the Constructor object.
A: Hm, it appears to have been user error. Using the constructor method outlined in the question does seem to have worked properly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Android Google API Java Client com.google.api.client.auth.oauth2.draft10 I was trying to do a simple app using the Google Tasks API. Something simple it's turning into a nightmare. Maybe it's something simple, probably it is, but I can't figure it out.
The problem: I was following the example of TasksSample.java from Google but I can't compile even after importing the libraries and dependencies required. I'm using Google API Java Client version 1.5.0.
The problem it's when I access the GoogleAccessProtectedResource class. The import is:
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
I always, and I mean always, no matter what code I have get the following error:
09-26 03:14:38.372: ERROR/dalvikvm(18731): Could not find class 'com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource', referenced from method com.greven.test.google.tasks.GoogleTasksTake100Activity.
09-26 03:14:38.402: ERROR/AndroidRuntime(18731): FATAL EXCEPTION: main
09-26 03:14:38.402: ERROR/AndroidRuntime(18731): java.lang.NoClassDefFoundError: com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource
I really can't see where the problem is. I imported all the needed .jars... I guess
As you can see in this picture the class is obviously imported:
So what other options do I have to fix this? Use Maven? I'm clueless now. I never thought I would have a problem like this. Oh I also tested on different computers, other Google java api client (version 1.4) and same thing happened. Thanks in advance.
A: It seems as per your screenshot that your imported jar is imported in Eclipse, however for your Android application to work you need these jars to be dropped into a specific folder so that it is added to your APK and so the emulator and the Android devices find it.
It seems you should drop these jars in a folder named /libs at the root of your project. See this SO question: How can I use external JARs in an Android project?
The Article you are referring too uses the /assets folder but this might have changed a few Android versions ago.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to load more on PHP array? I use jQuery (I found this code in an answer, tested and working) to show people.php and reload it every 100 seconds. People.php has an array peoples where there are saved name, job, birthday.
As you can see, the output stops at 30 names. How can I have a twitter like button "load more" and show 10 more at a time? Additionally, when there are e.g. 50 more people's name (assuming that the user clicked "load more" twice, will the jQuery timeout reload, returned them at 30 as the beginning ?
<script>
var timerID;
$(function () {
function loadfeed() {
$('#feed')
.addClass('loading')
.load('people.php', function () {
$(this).removeClass('loading');
timerID = setTimeout(loadfeed, 100000);
});
}
loadfeed();
});
</script>
A: How about passing a parameter to the URL in your load(..) call?
$(function () {
var startAt = 0;
function loadfeed() {
$('#feed')
.addClass('loading')
.load('people.php?start_at=' + startAt, function () {
$(this).removeClass('loading');
timerID = setTimeout(loadfeed, 100000);
startAt += 30;
});
}
});
Then in people.php you could get the passed parameter using $_GET:
$start_at = 0;
if (isset($_GET['start_at']) && is_numeric($_GET['start_at'])) {
$start_at = (int) $_GET['start_at'];
}
for ($i = $start_at; $i < min($start_at + 30, sizeof($peoples)); $i++) {
echo $peoples[$i]->name;
}
A: Well what you could do is save a variable that contains the number of people, this example should give you a good view of what i mean.
<script>
var timerID;
var cap;
$(function () {
function loadfeed() {
$('#feed')
.addClass('loading')
.load('people.php?cap='+cap, function () {
$(this).removeClass('loading');
timerID = setTimeout(loadfeed, 100000);
});
}
loadfeed();
});
</script>
<?php
foreach ($peoples as $people) {
if(++$i > $_GET['cap']) break;
echo $people->name;
}
?>
So all you have to do, is change the cap variable, you could do this easily making a javascript function and call this via a onClick event.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Launching Android Market Main Page from an application I'm trying to write a launcher-like application (I'm not planning to release it, it's just for me to use) but I don't seem to find any way to launch the Market.
All of the answers I've found actually perform a search on the Market (using a uri "market://") or even worse they run the Market on a specific app page, while I'm trying to show the main page of the Market, i.e. the page shown when you run it from the launcher.
I tried using just "market://" as a Uri, without query strings, but it doesn't work; I also tried to get exactly the same "signature" of the "start activity command" that appears in the LogCat when I run the Market from the Launcher (by manually editing component, flags and categories), but it still doesn't work.
Is there any way to get it to show the main page?
Thanks in anticipation.
A: Intent intent = new Intent();
intent.setClassName("com.android.vending", "com.android.vending.AssetBrowserActivity");
startActivity(intent);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What are the 'ref' and 'sealed' keywords in C++? I've just seen some (presumably) C++ code which sports two "keywords" unknown to me (I'm assuming keywords but, since I have no context, they may be simple #define things).
They also don't seem to appear in the C++11 standard, at least the draft I have but, since that's a pretty late draft, I can't imagine them being just dropped into the standard at the last minute. They are ref and sealed.
The code I found them in was something like:
public ref class DevIface sealed {
private:
int currOffset;
public:
DevIface (int initOffset);
: : :
Does anyone know what these keywords are, and what they're meant to achieve?
A: Thus summary is that "ref" and "sealed" are not standard C++ keywords. They are used in microsoft version.
A: sealed in C++/CLI is roughly equivalent to final in C++11.
A: If you are interested in the new C++/CX use of these keywords to project WinRT APIs into MS Visual C++, you may enjoy this video: http://channel9.msdn.com/events/BUILD/BUILD2011/TOOL-532T with these slides: http://video.ch9.ms/build/2011/slides/TOOL-532T_Sutter.pptx . See esp. slides 8-13. There are other talks with yet more information referenced on slide 29.
A: This is C++/CLI.
A ref class is a managed type.
sealed means that the class cannot be inherited
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Entity Framework Discriminated Associations Is there any way of getting discriminated associations to work in Entity Framework 4? That is, where we have the following tables
TableA
RelatedEntityTypeId
RelatedEntityTypeKey
TableB (1)
Id
TableC (2)
Id
TableD (3)
Id
and I want to have three associations on the entity for TableA:
TableB
TableC
TableD
which are defined by the RelatedEntityTypeId and RelatedEntityTypeKey fields...when RelatedEntityTypeId = 1, then the association is to EntityB, when RelatedEntityTypeId = 2, then the association is to EntityC, etc.
Thanks.
A: I don't know your purpose of doing this. I have used following approach to solve similer problem.
You can define a base type for all three tables (A,B,C). And when you want retrieve a object use a generic method for all tables (which returns a base object). And then you can check the type of the returned object to get the A,B,C object.
TableBase
Id
TableB (1):TableBase
TableC (2):TableBase
TableD (3):TableBase
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can nodejs be installed on a free webhost My goal is to create a chatting website. Not so much for the sake of the website, but for the experience so I know how; just something to work towards gradually. I tried long polling, but that always ends up pissing off the webhosts whose servers I'm using. I was told to use nodejs instead. I have some idea of what it is, but no idea how to use it.
I'm guessing that the reason I can't find the answer to this question anywhere is because of how obvious it is... to everyone else.
I've been looking around and all I see are tutorials on installing it on your server when you own the server. I know you can install forums on webhost's servers, so can you also install nodejs?
A: Most standard LAMP hosting companies don't let you run node.js.
I currently recommend you use the Cloud9 IDE to get up and running with not only your tests and development, but also potential deployment. Cloud9 allows you to run your app from their IDE and will provide you with URL to see your app running and get familiar with node.js development.
A more manual way is to find a node.js PAAS (Platform as a Service) such as Joyent or Nodester.
A: Another one is Open Shift. I use them a lot and they allow you to use your own domain on the free plan. I use Heroku as well and have tried AppFog and Modulus.
But what it comes down to is whether I can use my own domain and how much they throttle my traffic. AppFog and Modulus don't allow custom domains on their free plans and seriously throttle traffic. They will cut your website off if you have one visitor an hour.
Another issue I was concerned about was with the upload of files. In particular, with my website content is added via markdown files. Most node webhosts use a variation on git deploys to update websites, with content supplied by databases. However, if you are trying to run a website without a database, using flat files, then each update must be done by a git deploy. This takes the whole website down and recreates a new website altogether (it just happens to look like the previous one). This will normally take a few minutes. Probably not a problem for a low volume website. But imagine if you are making a blog entry and you deploy it and then notice you've made a spelling mistake. You need to do a deploy all over again.
So, one of the things that attracted me to Open Shift was that they have a reserved area for flat files within your project. You can upload your files there and when your project is re-started these files will be preserved.
A: Yes. You can check the full listing at https://github.com/joyent/node/wiki/Node-Hosting to check each site but it does not categorize it by free hosting..
Some I know of, I personally use Heroku.
*
*Heroku
*Nodester
A: Appfog provides a free plan where you can host NodeJS and many other technos.
However, free plans don't allow custom domain name anymore.
A: There is also the Node.js Smart Machine service from Joyent.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: exception during commit I am using hibernate 3.6.1 and jpa. At certain times when I try to commit the data into database I seem to get the following exception:
Exception in thread "pool-2-thread-1" javax.persistence.RollbackException: Error while committing the transaction
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:93)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1214)
at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1147)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:81)
... 5 more
Caused by: org.hibernate.exception.JDBCConnectionException: could not update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:99)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2612)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:2494)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2821)
at org.hibernate.action.EntityUpdateAction.execute(EntityUpdateAction.java:113)
at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:273)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:265)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:185)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:51)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
at org.hibernate.ejb.TransactionImpl.commit(TransactionImpl.java:76)
... 5 more
Caused by: java.sql.SQLRecoverableException: Closed Statement
at oracle.jdbc.driver.OracleClosedStatement.setObject(OracleClosedStatement.java:578)
at oracle.jdbc.driver.OraclePreparedStatementWrapper.setObject(OraclePreparedStatementWrapper.java:238)
at org.apache.commons.dbcp.DelegatingPreparedStatement.setObject(DelegatingPreparedStatement.java:163)
at org.apache.commons.dbcp.DelegatingPreparedStatement.setObject(DelegatingPreparedStatement.java:163)
at org.hibernate.type.EnumType.nullSafeSet(EnumType.java:147)
at org.hibernate.type.CustomType.nullSafeSet(CustomType.java:140)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2184)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:2558)
...
Kindly help me understand why I get this issue sometimes.
A: It seems connection to the DBMS was closed out from under it while in use. Check your DBMS
error log.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SharePoint 2007: How to cross-site lookup value? I'm working in application build in SharePoint 2007, my question is can we do lookup value of Site Column across Site?
A: Only possible with third party :
http://www.boostsolutions.com/Cross-SiteLookup.html
A: If your lookup list is at Site collection and the column is @sub sites of the site collection, then you can try by creating Site Columns as Look up type.
A: Create your source list in the top-level site. In the same site create a lookup column looking up valies from that list, now you can use this column throughout the site collection.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mac OS X + Rails 3.1 + Unicorn + HTTPS Here is my setup:
*
*Mac OS X 10.6
*Ruby 1.8.7
*Rails 3.1
I have a Rails 3.1 application that starts with Unicorn every time this machine starts up (via a .plist in /Library/LaunchDaemons). The .plist essentially does this:
cd /my_application_directory
sudo unicorn -E production -p 80
And everything's working fine. However, I'd like to be able to set up SSL so that traffic is encrypted. I don't need a real certificate signed by a real CA, because the application is only accessible over a local network.
I've found articles like this one on generating certs, but I'm not sure where to go from there (or even if that's the correct starting place).
For my basic needs, I've found the .plist method to be much easier to work with than something like Phusion Passenger, so I'd like to continue doing it that way if possible.
Any help would be greatly appreciated!
A: I don't believe Unicorn supports being an SSL endpoint, so you're going to need another process to decrypt/encrypt the traffic for you.
On Mac, it's probably easiest to use apache, because it's already installed.
Sorry to not have detailed steps, but you're looking to do the following:
*
*Change the port unicorn listens on, to prevent conflicts with apache.
*Set up Apache to serve SSL, just like your linked reference.
*Also set up apache to proxy requests to be handled by Unicorn, on the new port you setup. This involves the ProxyPass (and possibly ProxyPassReverse) directive.
*Configure apache to start when the Mac boots.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Javascript Json Parse I am using Json in javascript. I'm reading the json from test.js. How can I read for(;;).
<script type="text/javascript">
$.getScript('ajax/test.js', function(data, textStatus){
jQuery.each(data, function(return) {
alert(return.name);
alert(return.surname)
});
});
</script>
-
TEST JS
for (;;);
{
"name" : "Mustafa Can",
"surname" : "Pala"
};
A: You need to call $.get to fetch the content of the script as a string, then remove the for(;;);:
$.get('ajax/test.js', function(data, textStatus){
var json = data.replace(/^for\(;;\);/, "");
var obj = $.parseJSON(json);
alert(obj.name);
alert(obj.surname)
}, 'text');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: default Twitter button doesn't load image I went to Twitter's resource page here (https://twitter.com/about/resources/tweetbutton) and got the following code:
<a href="https://twitter.com/share" class="twitter-share-button" data-count="vertical">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>
When I put this in my Wordpress template, I don't get the Twitter button -- I just get the text "Tweet". However, when I change the src for widgets.js to include https:// or http:// at the beginning it works.
Could it be that it's just an error that they forgot the protocol? Also, do you think it is better to use https (for consistency with the share link) versus http, or does it not matter?
Thanks for your suggestions.
A: The URL "//example.com/script.js" tells the browser to open the URL using the protocol of the current page, which is likely to be "file://" if your browser opened an html file on your own machine. Of course, you don't have a file called "file://example.com/script.js" on your computer.
In the past, urls for embedded widgets used to include the protocol (http or https), but a site visitor would receive warnings whenever a secure page loaded a script from an insecure page, and sometimes even vice versa. Now, widgets from Twitter, Google Analytics, and other sites no longer specify the protocol so that the same embed code can work on any page on the internet. The downside is that this does not work when you embed such a widget into a file and view it on your own browser by double-clicking it!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: rails 3 get data from an association and display in flash message I'm using ActiveMerchant with Authorize.net and already setup 2 models Order and Transaction. (http://railscasts.com/episodes/145-integrating-active-merchant)
I would like to get error message from the transaction if error occurred then output in flash message. Here is my code:
#order_controller.rb
def create
@order = Order.new(params[:order])
respond_to do |format|
if @order.save
if @order.purchase
format.html { redirect_to(@order, :notice => 'Order was successfully created.') }
format.xml { render :xml => @order, :status => :created, :location => @order }
else
flash[:error] = @order.transactions.response
format.html { render :action => "new" }
end
else
format.html { render :action => "new" }
format.xml { render :xml => @order.errors, :status => :unprocessable_entity }
end
end
end
And here is my transaction model:
#models/order_transaction.rb
class OrderTransaction < ActiveRecord::Base
belongs_to :order
serialize :params
def response=(response)
self.success = response.success?
self.authorization = response.authorization
self.message = response.message
self.params = response.params
rescue ActiveMerchant::ActiveMerchantError => e
self.success = false
self.authorization = nil
self.message = e.message
self.params = {}
end
end
The transaction data has been saved to the database as below:
#models/order.rb
class Order < ActiveRecord::Base
has_many :transactions, :class_name => "OrderTransaction"
attr_accessor :card_type, :card_number, :card_month, :card_year, :card_verification
def purchase
response = GATEWAY.purchase(charge_amount, credit_card, purchase_options)
transactions.create!(:action => "purchase", :amount => charge_amount, :response => response)
response.success?
end
...
end
I want to flash up this transaction error message when transaction failed. And what would I should do to get these errors if I have 2 transactions for one order.?
Any help would be much appreciated.
Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Get column names of multiple tables and insert it to another table + PHP MySQL I have this code:
$createFields="CREATE TABLE temp_field (fld text NOT NULL, tablename char(50) NOT NULL)";
mysql_query($createFields);
$fields=array();
$campaign=mysql_query("SELECT campaignid FROM campaign ORDER BY campaignid");
while($row=mysql_fetch_array($campaign)){
$table="'campaign_".$row['campaignid']."'";
$temp_field="SELECT COLUMN_NAME,TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME=".$table;
$temp_fieldquery = mysql_query($temp_field);
while($rowL=mysql_fetch_array($temp_fieldquery)){
$fields[]="'".$rowL['COLUMN_NAME']."'";
}
$field=implode(",",$fields);
$insertFields='INSERT INTO temp_field (fld,tablename) VALUES ("'.$field.'","'.$table.'")';
mysql_query($insertFields);
and I need to have this kind of output:
fld | tablename
=====================================
fld1,fld2,fld3,fld4... | table1
fld1,fld2,fld3,fld4... | table2
but what I get is:
fld | tablename
========================================================
fld1,fld2,fld3,fld4... | table1
fld1,fld2,fld3,fld4,fld1,fld2,fld3,fld4... | table2
The second table gets the values of first table
What am I doing wrong with my code, please help
A: Just initialize your $fields array right before the while loop.
$fields = array();
while($rowL=mysql_fetch_array($temp_fieldquery)){
$fields[]="'".$rowL['COLUMN_NAME']."'";
}
$field=implode(",",$fields);
What happened in your code is that the $fields array continues to add new fields for each succeeding table due to $fields[] so resetting to a new array should fix it.
A: INSERT INTO temp_field
SELECT
GROUP_CONCAT(COLUMN_NAME separator ",") AS fld
TABLE_NAME AS tablename
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME LIKE 'campaign_%'
GROUP BY TABLE_NAME
Your code sample is much to complicated.
Just use the query above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I get touchesBegan event on SuperView In my program there is two views(scrollView-super, view-sub*2).
In my case two subviews are subviewed in scrollView. touchesBegan event called in subviews.
How Can I get event in scrollView???
@interface MyScrollView:UIScrollView
...
@implement MyScrollView
...
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//here is my code
//but I can't get event here
...
}
-(id)initWithFrame:(CGRect) frame
{
...
MyView *view1 = [[MyView alloc] initWithFrame:(0, 0, 320, 240);
MyView *view2 = [[Myview alloc] initWithFrame:(0, 240, 320,240);
[self addSubview: view1];
[self addSibvoew: view2];
...
}
@interface MyView:UIView
...
@implement MyScrollView
...
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
//break points
//here comes event
}
A: Try this code..
UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
[scroll addGestureRecognizer:singleTap];
- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)touch{
CGPoint touchPoint=[gesture locationInView:scrollView];
touchPoint = [touch locationInView:self.view];
}
A: I suggest making ur two subview global and then in the superview touchesbegan method pass the touches and the event to the subviews for handling. So somethig like [view1 touchesBegan:touches event:event];
i have not tested it but that should be one way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to edit/update a nested resource without going through the parent class? Can I update my nested resource without going through the parent class?
I put this in the routes
put 'ratings/:id' => 'ratings#update', :as => 'update_ratings'
and I put an exception for [:edit, :update] in the nested resource route
My controller
def update/edit
@rating = Rating.find(params[:id])
...
end
My edit view:
<%= form_for(@rating, :url => update_ratings_path(@rating)) do |f| %>
What happens is the server log says the put request happens, but no attributes are updated. The page then redirects to the show action, when it should go to parent class index page.
The log:
Started PUT "/ratings/21" for 127.0.0.1 at 2011-09-25 19:31:18 -0700
Processing by RatingsController#show as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"g4TkuG1xK8W96VSKdl3ZwedrqIXmcg9CDt6y8IqaFh0=", "rating"=>{"environ"=>"8"}, "commit"=>"Update Rating", "id"=>"21"}
Rating Load (0.3ms) SELECT ratings.* FROM ratings WHERE ratings.id = 21 LIMIT 1
Rendered ratings/show.html.erb within layouts/application (9.8ms)
User Load (0.4ms) SELECT users.* FROM users WHERE users.id = 1 LIMIT 1
Completed 200 OK in 151ms (Views: 143.4ms | ActiveRecord: 4.8ms)
A: From experience I can say that using a nested resource controller for an unnested action often becomes unmanageable in the long run. So be sure it's not easier to add a second controller. After all, a controller is just an interface to a resource. It's not a problem to have two interfaces to the same resource.
Your log shows "Processing by RatingsController#show", so it never reaches the #update action; instead it comes into #show.
The most probable cause I can think of is that you have a (named) route on a higher line in routes.rb to the ratings#show action, without a :via => 'get'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Reading Samsung firmware and serial from Android phones (java) I'm looking for a way to read the firmware version (e.g. I9100XXKI3) from a Samsung mobile phone running Android from within an App. I know it is possible as I've seen an app already doing this however I could not find anything in the SDK docs..
Also I'm looking for the serial number (S/N as also possible to retrieve via adb -service and printed on the sticker under the battery).
Thanks in advance.
A: Call getDeviceId() for the IMEI number.
As for the build string use : Build.DISPLAY
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: New Static Library has build error "libtool exited with code 1" I created a new static library in my iOS project and now I'm getting the build error
Command /Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/libtool failed with exit code 1
How do I go about debugging this?
A: To see the actual output and not just the error message, try building your target or scheme with xcodebuild from command line.
I had a problem with the same error message. In my case, I couldn't build for the simulator, but it worked find when building for the device. The output from xcodebuild confirmed that Xcode could not set the proper architecture to build for the simulator.
Long story short, it turned out that one build setting was corrupted. The Mach-O Type setting in the Linking category was set to Relocatable Object File for some reason. I switched it back to Static Library and the error disappeared.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: No idea where compiler errors are forming when using JLayeredPane So, in my last question ("Can't figure out how to overlap images in java") I was kindly advised to utilize layout managers and the JLayeredPane. However, after studying the demos, and forming my own code, I have a whopping 34 compiler errors. The compiler errors are consistently "" so there's probably something wrong with importing. However I copied the import list exactly from the LayeredPane Demo. Once again, I am stumped. And also once again, I thank anyone in advance for advice!
import javax.swing.*;
import javax.swing.border.*;
import javax.accessibility.*;
import java.awt.*;
import java.awt.event.*;
public class SlotAnimatorTest extends JPanel
{
JPanel pane = new JPanel ();
pane.setPreferredSize(new Dimension(1500, 1500));
JPanel slotAnim;
private JPanel showSlotAnimators ()
{
slotAnim = new JPanel ();
SlotAnimator a0 = new SlotAnimator (45);
SlotAnimator a1 = new SlotAnimator (90);
SlotAnimator a2 = new SlotAnimator (180);
slotAnim.setLayout (new GridLayout (3,0,20,30));
slotAnim.add (a0);
slotAnim.add (a1);
slotAnim.add (a2);
return slotAnim;
}
ImageIcon background = new ImageIcon ("/Users/haleywight/Documents/slotmachine.png");
JLabel bG = new JLabel (background);
bGsetBounds(1500, 760, background.getIconWidth(), background.getIconHeight());
pane.add (bG, newInteger(0),0);
pane.add (showSlotAnimators (), newInteger (1));
private static void createAndShowGUI()
{
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JComponent newContentPane = new SlotAnimatorTest();
newContentPane.setOpaque(true); //content panes must be opaque
frame.setContentPane(newContentPane);
//Display the window.
frame.pack();
frame.setVisible(true);
}
public static void main (String [] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGUI();
}
});
}
}
A: This has nothing to do with JLayeredPane and much to do with basic Java. You can't call a method in the class and outside of a method or constructor or static/non-static initializer blocks.
A: Following statements must be placed inside the method.
bGsetBounds(1500, 760, background.getIconWidth(), background.getIconHeight());
pane.add (bG, newInteger(0),0);
pane.add (showSlotAnimators (), newInteger (1));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Non virtual version of virtual class Lets say we have the following two class definitions.
#include <iostream>
#include <array>
class A
{
public:
virtual void f() = 0;
};
class B : public A
{
public:
virtual void f() { std::cout << i << std::endl; }
int i;
};
Here sizeof(B) == 8, presumably 4 the virtual pointer and 4 for the int.
Now lets say we make an array of B, like so:
std::array<B, 10> x;
Now we get sizeof(x) == 80.
If my understanding is correct, all method calls on elements of x are resolved statically, as we know the type at compile time. Unless we do something like A* p = &x[i] I don't see a need to even store the virtual pointer.
Is there a way to create an object of type B without a virtual pointer if you know it is not going to be used?
i.e. a template type nonvirtual<T> which does not contain a virtual pointer, and cannot be pointed to by a subtype of T?
A:
Is there a way to create an object of type B without a virtual pointer if you know it is not going to be used?
No. Objects are what they are. A virtual object is virtual, always.
After all, you could do this:
A *a = &x[2];
a->f();
That is perfectly legitimate and legal code. And C++ has to allow it. The type B is virtual, and it has a certain size. You can't make a type be a different type based on where it is used.
A: Answering my own question here, but I've found that the following does the job, by splitting A into it's virtual and non-virtual components:
enum is_virtual
{
VIRTUAL,
STATIC
};
template <is_virtual X>
class A;
template<>
class A<STATIC>
{
};
template<>
class A<VIRTUAL> : public A<STATIC>
{
public:
virtual void f() = 0;
virtual ~A() {}
};
template <is_virtual X>
class B : public A<X>
{
public:
void f() { std::cout << i << std::endl; }
int i;
};
The important thing here is that in B<> don't specify f() as virtual. That way it will be virtual if the class inherits A<VIRTUAL>, but not virtual if it inherits A<STATIC>. Then we can do the following:
int main()
{
std::cout << sizeof(B<STATIC>) << std::endl; // 4
std::cout << sizeof(B<VIRTUAL>) << std::endl; // 8
std::array<B<STATIC>, 10> x1;
std::array<B<VIRTUAL>, 10> x2;
std::cout << sizeof(x1) << std::endl; // 40
std::cout << sizeof(x2) << std::endl; // 80
}
A: That would be a nice one to have, but I can't think of any way to revoke virtual members or avoid storing the virtual pointer.
You could probably do some nasty hacks by keeping a buffer that's the size of B without the virtual pointer, and play with casts and such. But is all undefined behavior, and platform dependant.
A: Unfortunately it won't work in any normal sense as the code inside the method calls expects the virtual pointer to be in the class definition.
I suppose you could copy/paste all of A and B's code into a new class but that gets to be a maintenance headache fast.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550171",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Intercepting Outgoing SMS Is it possible to intercept outgoing SMS before it is actually sent, get its contents then ignore / send it according to some criteria?
eg. block all international text (numbers with leading 00), but allow everything else.
A: Based on what I've been able to find, it seems as though the answer is either, "It's impossible" or, that it could be possible, but you'd need to write your own SMS app, so that you received the text before it became an SMS, and then you could perform whatever checks you'd like on it before calling the API to actually queue it to be sent.
Sorry =(
A: As far as I know, you can spy on outgoing SMS messages but you cannot stop them from being sent out.
Here's how you can detect the outgoing SMS messages:
Listen outgoing SMS or sent box in Android
But since this is done basically by reading from a database, I doubt you can stop the SMS from leaving.
I wish you good luck.
Emmanuel
A: This is what i have done to make an OutgoingSMSReceiver hope it helps some one some dya!
public final class OutgoingSMSReceiver extends Service {
private static final String CONTENT_SMS = "content://sms/";
private CallerHistoryDataSource database = new CallerHistoryDataSource(UCDGlobalContextProvider.getContext());
static String messageId="";
private class MyContentObserver extends ContentObserver {
public MyContentObserver() {
super(null);
}
@Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
Uri uriSMSURI = Uri.parse(CONTENT_SMS);
Cursor cur = UCDGlobalContextProvider.getContext().getContentResolver().query(uriSMSURI, null, null, null, null);
// this will make it point to the first record, which is the last SMS sent
cur.moveToNext();
String message_id = cur.getString(cur.getColumnIndex("_id"));
String type = cur.getString(cur.getColumnIndex("type"));
if(type.equals(Constants.SMS_TYPE_OUTGOING)){
/**
* onChange is fired multiple times for a single SMS, this is to prevent multiple entries in db.
*
*/
if(!message_id.equals(messageId))
{
String content = cur.getString(cur.getColumnIndex("body"));
String msisdnWithCountryCodeOrPrefix = cur.getString(cur.getColumnIndex("address"));
String msisdn = MSISDNPreFixHandler.fixMsisdn(msisdnWithCountryCodeOrPrefix);
Sms sms = new Sms();
sms.setType(Constants.SMS_TYPE_OUTGOING);
sms.setMsisdn(msisdn);
sms.setContent(content);
Log.i("MyContentObserver", "Sent SMS saved: "+content);
}
messageId = message_id;
}
}
@Override
public boolean deliverSelfNotifications() {
return false;
}
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
MyContentObserver contentObserver = new MyContentObserver();
ContentResolver contentResolver = getBaseContext().getContentResolver();
contentResolver.registerContentObserver(Uri.parse(CONTENT_SMS),true, contentObserver);
//Log.v("Caller History: Service Started.", "OutgoingSMSReceiverService");
}
@Override
public void onDestroy() {
//Log.v("Caller History: Service Stopped.", "OutgoingSMSReceiverService");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Log.v("Caller History: Service Started.", "OutgoingSMSReceiverService");
/**
* Constant to return from onStartCommand(Intent, int, int): if this service's process is killed while it is started
* (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent.
* Later the system will try to re-create the service. Because it is in the started state, it will guarantee to call
* onStartCommand(Intent, int, int) after creating the new service instance; if there are not any pending start commands to be
* delivered to the service, it will be called with a null intent object, so you must take care to check for this.
* This mode makes sense for things that will be explicitly started and stopped to run for arbitrary periods of time, such as a
* service performing background music playback.
*/
return START_STICKY;
}
@Override
public void onStart(Intent intent, int startid) {
Log.v("Caller History: Service Started.", "OutgoingSMSReceiverService");
}
}
A: Based on "Saad Akbar" response , i make it work but only with rooted device with permission MODIFY_PHONE_STATE
public class OutgoingSMSReceiver extends Service
{
private static final String CONTENT_SMS = "content://sms/";
static String messageId = "";
private class MyContentObserver extends ContentObserver
{
Context context;
private SharedPreferences prefs;
private String phoneNumberBlocked;
public MyContentObserver(Context context) {
super(null);
this.context = context;
}
@Override
public void onChange(boolean selfChange)
{
super.onChange(selfChange);
prefs = context.getSharedPreferences("com.example.testcall", Context.MODE_PRIVATE);
phoneNumberBlocked = prefs.getString("numero", "");
Uri uriSMSURI = Uri.parse(CONTENT_SMS);
Cursor cur = context.getContentResolver().query(uriSMSURI, null, null, null, null);
if (cur.moveToNext())
{
String message_id = cur.getString(cur.getColumnIndex("_id"));
String type = cur.getString(cur.getColumnIndex("type"));
String numeroTelephone=cur.getString(cur.getColumnIndex("address")).trim();
if (numeroTelephone.equals(phoneNumberBlocked))
{
if (cur.getString(cur.getColumnIndex("type")).equals("6"))
{
ContentValues values = new ContentValues();
values.put("type", "5");
context.getContentResolver().update(uriSMSURI,values,"_id= "+message_id,null);
}
else if(cur.getString(cur.getColumnIndex("type")).equals("5"))
{ context.getContentResolver().delete(uriSMSURI,"_id=?",new String[] { message_id});
}
}
}
}
@Override
public boolean deliverSelfNotifications()
{
return false;
}
}
@Override
public void onCreate()
{
MyContentObserver contentObserver = new MyContentObserver(getApplicationContext());
ContentResolver contentResolver = getBaseContext().getContentResolver();
contentResolver.registerContentObserver(Uri.parse(CONTENT_SMS), true, contentObserver);
}
}
<uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
A: Incoming SMS
You can intercept an incoming sms thru sms listener using Broadcast receiver.You can modify the incoming sms or destroy it so that it does not reaches inbox.
Outgoing SMS
You can listen for outgoing sms by putting content observer over content://sms/out but you can not modify it with the native sms app.You can obviously modify the content of content://sms/out but it has no point.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550178",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
}
|
Q: Loading images from cache but return a blank screen i try the example i gotten from here. The example shows how to display a image that is larger then the screen and the screen acting like a window, allowing user to look at the images via scrolling. However, what i want to achieved is similar just that, instead of one single image, i tried to combining 18 smaller images (171X205) into one single image. I am able to did that but to save loading time on downloading of images from the server, i cached the images. Heres the problem, i cant seems to display the images out on screen even though the images are indeed cached. Thus, i tried something else by fetching image from the drawable folder but still the same issue arise. Does anyone have any idea how to go about solving this problem?
A snippets of code to load images from cache:
for(int i =0; i<18; i++)
File cacheMap = new File(context.getCacheDir(), smallMapImageNames.get(i).toString());
if(cacheMap.exists()){
//retrieved from cached
try {
FileInputStream fis = new FileInputStream(cacheMap);
Bitmap bitmap = BitmapFactory.decodeStream(fis)
puzzle.add(bitmap);
}catch(...){}
}else{
Drawable smallMap = LoadImageFromWebOperations(mapPiecesURL.get(i).toString());
if(i==0){
height1 = smallMap.getIntrinsicHeight();
width1 = smallMap.getIntrinsicWidth();
}
if (smallMap instanceof BitmapDrawable) {
Bitmap bitmap = ((BitmapDrawable)smallMap).getBitmap();
FileOutputStream fos = null;
try {
cacheMap.createNewFile();
fos = new FileOutputStream(cacheMap);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
puzzle.add(bitmap);
}
}
}
The function where it retrieved images from the server
private Drawable LoadImageFromWebOperations(String url) {
// TODO Auto-generated method stub
try
{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
I am drawing onto a canvas and so no ImageView is use to display the images.
A: For all of my lazy image loading I use Prime.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PHP MongoDB find nested element How can I do a select for all documents that have a parent.id that is equal to 3? I try doing this.parents.id == 3, but it doesn't seem to be working...
[parents] => Array (
[0] => Array (
[id] => 1
[title] => Folder 1
)
[1] => Array (
[id] => 3
[title] => Folder 2
)
)
A: OK, so the PHP input is actually unclear. The PHP you provided could be one of the following JSON objects:
Version 1:
{ parents:
[
{ id: 1, title: "Folder 1" },
{ id: 3, title: "Folder 2" }
] }
Version 2:
{ parents:
{ 0: { id: 1, title: "Folder 1" },
1: { id: 3, title: "Folder 2" }
} }
If you do find({'parents.id':3}) on version 1, this will work.
If you do find({'parents.id':3}) on version 2, this will not work.
The difference is not clear in PHP, so use the command-line and double-check.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I flush a 'RandomAccessFile' (java)? I'm using RandomAccessFile in java:
file = new RandomAccessFile(filename, "rw");
...
file.writeBytes(...);
How can I ensure that this data is flushed to the Operating System? There is no file.flush() method. (Note that I don't actually expect it to be physically written, I'm content with it being flushed to the operating system, so that the data will survive a tomcat crash but not necessarily an unexpected server power loss).
I'm using tomcat6 on Linux.
A: Have a look carefully at RandomAccessFile constructor javadoc:
The "rws" and "rwd" modes work much like the force(boolean) method of the FileChannel class, passing arguments of true and false, respectively, except that they always apply to every I/O operation and are therefore often more efficient. If the file resides on a local storage device then when an invocation of a method of this class returns it is guaranteed that all changes made to the file by that invocation will have been written to that device. This is useful for ensuring that critical information is not lost in the event of a system crash. If the file does not reside on a local device then no such guarantee is made.
A: You can use getFD().sync() method.
A: here's what i do in my app:
rf.close();
rf = new RandomAccessFile("mydata", "rw");
this is give 3-4times gain in performance
compared to getFd().sync() and 5-7 times compared to "rws' mode
deoes exactly what the original question proposed: passes
on unsaved data to the OS and out of JVM. Doesn't physically
write to disk, and therefore introduces no annoying delays
A: The only classes that provide a .flush() method are those that actually maintain their own buffers. As java.io.RandomAccessFile does not itself maintain a buffer, it does not need to be flushed.
A: I reached here with the very same curiosity.
And I really can't figure what need to flush on OS and not necessarily need to flush to Disk part means.
In my opinion,
The best thing matches to the concept of a managed flushing is getFD().sync(), as @AVD said,
try(RandomAccessFile raw = new RandomAccessFile(file, "rw")) {
raw.write...
raw.write...
raw.getFD().sync();
raw.wirte...
}
which looks like, by its documentation, it works very much like what FileChannel#force(boolean) does with true.
Now "rws" and "rwd" are look like they work as if specifying StandardOpenOption#SYNC and StandardOpenOption#DSYNC respectively while a FileChannel is open.
try(RandomAccessFile raw = new RandomAccessFile(file, "rws")) {
raw.write...
raw.write...
raw.wirte...
// don't worry be happy, woo~ hoo~ hoo~
}
A: I learned that you can't..
Some related links here: http://www.cs.usfca.edu/~parrt/course/601/lectures/io.html
and here: http://tutorials.jenkov.com/java-io/bufferedwriter.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Need help constructing a deterministic finite automata? What are the rules for constructing a deterministic finite automata in the form of a diagram? My professor explained by examples, but I am not exactly sure what rules must be followed by all diagrams. Any help is appreciated, thanks!
A: Off the top of my head, in a DFA, these are the main rules, (terms specific to DFAs are in double quotes):-
*
*each "state" must have a "transition" for each "input" defined in the DFA
so this means, that a transition must be defined for every input being considered in a dfa, for a state, so that one knows where to go from that state for each input.
*each "state" can have only ONE "transition" for each "input"
well this rule is pretty self explanatory, so if you have already defined a transition for an input for a particular state, don't create another transition for the same input from the same state.
Yeah these are the ones i remember. Hope it helps. Further these points can be used to differentiate a dfa from a nfa. Other simple rules for drawing would be :-
*
*make a start state, indicated with arrow pointing towards the state
*have at least one final state, indicated with concentric circles to draw the state boundary
*draw the transitions as arrows
*mark all the transitions with their respective input symbols
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I make cron jobs to POST to a url through PHP scripts? I am not sure how I can assign cron jobs through PHP script AND have that cron job POST to a PHP script. Any ideas? Also, what would I need to tell my webhost people? usually If i want to allow one or more PHP script to have write access to a csv or textfile I ask them to allow that csv or textfile to have apache writes. For this cron PHP script what would I need to ask them?
A: I imagine you'd want to use cURL - it should be installed as an extension for your php.
http://www.php.net/manual/en/function.curl-setopt.php has all the options for making a web request - browse through them at your leisure.
http://www.ipragmatech.com/post-form-data-java-php-curl.html has a quick example for doing so.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How can I capture audio from a mic to send it over a socket? I am using Windows 7 and developing a chat-like application with Visual Studio 2010. I am looking for an EASY way of capturing audio from a microphone (or rather, from the default recording device), collect the buffer from said input, and send it over a socket. I've seen DirectX solutions recommended, but from my research that is quite the opposite of simple. 5000 lines of sample code for a simple capture/save file program? That simply doesn't work for me (and yes, that was an official sample provided with the SDK).
Anyway, I don't need it to be cross-platform, and I would really prefer something that already comes with Windows, though I don't mind installing a library as long as it doesn't take longer than writing the hardware drivers from scratch to figure it out (exaggeration). I've heard of this waveInOpen function, but oddly enough I cannot find any demos on how to use it. If anyone has an idea or a link to some sample code, I would greatly appreciate it. Thanks everyone for your time!
P.S. I can figure out the networking part myself. I just need access to the raw audio data buffer.
A: If you're doing the sockets yourself try checking out:
http://www.techmind.org/wave/
http://www.bcbjournal.com/articles/vol2/9810/Low-level_wave_audio__part_3.htm
http://www.relisoft.com/freeware/recorder.html
I enjoyed all of them but the last one, but then again, you might find it far more helpful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: OCaml: Using a comparison operator passed into a function I'm an OCaml noob. I'm trying to figure out how to handle a comparison operator that's passed into a function.
My function just tries to pass in a comparison operator (=, <, >, etc.) and an int.
let myFunction comparison x =
if (x (comparison) 10) then
10
else
x;;
I was hoping that this code would evaluate to (if a "=" were passed in):
if (x = 10) then
10
else
x;;
However, this is not working. In particular, it thinks that x is a bool, as evidenced by this error message:
This expression has type 'a -> int -> bool
but an expression was expected of type int
How can I do what I'm trying to do?
On a side question, how could I have figured this out on my own so I don't have to rely on outside help from a forum? What good resources are available?
A: OCaml allows you to treat infix operators as identifiers by enclosing them in parentheses. This works not only for existing operators but for new ones that you want to define. They can appear as function names or even as parameters. They have to consist of symbol characters, and are given the precedence associated with their first character. So if you really wanted to, you could use infix notation for the comparison parameter of myFunction:
Objective Caml version 3.12.0
# let myFunction (@) x =
x @ 10;;
val myFunction : ('a -> int -> 'b) -> 'a -> 'b = <fun>
# myFunction (<) 5;;
- : bool = true
# myFunction (<) 11;;
- : bool = false
# myFunction (=) 10;;
- : bool = true
# myFunction (+) 14;;
- : int = 24
#
(It's not clear this makes myFunction any easier to read. I think definition of new infix operators should be done sparingly.)
To answer your side question, lots of OCaml resources are listed on this other StackOverflow page:
https://stackoverflow.com/questions/2073436/ocaml-resources
A: Several possibilities:
Use a new definition to redefine your comparison operator:
let myFunction comparison x =
let (@) x y = comparison x y in
if (x @ 10) then
10
else
x;;
You could also pass the @ directly without the extra definition.
As another solution you can use some helper functions to define what you need:
let (/*) x f = f x
let (*/) f x = f x
let myFunction comparison x =
if x /* comparison */ 10 then
10
else
x
A: Comparison operators like < and = are secretly two-parameter (binary) functions. To pass them as a parameter, you use the (<) notation. To use that parameter inside your function, you just treat it as function name:
let myFunction comp x =
if comp x 10 then
10
else
x;;
printf "%d" (myFunction (<) 5);; (* prints 10 *)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Unable to take screenshot on android using robotium and private method i have been trying to get a screenshot lately but every thing in vain the folders are created in android emulator with api level 8. i have mentioned the code below.
In the this code Method takeScreenShot() is supposed to create a directory and store the image while executing as android junit testcase i get result as 100% but not the folders are not Created and screen shot is not stored. should i root my phone to use its sd card ?
public class NewRobotiumTest extends ActivityInstrumentationTestCase2 {
......
......
// actual testcase
public void testRecorded() throws Exception {
solo.waitForActivity("com.botskool.DialogBox.DialogBox",
ACTIVITY_WAIT_MILLIS);
solo.clickOnButton("Show Alert");
solo.clickOnButton("Ok");
solo.clickOnButton("Show Yes/No");
takeScreenShot(solo.getViews().get(0), "testRecorded_1316975601089");
solo.sleep(2000);
solo.clickOnButton("Yes");
solo.clickOnButton("Show List");
solo.clickOnScreen(118f, 563f);
}
/**
* I have added this to the android-manifest.xml file
*
* <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
*
*/
public void takeScreenShot(final View view, final String name)
throws Exception {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
view.setDrawingCacheEnabled(true);
view.buildDrawingCache();
Bitmap b = view.getDrawingCache();
FileOutputStream fos = null;
try {
final String path = Environment.getExternalStorageDirectory()+ "/test-screenshots/";
File dir = new File("/mnt/sdcard/test-screenshots");
if(!dir.mkdirs()){
System.out.println("Creaet sd card failed");
}
if (!dir.exists()) {
System.out.println(path);
dir.mkdirs();
}
fos = new FileOutputStream(path + name + ".jpg");
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (IOException e) {
}
}
});
}
}
A: You need add permission to write to the SD Card in the main application. Not the JUnit test project!
Add this to the project manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Subtract (-) 2 Text Labels from each other to get result Well, I've tried it with ToInt, ToString, and I'm out of options.
I'm trying to substract 2 Label Texts from each other. (Those contains numbers from RSS)
What I have at the moment:
lblOldID.Text = nodeChannel["oldid"].InnerText;
lblNewID.Text = nodeChannel["newid"].InnerText;
So let's say oldid contains "500" and newid "530".
But for some reason, I can't substract (-) them.
What I want:
lblResultID.Text = lblOldID.Text - lblNewID.Text;
Example: Result = 530 - 500
So how is that possible?
A: If you want the label text to be, literally, 530 - 500, concatenate the strings like so:
lblResultID.Text = lblOldID.Text + " - " + lblNewID.Text;
If you want the label text to be the result of subtracting the numbers represented in the labels, convert them to integers first:
int old = Int32.Parse(lblOldID.Text);
int new = Int32.Parse(lblNewID.Text);
lblResultID.Text = (old - new).ToString();
(You'll need some error checking in there if there's the possibility that either value might not convert cleanly to an integer)
A: You need to convert the text to ints.
//These are the ints we are going to perform the calculation on
Int32 oldID = 0;
Int32 newID = 0;
//TryParse returns a bool if the string was converted to an int successfully
bool first = Int32.TryParse(lblOldID.Text, out oldID);
bool second = Int32.TryParse(lblNewID.Text, out newID);
//Check both were converted successfully and perform the calculation
if(first == true && second == true)
{
lblResultID.Text = (oldID - newID).ToString();
}
else
{
lblResultID.Text = "Could not convert to integers";
}
TryParse prevents an exception being thrown if the data in the labels cannot be converted to integers. Instead, it returns false (or true if the numbers were parsed successfully).
A: Perhaps because you really should parse them:
lblResultID.Text = (int.Parse(lblOldID.Text) - int.Parse(lblNewID.Text)).ToString();
Or in string format:
lblResultID.Text = lblOldID.Text + " - "+ lblNewID.Text;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Storing a Yes / No radio button into a MySQL database I've seen a Yes/No form radio buttons value be stored/saved in a couple different ways. I wonder which way is better and why? This is for a PHP/MySQL application with a typical Yes/No question as part of a form.
1.) Store it as 1, 0 or null. 1 being Yes, 0 being No and null being not answered.
2.) Store it as Yes, No, null. Assume a language conversion can be made.
3.) Use 1, 2 and null so as to better distinct the values.
Thanks, Jeff
Edit: I also must mention that most of the issues have been arising due to jQuery/JavaScript and the comparisons and $() bindings.
A: Use TINYINT(1). Allow NULL if you wish for the "not answered" option. You can also use BOOLEAN as it's just an alias for the aforementioned datatype. This way of storing boolean data is recommended by MySQL.
More details: Which MySQL data type to use for storing boolean values
A: Since MySQL has a BOOLEAN type, but it's simply an alias of TINYINT. I recommend against it because the equal sign in PHP == would not distinguish 0 from the lack of value. You'd always need to use triple equal === and it would be easy to make mistakes.
As for your options:
*
*This seems the natural choice with PHP, but then you've to be careful to distinguish 0 from the lack of value, so I wouldn't recommend it.
*I would not recommend this one.
*Possible, but the assignment to 1 and 2 is somewhat arbitrary and might be difficult to remember and read in code.
What I usually do, is use "Y", "N" and NULL if needed, in a CHAR(1) field, it reads well in code and doesn't create problems.
A: I would go with the 0/1/null for No/Yes/Blank. 0 is always used as false and 1 for true.
A: I don't know if it helps, but in my system I use 1 as yes, 0 as no and just NO value as null - or if I have to specify I set a default value in the structure.
I think this system is more flexible, you can always manipulate with this data, for example if you don't want to display 0/1 values you can set something like
if(table.field == 1)
echo yes;
else
echo no;
Also comparing this value to any other database value is easier.
A: as numbers are processed faster (while searching, sorting,..) by mysql,
it takes less space in ur case,
and also there are only 3 values (1, 0 nul
l)
and in binary format ,1 and 0 have just one significant bit (0000000, & 0000001), the speed, in case of any comparisons, while traversing these columns, should remain higher and queries will take less time.
so i think u can go for first option.
A: I think that's what ENUM type is for. You can set your storage field type like this:
ENUM('no','yes')
and allow NULL as default value. If the answer is 'no' - the field value will actually be 0 (the index of 'no') and 1 if the answer is 'yes'. And you will have a nice representation of the column - 'yes' and 'no' instead of 1 and 0. Though the values will be actially stored as 0 and 1. I think its an advantage of using TINYINT.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550214",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: fitting and plotting a parabola, matlab I have a very simple problem.
I have
x=[ 10 25 50];
y=[ 1.2 3 7.5];
I know my curve fitting function
f(x)=(a*x+1)/(bx+c);
How can I get coefficient(a,b,c) solve in matlab and also plot this curve?
A: Rearrange y = f(x) to make a, b, and c the unknowns:
y = (ax + 1) / (bx + c)
y(bx + c) = ax + 1
ax - bxy - cy = -1;
This describes a system of simultaneous linear equations in a, b, and c when you substitute your three paired values of x and y.
x = [10, 20, 100];
y = [1.2, 0.7, 0.4];
coeffs = [x', (-x.*y)', -y'];
knowns = [-1, -1, -1]';
v = coeffs \ knowns; % v is [a; b; c]
Now you have the coefficients a, b, and c so you can plot the function.
Addendum: plotting
To plot a function, first choose the x-values of the data points
xt = 1:100;
Then calculate the y-values (assuming you've already got a, b, c)
yt = (a*x + 1) ./ (b*x + c)
Then just plot them!
plot(xt, yt);
Read the Matlab help on the plot function for customizing the style of the plot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CSS selector just for elements in submenu I have this menu with a slide down submenu:
<ul class="sf-menu">
<li class="menu-item current-menu-item">
<a> whatever </a>
<ul class="sub-menu">
<li class="menu-item current-menu-item">
<a> whatever </a>
<li class="menu-item current-menu-item">
<a> whatever </a>
</ul>
</li>
</ul>
Right now this is my CSS:
.sf-menu .current-menu-item a {
background: blue url('images/diagonal.png') repeat;
}
This is changing all my menu items with class .current-menu-item, but I don't want to modify the ones inside the submenu.
How do I change the selector so it doesn't select LIs inside submenu? Or how do I make a selector to overwrite all LIs inside submenu with background:black?
I cannot modify the html, is it possible to do this?
A: Use the child selector parent > child.
.sf-menu > .current-menu-item > a {
background: blue url('images/diagonal.png') repeat;
}
A: One way to do this is to overwrite the rule for the submenu items.
So
.sf-menu .current-menu-item .sub-menu li a {
background: none;
}
A: its actually quite simple:
.sf-menu .sub-menu .current-menu-item a {
background: black;
}
Or alternatively if you want to be more specific:
.sf-menu .current-menu-item .sub-menu .current-menu-item a {
background: black;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How should I complete this type of notification? I am basically creating a site for recruiters. One of the functionality in my application requires posting to Facebook periodically. The posting frequency can be from 0(Never) to 4(High)
For Eg. If a recruiter has 4 open jobs and he has posting frequency set to 4, each job should be posted as per it's turn: 1st job on 1st day, 2nd job on 2nd, 3rd job on 3rd etc, on 5th day again 1st job (round robin fashion).
Had he set the posting frequency to 2, two jobs would be posted daily (thus each job would be posted every 2 days)
My only question is what type of threading should I create for this since this is all dynamic!! Also, any guidelines on what type of information should I store in database?
I need just a general strategy to solve this problem. No code..
A: *
*I think you need to seperate it from your website, I mean its better to run the logic for posting jobs in a service hosted on IIS ( I am not sure such a thing exists or not, but I guess there is).
*Also you need to have table for job queue to remember which jobs need to be posted, then your service would pick them up and post them one by one.
*To decide if this is the time for posting a job you can define a timer with a configurable interval to check if there is any job to post or not.
*Make sure that you keep the verbose log details if posting fails. It is important because it is possible that Facebook changes its API or your API key becomes invalid or anything else then you need to know what happened.
*Also I strongly suggest to have a webpage for reporting the status of jobs-to-post queue, if they failed what was the causes of problem.
A: If you program runs non-stop, you can just use one of the Timer classes available in .NET framework, without the need to go for full-blown concurrency (e.g. via Task Parallel Library).
I suspect, though, that you'll need more than that - some kind of mechanism to detect which jobs were successfully posted and which were "missed" due program not running (or network problems etc.), so they can be posted the next time the program is started (or network becomes available). A small local database (such as SQLite or MS SQL Server Compact) should serve this purpose nicely.
A: If the requirements are as simple as you described, then I wouldn't use threading at all. It wouldn't even need to be a long-running app. I'd create a simple app that would just try to post a job and then exit immediately. However, I would scheduled it to run once every given period (via Windows Task Scheduler).
This app would check first if it hasn't posted any job yet for the given posting frequency. Maybe put a "Last-Successful-Post-Time" setting in your datastore. If it's allowed to post, the app would just query the highest priority job and then post it to Facebook. Once it successfully posts to Facebook, that job would then be downgraded to the lowest priority.
The job priority could just be a simple integer column in your data store. Lower values mean higher priorities.
Edit:
I guess what I'm suggesting is if you have clear boundaries in your requirements, I would suggest breaking your project into multiple applications. This way there is a separation of concerns. You wouldn't then need to worry how to spawn your Facebook notification process inside your web site code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: iPhone Filling UITableView with JSON results (using search entered in UISearchBar) Does anyone have a link to a tutorial for using a UISearchBar as the entry for a search, and a UITableView to display results returned in JSON?
Thank you!
Please no suggestions to RTFM - I can't find anything about using a UISearchBar for a remote search.
A: Implement the UISearchBarDelegate methods in your class. Then you can hit the web service in this delegate method
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
//Hit the webservice from here using searchBar.text
}
or if u need a dynamic search you can use the following method.
- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText {
}
After getting the data from the server update the datasource of your tableView and call the
(You can use SBJSON parser to parse your JSON response)
[self.tableView reloadData];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Proper use of Response.ContentType I have a site that allows users to upload a document such as pdf, word, excel etc.
Now in my code, when I want to show the document in a browser, I am checking for the extension and setting the ContentType appropriately.
However, this switch statement just doesn't sound like the best solution.
Is there a way I can set the content type based on the Stream?
A: If you don't want to use switch like statements, use Dictionary to add possible MIME-entries.
Dictionary<string, string> map=new Dictionary<string, string>
{
{"txt", "text/plain"},
{"exe", "application/octet-stream"},
{"bmp", "image/bmp"}
};
and set content type,
Response.ContentType=map[ext];
I've found an interesting stackoverflow thread - Using .NET, how can you find the mime type of a file based on the file signature not the extension
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Collision Detection Between Rectangles - Resulting Angles Basically I have a bunch of rectangles floating around at 8 different angles (45 degrees, 90 degrees etc). I have collision detection going on between all of them, but one thing still doesn't work as it should. I don't know if I'm just not thinking or what, but I can't seem to get the resulting angles right. I've also tried searching multiple places, but haven't really gained anything from what I've found.
NOTE: the angle system here starts at 0 at the top and increases clockwise.
NOTE: all rectangles have the same mass
Say one rectangle going straight right (90 degrees) hits another going straight left (270 degrees). They will hit off of each other just fine.
Now say one going left gets hit by one going up. Here I can't simply reverse the angles or anything.
If you have more than one way, consider the following: unless I rearrange the CD so it spreads into the other code, I have the positions of all of the rectangles. The CD checks by seeing if two are overlapping, not by comparing where they are going.
As I've been working on pretty much everything except for the collision detection until now, I only have tonight left to get it working and add a few other small things before I'm done.
If you know of a way to make the angles come out right without hardcoding, great. At this point I'm ready to hardcode it (not too much really) if all I have is which rectangle hits the other (ex 2), or if they both do (ex 1). Either one is really helpful.
A: I think you mean something like this...
Each Rectangle has this functionality, testing against, say an array of other objects.
Obstacle* obstacle = new Obstacle;
Obstacle** obstacles = obstacle*[];
For(int i = 0; i <3; i++)
{
obstacles[0] = New Obstacle(x,y, etc...);
etc...
}
Or something similar... this is a little rusty
void collision(obstacles)
{
for(int i = 0; i < obstacles.sizeOf();i++)
{
//bottom y
if((this.ypos + this.height) > (obstacles[i].ypos - obstacles[i].height))
obstacles[i].doYCollision(this);
//top y
if((this.ypos - this.height) < (obstacles[i].ypos + obstacles[i].height))
obstacles[i].doYCollision(this);
//right x
if((this.xpos + this.width) > (obstacles[i].xpos - obstacles[i].width))
obstacles[i].doXCollision(this);
//left x
if((this.xpos - this.width) < (obstacles[i].xpos + obstacles[i].width))
obstacles[i].doXCollision(this);
}
}
again im a little rusty but if you follow it you should be able to relaise what im doing.
then all you need is the resulting function calls.
void doYCollision(Obstacle obstacle)
{
// Whatever y direction they are going do the opposite
obstacle.yDir = obstacle.yDir * -1;
}
void doXCollision(Obstacle obstacle)
{
// Whatever x direction they are going do the opposite
obstacle.xDir = obstacle.xDir * -1;
}
where yDir, xDir is the x and y velocity of the current object.
i should point out again this is very rusty and without having some code from you this is the best ive got. but either way this should start you off into collision detection, the code above shoudl allow for all collisions with all obstacles/objects/pink flamingos/ whatever youve got. Im hoping also that itll do what you want when it comes to multiple collisions at the same time.
You shouldnt need to worry too much about the exact angle (unless you need it for something else), as velocity is a vector mass so has both speed and direction and you can get direction by treating x and y as two different elements. You can do this using the dot product method aswell => http://www.topcoder.com/tc?d1=tutorials&d2=geometry1&module=Static, but if they are just rectangles this should be fine.
Hopes this helps
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Converting Java URL to valid File path in Linux Ok I'm developing in Linux using Eclipse a program that needs to read a text file. The idea is to have the JAR and text file on the same folder. So I'm getting the text file path like this:
Client.class.getClassLoader().getResource("Client.class");
This correctly returns the path and I append the file name and get the below path:
/home/marquinio/workspace/my_project/info.txt
Problem is when I export my project into an executable JAR file. The JAR can't read the file. I double checked and everything looks fine. The only problem I see is that now the path has some "file:" appended at the beginning like this:
file:/home/marquinio/workspace/my_project/info.txt
which is probably why I'm getting a "FileNotFoundException". The JAR and text file are both in the same folder.
Anyone knows how to fix this? Why would Java behave different between Eclipse and executing JAR in command prompt?
Is there a replacement to the "...getResource(...)" provided by Java without that "file:"?
NOTE: this JAR should also be compatible in Windows environment. Still need to test it.
Thanks in advance.
A: The resource you are referring to is not guaranteed to be a file on the file system. Why not use ClassLoader#getResourceAsStream()? Without looking into the details, my best guess is that the different behavior you are seeing is because a different classloader is being used in each case above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Facebook share URL code not working I realize Share has been deprecated by Facebook, but this is still posted on their documentation:
https://www.facebook.com/sharer.php?u=[url to share]&t=[title of content]
However, the title won't change no matter what I do -- including adding the "og:title" meta and changing the actual title of the page.
Any suggestions on how I can make it possible for people to share my page with a suggested message? thanks.
A: I would encourage you to use the Facebook Javascript SDK, this will give you much more flexibility with what you share.
https://developers.facebook.com/docs/reference/dialogs/feed/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to unit test administrator-only functionality? The design of my application is that standard user operations run first (and produce interested information even if the user cannot proceed) and then optionally offers to make some system changes accordingly, which requires elevation. If the user chooses to proceed, the program reruns itself requiring elevation with a command line switch that tells it where in the workflow to resume. The new process then picks back up where the old one left off and makes the changes the user requested.
My problem is I don't know how to write unit tests against the library methods that necessarily make privileged calls without running all of Visual Studio as administrator. I'd really like to avoid doing that so I'm fine with the system prompting me for credentials to run some or all of my unit tests. But currently as a standard user, the calls simply fail with the "System.Management.ManagementException: Access denied" exception.
Any ideas or experiences with handling this beyond elevating the whole of Visual Studio for the session? Since I'm using the built-in unit tests, ideally the solution would still display per-test results in the test results window but that's not a requirement.
A: I'm not sure what you are doing that requires administrator privileges, but I would suggest that in a unit test you shouldn't actually be calling those methods, but mocking out the classes that those methods are called on.
In this way you can make sure that the right calls are being made with the right parameters, but you aren't changing the state of the system.
A: You could impersonate an Admin account using LogonUser().
Take a look at this blog that’s trying to solve your problem.
I liked this codeproject implementation for calling LogonUser better. There's actually many codeproject examples of LogonUser() if you search around a little.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: VB.NET Webbrowser to textbox I need help getting all of the text from WebBrowser1 to my textbox1.text
I tried
WebBrowser1.Navigate(TextBox3.Text)
TextBox1.Text = WebBrowser1.DocumentText
textbox3 being my website
and textbox1 being were i want all the text.
A: You have to handle the DocumentCompleted event of WebBrowser control.
Private Sub WebBrowser1_DocumentCompleted(sender As System.Object,
e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs)
Handles WebBrowser1.DocumentCompleted
TextBox1.Text = WebBrowser1.DocumentText
End Sub
A: My solution:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' WebBrowser1
' TextBox1
' TextBox2
'
WebBrowser1.ScriptErrorsSuppressed = True ' we would like to suppress scripts error message
WebBrowser1.Navigate("http://codeguru.com")
End Sub
Private Sub WebBrowser1_DocumentCompleted(ByVal sender As System.Object, ByVal e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WebBrowser1.DocumentCompleted
' 1) Get entire html code and save as .html file
TextBox1.Text = WebBrowser1.DocumentText
' HOWTO retry while error UNTIL ok
' this needs to be done because Body.InnerText returns error when called too soon
' 2) Get Body text and save as .txt file
Dim retry As Boolean = True
Dim body As String = ""
While retry
Try
body = WebBrowser1.Document.Body.InnerText
retry = False
Catch ex As System.IO.IOException
retry = True
Finally
TextBox2.Text = body
End Try
End While
End Sub
End Class
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jqgrid inline edit beforeSubmit afterSubmit I was wanting to get beforeSubmit working .
colModel: [...],
onSelectRow : function(id)
{
alert("Hi");
},
beforeSubmit:function(postdata, formid) {
alert("In beforeSubmit");
},
I have onSelectRow firing but beforeSubmit won't fire. This is for a grid in inline edit mode.
Have I got it in the right place? I'm beginning to wonder if this method is only for form edits?
A: beforeSubmit exists only in case of the usage of form editing. You don't described which kind of work you want to do before sending the data to the server, but I suppose you can use serializeRowData event in your case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Yahoo BOSS API - V1 -> V2 I was using Yahoo BOSS API v1 and an URL I used got me backlinks for any site. Since the new update/upgrade to V2 the old URL is not working. Can anyone who has worked with V2 please help me out?
I found theold documentation very simple and organized really well but am lost with the new documentation.
Here is the old URL (which is not working anymore):
http://boss.yahooapis.com/ysearch/se_inlink/v1/http://www.domain.com/index.php?appid=<appid>-&format=xml&omit_inlinks=domain
How would I have to modify this for the new version.
A: I found the answer and its not good. The se_inlinks APIs are being discontinued with version Here is the announcement from Yahoo.
In light of the announcements made this Friday June 8th by Yahoo! Search here (http://www.ysearchblog.com/2011/07/08/site-exploror-7-8-11/) , Inlink data will be shutdown on July 20th 2011 with the rest of BOSS v1 API. Customers can continue to query the YDN Site Explorer API (http://developer.yahoo.com/search/siteexplorer/) for such data until September 15th 2011.
I think it is eventually going away.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does setting up a CNAME in the DNS record allow for POST'ing to that server's pages? I'm building a Shopify website and I'm trying to create a simple "Contact Us" page that allows the user to POST their comments (e.g. name, email, comments). The Shopify website is hosted (as all Shopify accounts are) but I can set up a CNAME from my domain to point the Shopify hosted pages (that way I have a vanity URL).
I'm wondering, will this enable me to POST directly from the Shopify hosted pages to a script on my server?
Example:
The Shopify pages are at: http://myawesomestore.shopify.com
On my contact-us page: http://myawesomestore.shopify.com/pages/contact-us/
I want to POST to a script on my domain (where I can store in a database): www.my-domain.com/contact-us.php
If I cannot do this, what is the best solution for posting from a hosted solution to an owned solution (i.e. I cannot set up a proxy on their domain to POST to mine).
I hope this makes sense, I'm still very much a novice and there are just too many fundamentals here to comprehend before I could logically build this solution myself.
Thank you all so much in advance!
Cheers,
Rob
A: POSTing a Form to any URL on the internet is never a problem. It doesn't matter if it's on the same domain or a different domain.
You can set up a contact form on your Shopify store and have it send a POST request to any URL where your custom application is listening to.
So the short answer is: This is absolutely no issue, just go ahead and add the form to your shop!
Some confusion on the topic might be caused by "Cross Domain AJAX". If you're doing your POST requests via Javascript then yes, it is only possible to do so if the target URL is on the same domain as the source that is sending the request. See also http://snook.ca/archives/javascript/cross_domain_aj
Hope this clears this up!
A: No, you can't just use a CNAME in most cases. The CNAME will forward to the target server and if it's using virtual hosting, it uses the domain name to figure out how to handle the request. If they have it set up so the server only uses one domain name, it may be set up without a virtual host, which will allow this to work, but you don't really want your script to be dependent upon their server setup.
If you need to have it look like your url, I'd just put it inside a frame.
A: A form can POST to any destination on the internet that the user's browser has access to.
A: you don't need a cname, if you can set up a html form you can post it to any url on the net
...
post is a standard http header, you cant really have a webserver and it not accept post. its up to the site posted to, to check the source of the post and decide what to do with the data
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550262",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why isn't DownThemAll able to recognize my reddit URL regular expression? So I'm trying to download all my old reddit posts using a combination of AutoPagerize and DownThemAll.
Here are two sample URLs I want to distinguish between:
*
*http://www.reddit.com/r/China/comments/kqjr1/what_is_the_name_of_this_weird_chinese_medicine/c2med97
*http://www.reddit.com/r/China/comments/kqjr1/what_is_the_name_of_this_weird_chinese_medicine/c2meana?context=3
The regexp I'm trying to use is this: (\b)http://www.reddit.com/([^?\s]*)?
I want all my reddit posts downloaded, but I don't want any redundancy, so I want to match all of my reddit posts except for anything with a question mark (after which there's a "context=3" character).
I've used RegEx Buddy to show that the regexp fits the first URL but not the second one. However, DownThemAll does not recognize this. Is DownThemAll's ability to parse regexp limited, or am I doing something wrong?
For now, I've just decided to download them all, but to use a renaming mask of *subdirs*.*text*.*html* so that I can later mass remove anything containing the word "context" in its filename.
A: Reddit does have an API, you might want to take a look at that instead, might be easier.
https://github.com/reddit/reddit/wiki/API
EDIT: Looks like http://www.reddit.com/user/USERNAME/.json might be what you want
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is time(NULL) in C? I learning about some basic C functions and have encountered time(NULL) in some manuals.
What exactly does this mean?
A: You can pass in a pointer to a time_t object that time will fill up with the current time (and the return value is the same one that you pointed to). If you pass in NULL, it just ignores it and merely returns a new time_t object that represents the current time.
A: The call to time(NULL) returns the current calendar time (seconds since Jan 1, 1970). See this reference for details. Ordinarily, if you pass in a pointer to a time_t variable, that pointer variable will point to the current time.
A: time() is a very, very old function. It goes back to a day when the C language didn't even have type long. Once upon a time, the only way to get something like a 32-bit type was to use an array of two ints — and that was when ints were 16 bits.
So you called
int now[2];
time(now);
and it filled the 32-bit time into now[0] and now[1], 16 bits at a time. (This explains why the other time-related functions, such as localtime and ctime, tend to accept their time arguments via pointers, too.)
Later on, dmr finished adding long to the compiler, so you could start saying
long now;
time(&now);
Later still, someone realized it'd be useful if time() went ahead and returned the value, rather than just filling it in via a pointer. But — backwards compatibility is a wonderful thing — for the benefit of all the code that was still doing time(&now), the time() function had to keep supporting the pointer argument. Which is why — and this is why backwards compatibility is not always such a wonderful thing, after all — if you're using the return value, you still have to pass NULL as a pointer:
long now = time(NULL);
(Later still, of course, we started using time_t instead of plain long for times, so that, for example, it can be changed to a 64-bit type, dodging the y2.038k problem.)
[P.S. I'm not actually sure the change from int [2] to long, and the change to add the return value, happened at different times; they might have happened at the same time. But note that when the time was represented as an array, it had to be filled in via a pointer, it couldn't be returned as a value, because of course C functions can't return arrays.]
A: The time function returns the current time (as a time_t value) in seconds since some point (on Unix systems, since midnight UTC January 1, 1970), and it takes one argument, a time_t pointer in which the time is stored. Passing NULL as the argument causes time to return the time as a normal return value but not store it anywhere else.
A: Time : It returns the time elapsed in seconds since the epoch 1 Jan 1970
A: You have to refer to the documentation for ctime. time is a function that takes one parameter of type time_t * (a pointer to a time_t object) and assigns to it the current time. Instead of passing this pointer, you can also pass NULL and then use the returned time_t value instead.
A: int main (void)
{
//print time in seconds from 1 Jan 1970 using c
float n = time(NULL);
printf("%.2f\n" , n);
}
this prints 1481986944.00 (at this moment).
A: You can pass in a pointer to a time_t object that time will fill up with the current time (and the return value is the same one that you pointed to). If you pass in NULL, it just ignores it and merely returns a new time_t object that represents the current time.
Nb:time(&timer); is equivalent to timer = time(NULL);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "68"
}
|
Q: can't add a .accde MS access file(located outside the project folder) as AccessDataSource I'm pretty sure that the .accde file does exist. I noticed that VS asks for .mdb file, but a .accde is also a MS Access generated database file.
Here is the screenshot(hope it helps):
A: From the MSDN AccessDataSource page.
The AccessDataSource class does not support connecting to Access
databases that are protected by a user name or password, because you
cannot set the ConnectionString property. If your Access database is
protected by a user name or password, use the SqlDataSource control to
connect to it so that you can specify a complete connection string.
So the .accde is protected in terms of security. Try use SqlDataSource.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Erlang exception Error - no function clause matching lists:map - what am I missing? I am working on Euler 8. After a bit of reading i decided that use of the map function would solve a problem for me. Throwing a simple test program together to make sure I understood the concepts came up short.
From within the shell.
1> List = {3, 1, 4}.
{3,1,4}
2> io:format("oh my ~w ~n", [List]).
oh my {3,1,4}
ok
3> lists:map(fun (Z) -> Z * Z end , List).
** exception error: no function clause matching
lists:map(#Fun<erl_eval.6.80247286>,{3,1,4})
I see the fun, and the list in the message.
What concept am I missing here?
A: You are trying to apply lists:map function on tuple. Initiate List = [3,1,4] not as List = {3,1,4} and apply the same function, you will get desired output.
A: your List is actually a tuple. {} is for tuples, [] is for lists.
your example should be:
1> List = [3,1,4].
[3,1,4]
2> lists:map(fun(Z) -> Z*Z end, List).
[9,1,16]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: facebook api error code: 191 Asp.Net MVC 3 using Dev Environment localhost and ACS I have been trying for the last couple of days to get the ACS integration for my identity providers. The main ones work, Google, Yahoo!, and Live, but I cannot get Facebook to work with my localhost dev environment. Also Facebook has changed their Apps Configuration Pages and I am confused.
Does anyone know the updated Step by Step for configuring ACS and Facebook to work together? My url is: http://localhost/webapp1/
I have been looking through all the posts but since things have changed, the old answers do not seem to work. I know it must be either on one of the setup pages in Azure ACS or in Facebook Apps Setup or a problem with my web.config. I would greatly appreciate all help.
A: I had a similar problem when I setup ACS for Facebook and ran it from my local machine. I had erroneously setup my application on Facebook, while my Azure ACS configuration was actually correct. I was using 'localhost/myapp' on the Site URL setup field on the Facebook site but I needed to change it to use the full ACS namespace for my application: (Your specific namespace will vary, please check your ACS settings for details)
I noticed you mentioned that your URL was: "http://localhost/webapp1/", I am not sure if this was your specific problem but hopefully this saves someone else a bit of time.
A: This should work (see Facebook API error 191 for an older example)
Check your domain is configured correctly in the app settings, the URL used much match what you've told Facebook you'll be using.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: HTTPHandler write Binary Data to Response , load image iv'e got a repeater bonded to a list of entities
BL_Engine engine = (BL_Engine)Application["engine"];
List<AppProduct> products = engine.Get_Products();
Repeater1.DataSource = products;
Repeater1.DataBind();
iv'e also got a user control i use to represent these product entities , i do this by overriding the Databind() in the user control :
public override void DataBind()
{
AppProduct product = (Page.GetDataItem() as AppProduct);
lbl_title.Text = product.Title;
lbl_short.Text = product.Short;
lbl_date.Text = product.Date.ToShortDateString();
Session["current_img"] = product.Image1;
base.DataBind();
}
in my HttpHanlder object kept in a .ashx file i write the image to the response
the response happens only once so only the last picture is written to (ALL) the user controls.
public void ProcessRequest(HttpContext context)
{
byte [] image = (byte[])context.Session["current_img"];
context.Response.ContentType = "image/bmp";
context.Response.OutputStream.Write(image, 0, image.Length);
}
any idea how i could write the binary data for each individual control
thanks in advance
eran.
A: Change your handler so that it takes the id of the current product as a query string parameter. In the handler load the correct image data based on the parameter and write that instead.
A: Let me suggest a different approach.
Declare a regular html image element in your control and set the "runat=server" property as so:
<img src="" runat="server" id="img_product" />
Then change your DataBind() method to do this instead:
public override void DataBind()
{
AppProduct product = (Page.GetDataItem() as AppProduct);
lbl_title.Text = product.Title;
lbl_short.Text = product.Short;
lbl_date.Text = product.Date.ToShortDateString();
img_product.src= "\"data:image/jpg;base64,"+System.Convert.ToBase64String(product.Image1)+"\"";
base.DataBind();
}
And get rid of the HTTPHandler. You don't need it for this.
A: well to conclude , for this case i think the best practice would be @icarus's answer ,
not the disregard @kmcc049's answer i just hadn't dug into it since it seemed like a more complicated architecture for my app.
in this case DROP THE HTTPHANDLER .
i saved the image's type , and data from the post file.
public enum ImageType : byte {jpg,jpeg,png,gif}
private byte[] Get_Image(HttpPostedFile file)
{
ImageType type = GetType(file.ContentType);
if (file.InputStream.Length <= 1)
return null;
byte[] imageData = new byte[file.InputStream.Length + 1 + 1];
file.InputStream.Read(imageData, 1, imageData.Length+1);
imageData[0] =(byte)type;
return imageData;
}
private ImageType GetType(string _type)
{
ImageType t = default(ImageType);
string s = _type.Substring(_type.IndexOf('/')+1).ToLower() ;
switch (s)
{
case "jpg": t = ImageType.jpg;
break;
case "jpeg": t = ImageType.jpeg;
break;
case "png": t = ImageType.png;
break;
case "gif": t = ImageType.gif;
break;
}
return t;
}
then i extracted and added it to the user control in my DataBind override(in my user control) :
public override void DataBind()
{
AppProduct product = (Page.GetDataItem() as AppProduct);
img_main.Attributes.Add("src",Build_Img_Data(product.Image1));
base.DataBind();
}
private string Build_Img_Data(byte[] imageData)
{
ImageType type = (ImageType)imageData[0] ;
byte[] new_imageData = new byte[imageData.Length - 1];
Array.ConstrainedCopy(imageData, 1, new_imageData, 0, new_imageData.Length);
MemoryStream ms = new MemoryStream(new_imageData);
string base64String = string.Format("data:image/{0};base64,{1}",type.ToString(),Convert.ToBase64String(ms.ToArray()));
return base64String;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Load balance/distribution for postgresql I am coming here after spending considerable time trying to understand how to implement load balancing (distributing database processing load) between postgresql database servers.
I have a postgresql system which attracts about 100s of transactions per second and this is likely to grow. Please do note that my case has so many updates + inserts + selects as well. So any solution for me needs to cater to all insert/update and reads.
*
*I am planning to use plproxy as suggested through db tools from skype at http://www.slideshare.net/adorepump/database-tools-by-skype.
*Now I am also hearing that "postgresql streaming replication + hot standby" in postgres 9.0 can be considered
Can someone suggest me if there is any simple (or complex) solution to implement for the above scenario?
A: If your database is smaller than 100GB then you should first try to maximize what you can from one computer.
You'd need:
*
*a good storage controller with large battery backed cache;
*a bunch of fast disks in RAID10;
*another bunch of disks in RAID10 for WAL;
*more RAM than you have data;
*as many fast processor cores as you can.
You'd be able to do several 1000s of tps with this one computer.
If it won't be enough I'd try to add a second hot standby server with streaming replication. You'd use it to run long running read-only report queries, backups etc. so your master server won't have to do these.
Only if it prove not enough then you should try to add more streaming replication hot standby servers to load balance read-only queries. This will be complicated though - because it is asynchronous there's delay between master confirming and stand-by seeing a change. You'd have to deal with it in your client application. Your setup will be a lot more complicated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to handle user input containing quotes (etc)? I have a standard text input field. It get it's value from $_POST and I use it to build an SQL query (ODBC, not just MySQL, if that makes a difference (or instance, I can't use mysql_escape_string() ) ) .
The query which I am building has single quotes on the PHP and double quotes on the SQL. E.g.:
$sql = 'SELECT * FROM ' . $table . ' WHERE field="' . $_POST['some_field'] . '"";
If the user includes a double quote in his input e.g 6" wrench the I get an SQL error on the unbalanced string (a single quote, as in O'reilly gives no problem).
What's the correct way to handle this? Again, I am using the ODBC interface, not MySQL.
Is it just a matter of addslashes()? Or magic quotes?
Update: the PHP manual says of magic quotes ...
This feature has been DEPRECIATED as of PHP 5.3.0. Relying on this feature is highly discouraged.
(not that they suggests an alternative; in fact, it also says that magic quotes will be dropped in PHP 6)
Should the answer be to use prepared statements?
A: Use PDO prepared statements. It supports ODBC
A: Use odbc_prepare and odbc_execute like PDO
A: Even easier... why not just use htmlspecialchars?
http://us3.php.net/manual/en/function.htmlspecialchars.php
I mean, it's faster, and I'm assuming that the reason why your giving users a data field that allows them to use quotes is because your going to print that data back out at some point. Which is still doable, and you don't have to change around where you store your data.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I modify shapes on each item in a DataRepeater? I have a DataRepeater with some shapes on the ItemTemplate that I want to toggle on and off based on data in each Item. With every other control, I have done similar things using e.DataRepeaterItem.Controls["whatever"] in the DrawItem event, however this doesn't work with a shape as shapes are held in a ShapeContainer within the ItemTemplate. Trying to access the shape using ShapeContainer.Shapes.get_item(int index) results in a null reference error. As best as I can figure, the shapes in the container have not been initialized at the time of the DrawItem event.
So, what is the best way to modify a shape in an Item if I can't do it when each Item is drawn?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Background job with a thread/process? Technology used: EJB 3.1, Java EE 6, GlassFish 3.1.
I need to implement a background job that is execute every 2 minutes to check the status of a list of servers. I already implemented a timer and my function updateStatus get called every two minutes.
The problem is I want to use a thread to do the update because in case the timer is triggered again but my function called is not done, i will like to kill the thread and start a new one.
I understand I cannot use thread with EJB 3.1 so how should I do that? I don't really want to introduce JMS either.
A: You should simply use and EJB Timer for this.
When the job finishes, simply have the job reschedule itself. If you don't want the job to take more that some amount of time, then monitor the system time in the process, and when it goes to long, stop the job and reschedule it.
The other thing you need to manage is the fact that if the job is running when the server goes down, it will restart automatically when the server comes back up. You would be wise to have a startup process that scans the current jobs that exist in the Timer system, and if yours is not there, then you need to submit a new one. After that the job should take care of itself until your deploy (which erases existing Timer jobs).
The only other issue is that if the job is dependent upon some initialization code that runs on server startup, it is quite possible that the job will start BEFORE this happens when the server is firing up. So, may need to have to manage that start up race condition (or simply ensure that the job "Fails fast", and resubmits itself).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SDL delete an image and replace it with the new one I've started SDL just a few days ago and I'm having a problem
I tried to erase an image from the screen and replace it with the new one
here is my logic :
*
*load image
*apply surface, then delay for 1s
*free old image surface (SDL_FreeSurface())
*load new image
*apply surface
The problem is the image is still there. (it didn't get erased, just stacked with the new image)
A: The screen doesn't work like you think it does. You cannot "delete" something from a screen buffer, you can only write new things to the screen buffer. To 'erase' something you need to write the "background" over it.
Some game loops just re-write the entire screen with the background every frame.
This probably belongs over at gamedev.stackexchange.com
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why method overloading does not work inside another method? In the class or object body, this works:
def a(s:String) {}
def a(s:Int) {}
But if it is placed inside another method, it does not compile:
def something() {
def a(s:String) {}
def a(s:Int) {}
}
Why is it so?
A: Note that you can achieve the same result by creating an object:
def something() {
object A {
def a(s:String) {}
def a(i: Int) {}
}
import A._
a("asd")
a(2)
}
In your example, you define local functions. In my example, I'm declaring methods. Static overloading is allowed for objects, classes and traits.
I don't know why it's not allowed for local functions but my guess is that overloading is a possible source of error and is probably not very useful inside a code block (where presumably you can use different names for in that block scope). I assume it's allowed in classes because it's allowed in Java.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: jqgrid - upload a file in add/edit dialog I'm new to jqgrid and I have learn many things through your answer.
Now I have a problem: I want to upload files when adding or modifying records to a jqgrid?
This is my code:
{
name: 'File',
index: 'file',
hidden: true,
enctype: "multipart/form-data",
editable: true,
edittype: 'file',
editrules: {
edithidden: true,
required: true
},
formoptions: {
elmsuffix: '*'
}
}
However the field I got in controller always be null :(. Any suggestion
Anyone know working example?
Thanks in advance
UPDATE
I have found a very good example at http://tpeczek.codeplex.com/releases
A: I got it working just yesterday..here's my colModel column for file upload,
{
name: 'fileToUpload',
index: 'customer_id',
align: 'left',
editable: true,
edittype: 'file',
editoptions: {
enctype: "multipart/form-data"
},
width: 210,
align: 'center',
formatter: jgImageFormatter,
search: false
}
You have to set afterSubmit: UploadImage. It uploads the file only after data has been post & response has come back. I'm checking here that if insert was succesfful then only start upload else show error. I've used Jquery Ajax File Uploader.
function UploadImage(response, postdata) {
var data = $.parseJSON(response.responseText);
if (data.success == true) {
if ($("#fileToUpload").val() != "") {
ajaxFileUpload(data.id);
}
}
return [data.success, data.message, data.id];
}
function ajaxFileUpload(id)
{
$("#loading")
.ajaxStart(function () {
$(this).show();
})
.ajaxComplete(function () {
$(this).hide();
});
$.ajaxFileUpload
(
{
url: '@Url.Action("UploadImage")',
secureuri: false,
fileElementId: 'fileToUpload',
dataType: 'json',
data: { id: id },
success: function (data, status) {
if (typeof (data.success) != 'undefined') {
if (data.success == true) {
return;
} else {
alert(data.message);
}
}
else {
return alert('Failed to upload logo!');
}
},
error: function (data, status, e) {
return alert('Failed to upload logo!');
}
}
) }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: any open source CAdES signature implementation I want to create an app for digital signature, and the standard seems to be CAdES, could anyone point me to an open source (so it can be customized) implementation with practical examples to follow?
A: BouncyCastle 1.46b17 has an implementation of CAdES which was provided as a series of patches to the main codebase.
If you examine the Issue tracker for Bouncy Castle http://www.bouncycastle.org/jira/browse/BJA-217 it shows the patches, the patching and that some testing has been performed by the original submitter.
This is relatively recent change, but you can find the latest release version from http://www.bouncycastle.org/latest_releases.html and on that page is a link to the betas which are at http://downloads.bouncycastle.org/betas/
The current beta is 147b14 so that should contain what you need.
There is probably limited documentation - but with BouncyCastle the best place to start is to look at the test code which will normally show how the implementation should be used.
A: There is a European Community Initiative in GitHub: https://github.com/nonorganic/dssnet
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Need to create separate log file for jar file? I am creating a jar file that i need to provide to client, but my client is asking for separate logger for the jar file as this is doing some integration work.
anyone can suggest how can i create logger for only one jar file, can i put log4j.properties in same jar file.
I am using web-logic server. we will not deploy this jar file instead we will just keep it in domain lib folder.
Thanks
A: If the properties file is in the jar, then you could do something like this:
Properties props = new Properties();
props.load(getClass().getResourceAsStream("/log4j.properties"));
PropertyConfigurator.configure(props);
The above assumes that the log4j.properties is in the root folder of the jar file.
If this does not work for your needs in this case then you can always use:
-Dlog4j.configuration=log4j_for_some_jar.properties
If the other application is using Log4j as well. The easier method would be to just config your log4j file to send anything from your classes in your jar to a new log file like so:
log4j.rootLogger=ERROR, logfile
log4j.appender.logfile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.logfile.datePattern='-'dd'.log'
log4j.appender.logfile.File=log/radius-prod.log
log4j.appender.logfile.layout=org.apache.log4j.PatternLayout
log4j.appender.logfile.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
log4j.logger.foo.bar.Baz=DEBUG, myappender
log4j.additivity.foo.bar.Baz=false
log4j.appender.myappender=org.apache.log4j.DailyRollingFileAppender
log4j.appender.myappender.datePattern='-'dd'.log'
log4j.appender.myappender.File=log/access-ext-dmz-prod.log
log4j.appender.myappender.layout=org.apache.log4j.PatternLayout
log4j.appender.myappender.layout.ConversionPattern=%-6r %d{ISO8601} %-5p %40.40c %x - %m\n
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550308",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mysql NOW() and PHP time()? I am salting users' passwords with a mysql column which has the type timestamp and default is CURRENT TIMESTAMP.
Both of my timezones for mysql and php are identical.
My problem is this,
$q = $dbc -> prepare("INSERT INTO accounts (password) VALUES (?)");
$q -> execute(array(hash('sha512', 'somestaticsalt' . $_POST['password'] . time())));
Now as you can see I have to hash with PHP's time function and on the mysql side it is a default timestamp.
Somewhere there must be an overlap because where users' are entering correct information it is still failing to match the hashed password in the database.
I have tried inserting time() into the joined column but it returns at 1970. Also I do not want to save the timestamp as an INT as this isn't the correct thing to do, so what is your thoughts?
A: Your salt really should be random.
A small improvement on your code (you could do a lot better, like use bcrypt or at least some stretching on sha512):
$salt = md5(time() . 'some-other-static-salt'); //more random than time() along.
$q = $dbc -> prepare("INSERT INTO accounts (password, salt) VALUES (?, ?)");
$q -> execute(array(hash('sha512', 'somestaticsalt' . $_POST['password'] . $salt), $salt));
Now you're no longer depending on CURRENT_TIMESTAMP returning the same thing as time(), and you've got a better salt.
EDIT: if you insist on doing it your way, look at what mysql returns for that timestamp column. I bet it looks like "Y-m-d H:i:s" and not like a unix timestamp. Of course, you should have been able to figure that out yourself. Assuming that's true, wrap it in strtotime and you might have some success.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Knowing if a value can be called Note that this question is about pure Lua. I do not have access to any module or the C side. Additionally, I can not use the IO, the OS or the debug library.
What I'm trying to make is a function that receives, as parameters:
*
*a number that is an ammount of second
*a callable value
By 'a callable value', I mean a value that can be called. This can be:
*
*a function
*a table with a metatable that allows calling (through a __call metamethod)
Here's an example of a callable table:
local t = {}
setmetatable(t, {
__call = function() print("Hi.") end
})
print(type(t)) --> table
t() --> Hi.
Here's the function:
function delay(seconds, func)
-- The second parameter is called 'func', but it can be anything that is callable.
coroutine.wrap(function()
wait(seconds) -- This function is defined elsewhere. It waits the ammount of time, in seconds, that it is told to.
func() -- Calls the function/table.
end)()
end
But I have a problem. I want the function to throw an error if the parameter 'func' is not callable.
I can check if it is a function. But what if it is a table with a metatable that allows calling?
If the metatable of the table is not protected by a __metatable field, then, I can check the metatable to know if it is callable, but, otherwise, how would I do it?
Note that I have also thought about trying to call the 'func' parameter with pcall, to check if it is callable, but to do that, I need to call it prematurely.
Basically, here's the problem: I need to know if a function/table is callable, but without trying to call it.
A: In general, if the metatable does not want you to be able to get it (by defining __metatable to being something special), then you're not going to get it. Not from Lua.
However, if you want to cheat, you can always use debug.getmetatable, which will return the metatable associated with that object.
You don't have to prematurely call anything with pcall. Observe:
pcall(function(...) return PossibleFunction(...) end, <insert arguments here>)
A: function iscallable(x)
if type(x) == 'function' then
return true
elseif type(x) == 'table' then
-- It would be elegant and quick to say
-- `return iscallable(debug.getmetatable(x))`
-- but that is actually not quite correct
-- (at least in my experiments), since it appears
-- that the `__call` metamethod must be a *function* value
-- (and not some table that has been made callable)
local mt = debug.getmetatable(x)
return type(mt) == "table" and type(mt.__call) == "function"
else
return false
end
end
return iscallable
Then you can do
> = iscallable(function() end)
true
> = iscallable({})
false
> = iscallable()
false
> = iscallable(nil)
false
> x = {}
> setmetatable(x, {__call=function() end})
> = iscallable(x)
true
If you don't have access to the debug library, then you may have trouble being totally accurate since you can mess with metatables. You could use pcall but its hard to separate out the errors properly. Even if you search for a particular error string as in the other answer here, that might be because of something inside the function being called not being callable, not this particular value not being callable, if that makes sense.
A: This attempt at refining Nicol's answer still has the problem that it needs to call the table, but it tells whether a supplied table actually was callable or not. Even if the table was callable, pcall() will return false if there is an error caused during the execution of the __call() metamethod.
local result = {pcall(PossibleFunction, ...)}
if not result[1] then
if result[2]:match"^attempt to call" then
error("The provided value is not callable.")
else
-- Table was callable but failed. Just hand on the error.
error(result[2])
end
end
-- Do something with the results:
for i = 2, #result do
print(result[i])
end
Checking the error message in this way however does not feel very "clean" (what if the used Lua interpreter was e.g. modified with localized error messages?).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: How can I check if the text contains at least one A to Z letter? How can I write this in PHP?
if ($text contains at least one letter from A to Z, regardless of numbers or other characters)
echo 'Yes';
else
echo 'No';
Please help.
A: Here's something that will help
preg_match("/[a-z]/i",$text);
A: Like this
if (preg_match('/[A-Za-z]/i', $variable)) {
echo 'Yes';
}
else {
echo 'No';
}
A: Use preg_match() function
if (preg_match('/[a-z]/i', $text))
echo "Matches";
else
echo "No matches";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to extract tags with content that have certain substring using CSS selectors? I have the following HTML:
<tr bgcolor="#DEDEDE">
<td>
<b>OK:Have idea</b>
</td>
<td>
<b>KO:Write code</b>
</td>
<td>
<b>KO:Run code</b>
</td>
<td>
<b>KO:Debug code</b>
</td>
</tr>
I want to extract the following:
<b>KO:Write code</b>
<b>KO:Run code</b>
<b>KO:Debug code</b>
By the substring KO:. How do I do it using CSS selector expressions?
A: You can use :contains() which was dropped from the CSS3 spec but is implemented by Selenium:
WebDriver.findElements(By.cssSelector("td b:contains('KO:')"));
There is no equivalent pseudo-class for starts-with or ends-with, though, so :contains() is the furthest you can go with a CSS locator. If you need to filter only by starting with the substring KO:, you should use an XPath locator:
WebDriver.findElements(By.xpath("//td/b[starts-with(text(), 'KO:')]"));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Twilio, is it possible to have 5 minute delays between a call with Rest api? I have a sequential dialling app but I want to add 5 minute delays between each call.. I am thinking cron job. is this possible? If so what do I need to do to make this happen? I have no experience with cron..
A: I would just set up some sort of queue in a database, then every 5 minutes execute a script that reads the next phone number to call from the queue. Running a script every 5 minutes with a cron will look like this:
*/5 * * * * php /path/to/call/script.php
A: I just found sleep function in PHP manual which did just what I needed. Plus its really simple, can't believe not many knew of this.
http://php.net/manual/en/function.sleep.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: mdx parameter that contains two words causing an error I require help of the experts again!
I have set up a drop down list to be a parameter of another dataset.
When I choose an item that contains two words, it gives me an error saying
the syntaxt for "the second word" is incorrect.
So is there any way to wrap the whole param as one single string entry?
This is the query of the dataset which is causing the error.
SELECT
NON EMPTY { [Measures].[Matters Count] }
ON COLUMNS,
NON EMPTY { ([Matters].[By Division].[APPLICANT TYPE].ALLMEMBERS ) } DIMENSION PROPERTIES MEMBER_CAPTION,
MEMBER_UNIQUE_NAME
ON ROWS
FROM
(
select
strtoset(@Division)
on columns
from
[CTTT]
)
CELL PROPERTIES VALUE,
BACK_COLOR,
FORE_COLOR,
FORMATTED_VALUE,
FORMAT_STRING,
FONT_NAME,
FONT_SIZE,
FONT_FLAGS
Thanks a lot in advance.
Cheers.
A: Try doing:
(StrToSet("[Dimension].[Hierarchy].["+@Division+"]") ON COLUMNS FROM [CTTT])
Where the Dimension and Hierarchy are the ones from your Division dim (e.g. [Matters].[By Division]). This will be more correct anyway, as if you don't include the dim.hier SSAS tries to find the @Division parameter anywhere in the cube.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What type would you map BigDecimal in Java/Hibernate in MySQL? After going through the previous develop's trainwreck of code I realized I need to move all of the money based columns to not use floating point math. On the Java side this means using BigDecimal but when using Hibernate/JPA and MySQL 5 what would be the appropriate MySQL data type to make that column?
A: DECIMAL and NUMERIC.
The recommended Java mapping for the DECIMAL and NUMERIC types is
java.math.BigDecimal. The java.math.BigDecimal type provides math
operations to allow BigDecimal types to be added, subtracted,
multiplied, and divided with other BigDecimal types, with integer
types, and with floating point types.
The method recommended for retrieving DECIMAL and NUMERIC values is
ResultSet.getBigDecimal. JDBC also allows access to these SQL types
as simple Strings or arrays of char. Thus, Java programmers can use
getString to receive a DECIMAL or NUMERIC result. However, this makes
the common case where DECIMAL or NUMERIC are used for currency values rather awkward since it means that application writers have to
perform math on strings. It is also possible to retrieve these SQL
types as any of the Java numeric types.
Have a look here for further details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "40"
}
|
Q: Take screenshot Webbrowser in wp7 I have a code to take screenshot in wp7.
int Width = (int)LayoutRoot.RenderSize.Width;
int Height = (int)LayoutRoot.RenderSize.Height;
// Write the map control to a WwriteableBitmap
WriteableBitmap screenshot = new WriteableBitmap(LayoutRoot, new TranslateTransform());
using (MemoryStream ms = new MemoryStream())
{
// Save it to a memory stream
screenshot.SaveJpeg(ms, Width, Height, 0, 100);
// Take saved memory stream and put it back into an BitmapImage
BitmapImage img = new BitmapImage();
img.SetSource(ms);
// Assign to our image control
ImageFromMap.Width = img.PixelWidth;
ImageFromMap.Height = img.PixelHeight;
ImageFromMap.Source = img;
// Cleanup
ms.Close();
}
In my screen have a webbrowser to display content in internet. when press button Take. i can take a photo of screen but webbrowser area display a white rectangle.
A: Currently, there is no way to implement a screenshot over WebBrowser. But if you just want a runtime display of screenshot not store to gallery or for tile usage, you can just implement the function by put your WebBrowser control on the screenshot view. Thumbnail of WebBrowser can be implement in WPF way
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: database query filling the var/temp I am not a programmer so please be gentle :)
Following query on our website loads a lot of data to server's var/temp folder and creates server load and all sorts of troubles.
{php}
global $db;
$res = $db->get_results("select * from ".table_links." , pligg_files where link_status='queued' and file_link_id = link_id and file_size = '85x85' ORDER BY `link_date` DESC LIMIT 5");
echo "<ul class='upcomstory'>";
foreach($res as $rslink)
{
$rslink->link_title = utf8_substr($rslink->link_title, 0, 40) . '...';
$cat = $db->get_var("select category_name from ".table_categories." where category__auto_id='".$rslink->link_category."'");
$catvar = $db->get_var("select category_safe_name from ".table_categories." where category__auto_id='".$rslink->link_category."'");
//echo "<li><div class='stcon'><div class='stpic'><img class='stimg' alt='".$rslink->link_title."' src='".my_base_url.my_pligg_base."/modules/upload/attachments/thumbs/".$rslink->file_name."' /></div><a href='".my_base_url.my_pligg_base."/story.php?id=".$rslink->link_id."'>".$rslink->link_title."</a><br /><br /> <span style='color:#044B9B;font-weight:bold;'>".$rslink->link_votes."</span> Vote -In: <span style='font-weight:bold;color:#044B9B;'>".$cat."</span></div> </li>";
echo '<li><div class="stcon"><div class="stpic"><img class="stimg" alt="'.$rslink->link_title.'" src="'.my_base_url.my_pligg_base.'/modules/upload/attachments/thumbs/'.$rslink->file_name.'" /></div><a href="'.my_base_url.my_pligg_base.'/story.php?id='.$rslink->link_id.'">'.$rslink->link_title.'</a><br /><br /> <span style="color:#044B9B;font-weight:bold;">'.$rslink->link_votes.'</span> Vote(s) </div> </li>';
}
echo "</ul>";
{/php}
Is there a way to 'clear' the output automatically as part of this query once every few minutes?
Thanks
A: It's not really clear how this could be filling your directory. But, you could use a cron job to periodically clean out that folder. This will delete any files that are older than 60 minues.
@hourly find /var/temp/ -mmin +60 -exec rm {} \;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Removing text using regular expressions I want to remove "2011" and everything before it plus a single space (" ") after "2011".
Not quite sure how to approach this, all I could think of is a simple regex-like find and replace.
string temp;
StringBuilder sb = new StringBuilder();
string[] file = File.ReadAllLines(@"TextFile1.txt");
foreach (string line in file)
{
if (line.Contains(" "))
{
temp = line.Replace(" ", " ");
sb.Append(temp + "\r\n");
continue;
}
else
sb.Append(line + "\r\n");
}
File.WriteAllText(@"TextFile1.txt", sb.ToString());
I have modified my code and with a bit of luck got it to work. Modifications look as follows:
if (line.Contains("2011"))
{
temp = line.Substring(line.IndexOf("2011 ") + 5);
sb.Append(temp + "\r\n");
continue;
}
A: string s = "653 09-23-2011 21 27 32 40 52 36 ";
s = s.Substring(s.IndexOf("2011 ") + 5);
The result is that s = "21 27 32 40 52 36 "
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Upload Photos Facebook api EVERYONE I'm working with fql and php sdk and I created a Facebook page and I want to allow all users who likes my pages to upload photos (created dynamic from different photos like a collage), my problem is that as administrator of the page I can upload pictures but as a normal user does not allow me:
There is some kind of rule that does not allow me to upload photos
public static function AddPhotoToAlbum ($ userId, $ message)
{
$albumID = '166X93X634658X2 ';
$facebook-> setFileUploadSupport (true);
$ file = "@". realpath ('img / image'. $ userId.. 'png');
$args = array (
'message' => $ message,
'access_token' => $ accessToken,
'image' => $ file);
$data = $ facebook-> api ('/'.$ album. '/ photos', 'post', $ args);
print_r ($ data);
}
Any idea how to solve this problem. regards
A: When uploading with graph API make sure you use album's object_id and not aid (album id) - they are different. Strange it works for you though in some scenarios as you say. Also it would be helpful if you copy-paste the error message you get from facebook API here.
hope this helps
EDIT: user has to be administrator of the page to be able to upload.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to escape in sqlite? I'm escaping two semi colons in the code below using a backslash. I'm executing this code in SQLite Database Brower 2.0 for Mac. It keeps freezing up. I'm guessing that is because of some syntax issue?
INSERT INTO question (QuestionId, QuestionText, AreaId, AnswerText)
VALUES(6019, 'Math Functions', 6, "
Added: 9/1/2011
The following is a listing of math functions available:
Power of:
double pow ( double, double )
Example:
double myvar = pow(2,4)\;
NSLog(@"%.f", myvar)\; //value is 16");
A: In SQL, strings are always delimited with single quotes, never with double ones.
'Added: 9/1/2011
The following is a listing of math functions available:
[...]'
No characters are escaped except these single quotes (not even semicolons), and that happens by doubling:
SELECT 'That''s not exactly what I''m looking for...';
(This means that a string with only one single quote is encoded as '''' in SQL.)
A: The semicolons aren't your problem, the double quotes in the NSLog call are:
NSLog(@"%.f", myvar)\; //value is 16"
^---^
Double them and SQLite will be happy:
NSLog(@""%.f"", myvar)\; //value is 16"
Or you can use single quotes around the whole thing:
INSERT INTO question (QuestionId, QuestionText, AreaId, AnswerText)
VALUES(6019, 'Math Functions', 6, '
Added: 9/1/2011
The following is a listing of math functions available:
Power of:
double pow ( double, double )
Example:
double myvar = pow(2,4)\;
NSLog(@"%.f", myvar)\; //value is 16');
Single quotes are standard for SQL strings but SQLite will let you use either single or double quotes for strings.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: how to get PC unique id?
*
*What is the PC unique ID?
*How could we get the PC unqiue ID?
*Is it about Hard disk or motherboard?
I'd like to store PC ID in my window program. Please share me.
A: This work for me
Private Function CpuId() As String
Dim computer As String = "."
Dim wmi As Object = GetObject("winmgmts:" & _
"{impersonationLevel=impersonate}!\\" & _
computer & "\root\cimv2")
Dim processors As Object = wmi.ExecQuery("Select * from " & _
"Win32_Processor")
Dim cpu_ids As String = ""
For Each cpu As Object In processors
cpu_ids = cpu_ids & ", " & cpu.ProcessorId
Next cpu
If cpu_ids.Length > 0 Then cpu_ids = _
cpu_ids.Substring(2)
Return cpu_ids
End Function
see here
A: Try this, it pulls the ID off the processor.
Dim win32MgmtClass as System.Management.ManagementClass
win32MgmtClass = new System.Management.ManagementClass("Win32_Processor")
Dim processors as System.Management.ManagementObjectCollection
processors = win32MgmtClass.GetInstances()
For Each processor As System.Management.ManagementObject In processors
MessageBox.Show(processor("ProcessorID").ToString())
Next
A: The "PC unique ID" normally means the hardware ID, used to uniquely identify a computer. For example, they can be used to track software use on computers.
According to this question, the "motherboard id, processor id and bios id" "are the least likely to change".
This question contains code to get such information in C#; I couldn't find any topics for VB.NET, unfortunately, but it should be easy to port.
A: I assume that you want to generate an ID that is unique to the machine. Hard drive is probably the easiest approach because other hardware is too diverse to have a set way of retrieving their serial numbers.
Probably the easiest is to use the number that Windows generates for the hard drive.
You can find it under HKEY_LOCAL_MACHINE\SYSTEM\MountedDevices
and the key name is \DosDevices\C: (assuming that the C: drive is the main system drive - which is not the case in some very rare cases, but then you can check for what the system drive is and use the appropriate key).
There's another number associated with Hard drives called UUID and you can find scripts to get that. For example: http://www.windowsnetworking.com/articles_tutorials/Deploying-Windows-7-Part18.html for Windows. Or http://blog.granneman.com/2007/07/26/find-out-a-hard-drives-uuid/ for Linux.
I also found this article on retrieving the motherboard's serial number: Getting motherboard unique ID number thru vc++ programming
A: requires
https://www.nuget.org/packages/System.Management/
System.Management 4.7.0
As you can see there is an "Unique Value" plus some special calculations. You can make this as hard as you can, but reverse engineering can ultimately expose this.
Better (but slower) version for computer ID (requires System.Management import and reference):
Code:
Public Shared Function GetComputerID() As Long
Dim objMOS As New ManagementObjectSearcher("Select * From Win32_Processor")
For Each objMO As Management.ManagementObject In objMOS.Get
GetComputerID += objMO("ProcessorID").GetHashCode
Next
GetComputerID += My.Computer.Name.GetHashCode
End Function
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: CoffeeScript Wrapping Block Header Comment in Closure I have the following CS snippet:
###
jQuery Observer
Copyright 2011 All Rights Reserved
###
$ = jQuery
...
Which compiles to:
(function() {
/*
jQuery Observer
Copyright 2011 All Rights Reserved
*/
var $;
$ = jQuery;
...
}).call(this);
However, I'd like the header comment to appear at the top of the file (not inside the closure). Is this settable within CS?
A: There's currently no way to do this, but there is an open pull request which looks promising: https://github.com/jashkenas/coffee-script/pull/1684
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550355",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I make my launchpad downloads faster I am bzr branching some launchpad repositories and it takes very long (hours)
As this is distributed version control, wouldn't it be possible to have a local copy of those repositories (that I could just manually update before I clone them), let's call it a cache machine, and then always clone them? What would be the steps and the commands on the 2 machines (the "local copy" machine and the "target machine"?)
I would prefer not having a bazaar serve as the local copy but just a normal repositoy.
But I expect this would be faster? If not, maybe I could rsync the cache to get the initial branch on the target machine, am I right?
A: The easiest thing to do would be to use a shared repository locally. That way bzr will automatically reuse any revisions present in the shared repository when you clone a branch.
http://wiki.bazaar.canonical.com/SharedRepositoryTutorial
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can CSS alter an input element's SRC attribute? Is it possible, via CSS to remove or change the src reference in the markup below?
The easy thing to do would be to change the markup, however, this code is in the wild and I need to deal with it as it is, so I'm trying to remove the image and use a background image instead.
<input type="image" src="wp-content/uploads/image.png" name="submit" class="submit" value="Submit" />
A: You can experiment with setting height and width to 0, add a padding and set the background image. You will have to make it display: block or display: inline-block for the height to take effect.
Here's an example - http://jsfiddle.net/zBgHd/1/
A: Actually, I just figured it out.
.submit {width:0;height:28px;background:url(go.png) no-repeat; padding-left:28px;}
My replacement image is 28x28. By specifying a left padding equal to that, and a width of zero, it effectively pushes the image off the viewable area of the box, leaving the background image to show.
A: Although that is specifically about the img src attribute, it still holds true for input src. This question pretty much answers it for you - How to change an input button image using CSS?
Another related question: Define an <img>'s src attribute in CSS
A: No, to answer your question. Not in any version of any browser (AFAIK).
Any solution will involve a workaround. I'm testing out one right now, where you use a :before rule to create a background image on top of it.
Update... Well, for what it's worth, :before is not respected on input elements, whereas @Chetan's fiddle does work when I change the img tag to input. So, kudos.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: new window with same content and a small change I have a page in php which has several check boxes. whenever a user selects one of the check boxes, I want to change the check box with an undo button. can you please give me a clue how I should do that?
A: If you're using jQuery you could have an undo link that looks like this:
<a href="#" class="undo">undo</a>
$(document).ready(){ function(){ //wait until the page has loaded
$(".undo").click(function(){ //bind to the click event of your undo link
$(".checkbox").attr('checked', !$(".checkbox").attr('checked')) // Toggle the checkbox
})
})
Of course, this assumes you only have one checkbox. Would need to know more about your current set up to understand how you want the user experience to go.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In C++11, what is the point of a thread which "does not represent a thread of execution"? Looking over the new threading stuff in C++11 to see how easily it maps to pthreads, I notice the curious section in the thread constructor area:
thread();
Effects: Constructs a thread object that does not represent a thread of execution.
Postcondition: get_id() == id()
Throws: Nothing.
In other words, the default constructor for a thread doesn't actually seem to create a thread. Obviously, it creates a thread object, but how exactly is that useful if there's no backing code for it? Is there some other way that a "thread of execution" can be attached to that object, like thrd.start() or something similar?
A: Not just guessing:
"thread object" refers to a std::thread.
"thread of execution" refers to the OS's collection of hardware registers that represent a thread.
C++11 is doing nothing but papering over the OS's API for access to OS threads in order to make C++ threading portable across all OS's.
thread();
Effects: Constructs a thread object that does not represent a thread of execution.
Postcondition: get_id() == id()
Throws: Nothing.
This means a default constructed std::thread does not refer to a thread of execution that the OS has produced.
A std::thread can be given a new value, and thus begin to refer to an OS thread of execution by a move assignment statement:
std::thread t; // Does not refer to an OS thread
//...
t = std::thread(my_func); // t refers to the OS thread executing my_func
A:
Is there some other way that a "thread of execution" can be attached to that object, like thrd.start() or something similar?
// deferred start
std::thread thread;
// ...
// let's start now
thread = std::thread(functor, arg0, arg1);
std::thread is a MoveConstructible and MoveAssignable type. So that means that in code like std::thread zombie(some_functor); std::thread steal(std::move(zombie)); zombie will be left in a special, but valid, state associated with no thread of execution. The default constructor comes free in a sense since all it has to do is put the object into that exact state. It also allows arrays of std::thread and operations like std::vector<std::thread>::resize.
A: Just guessing, but it simply means that the thread is not started. In other words, it is just an object like any other - there's not necessarily an actual OS thread behind it. To put it another way, if threads were implemented on top of pthreads, creating a C++11 thread object doesn't necessarily call pthread_create() - that only need happen when the thread is started.
A: It means the same thing as this:
std::vector<int> emptyList;
emptyList is empty. Just like a default-constructed std::thread. Just like a default-constructed std::ofstream doesn't open a file. There are perfectly reasonable reasons to have classes that default construct themselves into an empty state.
If you have an empty thread:
std::thread myThread;
You can actually start the thread by doing this:
myThread = std::thread(f, ...);
Where f is some callable thing (function pointer, functor, std::function, etc), and ... are the arguments to be forwarded to the thread.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
}
|
Q: Time between jQuery add/remove class How can I set a timer, 10 sec in between this?
addClass('loading').removeClass('loading')
This is the full code
$("#loadmore").click(function() {
cap += 10;
}).bind('click', loadfeed).addClass('loading').removeClass('loading');
Thank you.
A: Use setTimeout. Also not sure why you are binding to click twice in two different ways... so with those two changes it'd look something like this:
$("#loadmore").click(function() {
cap += 10;
loadfeed();
$(this).addClass("loading");
that = this
setTimeout(function() {
$(that).removeClass('loading');
}, 10000)
});
A: You can use the jQUery delay() method and create a new queue item to do the act of removing the class.
$("#loadmore").click(function () {
cap += 10;
loadfeed();
}).addClass("loading").delay(10000).queue(function(){
$(this).removeClass("loading");
$(this).dequeue();
});
If you don't like this, the setTimeout() solution that @jcmoney provided is awesome.
A: $(document).ready(function() {
$('.letsGo').click(function() {
$('.footerCta').addClass('ball');
setTimeout(function() {
$('.footerCta').removeClass('ball');
}, 1000)
});
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: browser extension and a (big?) database I am thinking of building a browser extension that would need access to a database of around 30 thousand items, with no more than 3 attributes each. Having this embedded in a json object doesn't seem like the right thing to do, but databases is not something I know much about.
Having the database on a server is not an option.
What is the right path to take? Should I use a sql file and a library?
Thanks!
A: If the 30000 items are not changing, with 3 attributes each, assuming each attribute is 10 bytes (large enough for a long or a short string), your data is 900 kilobytes. Storing and loading a json object isn't terrible but you might want to look into HTML5's local storage which can hold 5MB.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTML Component of jQuery.ajax() I am reading the documentation on the jQuery website about the $.ajax() method and I didn't see an example of the HTML. I'm wondering how you tie the $.ajax() function to a user's "Click" on the submit button. This is my best guess, is it the right way?
Here is the example:
<html>
<head></head>
<body>
<form id="my_form">
<input type="text" name="name"><br />
<input type="text" name="email"><br />
<textarea name="message"></textarea>
<input type="submit" name="submit">
</body>
</html>
Javascipt
submit: function {
var form_data = $("form#my_form").serialize();
function progress() {
//some loading gif
};
function removeProgress() {
//remove the loading gif
};
$.ajax ({
type: "GET",
url: "contact-us.php",
data: form_data,
beforeSend: progress(),
error: function() { alert("dude, something went wrong!"); },
success: function() { alert("WIN!"); },
complete: function() {
removeProgress();
alert("1 row added.");
}
});
A: You will need to bind the function to an event triggered by an element. For example, to bind a function to the submit event of the <form id="my_form"> element, you would do this:
$(document).ready(function () {
// ..
$('#my_form').submit(function (event) {
// ajax call here
});
});
In order to prevent the form from posting to a page (as it would normally do), you would need to add a call to preventDefault() on the event, like this:
$(document).ready(function () {
// ..
$('#my_form').submit(function (event) {
// ajax call here
event.preventDefault();
});
});
A: Wrap the whole $.ajax in a function and bind it in the form's submit handler:
function submitForm()
{
$.ajax({
...
});
}
<form ... onsubmit="submitForm(); return false">
</form>
The return false is important! Or else you'll be calling the default submit of the form too.
EDIT
rfausak's answer is better
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7550368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.