text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Why doesn't Facebook combine its CSS/JS files? I am curious as to why the Facebook developers have chosen to not combine their scripts and stylesheets into single files. Instead they are loaded on demand via their CDN.
Facebook is obviously a very complex application and I can understand how such modularity might make Facebook easier to maintain, but wouldn't the usual optimisation advice still apply (especially given its high level of usage)?
Or, does the fact that they are using a CDN avoid the usual performance impact of having lots of small scripts / styles?
A: They might be running into the case where the savings of being able to serve different combinations of JS files to the browser at different times (for different pages or different application configurations for different users) represents a larger savings than the reduced HTTP request overhead of combining all of the files into one.
If a browser is only ever executing a small percent of the total JS code base at any given time, then this would make sense. Because they have so many different users and different parts of different applications running in different configurations for those users, it is arguable that this is the case.
Second, those files only need to be downloaded once, then the browser won't ask for them again until they have changed or the cache has expired, so only the first visit really benefits from the all-in-one style. And yes having and advanced CDN with many edge locations around the world definitely helps.
A: In a word BigPipe. They divide the page up into 'pagelets' each is processed separately on their servers and sent to the browser in parallel. Essentially almost everything (CSS, JS, images, content) is lazy loaded, thus it comes down in a bunch of small files.
A: Maybe they think it's more likely that you visit Facebook more often than you clear your browser cache.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to setup iOS development environment?
Possible Duplicate:
How to use device instead of Simulator
I like to know how to test my own iOS app on my ipad or iphone. I know that there's IOS emulator in Mac OS, but I like to test my apps with a real hardware.
My research says that I have to jailbreak my ipad. Is this correct? or is there any other alternatives?
A: You do not need to jail break your device to test on it.
You do need to sign-up with apple and get a developer account. That will allow you to get a provisioning profile and certs, then you can run on your device to test.
If you want others to test your apps on real devices look into ad-hoc deployments.
The majority of your development will be with the simulator but by all means, always test on real devices ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Lucene Tokenizer with LookAhead can anyone point me in the right direction for implementing a Lucene Tokenizer with LookAhead?
I'm using a snowball stemmer and I want to be able to get phrases of city names and prevent them from being stemmed, so that "Los Angeles" will be set as a single token, as opposed to two tokens of "Los" and "Angeles".
I also need to keep tokens that don't match any city name as a single word.
any ideas?
TIA
A: Here is a gist of something I wrote which does what you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why does ffmpeg never finish when converting a video from my web app? I am trying to convert a video when the user submits a form. It seems to convert ok but the file "is being used by another proccess" when I try to do anything with it. It looks like ffmpeg.exe never exits. My code is below is there anything I should be doing different to allow the process to release the file? If I run this manually it exits fine.
internal class ConversionUtility : Utility
{
public void Convert(string videoFileName)
{
var video = new VideoFile(videoFileName);
if (!video.infoGathered)
GetVideoInfo(video);
var Params = string.Format("-y -i \"{0}\" -coder ac -me_method full -me_range 16 -subq 5 -sc_threshold 40 -vcodec libx264 -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -i_qfactor 0.71 -keyint_min 25 -b_strategy 1 -g 250 -r 20 \"{1}\"", video.Path, Path.ChangeExtension(videoFileName,".mp4"));
//var Params = string.Format("-y -i \"{0}\" -acodec libfaac -ar 44100 -ab 96k -coder ac -me_method full -me_range 16 -subq 5 -sc_threshold 40 -vcodec libx264 -s 1280x544 -b 1600k -cmp +chroma -partitions +parti4x4+partp8x8+partb8x8 -i_qfactor 0.71 -keyint_min 25 -b_strategy 1 -g 250 -r 20 c:\\output3.mp4", video.Path, videoFileName);
//var Params = String.Format(" {0} \"{1}\"",this.FFmpegLocation, video.Path);
var threadStart = new ParameterizedThreadStart(del => RunProcess(Params));
var thread = new Thread(threadStart);
thread.Start();
//RunProcess(Params);
}
}
internal class Utility
{
public string FFmpegLocation { get; set; }
private string WorkingPath { get { return Path.GetDirectoryName(FFmpegLocation); } }
protected string RunProcess(string Parameters)
{
//create a process info
var oInfo = new ProcessStartInfo(this.FFmpegLocation, Parameters)
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
//Create the output and streamreader to get the output
string output = null; StreamReader srOutput = null;
//try the process
try
{
//run the process
Process proc = System.Diagnostics.Process.Start(oInfo);
proc.WaitForExit();
//if (!proc.WaitForExit(10000))
// proc.Kill();
//get the output
srOutput = proc.StandardError;
//now put it in a string
output = srOutput.ReadToEnd();
proc.Close();
}
catch (Exception)
{
output = string.Empty;
}
finally
{
//now, if we succeded, close out the streamreader
if (srOutput != null)
{
srOutput.Close();
srOutput.Dispose();
}
}
return output;
}
A: After a good bit of research I came across this post. Which set me on the right track. I read more about RedirectStandardError and found I needed to change the order I was calling things. After calling WaitForExit at the end everything worked as expected. Here is the updated code:
protected string RunProcess(string Parameters)
{
//create a process info
var oInfo = new ProcessStartInfo(this.FFmpegLocation, Parameters)
{
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
var output = string.Empty;
try
{
Process process = System.Diagnostics.Process.Start(oInfo);
output = process.StandardError.ReadToEnd();
process.WaitForExit();
process.Close();
}
catch (Exception)
{
output = string.Empty;
}
return output;
}
A: Does your web application(app pool process identity) have the proper permissions for what's being done in the process threads you are spawning?
I have had issues like this in the past related to System.File.Move running Process Threads doing IO from ASP.NET, which is really a Win32 issue under the hood.
Use System.File.Copy or the Win32 equivalent and then delete the old file if you can. My guess is the .exe you are calling out(executing) to isn't yours(your own source code to be able to modify) and you can't change it.
You can also use SysInternals to see what may be holding on to or blocking resources.
A: You should always read the StandardOutput and the StandardError buffers while the process is running. Whenever the buffers reach their limits, the process will literally hang until you read the buffers to end.
FFMpeg constantly reports information about the conversion. Every update of the information you see in the bottom of the Command Prompt is added to the StandardOutput buffer, thus filling up the buffer. The buffer is likely to fill up quickly when converting large files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to change title of a Tab in TabActivity I have TabActivity with tabs on bottom which is composed of several different activities like this:
public class HomeScreen extends TabActivity {
private TabHost mTabHost;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
try{
setContentView(R.layout.hometabs);
Resources res = getResources(); // Resource object to get Drawables
mTabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Reusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
String strName;
// Create an Intent to launch an Activity for the tab (to be reused)
strName=Central.Res.getString(R.string.tab_Books);
intent = new Intent().setClass(this, BookList.class);
spec = mTabHost.newTabSpec(strName).setIndicator("",
res.getDrawable(R.drawable.ic_menu_database))
.setContent(intent);
mTabHost.addTab(spec);
// Create an Intent to launch an Activity for the tab (to be reused)
strName=Central.Res.getString(R.string.tab_Questions);
intent = new Intent().setClass(this, QuestionsList.class);
intent.putExtra("NoteType", UserDataSQLHelper.NOTE_TYPE_QUEST );
spec = mTabHost.newTabSpec(strName).setIndicator("",
res.getDrawable(R.drawable.ic_menu_dialog))
.setContent(intent);
mTabHost.addTab(spec);
My problem is that I have the same window title for every tab. This window title is set to application name.
I need to be able to change this title to the name of the tab.
I am trying to do it by calling setTitle("MyTitle"); in onCreate() of corresponding activity and by overriding TabActivity onChildTitleChanged:
public void onChildTitleChanged(Activity childActivity, CharSequence title)
{
View tabView = mTabHost.getCurrentTabView();
int idTitle = android.R.id.title;
TextView tvTitle = (TextView) tabView.findViewById(idTitle);
tvTitle.setText(title);
}
But the result I get isn't what I need - it sets text to tab under the tab icon.
Could you please help me?
A: try with following code,
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
Log.i("Tab id", ""+tabId);
setTitle(tabId);
}
});
A: setIndicator (CharSequence label, Drawable icon).
Use this function and the label will be shown as a title.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GWT LinkedHashMap.clone() issue Faced an interesting issue recently. I've catched ClassCastException while executing this code:
LinkedHashMap<Tag, Boolean> tags = new LinkedHashMap<Tag, Boolean>();
...
LinkedHashMap<Tag, Boolean> tagsCopy = (LinkedHashMap<Tag, Boolean>)tags.clone();//exception on this line
In development mode it works just fine, but it fails in production somewhy. Solved it by creating a shallow copy manually. But I'm still interested in what caused such a behaviour.
Any ideas?
UPD forgot to mention, I use java.util.LinkedHashMap.
A: clone is not supported by GWT, see issue 1843 on the GWT issue tracker. It does work in development mode as in that mode plain Java code is executed, while in production the generated JavaScript is executed, for which no working implementation of clone is generated. In issue 1843 are some suggestions for creating a GWT compatible version, but afaik those suggestions are not in the GWT implemented.
A: With GWT 2.4, LinkedHashMap.clone() returns a HashMap. Try using Map<...> = (Map<...>) anyOtherMap.clone(); in the general case to avoid such issues.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can Hadoop read arbitrary key binary file It looks like Hadoop MapReduce requires a key value pair structure in the text or binary text.
In reality we might have files to be split into chunks to be processed. But the keys may be
spread across the file. It may not be a clear cut that one key followed by one value. Is there any InputFileFormatter that can read such type of binary files? I don't want to use Map Reduce and Map Reduce. That will slow down the performance and defeat the purpose of using map reduce.
Any suggestions? Thanks,
A: According to the Hadoop : The Definitive Guide
The logical records that FileInputFormats define do not usually fit neatly into HDFS
blocks. For example, a TextInputFormat’s logical records are lines, which will cross
HDFS boundaries more often than not. This has no bearing on the functioning of your
program—lines are not missed or broken, for example—but it’s worth knowing about,
as it does mean that data-local maps (that is, maps that are running on the same host
as their input data) will perform some remote reads. The slight overhead this causes is
not normally significant.
If the file is split by HDFS between boundaries, then Hadoop framework will take care of it. But if you split the file manually, then boundaries have to be taken into consideration.
In reality we might have files to be split into chunks to be processed. But the keys may be spread across the file. It may not be a clear cut that one key followed by one value.
What's the scenario, we can look at a workaround for this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Form with multiple email fields to multiple recipients This is my html form. The user will input the email addresses he/she would like to send the html email to.
<form id="form1" name="form1" method="post" action="">
<table width="400">
<tr>
<td>Please enter your email address:</td>
<td<input type="text" name="email" id="email" /></td>
</tr>
<tr>
<td>Please enter the email addresses you would like to notify below:</td>
<td>
</td>
</tr>
<tr>
<td>Email:</td>
<td>
<input type="text" name="email1" id="email1" />
</td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email2" id="email2" />
</td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email3" id="email3" />
</td>
</tr>
<tr>
<td>Email:</td>
<td><input type="text" name="email4" id="email4" />
</td>
</tr>
</table>
</form>
This is somewhat the php code.
<?php
$ToEmail = '["email1"]["email2"]["email3"]["email4"]';
$EmailSubject = 'Check this out guys!';
$mailheader = "From: ".$_POST["email"]."\r\n";
$mailheader .= "Reply-To: "noreply@domain.com"\r\n";
$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n";
mail(......) or die ("Failure");
?>
<script type="text/javascript">
alert("Success! You have sent the notification to the emails you have entered.");
<!--
window.location = "form.html"
//-->
</script>
How do I:
1. Modify the PHP code so that it will send to the emails inputed by the user?
2. The body message of the notification is a html email. How do I go about adding it to the PHP code?
Your help is highly appreciated. Thanks in advance!
A: Looks like you need to $_POST the email1, email2 etc. values to a variable then use that as your value for $to in the mail() function - just make sure you add a comma after each:
$to = $_POST['email1'] . ', ';
$to .= $_POST['email2'] . ', ';
$to .= $_POST['email3'];
etc. Leave off the comma for the last email and you should be ready to go.
Regarding the content of your email, you should be able to send html no problem - just store it in a variable for ease of use later, e.g:
$message = '
<html>
<head>
<title>This is the HTML Email</title>
</head>
<body>
<div id="container">
<p>Welcome to the html!</p>
<img src="../img/some_image.jpg" alt="some image"/>
</div>
</body>
</html>
';
then make sure you add the relevant HTML headers:
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
Along with any other headers e.g.:
$headers .= 'From: HTML Email <you@example.com>' . "\r\n";
Then call mail() with your defined variables:
mail($to, $subject, $message, $headers);
Hope that helps.
p.s. its all available on the mail function definition: mail()
A: Look at the php manual for mail
Example:
$toemails = "user@example.com, anotheruser@example.com";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C++ question regarding classes and default values for function arguments and recursion I need to use recursion to count the nodes in a linked list.
unsigned CLL::CountNodes(CNode* val)
{
if(!val)
return 0;
else
return 1 + CountNodes(val->next);
}
So when I want to count the nodes in the linked list, from say, another function, I go:
int main()
{
CLL list();
cout << list.CountNodes(list.head);
}
This seems a bit dodgy though, because the class should be able to count the list without me passing in a point to the head of the head of the list. This seems straight forward with a for-loop; however, with recursion, I tried:
unsigned CLL::CountNodes(CNode* val = head)
{
if(!val)
return 0;
else
return 1 + CountNodes(val->next);
}
but this did not work because head is not static. Then making head static is a problem, because I have to declare it outside the class.
Is there anyway to solve the problem?
e.g. cout << list.CountNodes();
Or must the head of the list always be passed in when using recursion?
A: In C++ there is always a way. You may have two overloaded functions, for example:
unsigned CountNodes (CNode* val)
{
return val ? CountNodes(val->next) + 1 : 0;
}
unsigned CountNodes ()
{
return CountNodes (head);
}
I would also recommend making unsigned CountNodes (CNode* val) function static since it doesn't need anything from CLL class, and unsigned CountNodes () method constant because it doesn't change object's state.
And by the way, there is a ternary operator in C++ that makes life easier, code more readable and may even make it faster. So instead of:
if(!val)
return 0;
else
return 1 + CountNodes(val->next);
... you could write like:
return val ? 1 + CountNodes(val->next) : 0;
A: You could have a public function int CountNodes() that calls a private int CountNodes(CNode*) method with this->head.
// in class CLL
public:
unsigned int CountNodes()
{
return CountNodes(head);
}
private:
CNode* head;
unsigned int CountNodes(CNode* val)
{
if(!val)
return 0;
else
return 1 + CountNodes(val->next);
}
Now you have better encapsulation has your head data member is private and your client code can be made simpler.
int main()
{
CLL list();
cout << list.CountNodes();
}
A: Use 2 functions. The first one as written, plus one with no arguments which calls the first with 'head' as the argument.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C++ GetLine() Problem, Command Line Program I am writing this program for my programming class and it has a bunch of stupid constraints like I must use nested if else statements and I have to use the cin.getLine() to get a players name. It is supposed to grab the name of each player and calculate their batting average.
This is not the entire program but up to the part where I am having an error. When I run this in a command prompt I can recieve the first name fine, but after that the second cin.getline() does not read any input. Suggestions?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
char name1[100], name2[100], name3[100];
int numBat, numHit;
double avg1, avg2, avg3;
// Get Average for Player 1
cout << "What's Your Name? ";
cin.getline(name1, 100);
cout << "How many times have you been at bat? ";
cin >> numBat;
if(numBat < 0 || numBat > 25)
{
cout << "ERROR ::: Number of Times at Bat Cannot Be Less Than 0 or Greater Than 25. Run Program Again." << endl;
return 0;
}
else
{
cout << "How many times have you hit the ball? ";
cin >> numHit;
if(numHit < 0)
{
cout << "ERROR ::: Number Hit Cannot Be Less Than 0. Run Program Again." << endl;
return 0;
}
else
{
// Calculate Average for Player 1
avg1 = numHit / numBat;
// Get Average for Player 2
cout << "What's Your Name? ";
cin.getline(name2, 100);
cout << "How many times have you been at bat? ";
cin >> numBat;
cout << "How many times have you hit the ball? ";
cin >> numHit;
}
}
}
A: I think it's a buffer problem. Try to flush the cin before the second getline:
cin.clear(); // clear the buffer
cin.sync();
if that does not work, try something like this:
cin.ignore(256, '\n'); // ignore the endline and char(256)
A: After the getline, you need to output a newline using cout << endl;.
A: When you use
cin >> numBat;
It doesn't read the newline, so the next cin.getline() will read that and continue.
Use
cin >> numBat;
cin.ignore(80,'\n');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: os.path.join returning Errno22 in Enthought/Python I'm working with a fairly complex Enthought/Python program that is returning this error:
File "C:\Users\riddle\Desktop\FCI2\src\equation.py", line 41, in main
fci_data = np.load(os.path.join(local_data_path, "fci_data.npy"))
File "C:\Python27\lib\site-packages\numpy\lib\npyio.py", line 329, in load
fid = open(file, "rb")
IOError: [Errno 22] invalid mode ('rb') or filename: 'C:\\Users\white\\Desktop\
\FCI2New\\data\\fci_data.npy'
With respect to this:
fci_data = np.load(os.path.join(local_data_path, "fci_data.npy"))
fci_data = fci_data.replace("'\\','/'")
The additional slashes are particularly puzzling me. local_data_path is global and is defined like so:
local_data_path = static.base_data_path
base_data_path = "C:\Documents and Settings\white\Desktop\FCI2New\data" (from the static module)
Anyone have an idea what might be the issue here? 'rb' should be the correct mode for fci_data. Please forgive any errors or obvious questions, I'm a beginner.
Anne
A: try first to normalize the path :
local_data_path = os.path.normpath(local_data_path)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How could I create a shortcut on desktop in iOS through an app What do I mean is that I want to use the app to create a shortcut with icon on the desktop which will allow user to speed access some functions of this app.
How could I do that, any suggestions? Or anyone have experience with this.
An example:
FaceDial
A: You can not add icons to the 'desktop' (Springboard) other than your application's. What this app is doing is displaying a replica of the iPhone 'desktop' within their app.
UPDATE: The link now points to an app which does this and it seems it is somewhat possible although rather hack in my opinion.
This is how I believe the application works (it is similar to answer
below but in more detail).
*
*The application creates the webclip image and sends it and the phone number to a web service.
*The web service then creates a page with the webclip information attached. The phone number/email is converted to a url which will trigger the corresponding app (Mail/Messages/Phone). i.e "+834 895 734" -> tel:834895734 or sms:834895734
*The app then opens that page in MobileSafari and that page
presumably has instructions on how to "Add to Homescreen".
*The user will then have to navigate to and tap the "Add to Homescreen" button. This will add the webclip to the Springboard as an icon.
*When tapped the webclip activates the url and the Mail/Messages/Phone is launched with the number/email
You could implement something similar (although I wouldnt suggest it). These are the steps to follow:
*
*Register your own url scheme
*Host a page somewhere which contains a webclip for each function/url you want a shortcut for. If the urls are not static or you want dynamic icons, you will need a web service.
*Handle the url in your application in this AppDelegate method
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
Note: If your application is deleted, the webclips will no longer work and will confuse the user. Apple may also reject your app.
A: I guess the application works as follows,
1) It just creating a html for each contact
2) It using the safari functionality "Add to home screen"
Found an excellent answer for simulating the safari functionality,
I created an link from Safari using the "Add To Home Screen" button. It created a directory called 54C86B09482D4560BAB46091CC75825A.webclip inside of /private/var/mobile/Library/WebClips/. That directory contains two files, icon.png and Info.plist. icon.png is simply the icon that gets shown when looking at the apps screen.
The contents of Info.plist are where the real information is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>ClassicMode</key>
<false/>
<key>FullScreen</key>
<false/>
<key>IconIsPrecomposed</key>
<false/>
<key>IconIsScreenShotBased</key>
<true/>
<key>Scale</key>
<real>0.32653060555458069</real>
<key>ScrollPoint</key>
<dict>
<key>x</key>
<real>0.0</real>
<key>y</key>
<real>-183</real>
</dict>
<key>Title</key>
<string>The Daily WTF</string>
<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleGray</string>
<key>URL</key>
<string>http://thedailywtf.com/</string>
</dict>
</plist>
So, to test this out I created a new folder called C28C8FDC2F184AAD84F77B511442548F.webclip and copied the Info.plist file over from the other directory, edited the url to http://google.com. I then re-sprung the phone and it showed up just like any other webclip. The folder name is simply a hex encoded GUID, I used http://www.somacon.com/p113.php and just selected what was after 0x for this simple test
A: I spent a good while trying to implement this functionality into an app recently and wanted to put out some of the resources I found on the subject to save someone else a major headache. This is becoming an increasingly popular feature and is used in major apps like Workflow and Facebook's Groups app. Given that Workflow is now an Apple app, it doesn't look like Apple has any issues with using this technique either. The answer provided by @jin is essentially correct. The process looks something like this:
*
*Register a custom URL scheme for your app. Create dynamic URL links that, when followed, lead to content you wish to shortcut to. The only way currently to add a shortcut to the iOS springboard is via Safari's "add to homescreen" function. So what we want to do is use Safari to save our custom URLs that lead to our app to the springboard. The trick is, you can't just send your URL to Safari and save it because doing so will cause Safari to immediately follow the link and the user will never have a chance to hit "Add to homescreen". So to circumvent this issue you'll need to host a web-service somewhere that takes your URL and returns a base64 URL which your user can save to the homescreen.
*To create this webservice you can either host it remotely,which will require your user to be online to use, or embed one into your app, which is what Workflow and Facebook Groups does. For embeded servers theres some great fairly easy to use options. If you're using objective-c theres CocoaHTTP and if you're using Swift I'd recommend Swifter, which is what I used.
*Your webserver will need to display a page which returns another page in an base64 encoded format so that the user can use the shortcut after the webserver stops running (obviously you can't leave the embedded server running 24/7). The encode page will need to detect if the page was launched in standalone mode. If it was, then it should take you to your app, otherwise it should present you with a page where the user can save the page to the homescreen. Here's a sample of how my html looked for the service:
<!DOCTYPE html>
<html>
<div id="html">
<!DOCTYPE html>
<html>
<head>
<title>Add to Homescreen</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<meta content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no;" name="viewport"/>
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<meta content="SHORTCUT NAME HERE" name="apple-mobile-web-app-title"/>
<link rel="icon" type="image/png" href="data:image/png;base64, ICON IMAGE DATA"/>
<link rel="apple-touch-icon" href="data:image/png;base64, ICON IMAGE DATA"/>
<link rel="apple-touch-startup-image" href="data:image/png;base64, ICON IMAGE DATA"/>
</head>
<body>
<a id="redirectURL" href="YOUR CUSTOM URL" name = "redirectURL"></a>
<script>
if (window.navigator.standalone) {
var e = document.getElementById('redirectURL');
var ev = document.createEvent('MouseEvents');
ev.initEvent('click', true, true);
e.dispatchEvent(ev);
window.close();
} else {
document.write("<center><h1>Valet</h1><img id=\"imageIcon\" src=\"data:image/png;base64, IMAGE ICON DATA\"></img><h2> Add this page to your homescreen </h2></center>")
}
</script>
</body>
</html>
</div>
<script type="text/javascript">
var html = document.getElementById("html").innerHTML;
html = html.replace(/\s{2,}/g, '')
.replace(/%/g, '%25')
.replace(/&/g, '%26')
.replace(/#/g, '%23')
.replace(/"/g, '%22')
.replace(/'/g, '%27');
var dataURI = 'data:text/html;charset=UTF-8,' + html;
window.location.href = dataURI
</script>
</html>
Here's a list of resources on the topic that helped me out (Sorry, I don't have enough reputation to include more than 2 links... so you'll have to copy pasta these):
*
*Great example of how the web-service works with a live demo: https://gist.github.com/FokkeZB/5899387
*Another stack overflow question describing the process:
https://stackoverflow.com/questions/28042152/link-to-safari-add-to-home-screen-from-inside-app
*Great javascript widget for prompting the user to hit "Add to homescreen" once in Safari:
http://cubiq.org/add-to-home-screen
*Apple's documentation on custom URL schemes:
https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/Inter-AppCommunication/Inter-AppCommunication.html
*Apple's documention for built in schemes, which will be better for shortcutting simple task i.e. sending an email:
https://developer.apple.com/library/content/featuredarticles/iPhoneURLScheme_Reference/Introduction/Introduction.html
*Example showing how to base64 encode your HTML in Javascript:
https://stackoverflow.com/questions/9238890/convert-html-to-datatext-html-link-using-javascript
Let me know if anyone has any questions!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: What's the fastest way to check for the existence of a mongodb doc? What's the fastest way to check for the existence of a mongodb doc?
Should I just use find and if it returns nothing?
EDIT:
collection.findOne {#attribute}, (err, doc) ->
if err then console.log err
if interaction
#exists
else
#does not
A: If you are just testing for a single document, use findOne (or the equivalent in your driver); most drivers implement this in the most efficient possible way (by setting a negative limit of 1 on the request, which asks mongo to return immediately after finding one document, even if more might match, and not to create a cursor that won't ever be used by the client).
If you have an index that can serve your query, you can use field selection to select (a subset of) the fields in the index; this will make use of Mongo's "covered index" functionality to avoid a lookup to the underlying collection data. Be sure to set {_id: 0} in your field selector unless _id is in your index.
A: Covered Index is what you want. If the info you know about the document is indexed, then you can use this facility to query and retrieve info from the index only (in RAM) and will not go to disk to get the reference document. Explained in the mongo docs here.
A: http://www.mongodb.org/display/DOCS/mongo%20wire%20protocol#MongoWireProtocol-OPQUERY
numberToReturn : Limits the number of documents in the first CONTRIB:OP_REPLY message to the query. However, the database will still establish a cursor and return the cursorID to the client if there are more results than numberToReturn. If the client driver offers 'limit' functionality (like the SQL LIMIT keyword), then it is up to the client driver to ensure that no more than the specified number of document are returned to the calling application. If numberToReturn is 0, the db will used the default return size. If the number is negative, then the database will return that number and close the cursor. No futher results for that query can be fetched. If numberToReturn is 1 the server will treat it as -1 (closing the cursor automatically).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577890",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Efficient Algorithms for Computing a matrix times its transpose For a class, a question that was posed by my teacher was the algorithmic cost of multiplying a matrix times its transpose. With the standard 3 loop matrix multiplication algorithm, the efficiency is O(N^3), and I wonder if there was a way to manipulate or take advantage of matrix * matrix transpose to get a faster algorithm. I understand that when you multiply a matrix by its transpose you have to calculate less of the matrix because its symmetrical, but I can't think of how to manipulate an algorithm that could take less than O(n^3).
i know there's algorithms like Coppensmith and Straussen that are faster general matrix multiplication algorithms but could anyone give any hints or insights on how to computationally take advantage of the transpose?
Thanks
A: As of right now there aren't any aymptotic barrier-breaking properties of this particular multiplication.
The obvious optimization is to take advantage of the symmetry of the product. That is to say, the [i][j]th entry is equal to the [j][i]th entry.
For implementation-specific optimizations, there is a significant amount of caching that you can do. A very significant amount of time in the multiplication of large matrices is spent transferring data to and from memory and CPU. So CPU designers implemented a smart caching system whereby recently used memory is stored in a small memory section called the cache. In addition to that, they also made it so that nearby memory is also cached. This is because a lot of the memory IO is due to reading/writing from/to arrays, which are stored sequentially.
Since the transpose of a matrix is simply the same matrix with the indices swapped, caching a value in the matrix can have over twice the impact.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: SSL Server Cert Present One name for WCF? I have a self-hosted WCF service with TCP binding, now trying to layer on SSL.
The cert I got from the CA has two values for "Subject Alternative Name":
www.mysite.com
mysite.com
I only want to present "mysite.com" to WCF clients, somehow this www.mysite.com (which the CA added, I did not ask for www.mysite.com).
I am using the below code server-side. What do I have to tweak to "hide" the www.mysite.com address?
svc.Credentials.ServiceCertificate.SetCertificate(
StoreLocation.CurrentUser , StoreName.My , X509FindType.FindBySubjectName , "mysite.com" );
So right now when the client connects, I get
"Identity check failed for outgoing message. The expected DNS identity of the remote endpoint was 'mysite.com' but the remote endpoint provided DNS claim 'www.mysite.com'. If this is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'www.mysite.com' as the Identity property of EndpointAddress when creating channel proxy. "
I don't want the client to know anything about www.mysite.com. I only want them to use what the serve presents, and I want the sever to only present mysite.com.
A: Why do you want to hide it? A certificate with SAN alternatives means it is value for all of those FQDNs, so it will work on both www.mysite.com and mysite.com.
Additionally from the looks of your call to SetCertificate the subject name of the certificate is what you want, mysite.com and that's what's checked first.
The full text of the error message comes in the form of
Identity check failed for outgoing message. The expected DNS identity
of the remote endpoint was 'X' but the remote endpoint provided DNS
claim 'Y'
Now this has nothing to do with the certificate, but the host that IIS is configured for, or, in the case of self hosting, the host/machine Windows is configured to be. You can override the host that WCF will use by adding a new configuration setting for the endpoint;
<identity>
<dns value="mysite.com"/>
</identity>
or setting it in code when you create the endpoint.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Javascript page reload while maintaining current window position How do I refresh the page using Javascript without the page returning to
the top.
My page refreshes using a timer but the problem is it goes back to the top every time it reloads. It should be able to retain the current position of the page as it reloads.
P.S.
Additional mouse events are welcome if necessary to be a part of your suggestion.
I'm actually thinking of #idname to target on refresh but my HTML elements don't have IDs, only classes.
A: If there is a certain set of specific sections of the page that are possible initial "scroll to" points, then you can assign those sections CSS ids and refresh the page with an appended ID hash at the end. For example, window.location = http://example.com#section2 will reload the page and automatically scroll it down to the element with the id "section2".
If it's not that specific, you can grab the current scroll position prior to refresh using jQuery's .scrollTop() method on the window: $(window).scrollTop(). You can then append this to the refresh URL, and include JS on the page that checks for this in order to automatically scroll to the correct position upon page load:
Grab current scroll position
var currentScroll = $(window).scrollTop();
window.location = 'http://example.com#' + currentScroll;
JS that must run when DOM is ready in order to check for a currentScroll hash
$(function(){
if(window.location.hash !== ''){
var scrollPos = parseInt(window.location.hash.substring(1),10);
$(window).scrollTo(scrollPos);
}
});
If you don't like the idea of modifying the URL in the address bar (because you really want to hide what you're doing from the user for some reason), you could store the scrollTo() value in a cookie instead of the URL.
A: If you use JavaScript, this code will do the trick.
var cookieName = "page_scroll";
var expdays = 365;
// An adaptation of Dorcht's cookie functions.
function setCookie(name, value, expires, path, domain, secure) {
if (!expires) expires = new Date();
document.cookie = name + "=" + escape(value) +
((expires == null) ? "" : "; expires=" + expires.toGMTString()) +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
((secure == null) ? "" : "; secure");
}
function getCookie(name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg) {
return getCookieVal(j);
}
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function getCookieVal(offset) {
var endstr = document.cookie.indexOf(";", offset);
if (endstr == -1) endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}
function deleteCookie(name, path, domain) {
document.cookie = name + "=" +
((path == null) ? "" : "; path=" + path) +
((domain == null) ? "" : "; domain=" + domain) +
"; expires=Thu, 01-Jan-00 00:00:01 GMT";
}
function saveScroll() {
var expdate = new Date();
expdate.setTime(expdate.getTime() + (expdays*24*60*60*1000)); // expiry date
var x = document.pageXOffset || document.body.scrollLeft;
var y = document.pageYOffset || document.body.scrollTop;
var data = x + "_" + y;
setCookie(cookieName, data, expdate);
}
function loadScroll() {
var inf = getCookie(cookieName);
if (!inf) { return; }
var ar = inf.split("_");
if (ar.length == 2) {
window.scrollTo(parseInt(ar[0]), parseInt(ar[1]));
}
}
This works by using a cookie to remember the scroll position.
Now just add
onload="loadScroll()" onunload="saveScroll()"
to your body tag and all will be well.
Source(s): http://www.huntingground.freeserve.co.uk/main/mainfram.htm?../scripts/cookies/scrollpos.htm
A: You can do it using a cookie based method:
<html>
<head>
<script type="text/javascript">
var refreshPeriod = 120; // 120 Seconds
function refresh()
{
document.cookie = 'scrollTop=' + filterScrollTop();
document.cookie = 'scrollLeft=' + filterScrollLeft();
document.location.reload(true);
}
function getCookie(name)
{
var start = document.cookie.indexOf(name + "=");
var len = start + name.length + 1;
if(((!start) && (name != document.cookie.substring(0, name.length))) || start == -1)
return null;
var end = document.cookie.indexOf(";", len);
if(end == -1)
end = document.cookie.length;
return unescape(document.cookie.substring(len, end));
}
function deleteCookie(name)
{
document.cookie = name + "=" + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}
function setupRefresh()
{
var scrollTop = getCookie("scrollTop");
var scrollLeft = getCookie("scrollLeft");
if (!isNaN(scrollTop))
{
document.body.scrollTop = scrollTop;
document.documentElement.scrollTop = scrollTop;
}
if (!isNaN(scrollLeft))
{
document.body.scrollLeft = scrollLeft;
document.documentElement.scrollLeft = scrollLeft;
}
deleteCookie("scrollTop");
deleteCookie("scrollLeft");
setTimeout("refresh()", refreshPeriod * 1000);
}
function filterResults(win, docEl, body)
{
var result = win ? win : 0;
if (docEl && (!result || (result > docEl)))
result = docEl;
return body && (!result || (result > body)) ? body : result;
}
// Setting the cookie for vertical position
function filterScrollTop()
{
var win = window.pageYOffset ? window.pageYOffset : 0;
var docEl = document.documentElement ? document.documentElement.scrollTop : 0;
var body = document.body ? document.body.scrollTop : 0;
return filterResults(win, docEl, body);
}
// Setting the cookie for horizontal position
function filterScrollLeft()
{
var win = window.pageXOffset ? window.pageXOffset : 0;
var docEl = document.documentElement ? document.documentElement.scrollLeft : 0;
var body = document.body ? document.body.scrollLeft : 0;
return filterResults(win, docEl, body);
}
</script>
</head>
<body onload="setupRefresh()">
<!-- content here -->
</body>
</html>
or you can do it with a form method:
<html>
<head>
<script type="text/javascript">
// Saves scroll position
function scroll(value)
{
var hidScroll = document.getElementById('hidScroll');
hidScroll.value = value.scrollTop;
}
// Moves scroll position to saved value
function scrollMove(el)
{
var hidScroll = document.getElementById('hidScroll');
document.getElementById(el).scrollTop = hidScroll.value;
}
</script>
</head>
<body onload="scrollMove('divScroll');" onunload="document.forms(0).submit()";>
<form>
<input type="text" id="hidScroll" name="a"><br />
<div id="divScroll" onscroll="scroll(this);"
style="overflow:auto;height:100px;width:100px;">
<!-- content here -->
</div>
</form>
</body>
</html>
Just depends on your application's requirements and restrictions.
A: I would recommend refreshing only the part of the page you are interested in changing, using ajax. I mean, just replacing the content using javascript depending on the response of the ajax call. I would say you take a look at jQuery's ajax or get methods.
If you can give more information about what you are trying to do maybe I can be of more assistance. Anyway, I hope this helps a little bit.
Cheers!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: I would like to delete the row with 0 (zeroes) I honestly thought this would be easy.
Please see matrix below:
**Project Resources Hours**
TeamSite Web Developer 30
RFP Technical Writer 45
Db Conversion DBA 20
DB Conversion DB Developer 25
DB Conversion 0 0
DB Conversion 0 0
For some reason, when we add data to the db, 2 extra records of DB Conversion is added. Resources and Hours have zeros added.
We would like to NOT show any rows where values for Resources and Hours are either null or 0 even though Project Has DB Conversion value.
Here is the code I am playing with but doesn't show me, for instance, the first 4 rows where Resources and Hours are not 0.
SELECT project, Hours, Resources
FROM mytable
inner join empTable ON myTable.employeeID = empTable.employeeID
and empTable.employeeID = '@employeeId' AND (Resources <> 0 and Hours <> 0)
ORDER BY empTable.employeeID
I am either getting blank or one row. Please help.
I hope this isn't too much trouble.
Thanks a lot
A: I think that your problem is with the way you are using your parameter. It shouldn't be wrapped in '. Try this:
SELECT project, Hours, Resources
FROM mytable
inner join empTable ON myTable.employeeID = empTable.employeeID
WHERE empTable.employeeID = @employeeId AND (Resources <> 0 and Hours <> 0)
ORDER BY empTable.employeeID
A: You must find out why the extra rows are getting inserted. One approach is to put a constraint on the row so that the insert fails and work backwards from there.
I am either getting blank or one row. Please help.
As for your problem, try to break it into small parts:
*
*Drop the inner join and non-zero constraints and ensure your able to select rows for the employeeId, including the bad rows. If not, your employeeId is missing
*Add the constraints ('0' for Resources, not 0) and ensure you are able to select only good rows. If not either you did not write the predicate right or you have no good rows
*Add the inner join and ensure same result. If not, there are no rows in master table. This is a bad thing, because you have project time for non-existent employees.
A: Try this:
SELECT project, Hours, Resources
FROM mytable
inner join empTable
ON myTable.employeeID = empTable.employeeID
WHERE empTable.employeeID = @employeeId
AND (Resources <> '0' and Hours > 0)
ORDER BY empTable.employeeID
A: I think you should use table name like you used in ORDER BY clause. This will help a lot.
SELECT table_name.project, table_name.Hours, table_name.Resources
FROM mytable
inner join empTable ON myTable.employeeID = empTable.employeeID
where table_name.Resources is not null and table_name.Hours is not null and table_name.Resources <> '0'
and table_name.Hours <> '0' ORDER BY empTable.employeeID
A: Are you getting "one row"? Maybe it's the row corresponding to the empTable.employeeID.
If you want 4 rows, try this:
SELECT project, Hours, Resources
FROM mytable
inner join empTable
ON myTable.employeeID = empTable.employeeID
WHERE Resources <> '0' and Hours > 0
ORDER BY empTable.employeeID
A: Assuming following tables structure:
mytable(Projects,EmpID);
empTable(empID,hours,resources);
Using alias e and m,is more optimized to get fast results.
SELECT m.project, e.Hours, e.Resources
FROM mytable m
inner join
empTable e
ON (
m.employeeID = e.employeeID
AND
e.employeeID = @employeeId
AND
(e.Resources <> '0' AND e.Hours>0)
)
ORDER BY e.employeeID
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript 1 second apart ajax requests? Resource usage? I have a long-term goal of eventually creating a chat sort by any means, but for now I'd like to just have a simple one with some Mysql and ajax calls.
To make the chat seem instant, I'd like to have the ajax request interval as fast as possible. I get the feeling if it's as low or lower than a second, it's going to bog down the browser, the user's internet, or my server.
Assuming the server doesn't return anything, how much bandwidth and cpu/memory would the client use with constant, one second apart ajax calls?
edit: I'm still open to suggestions on how I can do a chat server. Anything that's possible with free hosting from x10 or 000webhost. I've been told of Henoku but I have no clue how to use it.
edit: Thanks for the long polling suggestion, but that uses too much cpu on the servers.
A: One technique that can be used is to use a long-running ajax request. The client asks if there's any chat data. The server receives the request. If there's chat data available, it returns that data immediately. If there is no chat data, it hangs onto the request for some period of time (perhaps two minutes) and if some chat data appears during that two minutes, the web request returns immediately with that data. If the full two minutes elapses and no chat data is received, then the ajax call returns with no data.
The client can then immediately issue another request to wait another two minutes for some data.
To make these "long" http requests work, you just need to make sure that your underlying ajax call has a timeout set for longer than the time you've set it for on the server.
On the server, you need to do an efficient mechanism of waiting for data, probably involving semaphores or something like that because you don't want to be polling internally in the server either.
Doing it this way, you can get near instantaneous response on the client, but only be making 30 requests an hour.
To be friendly to the battery of a laptop or mobile device, you need to be sensitive to when your app isn't actually being used (browser not displayed, not the current tab, etc...) and stop the requests during that time.
As to your other questions, repeated ajax calls (as long as they are spaced at least some small amount of time apart) don't really use much in the way of CPU or memory. They may use battery if they keep the computer from going into an idle mode.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Assigning Delegates to ViewController Classes Following this pattern.
// foo.m
Bar* bar = [[Bar alloc] init];
[baz setDelegate:bar];
[bar release];
I'm able to call UIImagePicker Delegates in the Bar Class. Specifically, didFinishPickingImage. However, I'm not able to set my the IBOutlet UIImageView myImageView. like.
// bar.m
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)img editingInfo:(NSDictionary *)editInfo
self.myImageView.image = img;
When I debug UIImageView, it's nil I think because the UIImage param passed to didFinishPickingImage is also blank.
My question is, why? I am assuming I set my delegate correctly as per this example.
A: You can't assign a UIImageView to a UIImage. This might work better:
self.myImageView.image = img;
A: Are you actually allocating memory for 'myImageView'? It isn't shown. That's not automatic, myImageView = [[UIImageView alloc] init]; would be needed
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In gdb sizeof(Apple::record_) is zero. But It runs well I encounterd a very strange g++ problem.
The output of the flowing program is "24 8 3", All things seems ok. But when I use gdb, to print sizeof(Apple::record_), it turns out to be 0. My gcc version is 4.5.2 (GCC)(MinGw), gdb version is GNU gdb (GDB) 7.3
Can anybody help me ??
#include <iostream>
using namespace std;
struct Record {
int age;
const char* name;
};
struct Apple {
static Record record_[];
};
Record Apple::record_[] = {
{ 18, "liming i love apple" },
{ 19, "liming" },
{ 20, "liming a y z o pq x y z o o o " } };
int main() {
cout << sizeof(Apple::record_) << " " << sizeof(Apple::record_[0]) << " "
<< sizeof(Apple::record_) / sizeof(Apple::record_[0]) << endl;
return 0;
}
A: Sounds like a bug in GDB, or in the compiler.
Your compiler is old (current is 4.6.1). You didn't say what version of GDB you are using, but it likely is not current (7.3.1) either.
If you can reproduce the problem with current version of GCC and GDB, you should file a bug report.
A: In the following version of GDB, p sizeof(Apple::record_) returns 48. (This is not 24 because the int and pointer on my system are 8 bytes each).
Perhaps the version of GDB you are using is buggy in this regard?
GNU gdb 6.3.50-20050815 (Apple version gdb-1705) (Fri Jul 1 10:50:06 UTC 2011)
Copyright 2004 Free Software Foundation, Inc.
GDB is free software, covered by the GNU General Public License, and you are
welcome to change it and/or distribute copies of it under certain conditions.
Type "show copying" to see the conditions.
There is absolutely no warranty for GDB. Type "show warranty" for details.
This GDB was configured as "x86_64-apple-darwin".
Just for comparison's sake, here's my gcc version as well.
i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)
Copyright (C) 2007 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: inline tags not showing on ie using jQuery I am facing problem rendering the contents of inline tag span. If i use div instead of span the contents are shown.
for (all objects in array) {
var A = jQuery("<img src='xyz'>")
if(some condition) {
var b = jQuery("<span class='X'>");
b.append(A);
A = b;
}
A.addClass(random);
} // for ends
In Ie8 n 9 the object which has condition true is not displayed. whereas it is displayed in mozilla, chrome, and safari.
any pointers will be really helpful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Actionscript 3, Parsing JSON Data problem I am sending a request to a server, and in return I get a long block of JSON.
{
"response":"success",
"assignments":{
"17733":{
"asnid":"17733",
"asnname":"Yitzhak Rabin PPT",
"asnclass":"11276",
"asndue":"2011-10-03",
"asnnotes":"5 Slides in Hebrew",
"asnpriority":"0",
"asnstatus":"open"
},
"9811":{
"asnid":"9811",
"asnname":"Java Chapter 1",
"asnclass":"11270",
"asndue":"2011-09-09",
"asnnotes":"Review Exercises 1-14. Programming Exercises 1-6 ",
"asnpriority":"0",
"asnstatus":"done"
},
"9815":{
"asnid":"9815",
"asnname":"Hebrew Poems",
"asnclass":"11276",
"asndue":"2011-09-12",
"asnnotes":"1 Name based poem, and One byline poem. See sheet for further reference.",
"asnpriority":"0",
"asnstatus":"done"
},
"11096":{
"asnid":"11096",
"asnname":"Java Ethics Essay",
"asnclass":"11270",
"asndue":"2011-09-15",
"asnnotes":"",
"asnpriority":"0",
"asnstatus":"done"
}
}
}
In order to parse this data I was using the com.adobe.serialization.json.JSON class. The class turned the data into objects but the problem is I need to check whats in object "17733" or "9811" and get an error.
" 1084: Syntax error: expecting rightparen before .17733"
My code is the following:
if (task == "getAssignments")
{
//trace(loader.data);
var getAssnNumbers:Object = JSON.decode(loader.data);
//Decode JSON Data
for(var i:* in getAssnNumbers.assignments.17733)
{
assnNumbers.push(i);
trace(i);
}
//Try to trace the data stored in getAssnNumbers.assigments.17733
}
Is there a way to do this? I checked if the property was enumerated and it returned true, but I cant find a way to access this data.
A: Try accessing your property using the bracket notation:
getAssnNumbers.assignments["17733"]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Merging arrays of different types i have two arrays:
$a =array(
'standard' => (object) array( 'id' => 'standard', 'title' => 'AustPost Standard' ),
'registered' => (object) array( 'id' => 'registered', 'title' => 'AustPost Registered' ),
'insured' => (object) array( 'id' => 'insured', 'title' => 'AustPost Insured' ),
'express' => (object) array( 'id' => 'express', 'title' => 'AustPost Express' ),
'satchexp' => (object) array( 'id' => 'satchexp', 'title' => 'AustPost Satchel Express' ),
'satchreg' => (object) array( 'id' => 'satchreg', 'title' => 'AustPost Satchel Registered' ),
'satchpla' => (object) array( 'id' => 'satchpla', 'title' => 'AustPost Satchel Platnium' )
);
and
$b = array( 'standard', 'sea', 'air', 'satchexp', 'satchreg', 'satchpla' )
how can i create a new array $c that has only elements from array $a that appear in array $b?
A: It's called array intersection
You can do it either by key or value.
In your case in $a you have (standard', 'sea', 'air'..) as keys, but in $b those words are actually values and the keys are (0, 1, 2...)
You can easilly flip the array $b to make the words array keys. Then you can intersect arrays by keys
$c = array_intersect_key($a, array_flip($b));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Read in Haskell It's possible to use the Scheme primitive read, which consumes a stream of characters and outputs an s-expression (sexpr).
I'm trying to write a parser in Haskell. What is the equivalent of the above? How would I implement it so that, if passed "{+ {- 3 4} 7}" it returns (list '+ (list '- 3 4) 7) (or the equivalent)?
Thanks in advance.
A: You'd be better off using a proper parsing library like uu-parsinglib, polyparse or parsec.
You can abuse Read to parse an arbitrary String into some data representation (which you'll have to define).
A: I think one of the first questions all those new to haskell should ask when they want to know "Can I do something?" is "What should the types be?". If you wanted to do what you're after, then I would suggest writing an AST like so:
data AST = Num Int
| Add AST AST
| Sub AST AST
| Mul AST AST
etc.
Then you could write a parser of potentially with the type:
parseAST :: String -> AST
To actually write this parser, you'll probably want to use something like parsec, though if the grammar is how you've described, then you could probably write your own parsed by hand that would work quite well (and help you learn).
From there, you can write functions that can evaluate the AST, or manipulate it however you like. But it is important to realise that you can't* create new code at runtime, because that's very likely to not be type safe, or safe at all.
* I'm sure there are ways to do this, but I felt that it was more important to foster the ideas that a beginning haskell programmer should learn before moving onto more advanced topics.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How does a HTTP Proxy utilize the HTTP protocol? a Proxy RFC? How does one go about implementing a HTTP proxy compared to implementing a HTTP webserver, what are the differences? Is there a definitive guide or RFC or a helpful book on this subject?
A: A proxy is very similar to a server; the only difference is that, after parsing the request, it merely forwards it and returns the result*, rather than processing the request, itself. Because the proxy does not have to do the same amount of processing as a normal server, it can often get away with a far more minimal parsing of the requests than a full-fleded server, but otherwise it is the same idea.
*Some proxies implement additional caching. Some also futz with the response/request, but that is the evil kind of proxy, which hopefully you do not have in mind.
A: The header sent to a proxy is different.
For example, here is what is sent by Google Chrome to www.baidu.com via a proxy server:
GET http://www.baidu.com/ HTTP/1.1
Host: www.baidu.com
Proxy-Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
DNT: 1
Accept-Encoding: gzip, deflate, sdch
Accept-Language: zh-CN,zh;q=0.8
We can see it is
GET http://www.baidu.com/ HTTP/1.1
instead of
GET / HTTP/1.1
and here is
Proxy-Connection: keep-alive
also
Host: www.baidu.com
Host field is required for http proxy.
For HTTPS tunnel proxy:
CONNECT comet.zhihu.com:443 HTTP/1.1
Host: comet.zhihu.com:443
Proxy-Connection: keep-alive
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
We can see
CONNECT comet.zhihu.com:443 HTTP/1.1
domain:443 instead of https://domain.
CONNECT field turn the proxy server to something like a TCP tunnel, then the protocol HTTPS is replaced by the port :443
For socks5 proxy, things become easy, because socks5 care nothing about higher protocol, you just tell it host and port.
A: The requirements on HTTP Proxy servers are specified within
*
*RFC7230 - Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and
Routing
*RFC7231 - Hypertext Transfer Protocol (HTTP/1.1):
Semantics and Content
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "46"
}
|
Q: empty ui:repeat, is the component created? I am trying to debug an issue with the following code:
<h:panelGroup id="items">
<ui:repeat value="#{itemController.items}" var="item">
<h:form>
<h:inputText id="title" value="#{item.fields['Title']}"/>
<a4j:commandButton action="#{dao.storeItem(item)}" value="Save" render="@form"/>
</h:form>
</ui:repeat>
</h:panelGroup>
The above works if a collection is displayed in the view directly. However, if the ui:repeat starts empty, and items are added through an AJAX request, and the ui:repeat rerendered, the forms break. Specifically the model is not updated, nor actions triggered. I want to understand why.
Right now my guess is that if the ui:repeat starts empty, the form component is not created at all. Can anyone verify this, or provide the correct explanation?
ADDITIONAL INFO
Here are relevant parts of the controller, I have also tried ViewScoped, and long-running conversations:
@Named
@ConversationScoped
public class ItemController implements Serializable
{
private static final long serialVersionUID = 1L;
@Inject
private HibernateDAO dao;
public List<Item> getItems()
{
return dao.getItems();
}
public void uploadListener(final FileUploadEvent event)
{
final UploadedFile item = event.getUploadedFile();
final FacesContext context = FacesContext.getCurrentInstance();
final Application application = context.getApplication();
final String messageBundleName = application.getMessageBundle();
final Locale locale = context.getViewRoot().getLocale();
final ResourceBundle resourceBundle = ResourceBundle.getBundle(messageBundleName, locale);
final String msg = resourceBundle.getString("upload.failed");
final String detailMsgPattern = resourceBundle.getString("upload.failed_detail");
try
{
CSVImporter.doImport(item.getInputStream(), dao, item.getName());
}
catch (ParseException e)
{
final Object[] params = {item.getName(), e.getMessage()};
final String detailMsg = MessageFormat.format(detailMsgPattern, params);
final FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, detailMsg);
context.addMessage("uploadForm:uploader", facesMsg);
}
catch (TokenMgrError e)
{
final Object[] params = {item.getName(), e.getMessage()};
final String detailMsg = MessageFormat.format(detailMsgPattern, params);
final FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, detailMsg);
context.addMessage("uploadForm:uploader", facesMsg);
}
}
}
The dao simple fetches the items from a database. Here is the relevant fileupload code:
<h:form id="uploadForm" enctype="multipart/form-data">
<h:message id="message" showDetail="true" for="uploader" errorClass="error" warnClass="warning" infoClass="info" fatalClass="fatal"/>
<rich:fileUpload id="uploader"
fileUploadListener="#{itemController.uploadListener}"
maxFilesQuantity="1"
acceptedTypes="csv"
render="items message" />
</h:form>
A: Okay posting it here because it will be longer than comments .
It works for me which is probably not what you wanted to hear :( but I had to teak few minor things . Firstly in controller add
public void storeItems(Item item)
{
dao.storeItems();
}
then change this
<a4j:commandButton action="#{dao.storeItem(item)}" value="Save" render="@form"/>
to
<a4j:commandButton action="#{itemController.storeItem(item)}" value="Save" render="@form"/>
That however is probably not the real issue and I think that is around here
CSVImporter.doImport(item.getInputStream(), dao, item.getName());
basically I am expecting that the method above would have uploaded data from where dao.getItems(); can fetch it. So put a breakpoint at public List<Item> getItems() and once file has been upload and render="items message" renders the items panel group again it should will hit this method and at that time see if dao.storeItems() is bringing any data back which it should. Reply back then and we will take it from there.
Update below to avoid running dao fetch twice.
You can not avoid two calls to your get thats part of JSF lifeCycle and is normal.
How ever you can avoid hitting the database twice as you should too but refactoring your code along the lines of
private List<Item> items;
public List<Item> getItems()
{
return items;
}
@PostConstruct
public void init()
{
this.items = dao.getItems();
}
public void uploadListener(FileUploadEvent event) throws Exception{
......
CSVImporter.doImport(item.getInputStream(), dao, item.getName());
this.items = dao.getItems();
.....
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577918",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Redis: possible to expire an element in an array or sorted set? Is it currently only possible to expire an entire key/value pair? What if I want to add values to a List type structure and have them get auto removed 1 hour after insertion. Is that currently possible, or would it require running a cron job to do the purging manually?
A:
Is it currently only possible to expire an entire key/value pair?
As far as I know, and also according to key commands and document about expiration, currently you can set expiration only to specific key and not to it's underlying data structure. However there is a discussion on google groups about this functionality with outlined alternative solutions.
A: I came upon a different method of handling this, don't know if it's helpful to any of you,but here goes:
The hash and the sorted set are linked by a guid.
*
*I have a hash that is set to expire in 'x' seconds
*I have a sorted set that is used for ranged queries
*The data for both is added in a transaction, so if one fails, they both fail.
*Upon a ranged query, use 'EXISTS' to see if the hashed value exists as the results are iterated over
*If it does not exist, it has expired, so delete the item from the sorted set
A: There is a common pattern that solves this problem quite well.
Use sorted sets, and use a timestamp as the score. It's then trivial to delete items by score range, which could be done periodically, or only on every write, with reads always ignoring the out of range elements, by reading only a range of scores.
More here: https://groups.google.com/forum/#!topic/redis-db/rXXMCLNkNSs
A: What about creating two seperate sorted sets?
Main sorted set which is key = value.
Expire sorted set which is key = expire_timestamp.
If you only want to expire a single score you can set as key:unique_id = expire_timestamp.
With mercy of zrangebyscore we can get expired keys. Then all we need to do is check periodically and zrem.
If you only want to expire a single score: zincrby -1.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "150"
}
|
Q: In Codeigniter: How to identify the model and controller of the views? Is there a way to identify the model name and controller name of the views like print_r($model) or print_r($controller)?
For example:
view.php
<div class="data">
<?php
echo "this is from".$controller;
echo "this is from".$model;
?>
</div>
A: You shouldn't be passing stuff from the model straight to the view. http://codeigniter.com/user_guide/overview/mvc.html and http://codeigniter.com/user_guide/overview/appflow.html
If you want to pass information to the you can do this.
model_name.php
//Class Declaration
function get_data()
{
return 'This is the Model Data';
}
controller.php
//Class Declaration
function index()
{
$data['controller'] = 'Data From the Controller';
$data['model'] = $this->Model_Name->get_data();
$this->load->view('view.php', $data);
}
The View remains the same as you have.
A: A controller can call from multiple models and the view is designated by the controller (or included in a view designated by the controller). You really shouldn't call data from the model directly into the view.
You could get the controller name from the appropriate URI segment if you're not using routes (or otherwise) to change the segment name. I'm not sure it's even possible to have two controllers at a time. Then again, I've never had the need to even try.
I suppose you could manually set variables in the controller under every function and echo them out on the page, but there isn't a built-in, automated way to do what you're looking for.
A: You can get the name of the controller with this:
$this->router->fetch_class();
You have to pass controller name to view (as a variable).
But you cannot identify model in the view - there could be more than one model (in one controller). The best way is to create method in your model and assign it to variable passed to the view.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577928",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can a child process return two values to the parent when using pipe()? I have my child process counting the frequency of words from a text file. I am using pipe() for IPC. How can the child process return both the word name and the word frequency to the parent process? My source code is in C and I am executing it in a UNIX environment.
A: Write the two values to one end of the pipe in the child, separated by some delimiter. In the parent, read from the other end of the pipe, and separate the content using the delimiter.
A: Writes to a pipe up to the size of PIPE_BUF are atomic (included in limits.h), therefore you can easily pack your information into some type of struct, and write that to the pipe in your child process for the parent process to read. For instance, you could setup your struct to look like:
struct message
{
int word_freq;
char word[256];
};
Then simply do a read from your pipe with a buffer that is equal to sizeof(struct message). That being said, keep in mind that it is best to only have either a single reader/writer to the pipe, or you can have multiple writers (because writes are atomic), but again, only a single reader. While multiple readers can be managed with pipes, the fact that reads are not atomic means that you could end up with scenarios where messages either get missed due to the non-deterministic nature of process scheduling, or you get garbled messages because a process doesn't complete a read and leaves part of a message in the pipe.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I display a native iOS/Android UI control/element in an HTML5 app? LinkedIn does this LinkedIn says the following about their new high-performance mobile app: “There’s this battle between HTML5 web apps and native apps. But we’ve interspersed HTML5 in the native app, where web-based content excels. The things that are hard to do in HTML5 are a scrolling infinite list, so we went native with that.”' via How LinkedIn used Node.js and HTML5 to build a better, faster app
How can I display a native iOS/Android UI control/element in an HTML5 app?
How can we display a scrolling infinite list in PhoneGap?
A:
How can I display a native iOS/Android UI control/element in an HTML5 app?
You can't. The quote you highlighted says "we've interspersed HTML5 in the native app", not "we've interspersed native controls in the HTML5 app". Read it again.
How can we display a scrolling infinite list in PhoneGap?
PhoneGap just adds device APIs to a webview. It doesn't generate native controls, so you can't, not without extending PhoneGap.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Android, HTTP GET not returning I have an Android app that sends commands to a robot via HTTP. (The robot server is written in Python using the BaseHttpServer class.) I'm setting up my connection in the app correctly as far as I can tell, but most requests fail to return and if they do there is a very long delay. Here is the initialization code:
private void setupHttpStuff() {
HttpParams params = new BasicHttpParams();
ConnManagerParams.setMaxTotalConnections(params, 10);
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(
new Scheme("http", PlainSocketFactory.getSocketFactory(), 1504));
ClientConnectionManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
this.HttpClient = new DefaultHttpClient(cm, params);
}
The GET request takes place in an AsyncTask and the code looks like:
HttpContext localContext = new BasicHttpContext();
HttpGet httpGet = new HttpGet(url);
mClient.execute(httpGet, localContext);
Where mClient is a variable shared from the Activity.
By using Log.d messages I've determined that the first two requests work fine but then all subsequent requests (in separate AsyncTasks) hang and never return from execute. I've also tried to manually create a Socket and send a HttpRequest:
Socket socket = new Socket("192.168.1.45", 1504);
HttpParams params = new BasicHttpParams();
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
conn.bind(socket, params);
HttpRequest request = new BasicHttpRequest("GET", "/");
conn.sendRequestHeader(request);
HttpResponse response = conn.receiveResponseHeader(); // Hangs here
conn.receiveResponseEntity(response);
socket.close();
But this hangs on the conn.receiveResponseHeader() line and the server never sees the request.
The Python server works fine with requests from a browser, just not with my Android app. I've tried this single-threaded as well in the main UI but the same effect occurs.
EDIT
Here is the Python code that causes the problems:
class MyHand(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
qv = parse_qs(get_qs(urlparse(self.path)))
if("method" not in qv):
self.send_nack()
elif(qv["method"][0] == "drive"):
createbot.Drive(int(qv["velocity"][0]), int(qv["radius"][0]))
self.send_ack()
else:
self.send_nack()
def send_ack(self, content_type='text/html'):
self.send_response(200)
self.send_header('Content-type', content_type)
self.end_headers()
def send_nack(self):
self.send_response(500)
self.send_header('Content-type', 'text/html')
self.end_headers()
A: This may be related to keep-alive. Android sends Connection: Keep-Alive and Python sends back a Connection: close. I've looked at the HTTP headers that are being sent from Firefox and HttpClient and there is no difference (other than Firefox sending some additional Accept headers). Somehow Android is expecting the Python server to send something other than HTTP/1.1 200 OK\nContent-type: text/html and therefore keeping the socket open. I ended up writing my own basic HTTP server and client.
Python code:
class SingleTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request.recv(1024)
parts = data.rsplit(" ")
if (parts[0] != "GET"):
self.request.close()
return
url = parts[1].split("?")[1]
qv = parse_qs(url)
...
Android:
Socket socket = null;
PrintWriter output = null;
try {
socket = new Socket(this.ipAddress, this.portNo);
output = new PrintWriter(new BufferedWriter
(new OutputStreamWriter(socket.getOutputStream())), true);
output.println("GET " + url);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (socket != null)
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
if (output != null)
output.close();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rails add value to instance variable I'm extremely new to RoR and am experiencing a roadblock in my learning.
I created a scaffold against a performers db table that has a foreign key tie to a genres table as a lookup table for the performers genres.
What I'm attempting to do is to use the the genre_id from the current performer row in a find against the genres table to extract the genre name. I have everything working as desired in the list action except I can't seem to figure out how to add a "genre_name" => @genre[:genre_name] into the @performers instance variable so that it will propagate through to the view.
In my list action, I have the following code, but am obviously doing it wrong and would really appreciate if someone could steer me right.
def list
@performer_pages, @performers = paginate :performers, :per_page => 10
@performers.each do |performer|
#logger.debug(performer[:genre_id])
@genre = Genre.find(performer[:genre_id], :select => 'genre_name')
@performers[performer[:id]][:genre_name] = @genre[:genre_name]
^-- THIS IS THE LINE I AM STUCK ON
end
logger.debug(@performers.inspect)
end
Thanks
A: You should be using associations, they will make this very easy.
In your Performer model, you should have a belongs_to :genre line.
In your Genre model, you should have a has_many :performers line.
Now in your code, you can access the name of a genre with this: (assuming you already have a @performer)
@performer.genre.genre_name
I hope this helps put you on the right track!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to change the scale of UIWebView after loading an online web page? I would like users to pinch in my UIWebView and already set the ScaleToFitPages to YES.
The page content does not contains anything like
<meta name='viewport' content='width=device-width; initianl-scale=1; maximum-scale:4; ....'>
Could I use any javascript code(jquery or not with jquery) to change the scale to original scale(1:1) after the page loaded(eg. in the delegate method didFinishLoading...)
A: In UIWebViewDelegate , there is protocol webViewDidFinishLoad:that will be call after a web view finishes loading a frame.
so you can put some javascript that custom the scale
[webView stringByEvaluatingJavaScriptFromString: [NSString stringWithFormat:@"your javascript code" ];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: request size problem in apache + weblogic with mod_wl.so We´re using apache (2.0, with ssl) to proxy the requests to a web service installed on weblogic. We have mod_wl.so installed, and all works fine with small requests.
However, with larger requests (say, 300 KB), the apache stalls and display this error message:
"Failure of server APACHE bridge: No Backend Sever available for connections": timed out after 20 seconds or idempotent is set to off."
We replicate the scenario in another server, and the error persists (instead of "20 seconds", it says "30 seconds" for the same request).
How can I avoid this size limitation? Is it a bug in mod_wl.so? Is it a config value that is missing? (As a side note, the web service works fine when tested directly from inside the weblogic console, no matter how big the file)
Thanks for any help!
UPDATE:
changed to mod_wl_20.so with same results, here is the chunk of the log:
Wed Sep 28 11:27:37 2011 <15359131722005124> Hdrs to WLS:[Content-Length]=[352196]
Wed Sep 28 11:27:37 2011 <15359131722005124> Hdrs to WLS:[Connection]=[Keep-Alive]
Wed Sep 28 11:27:37 2011 <15359131722005124> Hdrs to WLS:[WL-Proxy-SSL]=[true]
Wed Sep 28 11:27:37 2011 <15359131722005124> Hdrs to WLS:[WL-Proxy-Client-IP]=[163.247.57.10]
Wed Sep 28 11:27:37 2011 <15359131722005124> Hdrs to WLS:[Proxy-Client-IP]=[163.247.57.10]
Wed Sep 28 11:27:37 2011 <15359131722005124> Hdrs to WLS:[X-Forwarded-For]=[163.247.57.10]
Wed Sep 28 11:27:37 2011 <15359131722005124> Hdrs to WLS:[X-WebLogic-KeepAliveSecs]=[30]
Wed Sep 28 11:27:37 2011 <15359131722005124> Hdrs to WLS:[X-WebLogic-Request-ClusterInfo]=[true]
Wed Sep 28 11:27:37 2011 <15359131722005124> Hdrs to WLS:[x-weblogic-cluster-hash]=[2Ik836PQKnD7XHQ2RcWGOWkcRRA]
Wed Sep 28 11:27:37 2011 <15359131722005124> operation WRITE failed on fd 23: revents=0x00000018
Wed Sep 28 11:27:37 2011 <15359131722005124> IO TImed out error
Wed Sep 28 11:27:37 2011 <15359131722005124> POST timed out to the server 10.182.5.5:7005
Wed Sep 28 11:27:37 2011 <15359131722005124> ***Exception type [WRITE_ERROR_TO_SERVER] (POST ti
med out to the server 10.182.5.5:7005
) raised at line 152 of ap_proxy.cpp
Wed Sep 28 11:27:37 2011 <15359131722005124> error sending headers or Post Data to WebLogic, sys er
r#: [0] sys errmsg [Success]
Wed Sep 28 11:27:37 2011 <15359131722005124> Marking 10.182.5.5:7005 as bad
Wed Sep 28 11:27:37 2011 <15359131722005124> got exception in sendRequest phase: WRITE_ERROR_TO_SER
VER [os error=0, line 152 of ap_proxy.cpp]: POST timed out to the server 10.182.5.5:7005
at line 2994
Wed Sep 28 11:27:37 2011 <15359131722005124> Failing over after WRITE_ERROR_TO_SERVER exception in
sendRequest()
Wed Sep 28 11:27:37 2011 <15359131722005124> attempt #1 out of a max of 10
Wed Sep 28 11:27:37 2011 <15359131722005124> No good servers left in the general list, reverting ba
ck to the static list
Wed Sep 28 11:27:37 2011 <15359131722005124> Host extracted from serverlist is [10.182.5.5]
Wed Sep 28 11:27:37 2011 <15359131722005124> Host extracted from serverlist is [10.182.5.5]
Wed Sep 28 11:27:37 2011 <15359131722005124> Initializing lastIndex=0 for a list of length=2
A:
Post timed out to 10.182.5.5:7005
This is the WebLogic which Apache is trying to post to.
You have confirmed this works when directly posted to the same Weblogic server.
The 20 seconds mathces the default KeepAliveSecs which you can try to increase.
Have you set a value in the plugin for WLIOTimeoutSecs.
This defaults to 300. Defines the amount of time in seconds the plug-in waits for a response to a request from WebLogic Server.
But from your log it does not look like Apache is waiting for 300 seconds before failing.
Similarly MaxPostSize defaults to -1, just check that you have not set some low value for that.
Check out the other plugin parameters on this list
http://download.oracle.com/docs/cd/E12840_01/wls/docs103/plugins/plugin_params.html#wp1143055
You might also want to tinker with the FileCaching element for POST requests
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Put current time date in hidden field I would like to put the current time/date into a hidden text field with the format 19:19:09 Sep 27, 2011
<input type="hidden" name="current_date" value="" readonly="readonly">
Thank you
A: http://php.net/manual/en/function.date.php
<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
?>
<input type="hidden" name="current_date" value="<?php echo $today?>" readonly="readonly">
A: <input type="hidden" name="current_date" value="<?php echo date('H:i:s M d, Y'); ?>" readonly="readonly">
But you should know that the user can change the value easily.
Edit:
Use date_default_timezone_set to set the timezone.
The timezone of Australia is listed here: http://www.php.net/manual/en/timezones.australia.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Best Way To Store Tons of Data I'm working on an application that will need to pull from a list of data depending on where the user is located in the US. In a sense, I will have a database full of information based on their location, and a condition statement will determine while value from the list to use.
Example of data:
Tennessee:
Data2 = 25;
Data3 = 58;
...
Texas:
Data2 = 849;
Data3 = 9292;
...
So on...
My question is, what is the best practice to use when developing iOS apps and you have a lot of data? Should you just put all the related data in a file, and import that file when you need to like normal, or is there another method you should use? I know they state you should follow the MVC practice, and I think in this case my data would be considered the Model, but just want to double check if that applies here.
A: You have some options here:
*
*SQLite database
*Core Data (its not a relational database model like sqlite)
*write to plain text file. (using NSFileManager )
*NSKeyedArchiever
If you want to frequently keep appending data to a single file, I would recommend using sqlite fast and robust.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Layout with 2 TextViews on left and CheckBox on right has text over checkbox I am trying to have a complex ListView that has a Title and Description on the Left side and a Checkbox on the right side. I am doing this, but the text on the left is going over the Checkbox on the right.
How can I prevent that?
My layout code currently looks like:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:paddingTop="10dip"
android:paddingBottom="10dip"
android:paddingLeft="15dip">
<CheckBox
android:id="@+id/list_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:checked="false"
/>
<TextView
android:text="Some Title"
android:id="@+id/list_complex_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_toLeftOf="@+id/list_checkbox"
android:textAppearance="?android:attr/textAppearanceLarge"
/>
<TextView
android:text="Some long description Some long description Some long description Some long description Some long description."
android:id="@+id/list_complex_caption"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#98AFC7"
android:layout_below="@+id/list_complex_title"
android:textAppearance="?android:attr/textAppearanceSmall"
/>
</RelativeLayout>
Unfortunately I'm new to the site and need more points to post image :(
If possible, I would like to center the Checkbox vertically as well.
Any layout experts?
A: Write a statement
android:layout_toLeftOf="@+id/list_checkbox"
In your description textview so that it will be not goes over to checkbox
A: Nothing to do more. .
As per your Layout Code, Just give Left margin to the TextView that is going over the Checkbox.
It Will solve your problem.
I have done it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: observer-only jgroups cluster members? We are using jGroups to build two clusters: "server" and "app". They are independent clusters, running on different machines (communicating with each-other over JMS). Some of our code needs to run on only one node in a cluster, so we use the "coordinator" / master concept in jGroups to choose the node where to run that code.
We have yet another requirement: we need to notify server admin, when any of our cluster nodes die. We could have each cluster node monitor for membership changes, but we cannot send failure notifications from "app" cluster nodes, only from "server" cluster nodes.
Finally, the question: is it possible to join a jGroups channel/cluster without participating in the coordinator/master election? So that "server" cluster nodes could join "app" cluster as observer-only members (receiving "view changed" events, but not participating in the elections)?
A: I am not very clear on the requirement, but the following solution might work:
Include a "nodeType" property in your application and read it from a properties file.
Change the election algorithm so that only "app" node types participate in election, node types "server" discard the election messages.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How are heaps created in mixed language applications? We have a front end written in Visual Basic 6.0 that calls several back end DLLs written in mixed C/C++. The problem is that each DLL appears to have its own heap and one of them isn’t big enough. The heap collides with the program stack when we’ve allocated enough memory.
Each DLL is written entirely in C, except for the basic DLL wrapper, which is written in C++. Each DLL has a handful of entry points. Each entry point immediately calls a C routine. We would like to increase the size of the heap in the DLL, but haven’t been able to figure out how to do that. I searched for guidance and found these MSDN articles:
http://msdn.microsoft.com/en-us/library/hh405351(v=VS.85).aspx
These articles are interesting but provide conflicting information. In our problem it appears that each DLL has its own heap. This matches the “Heaps: Pleasures and Pains” article that says that the C Run-Time (C RT) library creates its own heap on startup. The “Managing Heap Memory” article says that the C RT library allocated out of the default process heap. The “Memory management options in Win32” article says the behavior depends on the version of the C RT library being used.
We’ve temporarily solved the problem by allocating memory from a private heap. However, in order to improve the structure of this very large complex program, we want to switch from C with a thin C++ wrapper to real C++ with classes. We’re pretty certain that the new and free operator won’t allocate memory from our private heap and we’re wondering how to control the size of the heap C++ uses to allocate objects in each DLL. The application needs to run in all versions of desktop Windows-NT, from 2000 through 7.
The Question
Can anyone point us to definitive and correct documentation that
explains how to control the size of the heap C++ uses to allocate
objects?
Several people have asserted that stack corruption due to heap allocations overwriting the stack are impossible. Here is what we observed. The VB front end uses four DLLs that it dynamicly loads. Each DLL is independant of the others and provides a handful of methods called by the front end. All the DLLs comunicate via data structures written to files on disk. These data structures are all structured staticlly. They contain no pointers, just value types and fixed sized arrays of value types. The problem DLL is invoked by a single call where a file name is passed. It is designed to allocate about 20MB of data structures required to do complete its processing. It does a lot of calculation, writes the results to disk, releases the 20MB of data structures, and returns and error code. The front end then unloads the DLL. While debugging the problem under discussion, we set a break point at the beginning of the data structure allocation code and watched the memory values returned from the calloc calls and compared them with the current stack pointer. We watched as the allocated blocks approached the the stack. After the allocation was complete the stack began to grow until it overlapped the heap. Eventually the calculations wrote into the heap and corrupted the stack. As the stack unwound it tried to return to an invalid address and crashed with a segmentation fault.
Each of our DLLs is staticly linked to the CRT, so that each DLL has its own CRT heap and heap manager. Microsoft says in http://msdn.microsoft.com/en-us/library/ms235460(v=vs.80).aspx:
Each copy of the CRT library has a separate and distinct state.
As such, CRT objects such as file handles, environment variables, and
locales are only valid for the copy of the CRT where these objects are
allocated or set. When a DLL and its users use different copies of the
CRT library, you cannot pass these CRT objects across the DLL boundary
and expect them to be picked up correctly on the other side.
Also, because each copy of the CRT library has its own heap manager,
allocating memory in one CRT library and passing the pointer across a
DLL boundary to be freed by a different copy of the CRT library is a
potential cause for heap corruption.
We don't pass pointers between DLLs. We aren't experiencing heap corruption, we are experiencing stack corruption.
A: OK, the question is:
Can anyone point us to definitive and correct documentation that
explains how to control the size of the heap C++ uses to allocate
objects?
I am going to answer my own question. I got the answer from reading Raymond Chen's blog The Old New Thing, specifically There's also a large object heap for unmanaged code, but it's inside the regular heap. In that article Raymond recommends Advanced Windows Debugging by Mario Hewardt and Daniel Pravat. This book has very specific information on both stack and heap corruption, which is what I wanted to know. As a plus it provides all sorts of information about how to debug these problems.
A: Could you please elaborate on this your statement:
The heap collides with the program stack when we’ve allocated enough memory.
If we're talking about Windows (or any other mature platform), this should not be happening: the OS makes sure that stacks, heaps, mapped files and other objects never intersect.
Also:
Can anyone point us to definitive and correct documentation that explains how to control the size of the heap C++ uses to allocate objects?
The heap size is not fixed on Windows: it grows as the application uses more and more memory. It will grow until all available virtual memory space for the process is used. It is pretty easy to confirm this: just write a simple test app which keeps allocating memory and counts how much has been allocated. On a default 32-bit Windows you'll reach almost 2Gb. Surely, initially the heap doesn't occupy all available space, therefore it must grow in the process.
Without many details about the "collision" it's hard to tell what's happening in your case. However, looking at the tags to this question prompts me to one possibility. It is possible (and happens quite often, unfortunately) that ownership of allocated memory areas is being passed between modules (DLLs in your case). Here's the scenario:
*
*there are two DLLs: A and B. Both of them created their own heaps
*the DLL A allocates an object in its heap and passes the pointer and ownership to B
*the DLL B receives the pointer, uses the memory and deallocates the object
If the heaps are different, most heap managers would not check if the memory region being deallocated actually belongs to it (mostly for performance reasons). So they would deacllocate something which doesn't belong to them. By doing that they corrupt the other module's heap. This may (and often does) lead to a crash. But not always. Depending on your luck (and particular heap manager implementation), this operation may change one of the heaps in a manner that the next allocation will happen outside of the area where the heap is located.
This often happens when one module is managed code, while the other is native one. Since you have the VB6 tag in the question, I'd check if this is the case.
A: If the stack grows large enough to hit the heap, a prematurely aborted stack overflow may be the problem: Invalid data is passed that does not satisfy the exit condition of some recursion (loop detection is not working or not existing) in the problem DLL so that an infinite recursion consumes ridiculously large stack space. One would expect such a DLL to terminate with a stack overflow exception, but for maybe compiler / linker optimizations or large foreign heap sizes it crashes elsewhere.
A: Heaps are created by the CRT. That is to say, the malloc heap is created by the CRT, and is unrelated to HeapCreate(). It's not used for large allocations, though, which are handed off to the OS directly.
With multiple DLLs, you might have multiple heaps (newer VC versions are better at sharing, but even VC6 had no problem if you used MSVCRT.DLL - that's shared)
The stack, on the other hand, is managed by the OS. Here you see why multiple heaps don't matter: The OS allocation for the different heaps will never collide with the OS allocation for the stack.
Mind you, the OS may allocate heap space close to the stack. The rule is just no overlap, after all, there's no guaranteed "unused separation zone". If you then have a buffer overflow, it could very well overflow into the stack space.
So, any solutions? Yes: move to VC2010. It has buffer security checks, implemented in quite an efficient way. They're the default even in release mode.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Creating a constant time data structure for DOM element references Relevant discussion.
I understand I can build an array of references to elements/nodes. I realize also that I could use the neat trick of treating an array like a heap (index 2n and 2n+1 for children) to build a (potentially wasteful) binary search tree using it.
But all that's still not enough for the premature optimizer in me. Besides, implementing a BST is going to be bug prone.
Here's my question. Can I somehow use an element reference as index into javascript's hashes (which are objects, or vice versa?). If not, can I conjure up a unique string from an element reference, which I can then use as my hash key? If not, how the hell does jQuery do it?
A: The easiest option is to just use your own attribute on the DOM object:
var element = document.getElementById("test");
element.myData = "whatever";
Here's the general idea behind how jQuery's .data() function works that you could use in your own plain javascript. It uses one custom attribute on the object and then stores everything else in a data structure indexed by the value of that custom attribute.
var idCntr = 0; // global cntr
var data = {};
var element = document.getElementById("test");
var id = element.uniqueID;
if (!id) {
id = idCntr++ + "";
element.uniqueID = id;
}
data[id] = "whatever";
// then some time later, you can do this
var element = document.getElementById("test");
console.log(data[element.uniqueID]); // whatever
It is a bit more involved to store multiple attributes for a given object in the data object, but this is the general idea.
And, if you can use jQuery, it's trivial:
$("#test").data("myData", "whatever"); // sets the data
console.log($("#test").data("myData")); // retrieves the data
If you want to really see how jQuery's .data() works, you can step through the first call to set data and then retrieve it when using the unminified jQuery. It's easy to see what it does.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I jump from while(getline(cin,tmp))? I am reading 'generic programming and the stl'
in chapter1, this is a sample like this,
int main()
{
vector<string> v;
string tmp;
while(getline(cin,tmp)) //problem is here, it keep asking me to input value
v.push_back(tmp);
sort(v.begin(), v.end());
copy(v.begin(), v.end(), ostream_iterator<string>(cout,"\n"));
return 0;
}
how do I get out of the while, it keep asking me to input value, no ending....
A: Send an end-of-file character: you can use CTRL-Z Return (Windows), or CTRL-D (Unix terminals). Then, getline will return false as there is nothing more to read from stdin.
An alternative is: pipe the output of another program into this one.
A: Your program asks for input until it reaches the EOF. Use CtrlD on UNIX-like systems or CtrlZ on Windows to send EOF to indicate end of input.
A: Because your not comparing anything basically in your while loop you only gave an iterator not a condition for exit.
So add a var and increment your loop to say 5 after five iterations it should exit
int x=0;
While(getline(cin,tmp),x!=5){
//other code
x++;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: xcode import corresponding files I get an error when I try and import corresponding files.
i.e.
UIViewController "VC.h" Imports "CustomObject.h"
CustomObject Imports "VC.h"
Starts giving error expected specifier qualifier list before
Any ideas? I want both objects to be able to call each other.
Thanks
A: You have a circular dependency. You need to break the circular dependency by using a forward declaration. A forward declaration says "this is the name of something, but I don't know the full definition of it".
For example:
// In VC.h
// Forward declaration of an Objective-C class. After this, you can now use
// pointers to CustomObject, but you can't cell methods or access properties
// of those objects
@class CustomObject;
@interface MyViewController
{
CustomObject *obj;
}
@end
Then, in the implementation files, you can include both header files with no problems.
A: Thanks for the detailed response.
This was the solution, I just did not understand fully the first time I read it.
//VC.h calls cannot be made to CustomObject here, however there is not really any need to
@class CustomObject;
@interface VC : ViewController {
CustomObject* gameController;
// ...
//VC.m calls made in .m only.
#import "CustomObject.h"
gameController = [CustomObject init];
and vice versa in CustomObject
Sorry I didn't post this as a reply to your answer, new here :S
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7577987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: DATABASE: Mysql.com was hacked twice this year should we still use mysql for our database? Last March(2011)
http://techie-buzz.com/tech-news/mysql-com-database-compromised-sql-injection.html
This Month(2011)
http://www.pcworld.com/businesscenter/article/240609/mysqlcom_hacked_to_serve_malware.html
A: Actually, the database wasn't hacked. The database did exactly what it was supposed to.
The application in front of the database was hacked.
Use any database and put a foul lot of code directly touching tables and you'll end up with a hackable pile.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: question about python GUI So I am taking a digital image processing class that requires implementing some image filters, reconstruction, enhancements. I plan to use python for it but my professor wants to have a simple GUI with two canvas for pre- and post-processing images, a drop down box for filter selection, some textboxes for filter value/thresholds and stuff. I have the following questions to ask:
*
*Is it possible to load image to a canvas in python GUI library?
*Does the advantage from coding out-weight the disadvantages of having to code the GUI manually?
*Given the requirements, what would be the best and easiest library to use? I choose python since it reduces implementation time, but if the GUI turns out to be a bummer I would rather use Java.
*If the answer for the 3 previous questions are YES, please point me in the right direction with some documents.
Thank you!
A: I recommend writing the processing code separately, then writing a GUI wrapper around it.
There are many choices, however I'd consider the big three below:
*
*Tkinter, in the standard install, simple but a bit clunky.
*wxPython, a better choice, higher quality but a bit more complicated. Uses native widgets.
*PyQT, many love this toolkit and its documentation. I have only limited expertise with it. Uses custom drawn widgets.
A: Look at Phatch. It is a Python Photo Batch Processor with a nice graphical user interface. It is based on PIL imaging library which you'll probably want to use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Incompatible Pointer Type Error, sws_scale, ffmpeg
My code is very straightforward; it consumes YUV420P data, resizes it, and produces a PNG or JPEG image (OS X Lion, Apple's gcc 4.2.1). It works fine; I'm using ffmpeg (HEAD, as of mumble days ago), but when running in -pedantic-errors mode (which I like to do from time to time):
zc_libav.c:30: error: passing argument 2 of ‘sws_scale’ from incompatible pointer type
Ouch! Well, what's my code look like?
sws_scale(sws_ctx,
in_pic->data,
in_pic->linesize,
0,
in->y,
out_pic->data,
out_pic->linesize);
(You can assume for the sake of argument that the in_pic and out_pic AVPicture structures have been properly initialized, as the code works).
Well, what're the offending data types?
from libswscale/swscale.h:
int sws_scale(struct SwsContext *c, const uint8_t* const srcSlice[], …
from libavcodec/avcodec.h
typedef struct AVPicture {
uint8_t *data[4];
int linesize[4]; ///< number of bytes per line
} AVPicture;
As I noted above, when I change -pedantic-errors to -pedantic, I get the same complaint, but the code compiles and runs correctly. For my own neurotic sanity, is there any way to get the advantages of -pedantic-errors and, you know, compile this code?
A: This would be ok in C++, but C doesn't have the same rules regarding const. It doesn't like that you are passing a non-const uint8_t ** to a function that takes a const uint8_t *const *.
In C, you can convert an X * to a const X *, but it only works for one pointer level. The next pointer level has to match exactly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: db2 SQLCODE -668 when inserting While I was inserting data into a table (db2), I got this error:
Message: Operation not allowed for reason code "7" on
table "ELSAG.ICGR1106".. SQLCODE=-668, SQLSTATE=57016, DRIVER=3.50.152,...
when I googled it, I found that the previous ALTER TABLE statement attempted to add a column to a table that has an edit procedure that is defined with row attribute sensitivity. No columns can be added to this table.
Is there is a way to rectify it?
Once I drop and re-create the table I can insert again.
Thanks in advance.
A: CALL SYSPROC.ADMIN_CMD('REORG TABLE TABLE_NAME') solves the problem
A: To add to James' answer and save people time looking around, you could execute
CALL SYSPROC.ADMIN_CMD('REORG TABLE MY_TABLE_NAME')
via any available SQL client (i.e. even over ODBC or JDBC connection) to rectify this problem. However, the connection has to be in autocommit mode and you have to have admin privileges to execute this command.
I highly recommend to read the documentation on REORG before calling it.
A: SELECT REORG_PENDING FROM SYSIBMADM.ADMINTABINFO where TABSCHEMA = '<schema_name>' and tabname = '<table_name>';
If above query returns Y
Then run below query:
call sysproc.admin_cmd('reorg table <schema_name>.<table_name>');
For more info visit: SQL0668N Operating not allowed for reason code '7'
A: According to this:
SQL0668
You have done some alteration to the table which requires a REORG before you can further update the table.
Run the REORG utility against the table and you should be OK.
A: I turned off integrity checks on some table and got that error message afterwards when altering data. This here generated the statements which helped:
select 'SET INTEGRITY FOR ' || rtrim(tabname) || ' IMMEDIATE CHECKED;'
from syscat.tables
where CONST_CHECKED like '%N%'
or status != 'N'
or access_mode != 'F'
with ur;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
}
|
Q: How to prevent AJAX generated content to be indexed by search engines? i am injecting some text into my pages but i need to prevent search engines from indexing it. I read that some engines are able to read this content now. How can one prevent them from doing so?
A: Search engines cannot read Ajax content yet. The closest they come is Google supporting it if you use their specifications. But that does require you using their specification otherwise Google can't crawl Ajax content.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: what is the correct syntax of BLPOP on Predis? I do it like this:
$r = new Predis\Client($single_server, $options);
$retval = $r->blpop('queue:query');
But I get this error:
ERR wrong number of arguments for 'blpop' command
Whenever I do this
$r = new Predis\Client($single_server, $options);
$retval = $r->blpop('queue:query',0);
I get the error:
Error while reading line from the server
Doing it from redis-cli
redis 127.0.0.1:6379> BLPOP queue:query
(error) ERR wrong number of arguments for 'blpop' command
redis 127.0.0.1:6379> BLPOP queue:query 0
1) "queue:query"
2) "hello world"
A: Seems like a bug. The latest version doesn't have this issue, also it apparently dropped namespaces:
<?
include_once "Predis.php";
$r = new Predis_Client();
$retval = $r->blpop('queue:query',0);
var_dump($retval);
?>
It blocked when I accessed the page. Then, I issued LPUSH queue:query 0, went back to the page, and got this:
array(2) { [0]=> string(11) "queue:query" [1]=> string(1) "0" }
Nevertheless, I would recommend the use of phpredis, it is faster than this library, because it is compiled as a php extension. If you have the rights in your server, that's a good pick.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why doesn't the where query work in postgresql? I have a ruby on rails app in which I am querying for a boolean column, Flag. The code is:
Merchant.where("Flag=?",false)
However this does not work at all and the only result is that the Merchants table does not have a column name "flag". Is there any way to fix this? The column name starts with an uppercase letter, but the search is being done for a lower case "flag"
A: If the column name was quoted when the table was created then you will have to quote it forever. So, if you started with this:
create table merchants (
-- ...
"Flag" boolean
-- ...
)
Then you'll have to refer to it using
Merchant.where('"Flag" = ?', false)
PostgreSQL normalizes all unquoted identifiers to lower case (not upper case as the standard says), that's why the error message complains about flag rather than Flag.
If you can, you might want to rebuild your table with only lower case column names.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Silverlight Grid does not fill I have Border control defined like so:
<Border Background="Azure" Grid.Row="2">
<ContentControl Width="Auto" Height="Auto" Regions:RegionManager.RegionName="MainContent" />
</Border>
I can see Azure background in whole area
Now I inject my view into this ContentControl (it's PRISM). View looks like this..
<toolkit:BusyIndicator IsBusy="{Binding IsBusy}">
<Grid Margin="10" DataContext="{Binding}"
infBehaviors:RegionPopupBehaviors.CreatePopupRegionWithName="ViewPopup"
infBehaviors:RegionPopupBehaviors.ContainerWindowStyle="{StaticResource PopupStyle}">
<!--Define rows in a grid-->
<Grid.RowDefinitions>
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="30" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<!--Define columns in a grid-->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="120"/>
<ColumnDefinition Width="200" />
<ColumnDefinition Width="65" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
Now when I place new UserCOntrol on top of my Grid - I expect it to cover whole "Azure" area. But I only see overlay with size of my data entry form. It seems that second grid does not "fill" ContentControl - only takes as much space as needed. How do I force it to fill? I set Auto column and row - thinking they will stretch but no..
EDIT:
Screenshot from Silverlight Spy.. It shows that ContentControl from Shell covers whole area but grid inside totally ignores my "*" sizes. Also it does work in design mode - it stretches to whole design area...
A: Make sure you have HorizontalContentAlignment and VerticalContentAlignment of the ContentControl set to Stretch. ^_^
e.g.
<Border Background="Azure" Grid.Row="2">
<ContentControl HorizontalContentAlignment="Stretch"
VerticalContentAlignment="Stretch"
Width="Auto" Height="Auto" Regions:RegionManager.RegionName="MainContent" />
</Border>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Dynamically add addthis to certain part of the page with jQuery I am trying to dynamically add the Addthis widget to a certain area of the page with jQuery. The following code works fine except in IE where it does not show at all.
jQuery(function(){
if (typeof global_Current_ProductCode != 'undefined'){
jQuery.getScript('http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-xxxxxxxxxxx',function(){
var add_this_html ='<div class="addthis_toolbox addthis_default_style " style="margin-top:20px">';
add_this_html += '<a class="addthis_button_facebook_like" fb:like:layout="button_count"></a>';
add_this_html += '<a class="addthis_button_tweet"></a>';
add_this_html += '<a class="addthis_button_google_plusone" g:plusone:size="medium"></a>';
add_this_html += '</div>';
jQuery('.text.colors_text:eq(0)').closest('table').before(add_this_html);
addthis.init();
});
}
});
This is all I see in IE with firebug lite.
<div class="addthis_toolbox addthis_default_style ">
<a class="addthis_button_facebook_like" fb:like:layout="button_count"/>
<a class="addthis_button_tweet"/>
<a class="addthis_button_google_plusone" g:plusone:size="medium"/>
</div>
Anyone have any idea why it will not appear in IE?
A: Try the addthis.toolbox() method instead of addthis.init()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to install multiple instances of the same application using msi Installer I am using visual studio set up project to create my msi Installer.My requirement is to create multiple instances of the application using this same installer without changing version number/product code.
Is there is any way to do it without using Wix/Installshield.
A: Sorry, if you want to use MSI and install multiple instances, you need instance Transforms (i.e. changing the Product Code)
http://msdn.microsoft.com/en-us/library/aa369528(v=VS.85).aspx
Why don't you want to change the product code using and instance transform?
A: Windows Installer doesn't support multiple instances with the same Product Code and Upgrade Code. Product Version can remain the same. A different instance is actually considered a different product.
Multiple instances are not supported by Visual Studio setup project files and they are not easy to implement. The general approach is this:
*
*Create a MST transform for each instance. Each transform should use a different Product Code and different component GUIDs.
*Write a custom EXE bootstrapper which can apply these transforms to your original MSI.
*Optionally find a way to include the transforms and MSI in a single EXE setup file.
Other authoring tools do offer support for multiple instances, but the instances number is usually limited. It all depends on how many transforms you create.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Displaying a google map on iPhone simulator - Phonegap I am running Mac OSX Lion and Xcode 4.1.1. I created a new Phonegap project and in the index.html, I added the following code.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<script type="text/javascript" charset="utf-8" src="phonegap-1.0.0.js">
</script>
<!-- Tried setting sensor=true, didn't work too -->
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript" charset="utf-8" >
function display(position){
var initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
var myOptions = {
zoom: 12,
center: initialLocation,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function error()
{
alert('Not working');
}
function init()
{
navigator.geolocation.getCurrentPosition(display,error);
}
</script>
</head>
<body onload="init()">
<div id="map_canvas"></div>
</body>
</html>
The code however, refuses to work. I even enabled the key "EnableLocation" in my Phonegap.plist. I don't get any sort of warning saying "Testapp would like to know your location, Allow?". All I get is this error on the console
navigator.geolocation.setError({ 'code': 1, 'message': 'Location Services Not Enabled' });
Can someone please help me out?
A: I wish I knew what to tell you, but I hope this helps. I think your code is fine. I just ran it on the iOS 4.3 simulator from Dreamweaver on Snow Leopard and it worked fine. However, I had to make some adjustments because the DIV was completely collapsed. The map was in there, but it was not showing.
Just to prove it to yourself, try adding this to your map_canvas div
style="height: 400px"
When I did that, I could see the map fine.
I am not CSS expert, so I do not know how to make the stupid div expand to the size of the map. Maybe you'll have to do it with CSS. Height 100% didn't work. Sometimes CSS really blows.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Creating aggregate node via XSLT with kicker I don't think well in xsl, so I'm having trouble comprehending how to handle this. I need to make an aggregate of the quantity, but grouped by the id in the attribute in the parent node. I'm thinking this should be a horribly simple recursion template, but I'm having trouble pumping it out
This input xml looks like this:
<foo>
<lines>
<line line_id="10000">
<qty>10</qty>
</line>
<line line_id="10000">
<qty>4</qty>
</line>
<line line_id="10000">
<qty>12</qty>
</line>
<line line_id="20000">
<qty>1</qty>
</line>
<line line_id="30000">
<qty>4</qty>
</line>
<line line_id="30000">
<qty>6</qty>
</line>
</lines>
<lines>
<line line_id="10000">
<qty>4</qty>
</line>
</lines>
</foo>
The output should be:
<newfoo>
<items>
<item>
<item_id>10000</item_id>
<quantity>26</quantity>
</item>
<item>
<item_id>20000</item_id>
<quantity>1</quantity>
</item>
<item>
<item_id>30000</item_id>
<quantity>10</quantity>
</item>
</items>
<items>
<item>
<item_id>10000</item_id>
<quantity>4</quantity>
</item>
</items>
</newfoo>
A: This can be achieved in XSLT1.0 by using a method called Muenchian Grouping.
Firstly, you define a key to look-up the line elements for a given lines element using the line_id attribute as the key. So, for a given lines element and line_id attribute, all matching line elements will be returned. You will need a concatenated key for this.
<xsl:key name="id"
match="line"
use="concat(concat(generate-id(..), ','), @line_id)"/>
Next, you need to match the line elements which have the first occurrence of each distinct line_id attribute within the lines element. This is achieved as follows:
<xsl:apply-templates
select="line[
generate-id() =
generate-id(key('id',concat(concat(generate-id(..),','),@line_id))[1])]" />
i.e. Match line elements which happen to be the first elements in the list for the given key.
Then, you can get the total quantity, simply by summing all elements in the key
<xsl:value-of
select="sum(key('id', concat(concat(generate-id(..), ','), @line_id))/qty)"/>
Here is the full XSLT document:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" indent="yes"/>
<xsl:key name="id" match="line" use="concat(concat(generate-id(..), ','), @line_id)"/>
<xsl:template match="/foo">
<newfoo>
<xsl:apply-templates select="lines"/>
</newfoo>
</xsl:template>
<xsl:template match="lines">
<items>
<xsl:apply-templates select="line[generate-id() = generate-id(key('id', concat(concat(generate-id(..), ','), @line_id))[1])]"/>
</items>
</xsl:template>
<xsl:template match="line">
<item>
<item_id>
<xsl:value-of select="@line_id"/>
</item_id>
<quantity>
<xsl:value-of select="sum(key('id', concat(concat(generate-id(..), ','), @line_id))/qty)"/>
</quantity>
</item>
</xsl:template>
</xsl:stylesheet>
When applied to the following XML:
<foo>
<lines>
<line line_id="10000">
<qty>10</qty>
</line>
<line line_id="10000">
<qty>4</qty>
</line>
<line line_id="10000">
<qty>12</qty>
</line>
<line line_id="20000">
<qty>1</qty>
</line>
<line line_id="30000">
<qty>4</qty>
</line>
<line line_id="30000">
<qty>6</qty>
</line>
</lines>
<lines>
<line line_id="10000">
<qty>4</qty>
</line>
</lines>
</foo>
The following XML is output:
<newfoo>
<items>
<item>
<item_id>10000</item_id>
<quantity>26</quantity>
</item>
<item>
<item_id>20000</item_id>
<quantity>1</quantity>
</item>
<item>
<item_id>30000</item_id>
<quantity>10</quantity>
</item>
</items>
<items>
<item>
<item_id>10000</item_id>
<quantity>4</quantity>
</item>
</items>
</newfoo>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP problem with concept I am creating a form in php. ai have given address of other file in action. LIke I have created A.php, and in action of A.php I have given address of processing file, Like takeinput.php. But now I have issue is I am validating A.php in action file that is takeinput.php. Suppose if name field is null. I have easily validate that. But what happen if error is occured. Will it again be navigated to A.php or I have to use header to navigate back to A.php
takeinput.php
$fname= $_REQUEST["fname"];
if ($fname==''){
$error='Field can't be empty.' exit();
}
Now i need to use header to locate back to A.php or it will automatically be navigated on error.
I am newbie help me with concept.
A: You can use empty() construct to validate input. You can also use isset() construct to check whether a a variable is set and is not NULL.
if(empty($fname))
{
}
You can use header() construct to request a new resource.
header("Location: file.php");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Map a set of values in python What would be the best approach to do the following:
if lang=="en-US":
chapter="chapter"
if lang=="fr-FR":
chapter="chapitre"
# etc.
Essentially I'm looking for a mapping that would do something like:
lang = ['en-US', 'fr-FR', ...] --> chapter = ['chapter', 'chapitre', ...]
How would I accomplish this? Thank you.
A: I always use a dictionary for that.
langs = {
"en-US" : "chapter",
"fr-FR" : "chapitre"
}
test = langs['en-US']
But for translations, you should also consider gettext.
A: Dictionaries are good for this.
>>> chapter = {
... "en-US": "chapter",
... "fr-FR": "chapitre",
... # ...
... }
>>> chapter['en-US']
'chapter'
>>> chapter['fr-FR']
'chapitre'
A: >>> chapter = {
... "en-US": "chapter",
... "fr-FR": "chapitre",
... # ...
... }
>>> chapter.keys(), chapter.values()
... (['en-US', 'fr-FR'], ['chapter', 'chapitre'])
If you are looking for translation then best option is gettext.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to monitor open file descriptors in Ruby on Rails? Background:
I had an issue with my Rails server recently where it would stop responding, requiring a bounce to get it back up and running. This issue was due to a controller that does some forking upon receiving a POST, to do some heavy-weight concurrent processing -- server response time kept increasing until the server completely stopped responding. I'm pretty sure I have fixed that issue (DB connections copied upon fork weren't getting closed in child processes), but it would be great to authoritatively test that.
Question:
Is there a way to monitor open file descriptors from inside my Rails app? It's running on Linux, so I've been mucking around with the proc filesystem and the lsof command to observe the open file descriptors; this is messy, because it only gives you a snapshot of the current processes. Ideally I would like to print the open file descriptors in the parent and child processes before, during, and after the processing, to ensure that file descriptors don't stay open past their welcome.
A: One method to consider (probably the simplest) is using a background worker of some sort, such as with Workling, and making it run lsof in intervals, and getting output using syntax:
`lsof | grep something` # shell command example.
Programs like lsof can really hurt performance if run too frequently. Perhaps every 10s to 30s. Perhaps down to maybe 5s, but that's really pushing it. I'm assuming you have a dedicated server or a beasty virtual machine.
In your background worker, you can store these command results into a variable, or grep it down to what you're really looking for (as demonstrated), and access/manipulate the data as you please.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to insert data to php numeric array I am trying to inset data to a numeric array php graph.
I tried to do it this way:
$query = "select id,sales from riders";
$results = mysql_query($query);
while($row = mysql_fetch_array($results)) {
//$rider[i]=$row['id'];
$rider[$counter]=$row['sales'];
$counter++;
}
and insert into data array as follows:
$data = array($rider[0],$rider[1],$rider[2],$rider[3],$rider[4]);
It gives me error.. Please help me... Thank you very much for your kind help.....
A: Add $counter = 0; before the while loop.
PS: You can just use $data[] = $row['sales']; in the loop without the $counter.
A: Use $rider[],
$rider=array();
while($row = mysql_fetch_array($results))
{
$rider[]=$row['sales'];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to show loading animation if browser supports JS I want to show loading animation if browser supports JS. if JavaScript is disabled then the image will show but never be hidden, in this case. For this purpose I wrote this code directly after the <body> tag:
<?php
$results = get_browser();
if ($results["javascript"] == 1) {
echo '<div id="loading"><img src="core/design/img/load/load.gif"/></div>';
}
?>
And my js looks like that
$(window).load(function(){
$('#loading').fadeOut(600);
});
Got error message browscap ini directive not set in. How can I realize my idea?
A: You can just use:
<body>
//set the div to hidden by default
<div id="loading" style="display:none"><img src="core/design/img/load/load.gif"/></div>
//place this code directly below the loading div, it will run before page/dom is loaded
<script type="text/javascript">
document.getElementById('loading').style.display = 'block';
</script>
<script type="text/javascript">
$(function() {
//this will run after the page has loaded
$('#loading').fadeOut(600);
});
</script>
...
If you want to do exactly what aquastyle.az does (though the above solution is faster), You can do this:
<body>
<script type="text/javascript">
//if JavaScript is enabled, append the loading div to be body
$('body').append('<div id="loading"><img src="core/design/img/load/load.gif" /></div>');
</script>
<script type="text/javascript">
$(function() {
//this will run after the page has loaded
$('#loading').fadeOut(600);
});
</script>
...
A: In your HTML, you could do something like this:
<html class="no-js">
...
Then, once the page loads, replace the no-js class with a js class via JavaScript.
$(window).load(function(){
$('html').removeClass('no-js').addClass('js');
});
Finally, in your CSS, show the loading image if the browser supports js and hide it if it doesn't.
.js #loading {
display: block;
}
.no-js #loading {
display: none;
}
Does that make sense?
A: The get_browser function must be download the appropriate INI file and include it in your PHP.ini file.
Instead of trying to figure out if the user has javascript enabled, why don't you build out the site from the perspective of progressive enhancement, so it works for all users regardless of their browser settings.
Alternatively, you could ask javascript to set a cookie, and then check that the cookie exists in PHP, it's by no means 100% foolproof method but could work for your situation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Automatically generate conf file during make I have a conf file that is of the format:
name=value
What I want to do is using a template, generate a result based on some values in another file.
So for example, say I have a file called PATHS that contains
CONF_DIR=/etc
BIN_DIR=/usr/sbin
LOG_DIR=/var/log
CACHE_DIR=/home/cache
This PATHS file gets included into a Makefile so that when I call make install the paths are created and built applications and conf files copied appropriately.
Now I also have a conf file which I want to use as a template.
Say the template contains lines like
LogFile=$(LOG_DIR)/myapp.log
...
Then generate a destination conf that would have
LogFile=/var/log/myapp.log
...
etc
I think this can be done with a sed script, but I'm not very familiar with sed and regular expression syntax. I will accept a shell script version too.
A: You may want to consider using m4 as a simple template language instead.
A: You should definitely go with autoconf here, whose very job is to do this. You'll have to write a conf.in file, wherein all substitutions are marked with @'s, e.g.
prefix=@prefix@
bindir=@bindir@
and write up a configure.ac, which is a shell script that will perform these substitutions for you and create conf. conf is subsequently included in the Makefile. I'd even recommend using a Makefile.in file, i.e. including your snippet in the Makefile.
If you keep to the standard path names, your configure.ac is a four-liner and has the added advantage of being GNU compatible (easy to understand & use).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Determining angle of line In Silverlight, is there a way to determine the angle of a Line object? If I have a Line with coordinates of 0,0 - 30,80, is there a way to determine the angle, in degrees, that the line is running?
A: You could try finding the arc tangent using the Math.Atan function. You just need to find the atan of the (delta of) y-value over the (delta of) x-value.
The answer will be in radians and you will need to convert it to degrees (rads * (180f / Math.PI)).
An example of this would be something like:
double rads = Math.Atan((line.Y2 - line.Y1) / (line.X2 - line.X1));
double degrees = rads * (180f / Math.PI);
(Note: I've never used Silverlight and I'm just basing this off the docs, so this might be completely wrong... you can also use Math.Atan2(delta y, delta x) too...)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Heap memory problems There's a WCF self hosted service that must work 99% of time. Sometimes we got some memory troubles like this:
But service is working as usual after that issues. How can we manage this? Any tips and points to make robust services that will survive in different except situations are very very welcome.
A: I am not too sure where the problem resides but memory leaking can be a reason.
All code is managed. And we use dotConnect for Oracle from devArt as
data layer library.
You assume all code is managed, but there can be unmanaged parts. However, you must call the Dispose method for all the disposable objects after using them, don't think they are properly dispose once they go out of scope. The best practice is, not to let Disposable objects to go out of scope without calling their Dispose method. You may be able to use 'using' statements if you are using them as local variables.
DbConnection is a good example for disposable objects, make sure you dispose all the connections (disposable objects).
A: If it's a WCF problem (I'm not sure what to do with your dump), I suggest you activate WCF server-side tracing, and have a look at the exceptions if there are any (and edit your question so we can further help you).
Here is a link that explain how to do this:
How to enable WCF tracing
A: What are your Service Behaviors particularly ConcurrencyMode and InstanceContextMode.
if you have Multiple as ConcurrencyMode and InstanceContext set to (PerCall, or PerSession(default)) you can definetely run into issues if you have large DataStructures or undisposed resources.
if you are using multiple Concurrency try InstanceContextMode Single [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.Single)]
A: Are you 100% none of you dependencies have unmanaged code? I've seen something very similar to this happen, and it was happening because we were deallocating memory that another process would also try to deallocate later.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: css formatting in php I have a css question.
I have the following php code which displays a name.
while ($db_field = mysql_fetch_assoc($result)) {
print $db_field['ship_name'] . "<BR>";
I'm trying to add some text style to it but I'm not that good in css and I'm somehow lost.
I'm trying to do something like <t> $db_field['ship_name'].<t/> but it gives me an error.
A: judging by your comment, probably you want
print "<span class='t'>".$db_field['ship_name']."</span><BR>";
and for your CSS file define
.t { font-size: 50pt; color:black; text-shadow: 0 1px 2px white; }
A: This will echo out the data into a span tag:
echo "<span>" . $db_field['ship_name'] . "</span>";
To add a css class:
echo "<span class=\"class_name\">" . $db_field['ship_name'] . "</span>";
Then in your css file:
span.class_name { font-size:24px; color:#666; }
A: There are 2 ways of doing this. Either you embed html in PHP or write separate HTML snippet. I will show you the both ways :
The first one is already explained above in the answer by sinclairchase.
echo "<td>" . $db_field['ship_name'] . "</td>";
The other way is :
<?php while ($db_field = mysql_fetch_assoc($result)) {
?>
<td>
<?php print $db_field['ship_name'] . "<BR>"; ?>
</td>
<?php } ?>
I dont unsderstand why you write t in question it would be td.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there any way to input a string in C++? Is there any alternative way to input a string (along with blank spaces) without using std::string in C++?
I know, std::string is the standard way. But, I am just curious.
A: std::istream::getline(char *, streamsize)
Stolen shamelessly from http://www.cplusplus.com/reference/iostream/istream/getline/
// istream getline
#include <iostream>
using namespace std;
int main () {
char name[256], title[256];
cout << "Enter your name: ";
cin.getline (name,256);
cout << "Enter your favourite movie: ";
cin.getline (title,256);
cout << name << "'s favourite movie is " << title;
return 0;
}
A: By using std::string. There is no reason not to use it.
If, by some obscure chance, you have additional requirements why you cannot use std::string, please state those requirements as they will impact the code.
Update: If the input is newline delimited, use string s; std::getline(cin, s);
A: You can use getline - the old C way of doing things. But why would you want to do this?
Ref: http://www.crasseux.com/books/ctutorial/getline.html
Or if you like headaches you could even use system calls!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: How can I create custom SEO-friendly URLs in OpenCart? How can you customize system URLs in OpenCart? For example, I would like http://example.com/index.php?route=checkout/cart to be displayed as http://example.com/cart
I know OpenCart provides SEO URLs for products, categories, manufacturers and information pages, but it doesn't look like there is anything built-in (at least prior to version 1.5.0) for anything else.
A: It turns out this can be done with a relatively simple change to a single file. No .htaccess rewrite rules, simply patch the catalog/controller/common/seo_url.php file and add your pretty URLs to an existing database table.
The patch to seo_url.php:
Index: catalog/controller/common/seo_url.php
===================================================================
--- catalog/controller/common/seo_url.php (old)
+++ catalog/controller/common/seo_url.php (new)
@@ -48,7 +42,12 @@
$this->request->get['route'] = 'product/manufacturer/product';
} elseif (isset($this->request->get['information_id'])) {
$this->request->get['route'] = 'information/information';
- }
+ } else {
+ $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE keyword = '" . $this->db->escape($this->request->get['_route_']) . "'");
+ if ($query->num_rows) {
+ $this->request->get['route'] = $query->row['query'];
+ }
+ }
if (isset($this->request->get['route'])) {
return $this->forward($this->request->get['route']);
@@ -88,7 +87,15 @@
}
unset($data[$key]);
- }
+ } else {
+ $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($data['route']) . "'");
+
+ if ($query->num_rows) {
+ $url .= '/' . $query->row['keyword'];
+
+ unset($data[$key]);
+ }
+ }
}
}
There are two edits required. The first extends the index() function to look in the url_alias table for any keyword matching $this->request->get['_route_'].
The second extends the rewrite() function to look in the url_alias table for all routes, not just those for products, manufacturers, and information pages.
Adding entries to the database:
INSERT INTO `url_alias` (`url_alias_id`, `query`, `keyword`) VALUES
(NULL, 'checkout/cart', 'cart');
That's it. http://example.com/cart should return the same thing that http://example.com/index.php?route=checkout/cart does, and OpenCart should recognize $this->url->link('checkout/cart'); and return a link to the pretty URL http://example.com/cart
A: A simple "no code" method is to install vQmod.
Instructions here:
vQmod install wiki
And then upload the xml file available in this Opencart forum thread to the vqmod/xml/ folder.
The xml contains a relatively easy to read script that maps the urls similar to the two answers above, but without modifying core files. So site updates will not kill it.
A: I'm using Opencart version 1.5.5.1 and this is the exact code that worked for me:
<?php
class ControllerCommonSeoUrl extends Controller {
/* SEO Custom URL */
private $url_list = array (
'common/home' => '',
'checkout/cart' => 'cart',
'account/register' => 'register',
'account/wishlist' => 'wishlist',
'checkout/checkout' => 'checkout',
'account/login' => 'login',
'product/special' => 'special',
'affiliate/account' => 'affiliate',
'checkout/voucher' => 'voucher',
'product/manufacturer' => 'brand',
'account/newsletter' => 'newsletter',
'account/order' => 'order',
'account/account' => 'account',
'information/contact' => 'contact',
'account/return/insert' => 'return',
'information/sitemap' => 'sitemap',
);
/* SEO Custom URL */
public function index() {
// Add rewrite to url class
if ($this->config->get('config_seo_url')) {
$this->url->addRewrite($this);
}
// Decode URL
if (isset($this->request->get['_route_'])) {
$parts = explode('/', $this->request->get['_route_']);
foreach ($parts as $part) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE keyword = '" . $this->db->escape($part) . "'");
if ($query->num_rows) {
$url = explode('=', $query->row['query']);
if ($url[0] == 'product_id') {
$this->request->get['product_id'] = $url[1];
}
if ($url[0] == 'category_id') {
if (!isset($this->request->get['path'])) {
$this->request->get['path'] = $url[1];
} else {
$this->request->get['path'] .= '_' . $url[1];
}
}
if ($url[0] == 'manufacturer_id') {
$this->request->get['manufacturer_id'] = $url[1];
}
if ($url[0] == 'information_id') {
$this->request->get['information_id'] = $url[1];
}
} else {
$this->request->get['route'] = 'error/not_found';
}
}
/* SEO Custom URL */
if ( $_s = $this->setURL($this->request->get['_route_']) ) {
$this->request->get['route'] = $_s;
}/* SEO Custom URL */
if (isset($this->request->get['product_id'])) {
$this->request->get['route'] = 'product/product';
} elseif (isset($this->request->get['path'])) {
$this->request->get['route'] = 'product/category';
} elseif (isset($this->request->get['manufacturer_id'])) {
$this->request->get['route'] = 'product/manufacturer/info';
} elseif (isset($this->request->get['information_id'])) {
$this->request->get['route'] = 'information/information';
}
if (isset($this->request->get['route'])) {
return $this->forward($this->request->get['route']);
}
}
}
public function rewrite($link) {
$url_info = parse_url(str_replace('&', '&', $link));
$url = '';
$data = array();
parse_str($url_info['query'], $data);
foreach ($data as $key => $value) {
if (isset($data['route'])) {
if (($data['route'] == 'product/product' && $key == 'product_id') || (($data['route'] == 'product/manufacturer/info' || $data['route'] == 'product/product') && $key == 'manufacturer_id') || ($data['route'] == 'information/information' && $key == 'information_id')) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "'");
if ($query->num_rows) {
$url .= '/' . $query->row['keyword'];
unset($data[$key]);
}
} elseif ($key == 'path') {
$categories = explode('_', $value);
foreach ($categories as $category) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = 'category_id=" . (int)$category . "'");
if ($query->num_rows) {
$url .= '/' . $query->row['keyword'];
}
}
unset($data[$key]);
}
/* SEO Custom URL */
if( $_u = $this->getURL($data['route']) ){
$url .= $_u;
unset($data[$key]);
}/* SEO Custom URL */
}
}
if ($url) {
unset($data['route']);
$query = '';
if ($data) {
foreach ($data as $key => $value) {
$query .= '&' . $key . '=' . $value;
}
if ($query) {
$query = '?' . trim($query, '&');
}
}
return $url_info['scheme'] . '://' . $url_info['host'] . (isset($url_info['port']) ? ':' . $url_info['port'] : '') . str_replace('/index.php', '', $url_info['path']) . $url . $query;
} else {
return $link;
}
}
/* SEO Custom URL */
public function getURL($route) {
if( count($this->url_list) > 0) {
foreach ($this->url_list as $key => $value) {
if($route == $key) {
return '/'.$value;
}
}
}
return false;
}
public function setURL($_route) {
if( count($this->url_list) > 0 ){
foreach ($this->url_list as $key => $value) {
if($_route == $value) {
return $key;
}
}
}
return false;
}/* SEO Custom URL */
}
?>
A: Put this near the top of your index.php file. It was the only solution that worked for me.
switch($_SERVER["REQUEST_URI"])
{
case '/old-url': $three01 = "/new-url"; break;
}
if($three01)
{
header("HTTP/1.1 301 Moved Permanently"); header("Location: ".$three01); exit;
}
A: vQmod xml file
<modification>
<id>Seo All Alias</id>
<version>1.0</version>
<vqmver>2.1.7</vqmver>
<author>noname</author>
<file name="catalog/controller/common/seo_url.php">
<operation>
<search position="after" offset="2"><![CDATA[
$this->request->get['route'] = 'information/information';
]]></search>
<add><![CDATA[
else {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE keyword = '" . $this->db->escape($this->request->get['_route_']) . "'");
if ($query->num_rows) {
$this->request->get['route'] = $query->row['query'];
}
}
]]></add>
</operation>
<operation>
<search position="after" offset="1" index="2"><![CDATA[
unset($data[$key]);
]]></search>
<add><![CDATA[
else {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($data['route']) . "'");
if ($query->num_rows) {
$url .= '/' . $query->row['keyword'];
unset($data[$key]);
}
}
]]></add>
</operation>
</file>
A: OpenCart SEO for OpenCart 1.5.X free :)
You can use as you wish. Category Name / ID / ID for quicker SEO resolving
<?php
class ControllerCommonSeoUrl extends Controller {
/* SEO Custom URL */
private $url_list = array (
'common/home' => 'home',
'checkout/cart' => 'cart',
'account/register' => 'register',
'account/wishlist' => 'wishlist',
'checkout/checkout' => 'checkout',
'account/login' => 'login',
'product/special' => 'special',
'affiliate/account' => 'affiliate',
'checkout/voucher' => 'voucher',
'product/manufacturer' => 'brand',
'account/newsletter' => 'newsletter',
'account/order' => 'order',
'account/account' => 'account',
'information/contact' => 'contact',
'account/return/insert' => 'return/insert',
'information/sitemap' => 'sitemap',
);
/* SEO Custom URL */
public function index() {
// Add rewrite to url class
if ($this->config->get('config_seo_url')) {
$this->url->addRewrite($this);
}
// Decode URL
if (isset($this->request->get['_route_'])) {
$parts = explode('/', $this->request->get['_route_']);
if ( count($parts) > 1 ) {
if ($parts[1] == 'category'){
$this->request->get['path'] = $parts[2];
for ( $i = 3 ; $i < count($parts); $i++) {
$this->request->get['path'] .= '_' . $parts[$i];
}
}elseif( $parts[1] == 'item' ) {
$this->request->get['product_id'] = $parts[2];
}
}
foreach ($parts as $part) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE keyword = '" . $this->db->escape($part) . "'");
if ($query->num_rows) {
$url = explode('=', $query->row['query']);
if ($url[0] == 'product_id') {
$this->request->get['product_id'] = $url[1];
}
if ($url[0] == 'category_id') {
if (!isset($this->request->get['path'])) {
$this->request->get['path'] = $url[1];
} else {
$this->request->get['path'] .= '_' . $url[1];
}
}
if ($url[0] == 'manufacturer_id') {
$this->request->get['manufacturer_id'] = $url[1];
}
if ($url[0] == 'information_id') {
$this->request->get['information_id'] = $url[1];
}
} else {
$this->request->get['route'] = 'error/not_found';
}
}
/* SEO Custom URL */
if ( $_s = $this->setURL($this->request->get['_route_']) ) {
$this->request->get['route'] = $_s;
}/* SEO Custom URL */
if (isset($this->request->get['product_id'])) {
$this->request->get['route'] = 'product/product';
} elseif (isset($this->request->get['path'])) {
$this->request->get['route'] = 'product/category';
} elseif (isset($this->request->get['manufacturer_id'])) {
$this->request->get['route'] = 'product/manufacturer/product';
} elseif (isset($this->request->get['information_id'])) {
$this->request->get['route'] = 'information/information';
}
if (isset($this->request->get['route'])) {
return $this->forward($this->request->get['route']);
}
}
}
public function rewrite($link) {
if ($this->config->get('config_seo_url')) {
$url_data = parse_url(str_replace('&', '&', $link));
$url = '';
$data = array();
parse_str($url_data['query'], $data);
foreach ($data as $key => $value) {
if (isset($data['route'])) {
if ( (($data['route'] == 'product/manufacturer/product' || $data['route'] == 'product/product') && $key == 'manufacturer_id') || ($data['route'] == 'information/information' && $key == 'information_id')) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "url_alias WHERE `query` = '" . $this->db->escape($key . '=' . (int)$value) . "'");
if ($query->num_rows) {
$url .= '/' . $query->row['keyword'];
unset($data[$key]);
}
} elseif( $key == 'product_id' ) {
$url = '/shop/item/'.$value;
unset($data[$key]);
}elseif ($key == 'path') {
$categories = explode('_', $value);
$url = '/shop/category';
foreach ($categories as $category) {
$url .= '/'.$category;
}
unset($data[$key]);
}//
/* SEO Custom URL */
if( $_u = $this->getURL($data['route']) ){
$url .= $_u;
unset($data[$key]);
}/* SEO Custom URL */
}
}
if ($url) {
unset($data['route']);
$query = '';
if ($data) {
foreach ($data as $key => $value) {
$query .= '&' . $key . '=' . $value;
}
if ($query) {
$query = '?' . trim($query, '&');
}
}
return $url_data['scheme'] . '://' . $url_data['host'] . (isset($url_data['port']) ? ':' . $url_data['port'] : '') . str_replace('/index.php', '', $url_data['path']) . $url . $query;
} else {
return $link;
}
} else {
return $link;
}
}
/* SEO Custom URL */
public function getURL($route) {
if( count($this->url_list) > 0) {
foreach ($this->url_list as $key => $value) {
if($route == $key) {
return '/'.$value;
}
}
}
return false;
}
public function setURL($_route) {
if( count($this->url_list) > 0 ){
foreach ($this->url_list as $key => $value) {
if($_route == $value) {
return $key;
}
}
}
return false;
}/* SEO Custom URL */
}
?>
A: Depending on the level of customization you need, there are a few extensions available, including free ones.
This one works both on OpenCart 1.5 and OpenCart 2 and seems quite customizable. However it does not support customization of hardcoded URL parts like "checkout/cart" or "account/wishlist".
Here is a vQmod for OpenCart 2.0 (might work with 1.5, not tested) which applies to the forementioned extension and allows to change these hardcoded strings into whatever you want, and support multilanguage websites.
E.g. "checkout/cart" will become "cart" for English, "panier" for French, etc.
A: here is a free Extension that adds custom SEO URLs, as well as lets you manage multi-langauge URLs, 404s, export/import, and bulk edit.
SEO Module URL
Hey, before you click down, check the extension. It is my extension, I know that it is coded properly and it does exactly what the user asks for and much more and it is FREE.
I really hope it helps someone.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
}
|
Q: URL rewriting variable name I am trying to rewrite an URL so that a passed variable is replaced with a new id, for example;
wwww.domain.com/default.php?s=1&lang=en
To be rewritten to:
www.domain.com/default.php?id=1$lang=en
The s variable being replaced with id
I have tried:
RewriteEngine on
Options +FollowSymlinks
RewriteBase /
RewriteCond %{QUERY_STRING} ^s=(.+)$
RewriteRule ^s=(.+)$ id=$1 [R,NC,L]
also
RewriteRule ^s=(.+)$ id=%1 [R,NC,L]
no luck... what am I doing wrong?
Thanks for any help!!
A: This should work if even if you don't have s as the first variable. (Not sure what you really want.)
Options +FollowSymlinks
RewriteEngine On
RewriteCond %{QUERY_STRING} ^(.*&)*s=(.*)(&*)$
RewriteRule ^default.php$ default.php?%1&id=%2%3
A: Try this out:
RewriteRule ^default.php?s=([0-9]+)&lang=en$ default.php?id=$1&lang=en
Edit.
A more generic version.
RewriteRule ([^?]+)?s=([0-9]+)&lang=([A-z]{2})$ $1?id=$2&lang=$3
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Besides AND/OR/NOT, what's the point of the other logical operators in programming? I've been programming nearly all of my life (around 20+ years), and I don't think I can remember a single time when I was looking at a if-statement and think "Hmmm, this would be a good time to use XOR." The entire logical programming universe seems to revolve around just these three.
Granted, with AND/OR/NOT gates, you can make any other logical statement. However, there might be a time where it might save you some code to combine two or three statements into a single logical statement. Let's look at the 16 possible combinations of logical connectives:
*
*FALSE = Contradiction = 0, null, NOT TRUE
*TRUE = Tautology = 1, NOT FALSE
*X = Proposition X = X
*NOT X = Negation of X = !X
*Y = Proposition Y = Y
*NOT Y = Negation of Y = !Y
*X AND Y = Conjunction = NOT (X NAND Y)
*X NAND Y = Alternative Denial = NOT (X AND Y), !X OR !Y
*X OR Y = Disjunction = NOT (!X AND !Y)
*X NOR Y = Joint Denial = NOT (X OR Y), !X AND !Y
*X ⊅ Y = Material Nonimplication = X AND !Y, NOT(!X OR Y), (X XOR Y) AND X, ???
*X ⊃ Y = Material Implication = !X OR Y, NOT(X AND !Y), (X XNOR Y) OR X, ???
*X ⊄ Y = Converse Nonimplication = !X AND Y, NOT(X OR !Y), (X XOR Y) AND Y, ???
*X ⊂ Y = Converse Implication = X OR !Y, NOT(!X AND Y), (X XNOR Y) OR Y, ???
*X XOR Y = Exclusive disjunction = NOT (X IFF Y), NOT (X XNOR Y), X != Y
*X XNOR Y = Biconditional = X IFF Y, NOT (X XOR Y), !X AND !Y
So, items 1-2 involve zero variables, items 3-6 involve one, and items 7-10 are terms we are familiar with. (Though, we don't usually have a NAND operator, but at least Perl has "unless" for universal NOT.)
Items 11-14 seem like interesting ones, but I've never seen these in programming. Items 15-16 are the XOR/XNOR.
Can any of these be used for AND/OR/NOT simplification? If so, have you used them?
UPDATE: "Not equal" or != is really XOR, which is used constantly. So, XOR is being used after all.
A: Going to close this question after the Not Equals/XOR thing. Out of the 16 possible operators, programmers use 9 of them:
FALSE, TRUE, X, Y, !X, !Y, AND (or ==), OR, XOR (or !=)
All of the other operators don't typically exist in programming languages:
X NAND Y = Alternative Denial = NOT (X AND Y), !X OR !Y
X NOR Y = Joint Denial = NOT (X OR Y), !X AND !Y
X ⊅ Y = Material Nonimplication = X AND !Y, NOT(!X OR Y), (X XOR Y) AND X, ???
X ⊃ Y = Material Implication = !X OR Y, NOT(X AND !Y), (X XNOR Y) OR X, ???
X ⊄ Y = Converse Nonimplication = !X AND Y, NOT(X OR !Y), (X XOR Y) AND Y, ???
X ⊂ Y = Converse Implication = X OR !Y, NOT(!X AND Y), (X XNOR Y) OR Y, ???
X XNOR Y = Biconditional = X IFF Y, NOT (X XOR Y), !X AND !Y
Perhaps there's room for them later on, because NAND/NOR seems pretty handy, and cleaner than typing NOT (X xxx Y).
A: Consider this:
if(an odd number of conditions are true) then return 1 else return 0
Using and/or/not, you might try
if(one is true || three are true || ... 2n+1 are true) then return 1 else return 0
That's pretty ugly because you end up having to specify each of the 1-sets, 3-sets, 5-sets, ..., 2n+1 sets which are subsets of the set of your conditions. The XOR version is pretty elegant, though...
if(C1 XOR C2 XOR ... XOR CN) then return 1 else return 0
For a large or variable N, this is probably better handled with a loop and counter system anyway, but when N isn't too large (~10), and you aren't already storing the conditions as an array, this isn't so bad. Works the same way for checking an even number of conditions.
You can come up with similar examples for the others, too. An interesting exercise would be to try programming something like
if((A && !B) || (!A && B)) then return 1 else return 0
And see whether the compiler emits assembly language for ANDs, ORs and NOTs or is smart enough to recognize this is XOR and, based on this, emits (a possibly cheaper) XOR instruction.
A: When programming in java, I tend to mostly use the following logic functions:
*
*not !
*and &&
*or ||
*xnor ==
*xor !=,
extending this to other basic functions:
*
*material implication A || !B
*converse implication !A || B
*material nonimplication !A && B
*converse nonimplication A && !B
Knowing when to use the xor and xnor comes down to simplifying the logic. In general, when you have a complex function:
1) simplify to either CNF ("conjunctive normal form" aka "sum over product") or DNF ("disjunctive normal form" aka "product over sum").*
2) remove extra terms A && (A || B),A || (A && B) -> A
2) simplify (A || !B) && (!A || B),(!A && !B) || (A && B) -> A == B
3) simplify (A || B) && (!A || !B),(A && !B) || (!A && B) -> A != B
Using these 3 simplifications can lead to much cleaner code using both the xor and xnor functions.
*It should be noted that a logical function may be much simpler in DNF than CNF or vice versa.
A: "Items 11-14 seem like interesting ones, but I've never seen these in programming."
I disagree. item 12, Material Implication is basically a "IF" statement, it is everywhere in programming.
I see Material Implication same as:
if(A) {
return B
}
A: Material nonimplication/abjunction use case
Got an instance now where I'd like to do a material nonimplication/abjunction.
Truth Table
╔═══╦═══╦══════════╗
║ P ║ Q ║ P -/-> Q ║
╠═══╬═══╬══════════╣
║ T ║ T ║ F ║
║ T ║ F ║ T ║ <-- all I care about. True followed by false.
║ F ║ T ║ F ║
║ F ║ F ║ F ║
╚═══╩═══╩══════════╝
I'm dealing with a number of permissions (all luckily true/false) for a number of entities at once and have a roles and rights situation where I want to see if a system user can change another user's permissions. The same operation is being attempted on all the entities at once.
First I want the delta between the between an entity's old permission state and new commonly desired permission state for all entities.
Then I want to compare that delta to the current user's change rights for this specific entity.
*
*I don't care about permissions where the delta requires no change.
*I only want a true flag where an action should be blocked.
Example
before: 10001
proposed after: 11001
delta: 01000 <<< I want a material nonimplication...
user rights 10101 <<< ... between these two...
blocked actions: 01000 <<< ... to produce this flag set
Right now I'm just doing an XOR and then an AND, which is the same thing.
Which kinda code smells that there's an easier way to do the comparison, but at least in this incredibly stodgy, step-by-step logic, it would be nice to have that operator.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Like Button: Make Facebook NOT take specific images I'd still like my users to have a choice of image to select when sharing links from my site but I would like to restrict certain images from showing in the Facebook sharer. I don't want to select a specific image using meta tags (this has been suggested often).
Would appreciate any help!
EDIT (9 Jul 2012): This question is not an exact duplicate to any others on stack overflow. I asked for a method to restrict images from showing without specifying OG or meta tags, unlike others who have simply asked how to show a specific image. Why do people on this site assume (and rate my question down) before even reading it carefully and considering whether it is a duplicate.
A: The only way to do this is to specify multiple og:image tags of images that you want to allow and then the user will be able to choose from the images you select.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Cannot Install into iPhone Simulator I've got an Xcode project that I've been working on over the past few weeks.
I just made some changes to an embedded framework that I'm working on (recompiled, to be specific) now, however, I am unable to launch the application in the simulator.
The app hangs on "Attaching to [app name]," if I have a debugger on. If I don't have a debugger on, Xcode just says the app has finished running.
There is no icon installed on the device.
Here's what I've done so far:
*
*Restarted
*Reset simulator
*Clean and build
*Deleted derrived data
I cannot install onto a device either, but then I get an error:
Error launching remote program: No such file or directory (/Users/peter/Library/Developer/Xcode/DerivedData/x-gtwuuwmavjonyrcxjmpcletdpyjw/Build/Products/Debug-iphoneos/x.app/x).
A: Oddly enough, what worked was installing another app in the sim (just launched another project and ran it) and then launching the other app in the sim.
I'm not sure what the issue was, but I tried it on two computers and it was hanging on each, so it was related to the project rather than the simulator. There's an issue to think about...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Slickgrid - How to update dataView with changed data I'm using grid.onBeforeEditCell event to make a one-click YesNoCheckboxCellEditor.
Not sure if this is the best way to do this, but here is the code I created for this:
Slickgrid - One-click checkboxes?
This works fine, but setting the data[] array directly doesn't seem to effect the dataView().
My understanding is that the dataView and data are completely uncoupled, and so when I have a filtered view, my data behind the filtered viewport will be incorrect.
Based on my code snippet, how do I also update the corresponding cell in the dataView ?
(I found the dataView.getItembyId and dataView.updateItem methods but unsure how to use these)
I've also tried: dataView.refresh(), grid.invalidateRow(), grid.render()
BTW, I'm following this example: http://mleibman.github.com/SlickGrid/examples/example-header-row.html
A: Use the grid.onClick instead of onBeforeEditCell.
See the http://mleibman.github.com/SlickGrid/examples/example7-events.html example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does there exist a Python IDE that allows one to emulate C#-like intellisense for autocompleting method calls on an object? For example, suppose I have the code:
class Foo(object):
def bar(self, x):
'''blah blah blah'''
return x+1
And suppose I am creating another class, that has a method that takes an instance of a Foo object and does something:
class Baz(object):
def goo(self, foo):
foo.bar(1) ### I am a 'Foo' object. Auto-complete me, please
I would desperately LOVE if after typing foo. while creating the goo() method in the Baz class, the IDE would provide me with intellisense. You know, show the available methods of the Foo class, their params, their doc, etc.
In C# I would have to declare that param 'foo' is type 'Foo', so the autocompletion is trivial.
I realize that Python is dynamically typed, so there is no way for any IDE to know that the 'foo' parameter is of type Foo. But is there some other info, directive, or convention that some IDE can use to determine the type ... strictly for the sake of intellisense and auto-completion?
One workaround I've found is to type Foo. which will cause most IDE's to show intellisense for the methods in Foo. This is useful, but it's not exactly what I'm looking for.
Another workaround is to type foo = Foo(), and then go about using foo as you normally would. Some IDE's sniff that foo is type Foo and provide intellisense. But then you must remember to delete the line foo = Foo(), else you've got a nasty bug.
Perhaps, there is a much better way to accomplish what I'm trying to do. I'm using C# intellisense as a point of reference, and maybe that's a Visual Studio thing, whereas when coding Python I should open my mind for a different way of accomplishing a similiar thing. Any suggestions would be much appreciated. I'm sure I can't be the only one craving intellisense for Python objects.
A: If you just have def goo(self, foo): with nobody calling it, there's no way to know what type foo will be. However, if you call goo in your code with a known Foo, the IDE can figure out that goo is always passed a Foo and autocomplete can work. This is how the Python Tools for Visual Studio works.
Note that this isn't terribly useful, though, because it requires that you write code that calls a function before that function is actually written. Here's a snippet showing that it works if you make it obvious:
A: Look at PyCharm by Jetbrains. It can auto-complete method names on an instance when the name of the referring variable matches (case-insensitive) a class name.
http://www.jetbrains.com/pycharm/
Nice screenshot here (scroll down and click the third image from the left):
http://www.jetbrains.com/pycharm/features/index.html
I should mention that this functionality is limited (because Python is dynamically typed) but it's better than any other Python IDE I've tried. This, along with many other great features make it my PyCharm IDE of choice.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to load these facebook plugins on Dom Ready They take so long to load, I want to do it after Dom loaded.
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'facebook-jssdk'));
</script>
<div class="fb-like" data-href="http://www.mywebsite.com<%=HttpContext.Current.Request.Url.AbsolutePath %>"
data-send="false" data-width="450" data-show-faces="true">
</div>
A: First, if you're not already using jQuery, you don't need jQuery. Follow a solution more like the one here, or if you don't need that kind of complexity and support for very old browsers, you can put together a much simpler version.
Once you have your "DOM ready handler", you should do one of the following two things:
*
*Move the JS SDK loading code into your DOM ready handler. No matter how many social plugins you have on the page, you only need to load the SDK once.
*Take xfbml: true out of FB.init(...), if you have it (in this case, you don't), and take xfbml=1 out of the SDK URL. This prevents social widgets from being parsed and initialized immediately. Then, call FB.XFBML.parse() in your DOM ready handler. See the documentation here for that method.
A: Thanks amosrivera :) Heres a code snippet I whiped up for anyone who finds this:
var Interface = {
Facebook: (function () {
function Init() {
}
function LikeButton() {
var $facebookLike = $('.facebook-like');
$facebookLike.html('<div id="fb-root"></div>');
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) { return; }
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
} (document, 'script', 'facebook-jssdk'));
$facebookLike.append('<div class="fb-like" data-href="'+$facebookLike.data('url')+'" data-send="false" data-width="450" data-show-faces="true"></div>');
}
function Comments() {
var $facebookComments = $('.facebook-comments');
$facebookComments.html('<div id="fb-root"></div>');
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
$facebookComments.append('<div class="fb-comments" data-href="'+$facebookComments.data('url')+'" data-num-posts="10" data-width="500"></div>');
}
return {
Init: Init,
LikeButton: LikeButton,
Comments: Comments
}
})()
}
A: Just use the document ready event from jQuery
$(document).ready(function(){
//code here
});
Demo: http://jsfiddle.net/ZCcyy/
Note that this will only wait until the dom is ready. If you want to load until the whole page is loaded including images use the window load event instead.
$(window).load(function(){
// code here
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: what does "movl (%esi, %ecx, 4), eax" imply? What does it mean to have these 3 instructions as the source of a movl instruction?
(%esi, %ecx, 4)
A: It means:
Calculate Address = (ESI + ECX * 4).
Read the value into EAX from 32-bit value at that memory address.
From the linked article:
GAS instructions generally have the form: mnemonic source, destination.
See: http://en.wikibooks.org/wiki/X86_Assembly/GAS_Syntax
Personally I prefer the more readable MASM syntax
mov EAX, dword ptr [ESI + ECX * 4]
^ ^
| +-- source in a readable syntax
+-------- destination
Which has the form: mnemonic destination, source (exactly the other way round).
Comment
Oh and what you call instructions, are really parameters.
The instruction is the whole statement.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Need the settings of SQL developer "F5" I need the settings in SQL Developer while performing the action Run as Script -f5.
Since, if I use sqlplus. it is not giving the exact result format what I want. But, in SQL Developer gives the needed format. I tried in all kind of settings, its not giving the same as SQL Developer prints...
So, settings like,
SET SERVEROUTPUT ON SIZE 1000000 FORMAT WRAPPED;
SET LONG 5000;
SET LIN 4000;
SET PAGESIZE 5000;
I need this kind of settings, for output display settings.
Anyone can help on this?
TIA
A: This is a non-answer, but try posting in the official OTN Sql Developer forums. The devs are very active about fielding questions posted there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Spring and Jackson Json: serialising two different sets of fields I've a Classified interface, annotated with @JsonAutoDetect with Visibility.NONE, so I can pick individual getters to be serialized with the @JsonSerialize annotation
@JsonAutoDetect(getterVisibility = Visibility.NONE)
public interface Classified {
@JsonSerialize
String getModel();
Until here there is no problem, and when I return Classified with @ResponseBody annotation, from my @Controller, it works returning the expected JSON:
@RequestMapping(value = "/classified/{idClassified}", method = RequestMethod.GET)
@ResponseBody
public final Classified getClassified(@PathVariable final int idClassified) {
However when I return a List of Classifieds, I would like to return a smaller set of getters, while with the following signature, obviously it returns all marked getters:
@RequestMapping(value = "/classified", method = RequestMethod.GET)
@ResponseBody
public final List<Classified> searchClassified(@RequestParam final int idBrand,
@RequestParam final String priceMax, @RequestParam final int page) {
I don't know how to return a smaller subset of Classified getters in each item of the list.
A:
"return a smaller set of getters"
If you mean reduce the number of items in the list, change the business logic in the controller's searchClassified method.
If you mean reduce the number of available public getter methods on each item, you could create a interface that only implements a subset of the original items getters, and return a list of them instead.
A: Check out "filtering properties", which lists multiple ways to change what gets serialized. I would guess that Json Views might be the easiest one; could use one smaller view, and then default "all" mode when no view is defined (default is then to serialize all properties).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Video Will Not Work On IE8 Here is my code:
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="322" height="266" align="Default*">
<param name="allowScriptAccess" value="sameDomain">
<param name="movie" value="Pro Tools Tutorials.swf">
<param name="quality" value="high">
<param name="bgcolor" value="#ffffff">
<param name="allowFullScreen" value="true">
<embed src="videos/Pro Tools Tutorials.swf" quality="high" align="middle" bgcolor="#ffffff" width="250" height="230" allowFullScreen="true" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">
A: Have you tried it with other browsers? and does it work?
Try changing this line:
<param name="movie" value="videos/Pro Tools Tutorials.swf">
and make sure you are locating in a proper path i suggest also you try to play the video in its direct path i.e (http://localhost/ < path of file >)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: I'm in trouble with inheritance and polymorphism in C++ I'm new to C++, and I'm trying to use inheritance but I have an error.
It says
Error 6 error LNK1120: 2 unresolved externals L:\2011-08\C++\Assignment\Drug Management\Debug\Drug Management.exe 1 1 Drug Management
There're three classes which are Animal, Sheep, and Cattle.
What I've done so far is:
//Animal.h
#ifndef ANI_H
#define ANI_H
#include <string>
#include "Treatment.h"
#include "jdate.h"
class Animal{
protected:
int id;
double weight;
int yy;
int mm;
int dd;
double dose;
char sex;
//Treatment treatArray[];
public:
Animal();
Animal(int newid, double newweight, int yy, int mm, int dd, double newdose, char newsex);
~Animal();
virtual double calcDose();
//void addAnimal();
double getDaysDifference();
};
#endif
//Cattle.h
#ifndef CATT_H
#define CATT_H
#include "Animal.h"
#include <string>
using namespace std;
class Cattle : public Animal{
private:
string category;
public:
Cattle();
Cattle(int newid, double newweight, int yy, int mm, int dd,
double newdose, char newsex, string newcategory);
~Cattle();
virtual double calcDose();
string getCategory();
};
#endif
//Animal.cpp
#include "Animal.h"
using namespace std;
Animal::Animal(int newid, double newweight, int yy, int mm, int dd, double newaccDose, char newsex)
{
id = newid;
weight = newweight;
dose = newaccDose;
sex = newsex;
}
double Animal::getDaysDifference(){
jdate dateOfBirth(dd,mm,yy);
jdate now;
double diff = now-dateOfBirth;
return diff;
}
//Cattle.cpp
#include "Cattle.h"
Cattle::Cattle(int newid, double newweight, int yy, int mm, int dd,
double newdose, char newsex, string newcategory)
: Animal(id, weight, yy,mm,dd, dose, sex)
{
id = newid;
weight = newweight;
dose = newdose;
sex = newsex;
Cattle::category = newcategory;
}
string Cattle::getCategory(){
return category;
}
double Cattle::calcDose(){
Cattle* c1;
if(c1->getDaysDifference() < 90 || c1->getCategory() == "Meat"){
c1->dose = 0;
return c1->dose;
}
else if(c1->getCategory() == "Dairy"){
if (c1->weight < 250 || c1->dose > 200){
c1->dose = 0;
}
else{
c1->dose = c1->weight * 0.013 + 46;
}
return c1->dose;
}
else if(c1->getCategory() == "Breeding"){
if (c1->weight < 250 || c1->dose > 250){
c1->dose = 0;
}
else{
c1->dose = c1->weight * 0.021 + 81;
}
return c1->dose;
}
else
{
cout << "It is not valid category" << endl;
}
}
Sheep class is pretty much same as Cattle.
I'm not sure if I'm on the right track.
What I'm trying to do is inherit (or polymorphism) calcDose() in Cattle.cpp taking from Animal.h.
Can you give me a piece of advice?
Cheers
A: You declared but did not define a default constructor and a destructor for Animal, and for Cattle (and presumably the others as well). Define them, or don't declare them (you probably do need a destructor though, even if it does nothing).
Another problem is your calcDose method. One way to deal with that is to make it "pure virtual" in Animal: use virtual double calcDose() = 0;
One final problem: Don't use use namespace std;. Don't ever, ever, ever use it in a header file.
A: Without seeing all of your program's code, or without you specifying which symbols the linker couldn't find, it's hard to say exactly which symbols it's complaining about, but Animal is missing implementation for 3 of its member functions, and Cattle is missing implementation for 2 of its member functions.
A: You've declared calcDose inside your Animal class, but you haven't defined it. If you intended for that just to be implemented in the derived classes, then you should make it be pure virtual in your Animal class like this:
virtual double calcDose() = 0;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: what does the term rep-invariant and rep ok means? I heard this a lot when talking about software engineering and abstract data types, what does this do? Can anyone give me a concrete example of this concept?
A: A representation invariant is a condition concerning the state of an object. The condition can always be assumed to be true for a given object, and operations are required not to violate it.
In a Deck class, a representation invariant might be that there are always 52 Cards in the deck. A shuffle() operation is thus guaranteed not to drop any cards on the floor. Which in turn means that someone calling shuffle(), or indeed any other operation, does not need to check the number of cards before and after: they are guaranteed that it will always be 52.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: Better Table Design Me and a few others are currently working on a game that will be using MySQL to save characters. We presently have a table that holds character information (username, password, id, inventory, and item storage chest).
We are trying to think of the best way to handle the item storage chest data. As of right now, we just store it in 2 columns. A character's storage chest will have a capacity to hold around 300 items, with each item being able to have a stack size of the maximum value of an integer. We save item id's in one column and the items respective amounts in another.
However, we have been discussing this design and have been thinking of ways to better it. Right now, we have the following ideas:
*
*Create a new table just for the item storage. In this table, have a column for the player's id number (a primary key) from the users table previously mentioned, a column for the item id numbers, and another column for the amounts
*Create a new table just for the item storage. In this table, have a column for the player's id number (a primary key) from the users table previously mentioned and a column for all of the id numbers and amounts separated by delimiters.
*Leave it how it is
We are expecting around 10,000 accounts to be made and used, with a good possibility of more being created. We are just unsure of what would be the best performance wise
A: In this case having 1 or 2 tables has more impact in scalability than performance. A better approach is having 3 tables. 1 for players, 1 for items and 1 for the relationship player-item.
player
id name
item
id amount description
player_item
id_player id_item
Having this extra table for items will allow you to have item types. You will be able to add items easly extra information e.g description and you will only need to set the amount once.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Object references in WinForms PropertyGrids Say I have a class called StaffMember and it has a member variable of type Position.
If I have an enum which defines all possible positions, then when I load the StaffMember object into my PropertyGrid, I can see a drop-down box allowing me to select from the positions defined in my enum.
However, I do not know all the different types of positions - and they can change from week to week - or even at runtime for that matter.
So I don't have a static enum with positions: instead I have a List<Position> which contains the current list which can be added to, changed, etc.
When I put my StaffMember object with a List variable into the PropertyGrid, the Position variable is disabled and I am unable to set/modify it.
Is it possible to get this to work, or am I doing something fundamentally wrong/impossible?
A: Looks like you want an UI Type Editor ...
have a look at this:
http://msdn.microsoft.com/en-us/library/ms171840.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to encode url parameter in Joomla I am working with Joomla component
Problem is:
I have an URL like this
http://localhost/Joomla_16/index.php/component/mycomponent_name/?view=mycomponent_view&cre=15
I want to encode the value of &cre=15
How can I do that?
Thanks in advance.
A: Problem solved
It is easy. Using base64_encode. silly me!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Perform uneven stretch draw with Delphi OK, this is something that is best explained with an image...
I am looking for a function similar to StretchBlt but where i can copy an image to a canvas defining the four corners of the destination, i.e. a Trapezoid/Quadrilateral stretch draw of an image onto a canvas.
I can think of a number of slow ways to do this, but I want to know if there is something of a similar speed to StretchBlt (e.g. no more than ten times slower).
Thanks
A: There are very fast methods for this in the Graphics32 library.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Facebook insights domain_widget_likes -> lifetime don't return results? I'm doing a query to get the total likes for a domain and I am using the following:
https://api.facebook.com/method/fql.query?query=SELECT metric, value FROM insights WHERE object_id=xxxxxxxxx AND metric='domain_widget_likes' AND end_time=end_time_date('2011-08-27') AND period=period('lifetime')&access_token=xxxxxxxxx
I already claimed my domain, have the object id for my domain and installed an app to get access to insights and send the token.
But return nothing, if I try with period('day') the query works fine but I need all likes not only daily.
Anyone knows if it is a new rule on the insights data or is a bug?
Thanks a lot.
A: Are you able to use a wildcard % in the query like so (period LIKE period('%')):
https://api.facebook.com/method/fql.query?query=SELECT metric, value FROM insights WHERE object_id=xxxxxxxxx AND metric='domain_widget_likes' AND end_time=end_time_date('2011-08-27') AND period LIKE period('%')&access_token=xxxxxxxxx
String Comparison Functions Reference has more info on query wildcards, etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In app purchase for auto-renewable content prompts user to share information I am adding the ability to purchase auto-renewable content through the iOS SDK's StoreKit API.
When testing this in the sandbox on my iOS device, the following message appears in an alert after agreeing to purchase:
Share your Information?
The publisher of [app name here] would like
your name, email, and zip code for use in accordance with their
privacy policy.
With buttons for "Don't Allow" and "Allow"
I don't want / need this information and don't want to annoy my users by prompting for it. However, I can't figure out how to disable this prompt to collect private information.
Any tips are appreciated!
A: This is a marketing opt-in in your in-app product! Just uncheck it! This should do the trick!
EDIT:
This option is in the iTunesConnect: Select your app in iTunesConnect, select "Manage In-App Purchases" (if you can't see it, you will have to subscribe for it in iTunesConnect > see Contracts).
Select your autorenewable product and than the duration, you have already registered (e.g: 1 month). There you'll see the option "Offer a marketing opt-in incentive?". Select the option "No". After Apple has verified the product, the option should have gone when a user buys the autorenewable product.
A: There is currently no option to disable this prompt.
A: This is an answer from apple: "You need to send a request to App Review and they can disable this feature. You can contact App Review using the email address appreview@apple.com."
A: Here is an official answer from Apple Staff
The "Share Your Information" dialog can be disabled by App Review.
Please submit a request to appreview@apple.com, provide the
application ID with the request. App Review may ask for additional
information, but they can change the setting which triggers the
presentation of this alert to users.
You may be aware of the option for Auto Renewing subscriptions to
"Offer a marketing opt-in incentives" - yes/no. This setting controls
whether the user will be provided a bonus free period for sharing
their information. This option does not control whether the "Share
Your Information" alert is presented.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
}
|
Q: Nested presenters with GWTP I have content slots in my mainpresenter, how can i put, when app load, put the home presenter in one slot and the menu slot in the another ?
or isn't possible?
thanks in advance.
A: Yes you can ! In the following example code, I assume that your HomePresenter is a place and extends Presenter, and your MenuPresenter extends PresenterWidget.
In your MainPresenter :
@ContentSlot public static final Type<RevealContentHandler<?>> MAIN_SLOT = new Type<RevealContentHandler<?>>();
@ContentSlot public static final Type<RevealContentHandler<?>> MENU_SLOT = new Type<RevealContentHandler<?>>();
@Override
protected void onReveal() {
super.onReveal();
setInSlot(MENU_SLOT, menuPresenter);
}
In your HomePresenter :
@Override
protected void revealInParent() {
RevealContentEvent.fire(this, MainPresenter.MAIN_SLOT, this);
}
Then in MainView :
@UiField Panel mainContainer;
@UiField Panel menuContainer;
@Override
public void setInSlot(Object slot, Widget content) {
if (slot == MainPresenter.MAIN_SLOT) {
mainContainer.clear();
mainContainer.add(content);
} else if (slot == MainPresenter.MENU_SLOT) {
menuContainer.clear();
menuContainer.add(content);
} else {
super.setInSlot(slot, content);
}
}
A: For users of GWTP 1.5+, note that a lot of new changes have been introduced to slots, and revealing presenters. The case in question may now be accomplished using a NestedSlot for the page content and a PermanentSlot for a menu that you want displayed on all of your pages.
Fortunately, these changes are well documented. See the GWTP slot documentation for an explanation on the new slot types with examples on how to use them.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: JQuery Ajax call for PDF file download My question is similar to Download and open pdf file using Ajax
But not exactly the same , the reason I want an JQuery ajax is that my file is being generated dynamically from the data which would be fetched from the same page.
So basically I have a Json Object which needs to be sent to the server which would dynamically generate a file and send it back to the browser.
I would not like to use query strings on an anchor with my Json object stringyfied ,
as I think it would be a potential threat as query strings have character restrictions ( am I right here ?).
Please let me know If my workflow is right or I can achieve the same thing thing using a different flow.
A: You should not use AJAX to download files. This doesn't work. This being said you are left with 2 options:
*
*action link and query string parameters or if the download must be trigerred at some specific javascript event you could also set the window.location.href to the action that is supposed to generate the PDF file and pass query string parameters to it.
*or if you are afraid that you have lots of data to pass to the controller action that will generate the PDF to download you use a <form> with method="POST" and inside you use hidden fields to store as much parameters and data as you like:
@using (Html.BeginForm("download", "home"))
{
... hidden fields containing values that need to be sent to the server
<input type="submit" value="Download PDF" />
}
A: Instead of making one more ajax call in your page you can use anchor tag and php force download to perform pdf download
HTML
<a href="www.example.com/download_file.php?file_source=example.pdf">Download pdf here</a>
PHP
<?php
$fullPath = $_GET['fileSource'];
if($fullPath) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
header("Content-type: application/pdf"); // add here more headers for diff. extensions
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
if($fsize) {//checking if file size exist
header("Content-length: $fsize");
}
readfile($fullPath);
exit;
}
?>
I am checking for file size because if you load pdf from CDN cloudfront, you won`t get the size of document which forces the document to download in 0kb, To avoid this i am checking with this condition
if($fsize) {//checking if file size exist
header("Content-length: $fsize");
}
I too was struggling with this problem, above code worked for me I hope it helps
A: I have a very sure answer. You can't download PDF file while using the ajax request to server. So instead of that you should use html actionlink. for example
@Html.ActionLink("Convert Data into PDF", "PDFView", null, new { @class= "btn btn-info" });
Above code will generate a link button and you can access Action Method of controller. Also you can use any technique to return PDF file from controller for example you can return PDF file using FileResult class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Need help to figure out why current code does not work with current latest (1.6.4) version of JQuery Below is the code, the program is split into two main segments.
One that performs operation on each Select element and the other
on all the option elements within this\each select and this one
does not work as it should append a price "[+$00]" to each select option text value,
bar the currently selected one. The piece of code that does not work is tagged.
Worked fine with 1.5.1, 1.5.2 and does not work with all starting from 1.6
// ===== CODE DOES NOT WORK FROM HERE WITH 1.6.4============
$(this).find('option').each(function () {
//$(this).append('<span></span>');
var uov = parseInt($(this).attr('value')) || 0; //Unselected option value
var uop; //Unselected Option Price
for (d = 0; d <= data.length; d++) {
if (data[d].partid == uov) {
uop = data[d].price;
break;
}
}
//debugger;
var pricediff = Math.abs(uop - sop);
var xtext = $(this).text();
if (xtext.match(/\✔/) != null) {
var temp = xtext.replace(/✔/g, '');
xtext = temp;
}
if (xtext.match(/\[.*\]/) != null) {
var temp = xtext.split('[')[0];
var temp2 = xtext.split(']')[1];
xtext = temp2;
}
if (uov != 0) {
if (pricediff != 0) {
var diff = '[' + (sop > uop ? '-' : '+') + '$' + pricediff + ']';
$(this).attr("text", diff + " " + xtext);
}
else {
$(this).attr("text", " ✔ " + " " + xtext);
}
}
//=============== TO HERE ========================
A: Don't use:
$(this).attr('value')
to get the value of a form field. Use:
$(this).val()
This has caused many headaches with our client developers when we changed our framework's jQuery version.
--- Edit ---
You most certainly should not be trying to edit the text of an element with the attr() function as you have here:
$(this).attr("text", diff + " " + xtext);
You should use:
$(this).text(diff + " " + xtext);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Data validations while transforming data in Pentaho How do I check for foreign key validations while using Pentaho for transformation? Like I would like to transfer one table named employee from a source MySQL database to another target MySQL, and if the employee table in target MySQL database is linked to a country table.
The incoming employee data to Pentaho(during transformation) may have any country or null, I would like to leave the country field as such if it is already a country existing in the target MySQL database country table, other wise set it to NULL.
Similar to country, I have few other fields also to be transformed in the same way. I checked the "Data validation" in Pentaho but it just gives an option to predefine or enter predefined values, which is not so good as the country table may be subject to CRUD operations.
A: Just perform a "database lookup" against your country table. It can return the key or the country name whatever you need. It will return null if not found, or you can set a default value. then use the field returned from the database lookup step in your target table.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Deducing string transformation rules I have a set of pairs of character strings, e.g.:
abba - aba,
haha - aha,
baa - ba,
exb - esp,
xa - za
The second (right) string in the pair is somewhat similar to the first (left) string.
That is, a character from the first string can be represented by nothing, itself or a character from a small set of characters.
There's no simple rule for this character-to-character mapping, although there are some patterns.
Given several thousands of such string pairs, how do I deduce the transformation rules such that if I apply them to the left strings, I get the right strings?
The solution can be approximate, working correctly for, say, 80-95% of the strings.
Would you recommend to use some kind of a genetic algorithm? If so, how?
A: If you could align the characters, or rather groups of characters, you could work out tables saying that aa => a, bb => z, and so on. If you had such tables, you could align the characters using http://en.wikipedia.org/wiki/Dynamic_time_warping. One approach is therefore to guess an alignment (e.g. one for one, just as a starting point, or just align the first and last characters of each sequence), work out a translation table from that, use DTW to get a new alignment, work out a revised translation table, and iterate in that way. Perhaps you could wrap this up with enough maths to show that there is some measure of optimality or probability that such passes increase, climbing to a local maximum.
There is probably some way of doing this by modelling a Hidden Markov Model that generates both sequences simultaneously and then deriving rules from that model, but I would not chose this approach unless I was already familiar with HMMs and had software to use as a starting point that I was happy to modify.
A: You can use text to speech to create sound waves. then compare sound waves with other's and match them with percentages.
This is my theory how Google has such a advanced spell checker.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Problem in running .net framework 4.0 website on iis 7.0 Hey I got problem in running .NET framework 4.0 website on IIS7.0.
the error I got is like:
HTTP Error 404.2 - Not Found "The page you are requesting cannot be served because of the ISAPI and CGI Restriction list settings on the Web server".
Module : IsapiModule ,
Notification : ExecuteRequestHandler,
Handler : PageHandlerFactory-ISAPI-4.0_32bit ,
Error Code : 0x800704ec
A: If you look in the ISAPI And CGI Restrictions, and everything is already set to Allowed, then make sure that the ASP.NET v4.0.30319 handlers are even in the list. In my case they were not. This can be easy to overlook.
I added one for 32 %windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll and another for 64 bit %windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll. You can name them both the same ASP.NET v4.0.30319.
Check Allow extension path to execute.
A: *
*Go to the IIS Manager.
*open the server name like (PC-Name)\.
*then double click on the ISAPI and CGI Restriction.
*then select ASP.NET v4.0.30319(32-bit) Restriction allowed.
A: In my case, the problem was more severe: turns out asp.net was not correctly registered.
This response worked fine.
simply ran the following command at the command prompt
%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i
If I had been on a 32 bit system, it would have looked like the following:
%windir%\Microsoft.NET\Framework\v4.0.21006\aspnet_regiis.exe -i
A: Step 1: Open IIS and click the server name
Step 2. Double click “ISAPI and CGI Restrictions”
Step 3. Right click ASP.NET v4.0.30319 and select “allow”
After
Stopping and Starting the World Wide Web Publishing Service
1.Go to Start > All Programs > Administrative Tools > Services.
2.In the services list, right-click World Wide Web Publishing Service, and then click Stop (to stop the service), Start (to start it after it has been stopped), or Restart (to restart the service when it is running).
Pramesh
A: Go to IIS manager and click on the server name. Then click on the "ISAPI and CGI Restrictions" icon under the IIS header. Change ASP.NET 4.0 from "Not Allowed" to "Allowed".
A: If you are running Delphi, or other native compiled CGI, this solution will work:
*
*As other pointed, go to IIS manager and click on the server name. Then click on the "ISAPI and CGI Restrictions" icon under the IIS header.
*If you have everything allowed, it will still not work. You need to click on "Edit Feature Settings" in Actions (on the right side), and check "Allow unspecified CGI modules", or "Allow unspecified ISAPI modules" respectively.
*Click OK
A: In our case the solution to this problem did not involve the "ISAPI and CGI Restrictions" settings. The error started occuring after operations staff had upgraded the server to .NET 4.5 by accident, then downgraded to .NET 4.0 again. This caused some of the IIS websites to forget their respective correct application pools, and it caused some of the application pools to switch from .NET Framework 4.0 to 2.0. Changing these settings back fixed the problem.
A: If you look in the ISAPI And CGI Restrictions, and everything is already set to Allowed, and the ASP.NET installed is v4.0.30319, then in the right, at the "Actions" panel click in the "Edit Feature Settings..." and check both boxes. In my case, they were not.
A: Try changing the AppPool Manged Pipeline Mode from "Integration" to "Classic".
A: Depending on the type of application, another thing to check is under the Advanced Settings for the Application Pool make sure "Enable 32-Bit Applications" is set to True.
I'd checked everything in this thread when I had this issue but all had already been setup correctly, I found this was the problem for me.
A: If you don't have ISAPI and CGI Restrictions option listed, here is how to add it. How to add ISAPI and CGI Restrictions
A: After mapping of Application follow these steps
Open IIS
Click on Applications Pools
Double click on website
Change Manage pipeline mode to "classic"
click Ok.
Ow change .Net Framework Version to Lower version
Then click Ok
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "119"
}
|
Q: How to change the text of an anchor when clicked with the mouse? This is my website. http://www.sarahjanetrading.com/js/j/index.html All the code+images+css is there with access to anyone
When anyone clicks on the listen button its background changes into the stop listening and vice versa. This is the functionality I wanted and I got it using jQuery.
What I also want now is the text to change too accordingly. Like, when someone clicks on the "listen" anchor, its text should change to "stop listening", and the same for the stop listening anchor. Like a toggle anchor.
Thanks for the help ! Really appreciate it... :)
A: $("#first").toggle(function(){
$(this).text("Stop listening");
}, function(){
$(this).text("Listen");
});
Online demo: http://jsfiddle.net/5AUdJ/
UDPATE
I see you are using a class to control the listen/stop state. Maybe this will work better.
$("a").click(function(){
if($(this).is(".listen")){
$(this).text("Stop listening").removeClass("listen");
} else {
$(this).text("Listen").addClass("listen");
}
});
A: Here, I made this JSFiddle using your source code.
http://jsfiddle.net/K4Njj/2/
Here is the jQuery code:
$(function(){
$("#container a").click(function(){
if ($(this).html() == "Stop Listening")
{
$(this).html("Listen");
}
else if ($(this).html() == "Listen")
{
$(this).html("Stop Listening");
}
});
});
That will simply check to see if the text on the anchor is "Stop Listening" or "Listen" and if it is, it will switch it when you hit the button. It's really the most elegant solution.
A: In your Javascript, you can use the innerHTML property to access and/or change the HTML text of an element.
getElementById("first").innerHTML = "newtext"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to inline wrap layouts? How do we make inline layouts in Android?
Something like this:
I tried using margin right in Relative layouts but they are separated into 2 columns instead of wrapping each other:
<RelativeLayout
android:id="@+id/Container"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:id="@+id/Layout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginRight="60sp">
.... //something here
</RelativeLayout>
<RelativeLayout
android:id="@+id/Layout2"
android:layout_width="60sp"
android:layout_height="wrap_content"
android:layout_alignParentRight="true">
.... //something here
</RelativeLayout>
</RelativeLayout>
A: Layout2 have width 60dp and in layout1 you are putting margin to 60dp so that they looks like a two column If you want to check it change margin of layout1 to 30dp you will see that wrapping effect
and also put some controls inside layouts so that you can see the area
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Tracking history of a branch How can I see the history of a particular branch?
I have been creating and merging branches. However, on one particular branch say for example new_feature. I want to know the history of what has been merged into this branch, and what branch this was created from?
The reason is I have this new_feature branch, and I want to know what other branches was merged into it, and what branch the new_feature was made from?
I an not really interested in using any GUI tools, maybe some on the command line.
I'm using Git version 1.7.5.4 and Ubuntu 11.10.
A: git log --oneline --graph --all may give you what you want, without the need for third-party tools.
*
*--oneline makes the commits display on one line only, instead of the longer default format.
*--graph shows branch/merge history with ASCII characters.
*--all shows all branches in the history, not just the current one.
A: You can see only merge commits with git log --merges. As long as you haven't messed with your merge commit messages, you'll see what branches you've merged. (If you don't want to use HEAD as a starting point, provide a commit/branch/tag as an argument.) Tweak the output to your liking with other options - see the man page. You might like --oneline (one line commit summaries) or even --pretty=%s (print only commit subjects). You might also like --first-parent, which by following only the first parents of merges, prevents it from reporting commits from the merged branches.
Knowing what branch a branch started from is a little trickier - that's not really information that gets recorded. You might find it as the first (bottom) entry in the output of git reflog <branch>, if it was recent enough.
A: I often use tig, which is a text mode repository browser for Git. However, the gitk program that comes with Git is also useful for viewing repository history, because sometimes the lines between branches can get pretty complicated and it's easier to see in a GUI tool.
For low-level history, the git reflog command will show you all the actions that have caused the current (or specified) branch head to move.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: how to implement swf address navigation in struts 2 I want to implment swf address navigation in struts 2 like twitter and facebook navigation. I meant to say for each page user navigation header and footer and some common components across the websites will not be loaded for each user navigation. in some sites like twitter and facebook they have done with swf address implementation by concatinating '#' to current url for each user navigation with required pagename.so i want to implement same thing in struts 2. So how can i implement it.
A: I don't know what you mean by "swf" navigation; I only know swf as Flash, which neither Twitter nor Facebook use for navigation.
Why do you want a "#" in the URL? What do you think it does?
In any case, if what you're asking is really "How do I get only some parts of the UI to update during navigation", the answer is either Ajax, or iframes. (Personally, I think iframes are almost always wrong, especially with what modern JavaScript and CSS allow, but they have their uses.)
A: First of all I am not sure about the term SWF Address Navigation. Hash Bookmarking is a more common phrase for libraries that actually does this task.
This is a matter of client side programming and it has nothing to do with struts 2. There is a good jQuery plugin for that. It is called jQuery history plugin.
You can find lots of other libraries and the best choice depends on your application requirements.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Meanings of dollar sign in Java method descriptor? For example, its part of the Jikes RVM stack.
at [0x70cfba90, 0x708cfaa4] Lorg/apache/lucene/index/SegmentInfos;
**access$000**(Ljava/lang/String;)V
at [0x70cfbb04, 0x708b55c8] Lorg/apache/lucene/index/SegmentInfos$
FindSegmentsFile; run()Ljava/lang/Object; at line 554
at [0x70cfbb24, 0x708c4a8d] Lorg/apache/lucene/index/SegmentInfos;
read(Lorg/apache/lucene/store/Directory;)V at line 272
'access' should be a method name. But I checked the class source code and its interfaces, there is no method there called 'access'. I couldn't find an answer on Google, since Google hates all kinds of punctuations. Can anyone help here? Thanks very much.
A: Quoted from the article linked by @birryree:
A private member m of a class C may be used by another class D, if one class encloses the other, or if they are enclosed by a common class. Since the virtual machine does not know about this sort of grouping, the compiler creates a local protocol of access methods in C to allow D to read, write, or call the member m. These methods have names of the form access$0, access$1, etc. They are never public. Access methods are unique in that they may be added to enclosing classes, not just inner classes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: JS error 'redeclaration' of var when it's first line in program? SCRPT5039: Redeclaration of const property line 1 character 1
line1: var editObj = null;
This is the beginning of the file and I checked to make sure that variable is not in any other js files being called. Is it saying that I redeclare it later? (if so that line reference is not useful) or what is wrong with this?
A: I got this error with the following code:
var window;
I had added this declaration to workaround a node error when using the following code:
if (!window) {
//node-specific stuff
}
Without the above declaration, node wold complain. In the end, I chose to copy/paste rather than try to share the exact same file between node and browser implementations.
A: EDIT: Fixed it. For me, anyway. I got this error before the redeclaration error:
HTML1113: Document mode restart from Quirks to IE9 Standards
This suggests that IE finds what it thinks is an error, so loads the page again in Quirks mode. Loading the page twice makes it think everything is declared twice. So the solution is to find what IE didn't like.
First I ran the page through the online HTML validator. Next I ran my javascript through jsLint. After all that, IE9 seemed happy. And as a bonus I have better quality code. I hope.
A: I had a similar problem with the same error, but my first line of code was an alert(0); which I had inserted to make sure the script was being loaded! Interestingly, the script was loaded according to IE9's developer tools, but the first line was never executed and the error pointed to this alert(0); as the redeclaration. I even inserted lines and spaces before it and the line and character number changed accordingly. However, this (obviously) wasn't the thing being redeclared because it's not even a declaration, let alone a redeclaration!
I deleted chunks from the end of the script until it executed the alert(0); (indicating that the script had loaded and been parsed successfully), and I discovered that the offending line was:
var screen;
Turns out IE9 already has a window.screen with which this declaration collided, and renaming my screen to eScreen fixed the problem.
So my answer is: don't trust IE9's indication of where the redeclaration is!
(It's also worth noting that the script ran fine in its original form on IE7, IE8 and IE10, just not on IE9.)
A: I had the same problem in my code and it turn out that IE show wrong line were the redeclaration appear. In my case it was history I use later in the code. You should check whole code for redeclaration of the constants. You can try to comment out part of the code and see when it throw that error.
A: The error comes because you have declared some global/local variable which matches with default browser property. Something like
var window = '';
var navigator = '';
Try removing/commenting such declaration and see the effects.
A: I was getting this error too -- problem is the line it fires on is completely bogus. Like the OP, it was an early line in my script that was being flagged:
var h_combinedView = true;
The error message is very misleading: "0x800a041c - JavaScript runtime error: Let/Const redeclaration"
The flagged line is not a const definition, and the value on it is defined once in my entire project and never again.
Eventually I tracked the problem down to an actual duplicated const definition.
const ve = { Normal: 'default', Search: 'search', View: 'view', Alts: 'ViewAlts', Edit: 'edit' }
(I had moved a definition used in multiple places into a shared file & forgot to remove one copy). The error message was legit -- it was a duplicated const definition -- but the line and identifier flagged had NOTHING to do with the problem.
Nothing like inaccurate error messages to force me to walk through my code.
:-)
A: I had the same error and came across this post. While I did not have the same root issue as the OP I thought I would share my solution in case others make my same mistake and arrive here. I received the error in a separate js file. After simplifying it, I found I could generate the error from the following code:
var foo = null;
var bar = null;
var localData = null;
The error said it was from the first line. However, foo was not being redeclared. The problem was that localData must have been used elsewhere (not in my code). No matter how far down in the file localData was declared, the error listed as being on the first real line of code.
So, if other solutions don't work, try renaming each variable in the code file to determine which one may be causing the problem. Don't trust that the debugger is pointing to the right line.
Encountered: HTML5/JS Window Store app.
A: From an error by me doing a git merge, I found that I had included the script in my HTML twice. This way, when it ran the script the second time, it redeclared the variable.
And it only gave me the error for the first const, which was confusing to me, as I tried to remove the variable or add another one to the file, it always gave me the error for the first line.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: PHP/GD Library Imagettftext save image on server and send to browser I am overlay some text on an image (that is already on my server) using GD. I am trying to save the new image on the server.
Below is my code but all it does is show the new image to the browser it doesnt save it to the server.
<?
//PHP's GD class functions can create a variety of output image
//types, this example creates a jpeg
header("Content-Type: image/jpeg");
$im = imagecreatefromjpeg($image_full);
$black = ImageColorAllocate($im, 255, 255, 255);
$copy_1_x = 10;
$copy_1_y = 20;
$copy_2_x = 10;
$copy_2_y = 20;
$copy_3_x = 10;
$copy_3_y = 20;
//writes text to image
Imagettftext($im, 12, 0, $copy_1_x, $copy_1_y, $black, 'verdana.ttf', $main_number);
Imagettftext($im, 12, 0, $copy_2_x, $copy_2_y, $black, 'verdana.ttf', $prime_number);
Imagettftext($im, 12, 0, $copy_3_x, $copy_3_y, $black, 'verdana.ttf', $legal);
//Creates the jpeg image and sends it to the browser
//100 is the jpeg quality percentage
Imagejpeg($im, '', 100);
ImageDestroy($im);
?>
A: Thanks @Ignacio
Imagejpeg($im, '/path_to_folder/imagename.jpg', 100);
Found at http://php.net/manual/en/function.imagejpeg.php
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Quartz.NET job configurared to run once daily works the first day but fails to fire on subsequent days I've configured quartz.net within my asp.net application and I have a job set to run daily at 1am. If I change the job-config.xml file to have the job run in 2 minutes time, the change is automatically picked up without restarting the app-pool, and the job is fired off. However, if I revert the change to have the job fire off at 1am in the morning again, it doesn't seem to fire off. The obvious reason to me would be that either the app-pool or IIS has been restarted, which would have caused my asp.net app to shutdown (in effect shutting down quartz.net as it's part-and-parcel of the same asp.net process), but to test whether quartz.net is still running, without any iisreset or app-pool recycle, I change the job-config.xml file again to fire off within 2 minutes again and the job runs, so it doesn't seem to be the case where an app-pool recycle or IIS reset has occurred - I don't understand.
I would like to keep the job running under my asp.net application without having to create an additional windows service, so any help would greatly be appreciated. Below is a snippet of my quartz.net config file.
<job>
<job-detail>
<name>xjob</name>
<group>MyJobs</group>
<description>blah blah</description>
<job-type>yyy.xxx,yyy</job-type>
<volatile>false</volatile>
<durable>true</durable>
<recover>false</recover>
</job-detail>
<trigger>
<cron>
<name>xJobTrigger</name>
<group>MyJobs</group>
<description>blah blah</description>
<job-name>xJob</job-name>
<job-group>MyJobs</job-group>
<cron-expression>0 0 1 * * ?</cron-expression>
</cron>
</trigger>
Thank you
A: I think there are a couple of things going on. As you mention, if you run the scheduler under asp.net, the process might get recycled and your scheduler might not be available to run the job when it is supposed to run. If having the job run at a give time is important, then you need to set up Quartz.net as a service.
The other thing that is missing is that I think you are using a RAM jobs tore, which means that when the scheduler restarts, it reschedules the job, so in your case, it will not fire again until 1. If the scheduler is not running at 1, then the job won't fire, even if the scheduler restarts (and so on). If you use an ADO job store, then at least the trigger will get persisted and the job will run once the scheduler starts again and the misfire is detected.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What exactly am I supposed to do for OAuth 2.0 and https update? I am a php developer. I created an application using fbml(non iframe) and didn't check roadmap regularly.
Today I received an email saying update to OAuth 2.0 and HTTPS by October 1st or the apps may be disabled.
I went through the documentation but could not get what exactly I am supposed to do.
From what I understood.
for https
we need to enable or buy ssl for our site and make https://example.com/facebookapps_folder/ accessible and fill the new url in Secure Canvas URL
Is that right?
I am confused about OAuth 2.0.For this do we need to change the whole code and libraries we are referring to.
Where can I get how do I change it.
I see some php examples but could not find clue what needs to be changed?
I think it is way authentication is being done, but I do I do that.
If I fail to do it immediately(as only 3 days left) is that any way I can save my application being disabled?
A: Make sure you have implemented Oauth2.0 for authentication .. Also you will need an SSL certificate for your app to support https:// protocol
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using GPS to two location (Position 1 to 2) , OnLocation Changed I am targeting of using Android 2.2 to find distance using GPS however there are some problem in regarding my on Location changed. Previously, I put my code at On click listener and it does not work well. I manage to get the distance only after pressing the start and stop button after a numerous times.
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc) {
if(originalCoordinates!=null){
coordinates1 = getGPS();
gpsEnd=coordinates1;
double d = distFrom(originalCoordinates[0],originalCoordinates[1],gpsEnd[0],gpsEnd[1]);
totalDistanceTravel+=d;
disTrav.setText(Double.toString(d));
txtViews.setText("" + coordinates1.length + " new counts!!!" + coordinates1[0] + "," + coordinates1[1] );
}
if(coordinates!=null)
{
double[] coordinatesPrev=coordinates;
txtView.setText("" + coordinates.length + " counts!!!" );
//double d = distFrom(coordinatesPrev[0],coordinatesPrev[1],coordinates[0],coordinates[1]);
//totalDistanceTravel+=d;
}
else
{
coordinates = getGPS();
gpsOrg=coordinates;
if(originalCoordinates == null){
originalCoordinates = gpsOrg;
coordinates1 = getGPS();
txtView.setText("" + originalCoordinates.length + " original counts!!! " + originalCoordinates[0] + "," + originalCoordinates[1] );
}
//txtView.setText("" + coordinates.length + " counts" );
}
startButton.setEnabled(true);
}
A: dear do it like this.
*
*Switch on GPS of your device
*Wait until it get connected to a satellite.
*Make a flag like booelan detecting_position.
*Set it true on start button.
*OnLocationChange Listner, check if flag is true, then get the
points using location.getLat,and getLong... and save them.
*Here you can do a trick, initialize start location variables with
null, and check if startPosition is null then on first iteration of
location listner set long and lat as start location, in further
location change iterations set long and lat to stop_location
variables.
*Once you tap the stop button set flag to false.
*Now you have both start and end position. Use the distance formula
to calculate distance.
A: first of all take activity and do like below
public class MainActivity extends Activity implements OnClickListener
{
Button btnStart = null;
Button btnStop = null;
Context context = null;
Button btnTouch = null;
float distance ;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
context = this;
btnStart = (Button)findViewById(R.id.btnStart);
btnStop = (Button)findViewById(R.id.btnStop);
btnStart.setOnClickListener(this);
btnStop.setOnClickListener(this);
}
@Override
public void onClick(View v)
{
Intent i = new Intent(context, MyService.class);
if(v.getId() == R.id.btnStart)
{
startService(i);
}
else if(v.getId() == R.id.btnStop)
{
distance = MyService.final_distance;
stopService(i);
}
}
}
then take one service and put our logic for location change in this service.i have use service because service run in background continue and look for location change when location is update.
public class MyService extends Service implements LocationListener
{
public static float final_distance = 0.0f;
private float distance = 0.0f;
private double old_latitude = 0.0;
private double old_longitude = 0.0;
private double new_latitude = 0.0;
private double new_longitude = 0.0;
LocationManager locationManager = null;
float[] result = null;
@Override
public IBinder onBind(Intent intent)
{
return null;
}
@Override
public void onCreate()
{
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0f, this);
result = new float[3];
}
@Override
public void onStart(Intent intent, int startid)
{
}
@Override
public void onDestroy()
{
locationManager.removeUpdates(this);
}
@Override
public void onLocationChanged(Location location)
{
if(old_latitude == 0.0 && old_longitude == 0.0)
{
old_latitude = location.getLatitude();
old_longitude = location.getLongitude();
}
new_latitude = location.getLatitude();
new_longitude = location.getLongitude();
Location.distanceBetween(old_latitude, old_longitude, new_latitude, new_longitude, result);
distance = final_distance +result[0];//distance in meters between two locations
final_distance = distance;
old_latitude = new_latitude;
old_longitude = new_longitude;
}
@Override
public void onProviderDisabled(String provider)
{
}
@Override
public void onProviderEnabled(String provider)
{
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
and also add uses permission android.permission.ACCESS_FINE_LOCATION in android manifest.xml
Hope this may help you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7578180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.