text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Nested SOAP Header Element I want to create nested SOAPHeaderElement in Metro web services... It sould be something like
I am using JAVA .JAX-WS 2.2.5 (Metro)
<Auth>
<UserName> data1
</UserName>
<Password> data2
</Password>
</Auth>
Metro provides WSBindingProvider to create headers but I want to create headers within <Auth> tag?
A: you will need to implement a custom javax.xml.ws.handler.soap.SOAPHandler and add it as part of a HandlerChain to the webservice provider. some useful getting started info (more here).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JWPlayer 4 javascript events are ignored First of all, I can't upgrade to a newer version of the player, because I need the displayclick=fullscreen option to work, and it doesn't with version 5.
So, what I need to do is this: have the player auto-start with no volume and no controls on the page (this works just fine), and when the user clicks the screen the player must go full-screen and the volume must turn on.
The problem is all Javascript interaction seems to be completely ignored by the player, and I really can't see where the problem is.
When the page is loaded, I embed the player:
var so = new SWFObject('path_to_player.swf','div_id','200','120','10');
so.addParam('allowfullscreen','true');
so.addParam('allowscriptaccess','sameDomain');
so.addParam('bgcolor','#000000');
so.addParam('flashvars','file=path_to_playlist.xml&autostart=true&displayclick=fullscreen&controlbar=none&volume=0&icons=false&image=path_to_thumb.jpg');
so.write('div_id');
This seems to work just fine, the player is loading.
Then I add the event listeners:
var player = null;
function playerReady(p) {
player = document.getElementById(p.id);
addListeners();
}
function addListeners() {
if (player) {
console.log('add the listener');
console.log(player.getConfig().volume);
player.addControllerListener("RESIZE", "checkResize");
} else {
setTimeout("addListeners()", 100);
}
}
function checkResize(obj) {
console.log('resized');
if (obj.fullscreen) {
player.sendEvent("VOLUME", "60");
} else {
player.sendEvent("VOLUME", 0);
}
}
The "add the listener" message gets displayed in the console, but the second one, with the player's volume doesn't, and neither does the "resized" one when the player enters or exits fullscreen (and, obviously, the volume doesn't turn on).
I've tried other listeners, for both model and controller, and they don't seem to work. Sending events doesn't work either.
I've tried running just the code for the player separately, to make sure there are no other things interfering with the code, but I still have the same problem.
A: Well, it seems I've found the answer myself. Upgrading to a newer version of swfobject and using swfobject.embedSWF() seems to work just fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iframe resize issue in firefox i know this is so basic ,its so basic that it hurts me to ask this question but the issue is starting to make my hair too fall out lol.
i'm making a liquid website so everything resizes,so far so good...my page has a couple of iframes ,they will resize just great in i.e using % for height and width but when it comes to firefox only the width will resize and not the height ,the frame ends up pushing over my tables and making the whole thing look wrong
does anyone have a fix/solution to this please.
A: thanks to everyone that tried to help ,it was a bit vauge i managed to solve it in the end simply by
putting the iframe i wanted inside a layer/div set the layer to absolute and size it in % and then add the iframe inside the layer worked a treat for all browsers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to allow decimal values in Telerik Silverlight GridViewDataColumn filter dialog? I've got a data column defined within a RadGridView that uses a currency value. Here's the definition:
<telerik:GridViewDataColumn UniqueName="WSA" Header="WSA" DataMemberBinding="{Binding TicketSalesRolling12WeekAvg, Converter={StaticResource DollarFormatConverter}}">
<telerik:GridViewDataColumn.CellStyle>
<Style TargetType="telerik:GridViewCell">
<Setter Property="HorizontalAlignment" Value="Right"/>
</Style>
</telerik:GridViewDataColumn.CellStyle>
</telerik:GridViewDataColumn>
As the column is defined now, in the filter dialog I can't enter decimal values. So, something like "$2.99" won't work b/c it won't let me enter the decimal point (or the dollar sign, for that matter).
I've tried using a string type as the backing field; that works fine. But then I lose the numeric filter conditions and instead see the string filter conditions ("contains", "starts with", etc.). The user wants to see the numeric filter conditions, which leads me to my current dilemma.
I figure if I can get at the filter dialog template maybe I can manipulate things from there.
Any ideas?
A: Problem resolved. Just define the column's DataType as "double".
var gridViewBoundColumnBase = cisidsRadGridView.Columns["WSA"] as GridViewBoundColumnBase;
if (gridViewBoundColumnBase != null)
{
gridViewBoundColumnBase.DataType = typeof (double);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: android emulator not working? I develop mostly for iPhone and have started very recently with Android.
Tried the hello world, but when hit run the emulator just shows a black screen with an Android logo shining.
package com.hyper.tuti;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class TutiActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
TextView tv = new TextView(this);
tv.setText("Hello, Android");
setContentView(tv);
}
}
why is my simulator not working??
A: give it time... it takes a WHILE to boot up! (seriously)
A: Yeah I've had emulator boot times of 5-10 minutes initially.
Hint
When you edit your AVD, there is an option to take a snapshot. What this does is when you close your AVD, it takes a snapshot and opens that next time, bypassing boot.
Edit 1/9/2014
I have recently gotten back into Android development, and I now use Genymotion to run my emulators. It is based off of VirtualBox - it runs incredibly fast. I have not tried the Android Emulator in years so I cannot say whether or not it is any faster. I know my emulators start up almost instantly now and are not slow and buggy like before.
A: Haha I had the same problem first time I used the emulator too.
But yes it just takes alot of time to boot it up, especially if you're booting it up for Android 3.0+ Honeycomb(platform 11+) wich in effect is the tablet platform.
Use Android 2.3 Gingerbread or Android 2.2 Froyo if you want your emulator to look like an android phone.
Configure your AVD settings to use platform version 10 or 8.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: gettext usage for 2 strings that are the same Is there a more compact way if I want 2 keys have the same value? This works:
msgid "Next"
msgstr "Pág. seguinte"
msgid "Next page"
msgstr "Pág. seguinte"
I could imagine writing it like this instead but is it legal?
msgid "Next", "Next page"
msgstr "Pág. seguinte"
I have more questions about gettext, what do you recommend? I.e. how to do with html in translations and escape characters.
A: i think best option is split words in code like:
a = _('next')
b = '%s %s' % ( _('next'), _('page') )
and in .po
msgid "Next"
msgstr "seguinte"
msgid "page"
msgstr "Pág."
why you need to translate html special characters ? For example, © on all languages ©
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery UI - Resizable: alsoResize not accurate? Ok I'm not using the 'alsoResize' but I've tested and it behaves the same.
When you resize the main element, the black border from the bottom element 'marquee' often nudges out of line with the dashed white border from the top element.
$(".layer").resizable({
//alsoResize: '.marquee',
resize: function(event, ui) {
$('.marquee').css({
width : ui.size.width + "px",
height : ui.size.height + "px",
left : ui.position.left + "px",
top : ui.position.top + "px",
});
},
handles: 'all',
aspectRatio: true,
});
http://jsfiddle.net/digitaloutback/uGr3w/3/
Using firebug on a local demo, at the stage they go out of line, you can see the inline element styles for left, top and width, height are different.
I wonder if a work around would be to send the position and size stats to function which outputs an exact measurement to both elements? Any simpler options? Thanks
UPDATE:
I've got a workaround which works cleanly.. it is to pass the resizable-calculated dimensions to a function which sets the top layer to these dimensions also.
I'm sure there's a more efficient method to do this, feel free to offer an optimised version..
http://jsfiddle.net/digitaloutback/VDfpY/5/
A: There seems to be a discrepancy in the size and position reported by the ui parameter to the resize event, and the actual sizes and positions. This is possibly due to a delay between the ui parameter being built and the event being fired.
I experimented using the actual position and size reported at the time of the event running:
$('.marquee').css({
'left' : $(this).position().left,
'top' : $(this).position().top,
'width' : $(this).width(),
'height' : $(this).height()
});
This seems to match much more precicely the actual dimensions.
http://jsfiddle.net/VDfpY/1/
A: How about this?
Let the CSS handle the sizes and not the JS
http://jsfiddle.net/HerrSerker/uGr3w/5/
--edit added code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".layer").resizable({
handles: 'all',
aspectRatio: true,
});
});
</script>
<link type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/themes/redmond/jquery-ui.css" rel="stylesheet" />
<link type="text/css">
#canvas {
width: 500px;
height: 500px;
position: relative;
overflow: hidden;
background: #999}
.marquee {
border: 1px dashed #fff;
position: absolute;
left: -1px; top: -1px;
width: 100%; height: 100%;
display: block;
z-index: 2500;
}
.layer {
border: 1px solid black;
position: absolute;
left: 150px; top: 150px;
width: 250px; height: 226px;
display: block;
z-index: 2501;
}
</link>
<body>
<div id="canvas">
<a class="layer" href="#"><span class="marquee"></span></a>
</div>
</body>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Preventing entire table from locking while bulk INSERT I have a stored procedure that performs a bulk insert in a table. I added BEGIN TRANSACTION command just above the INSERT query to enable ROLL BACK if something goes wrong. When the bulk insert initiated, it locked the entire table and other users were unable to execute SELECT on the same table.
I am not following why SQL Server locks entire table for even a SELECT.
I am using SQL Server 2005 Express. Is this a problem with this version or it persists in 2008 as well? How to overcome this situation? Writers should not block Readers.
A: Writers should not block Readers
This is true only for snapshot isolation, all other isolation levels require both readers to block writes and writers to block readers (dirty reads not considered, since they are inconsistent and should never be used). If you need this behavior, then use row versioning (the link contains the solution).
Why does bulk insert lock the entire table?
This actually may or may not be true. The behavior is under your control:
TABLOCK
Specifies that a table-level lock is acquired for the duration of
the bulk-import operation. A table can be loaded concurrently by
multiple clients if the table has no indexes and TABLOCK is specified.
By default, locking behavior is determined by the table option table
lock on bulk load.
For more details, read the product specifications: Controlling Locking Behavior for Bulk Import.
A: You have an open transaction. That means SQL Server needs to preserve the state of the table, and any changes you are in the process of making are "dirty" and uncommitted.
If you SELECT from a table that is currently being altered with an open (explicit) transaction, the SELECT will wait until the table is in a stable state and the transaction has been either committed or rolled back.
To get around this, you can alter the transaction isolation level on the SELECT query.
A: If you're specifying TABLOCK in your proc, don't.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Open Second Link on a page using Jquery I am trying to open a link on my page in a new page with Jquery.
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("a:eq(0)").attr("target","_blank");
});
</script>
</head>
<body>
<h1>Welcome to My Homepage</h1>
<p class="intro">My name is Donald</p>
<a href="http://google.com">I live in Duckburg</a>
<p>My best friend is Mickey</p>
Who is your favourite:
<ul id="choose">
<li>Goofy</li>
<li>Mickey</li>
<li>Pluto</li>
</ul>
</body>
</html>
(copied wrong code on last edit this is the code I am using now. This is executed at page load time via a javascript that calls a bunch of other load time things.)
I have all the other code in place, and this continues to not work properly.
But this code still opens the second link in the same window. Can anyone help?
A: Wait until after the link actually exists before trying to modify it and start counting from 0 not 1.
(Untested):
<html>
<body>
<a href="http://cnn.com">CNN</a><br />
<a href="http://google.com">Google</a>
<script>
$("a:eq(1)").attr("target", "_blank");
</script>
</body>
</html>
A: eq references an array of elements. Arrays start with the index of 0, so you will want to look for the element with an index of 1
$(function(){
// wait for the DOM to load.
$("a").eq(1).attr("target", "_blank");
});
Look here for reference http://api.jquery.com/eq/
Here is a working example based on your code. http://jsfiddle.net/3wz9a/2/
A: Change eq(2) to eq(1), because eq() starts from index 0 and also make sure you change attributes after DOM is ready
<html>
<script>
$(function(){ $("a:eq(1)").attr("target", "_blank"); });
</script>
<body>
<a href="http://cnn.com">CNN</a><br />
<a href="http://google.com">Google</a>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: What is the difference between a Confusion Matrix and Contingency Table? I'm writting a piece of code to evaluate my Clustering Algorithm and I find that every kind of evaluation method needs the basic data from a m*n matrix like A = {aij} where aij is the number of data points that are members of class ci and elements of cluster kj.
But there appear to be two of this type of matrix in Introduction to Data Mining (Pang-Ning Tan et al.), one is the Confusion Matrix, the other is the Contingency Table. I do not fully understand the difference between the two. Which best describes the matrix I want to use?
A: Wikipedia's definition:
In the field of artificial intelligence, a confusion matrix is a
visualization tool typically used in supervised learning (in
unsupervised learning it is typically called a matching matrix). Each
column of the matrix represents the instances in a predicted class,
while each row represents the instances in an actual class.
Confusion matrix should be clear, it basically tells how many actual results match the predicted results. For example, see this confusion matrix
predicted class
c1 - c2
Actual class c1 15 - 3
___________________
c2 0 - 2
It tells that:
*
*Column1, row 1 means that the classifier has predicted 15 items as belonging to class c1, and actually 15 items belong to class c1 (which is a correct prediction)
*the second column row 1 tells that the classifier has predicted that 3 items belong to class c2, but they actually belong to class c1 (which is a wrong prediction)
*Column 1 row 2 means that none of the items that actually belong to class c2 have been predicted to belong to class c1 (which is a wrong prediction)
*Column 2 row 2 tells that 2 items that belong to class c2 have been predicted to belong to class c2 (which is a correct prediction)
Now see the formula of Accuracy and Error Rate from your book (Chapter 4, 4.2), and you should be able to clearly understand what is a confusion matrix. It is used to test the accuracy of a classifier using data with known results. The K-Fold method (also mentioned in the book) is one of the methods to calculate the accuracy of a classifier that has also been mentioned in your book.
Now, for Contingency table:
Wikipedia's definition:
In statistics, a contingency table (also referred to as cross
tabulation or cross tab) is a type of table in a matrix format that
displays the (multivariate) frequency distribution of the variables.
It is often used to record and analyze the relation between two or
more categorical variables.
In data mining, contingency tables are used to show what items appeared in a reading together, like in a transaction or in the shopping-cart of a sales analysis. For example (this is the example from the book you have mentioned):
Coffee !coffee
tea 150 50 200
!tea 650 150 800
800 200 1000
It tells that in 1000 responses (responses about do they like Coffee and tea or both or one of them, results of a survey):
*
*150 people like both tea and coffee
*50 people like tea but do not like coffee
*650 people do not like tea but like coffee
*150 people like neither tea nor coffee
Contingency tables are used to find the Support and Confidence of association rules, basically to evaluate association rules (read Chapter 6, 6.7.1).
Now the difference is that Confusion Matrix is used to evaluate the performance of a classifier, and it tells how accurate a classifier is in making predictions about classification, and contingency table is used to evaluate association rules.
Now after reading the answer, google a bit (always use google while you are reading your book), read what is in the book, see a few examples, and don't forget to solve a few exercises given in the book, and you should have a clear concept about both of them, and also what to use in a certain situation and why.
Hope this helps.
A: In short, contingency table is used to describe data. and confusion matrix is, as others have pointed out, often used when comparing two hypothesis. One can think of predicted vs actual classification/categorization as two hypothesis, with the ground truth being the null and the model output being the alternative.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: tools.jar exists, but cant find sun.security.tools.JarSignerResources I am seeing the following exception (on a Linux Java6-sun install, but not on OSX)
Caused by: java.util.MissingResourceException: Can't find bundle for base name sun.security.tools.JarSignerResources, locale en_US
at java.util.ResourceBundle.throwMissingResourceException(Unknown Source)
at java.util.ResourceBundle.getBundleImpl(Unknown Source)
at java.util.ResourceBundle.getBundle(Unknown Source)
at com.wuntee.aat.security.tools.JarSigner.<clinit>(JarSigner.java:96)
... 12 more
but, I can see that the tools.jar exists in the java install directory, and that tools.jar contains the JarSignerResource class. Any ideas?
A: The problem is not related with not finding the jar. The problem is related with not finding some resource for en_US locale within the jar instead.
Two things can be happening:
*
*if you open the tools.jar file and check the content of sun\security\tools you will find that one of them doesn't have the resource JarSignerResources_en_US.class, or
*check the default locate of the two different OS you are using: one of them should be en_US and the other is not. This is most probable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to read certain registry keys in C I'm using RegOpenKeyEx() and RegQueryValueEx() to try and get the value for six keys in the Windows registry. I'm able to do it for four of the six but am failing on certain others.
wchar_t * getRegKeyValue(HKEY rootKeyToGet, LPCWSTR subKeyToGet, LPCWSTR valueToGet)
{
HKEY resultHKey = 0;
wchar_t resultString[255] = L"";
DWORD dwType = REG_SZ;
DWORD resultSize = 255;
// See if the subkey exists. If it does, get its value.
if (RegOpenKeyEx(rootKeyToGet, subKeyToGet, NULL, KEY_ALL_ACCESS, &resultHKey) == ERROR_SUCCESS)
{
RegQueryValueEx(resultHKey, valueToGet, NULL, &dwType, (LPBYTE) &resultString, &resultSize);
}
RegCloseKey(resultHKey);
resultHKey = NULL;
RegCloseKey(rootKeyToGet);
rootKeyToGet = NULL;
return resultString;
}
The following are some successful calls:
swprintf(buffer, L"&ie=%s", getRegKeyValue(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Internet Explorer", L"Version"));
swprintf(buffer, L"&os=%s.", getRegKeyValue(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", L"CurrentVersion"));
wcscat(url, getRegKeyValue(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", L"CurrentBuild"));
Example of an unsuccessful call:
wcscpy(buffer, getRegKeyValue(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", L"CSDVersion"));
I'm able to open the key in the unsuccessful call but the query for that value returns an empty string. I'm running Visual Studio as an administrator. Have been scratching my head for the last day on where I am going wrong.
Update: The code returned is ERROR_FILE_NOT_FOUND. The codes are most definitely shown to exist in regedit.
A: I guess that you have a 32 bit process and a 64 bit machine. When this happens, registry redirection confounds matters. Attempts to read HKLM\Software\... get redirected to HKLM\Software\Wow64Node\.... So you need to open the 64 bit view of the registry with the RegistryView enumeration.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Ordering file location on linux partition I have a process which processes a lot of files (~96,000 files, ~12 TB data). Several runs of the process has left the files scattered about the drive. Each iteration in the process, uses several files. This leads to a lot of whipsawing around the disk collecting the files.
Ideally, I would like the process to write the files it uses in order, so that the next run will read them in order (file sizes change). Is there a way to hint at a physical ordering/grouping, short of writing to the raw partition?
Any other suggestions would be helpful.
Thanks
A: There are two system calls you might lookup: fadvise64, fallocate tell the kernel how you intend to read or write a given file.
Another tip is the "Orlov block allocator" (Wikipedia, LWN) affects the way the kernel will allocate new directories and file-entries.
A: In the end I decided not to worry about writing the files in any particular ordering. Instead, before I started a run, I would figure out where the first block of each file was located, and then sort the file processing order by first block location. Not perfect, but it did make a big difference in processing times.
Here's the C code I used to get the first block of supplied file list I adapted it from example code I found online (can't seem to find the original source).
#include <stdio.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <linux/fs.h>
//
// Get the first block for each file passed to stdin,
// write filename & first block for each file to stdout
//
int main(int argc, char **argv) {
int fd;
int block;
char fname[512];
while(fgets(fname, 511, stdin) != NULL) {
fname[strlen(fname) - 1] = '\0';
assert(fd=open(fname, O_RDONLY));
block = 0;
if (ioctl(fd, FIBMAP, &block)) {
printf("FIBMAP ioctl failed - errno: %s\n", strerror(errno));
}
printf("%010d, %s\n", block, fname);
close(fd);
}
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: An optimized method to compare IP addresses with wildcards in PHP? Anyone know of an effective and secure method to see if this input:
$_SERVER['REMOTE_ADDR']
matches against something similar to this array of inconsistent filters (note that 200.100.*.* could be expressed as just 200.100.*) with wildcards indicated by *'s:
array(
'192.168.1.*',
'192.168.2.1*',
'10.0.0.*',
'200.100.*.*',
'300.200.*',
)
Update
Thoughts?
foreach($instanceSettings['accessControl']['allowedIpV4Addresses'] as $ipV4Address) {
echo 'Now checking against '.$ipV4Address.'.';
// Compare each octet
$ipV4AddressOctets = String::explode('.', $ipV4Address);
$remoteIpV4AddressOctets = String::explode('.', $_SERVER['REMOTE_ADDR']);
$remoteIpV4AddressIsAllowed = true;
for($i = 0; $i < Arr::size($ipV4AddressOctets); $i++) {
echo 'Comparing '.$ipV4AddressOctets[$i].' against '.$remoteIpV4AddressOctets[$i].'.';
if($ipV4AddressOctets[$i] != $remoteIpV4AddressOctets[$i] && $ipV4AddressOctets[$i] != '*') {
echo 'No match.';
$remoteIpV4AddressIsAllowed = false;
break;
}
}
// Get out of the foreach if we've found a match
if($remoteIpV4AddressIsAllowed) {
break;
}
}
A: Remove the asterisks and just do:
$ips = array('192.168.1.', '10.0.0.');
foreach ($ips as $ip) {
if (strpos($_SERVER['REMOTE_ADDR'], $ip) === 0) {
// match
}
}
A: This one allows all cases in the question plus short masks with no asterisks like 123.123.
/**
* Checks given IP against array of masks like 123.123.123.123, 123.123.*.101, 123.123., 123.123.1*.*
*
* @param $ip
* @param $masks
* @return bool
*/
public static function checkIp($ip, $masks)
{
if (in_array($ip, $masks)) {
return true; // Simple match
} else {
foreach ($masks as $mask) {
if (substr($mask, -1) == '.' AND substr($ip, 0, strlen($mask)) == $mask) {
return true; // Case for 123.123. mask
}
if (strpos($mask, '*') === false) {
continue; // No simple matching and no wildcard in the mask, leaves no chance to match
}
// Breaking into triads
$maskParts = explode('.', $mask);
$ipParts = explode('.', $ip);
foreach ($maskParts as $key => $maskPart) {
if ($maskPart == '*') {
continue; // This triad is matching, continue with next triad
} elseif (strpos($maskPart, '*') !== false) {
// Case like 1*, 1*2, *1
// Let's use regexp for this
$regExp = str_replace('*', '\d{0,3}', $maskPart);
if (preg_match('/^' . $regExp . '$/', $ipParts[$key])) {
continue; // Matching, go to check next triad
} else {
continue 2; // Not matching, Go to check next mask
}
} else {
if ($maskPart != $ipParts[$key]) {
continue 2; // If triad has no wildcard and not matching, check next mask
}
// otherwise just continue
}
}
// We checked all triads and all matched, hence this mask is matching
return true;
}
// We went through all masks and none has matched.
return false;
}
}
A: I haven't bench-marked this, but I would opt to use the method that networking hardware/software uses...
Replace any * with 0 and 255.
Convert the IPs to integers
So if 255.255.255.* becomes 255.255.255.0 and 255.255.255.255
Then do ip2long function on these two ips.
Then you can convert the given ip into long ip. for example 255.255.50.51 into long ip.
Then you can compare whether the long ip for this given ip is between the converted long ips in the blacklist. If it is then it is not allowed else it is.
$ips = array("ip1", "ip2");
foreach($ips as $ip){
$ip1 = str_replace("*", "0", $ip);
$ip2 = str_replace("*", "255", $ip);
$ip1 = ip2long($ip1);
$ip2 = ip2long($ip2);
$givenip = $_GET["ip"];
$givenip = ip2long($givenip);
if($givenip >= $ip1 && $ip <= $givenip){
echo "blacklist ip hit between {$ip1} and {$ip2} on {$ip}";
}
}
A: Why not just use a regular expression?
preg_match("((192\\.168\\.1)|(10\\.0\\.0)|(127\\.0\\.0)\\.[012]\\d{0,2}|(\\:\\:1))",$_SERVER['REMOTE_ADDR'])
A: Just for fun, I'm going to over-engineer this. Well, unless you have a fairly long list to match against.
Assuming you're only using wildcards to mean "I don't care about this octet", then you can parse each entry in your array into four values (one per octet). Say that you use -1 to mean wildcard, 0–255 means to match that value exactly. (If you need better performance than O(n), where n is the size of the match list, then there are better data structures you can use here—a trie, for example.) Call this array L. Of course, you only need do this once—not per-request.
You can then parse the remote address the same way (except without wildcards). You can also catch REMOTE_ADDR not being in the expected format here It now becomes fairly trivial to check matches:
has_match(ip) =
for n in [0 … L.length)
if (-1 == L.n.0 || L.n.0 = ip.0) && (-1 == L.n.1 || L.n.1 == ip.1) && …
return true
return false
(That's pseudo-code, of course)
A: This one is based on preg_match(), you provide the pattern and the subject to test it against.
/**
* ip_match("172.30.20.*", "172.30.20.162"); // true
* ip_match("172.30.20", "172.30.20.162"); // true; works if incomplete
* ip_match("172.30.*.12", "172.30.20.12"); // true
* ip_match("172.30.*.12", "172.30.20.11"); // false
* ip_match("172.30.20.*", "172.30.20.*"); // true; wildcards in the subject will match with wildcards in the pattern
* ip_match("172.30.20.12", "172.30.*.*"); // false
*
* @param $pattern The pattern to test against as a string
* @param $subject The input string
*
* @return bool
*
*/
function ip_match($pattern, $subject) {
$pattern = explode(".", trim($pattern, "."));
$pattern = array_pad($pattern, 4, "*");
$subject = explode(".", trim($subject, "."));
$subject = array_pad($subject, 4, "1");
foreach ($pattern as $i => $octet) {
if ($octet != "*" && $subject[$i] != $octet) {
return false;
}
}
return true;
}
A: <?php
function ipArrCheck($allowedIPArr = [], $IP = '')
{
$IP_ARR = explode('.', $IP);
$resultArr = [];
foreach ($IP_ARR as $IPkey => $IPvalue) {
foreach ($allowedIPArr as $IPArrKey => $IPArrValue) {
$checkIPArr = explode('.', $IPArrValue);
$resultArr[$IPArrKey][$IPkey] = $checkIPArr[$IPkey] == $IP_ARR[$IPkey] || $checkIPArr[$IPkey] == '*';
}
}
foreach ($resultArr as $value) {
if (count(array_unique($value)) == 1 && current($value)) {
return TRUE;
}
}
return FALSE;
}
$MY_IP = '192.168.52.10';
$ALLOWED_IP_ARR = ['127.0.0.1', '192.168.*.*'];
var_dump(ipArrCheck($ALLOWED_IP_ARR, $MY_IP));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: increment variable according to numbers of clicks I have following code:
javascript:
var counter = 0;
var totalItems = 8;
var restItems = $num-totalItems;
if (restItems==22) {
$('#next').click(function(e) {
e.preventDefault();
counter++;
updatestatus();
});
}
function updatestatus() {
totalItems = totalItems + 8 * counter;
}
HTML:
<input type = "button" id="next" value="click me">
what I want is that before I click the button, the totoalItems is equal to 8, and each time when I click it, the totoal item is added by 8, but at the moment that bit of code dosen't work and give me a very large number, any one could help me figure it out, thanks a lot.
A: Why are you multiplying by the counter?
totalItems = totalItems + 8;
A: var counter = 0;
var totalItems = 8;
var restItems = $num - totalItems;
if (restItems == 22) {
$('#next').click(function(e) {
e.preventDefault();
counter++;
updatestatus();
});
}
function updatestatus() {
totalItems = totalItems + 8 * counter;
}
With this code, every time you run updatestatus(), it increments totalItems by its own value and 8 * counter. You don't need to increment it:
function updatestatus() {
totalItems = 8 + 8 * counter;
}
But ideally, I'd just simplify the code:
var counter = 0;
var totalItems = 8;
var restItems = $num - totalItems;
$('#next').click(function(e) {
if (restItems == 22) {
e.preventDefault();
totalItems += 8;
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Matlab: Optimize this (pt 2) Here's another one:
ValidFirings = ((DwellTimes > 30/(24*60*60)) | (GroupCount > 1));
for i = length(ValidFirings):-1:2
if(~ValidFirings(i))
DwellTimes(i-1) = DwellTimes(i)+DwellTimes(i-1);
GroupCount(i-1) = GroupCount(i)+GroupCount(i-1);
DwellTimes(i) = [];
GroupCount(i) = [];
ReducedWallTime(i) = [];
ReducedWallId(i) = [];
end
end
It appears that the intent is to sum up 'dwelltimes' based on whether or not the sensor firing is considered valid. So I have a vector of sensor firings that Im walking through backwards and summing into the previous row if the current row is not marked as valid.
I can visualize this in C/C++ but I don't know how to translate it into better Matlab vector notation. As it stands now, this loop is v slow.
EDIT:
Could I use some form of DwellTimes = DwellTimes( cumsum( ValidFirings ))?
A: As with your previous question, replacing the for loop should improve the performance.
%# Find the indices for invalid firings
idx = find(~(DwellTimes > 30/(24*60*60)) | (GroupCount > 1));
%# Index the appropriate elements and add them (start the addition
%# from the second element)
%# This eliminates the for loop
DwellTimes(idx(2:end)-1) = DwellTimes(idx(2:end)-1)+DwellTimes(idx(2:end));
GroupCount(idx(2:end)-1) = GroupCount(idx(2:end)-1)+GroupCount(idx(2:end));
%# Now remove all the unwanted elements (this removes the
%# first element if it was a bad firing. Modify as necessary)
GroupCount(idx)=[];
DwellTimes(idx)=[];
A: I would consolidate first as shown, then eliminate the invalid data. This avoids the constant resizing of the data. Note that you can't reverse the order of the FOR loop due to the way that the values propagate.
ValidFirings = ((DwellTimes > 30/(24*60*60)) | (GroupCount > 1));
for i = length(ValidFirings):-1:2
if (~ValidFirings(i))
DwellTimes(i-1) = DwellTimes(i) + DwellTimes(i-1);
GroupCount(i-1) = GroupCount(i) + GroupCount(i-1);
end
end
DwellTimes = DwellTimes(ValidFirings);
GroupCount = GroupCount(ValidFirings);
ReducedWallTime = ReducedWallTime(ValidFirings);
ReducedWallId = ReducedWallId(ValidFirings);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: uncaught syntaxerror unexpected string I'm trying to make a drop-down menu, works fine in firefox
It does not work in other browsers
get the following error:
jQuery(".parent").hover( function () {
jQuery(this).toggleClass("activeli").(".parent").stop(true, true).slideToggle(); << error line
});
This is the web link
http://www.jeanca.com/clientes/evoca/
A: The problem is toggleClass("activeli").(".parent") Probably should be.
jQuery(this).toggleClass("activeli").find(".parent").stop(true, true).slideToggle();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to create an installer for a set of components, some optional, from Visual Studio 2010? I have a package I am putting together that contains the following components:
*
*Core windows service
*Core web service ( requires windows service )
*Secondary web service
*Front end
This is designed for a distributed configuration, where the Core Windows and Core web services have to be installed on every machine, the Secondary web service only needs to be installed on one machine and the front end only needs to be installed on one machine.
All four can be co-located on one machine but aside from the core services having to be installed on the same machine they don't have to be.
All four projects have x86 and x64 variants.
Currently I have an installer for each component built as VS2010 deployment projects. This works fine, but it means a lot of files have to be copied and installed before we can get going and it is far too easy to miss one out. I would like to have an integrated installer that pulls them all together and then allows the user to suggest which components to install on any given machine.
Is there a way to do this with a Deployment Project in Visual Studio 2010? I don't believe I can chain MSI packages, but could I create a single one that deployed the windows service and web services to their various locations in such a way that the windows service was guaranteed to be installed before the web service and that all components can be optional with no installation directories created for components that aren't installed? If so, is there anything I can do to ensure that users only see relevant parts of the interface- showing panels conditionally based on previous checkbox responses or similar?
If not is the best alternative ( as suggested in this question ) to put together a simple Forms application to package the files up and chain them manually?
A: Take a look at Wix (Windows Installer XML). http://wix.sourceforge.net/ Its an add on to visual studio. You can create much more powerful and flexable msi installers with it than with the default VS projects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: set 100% width and a maxwidth of 400px? I want to do the folowing:
image.style.maxWidth = "400px";
image.style.width = "100%";
so the image maxwidth is 400px but if the user resizes his webbrowser window to a width of -400px the image will be resized to the same with as the window. The problem is: How do you this is non maxwidth browser? is there any way of doing this without using maxwith?
A: You can use this css3 rule:
@media only screen and (min-width: 768px) and (max-width: 991px) {
#image {
width: 400px;
}
}
Go and check http://lessframework.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: android XML parse into Hash map not working I am getting the most bizzarre behavior with trying to parse an XML, I run through it step by step and all values are assigned and retrieved in order and then the object I create is added to a HashMap for easy look up, the problem is when I am done retrieving it all the HashMap has null values and the ones that aren't null are the value of the very last node that was read, I have walked through it over and over and it all seems correct, but when it's done loading the values in the HasMap look like:
[0] null
[1] NarrationItem@44e9d170
[2] null
[3] null
[4] NarrationItem@44e9d170
etc, etc.
The format of my XML files is:
<narrations>
<narration id="0" name="A" alias="a" >
<line text="This is a test."></line>
</narration>
<narration id="1" name="B" alias="b" >
<line text="This another a test."></line>
</narration>
<narration id="2" name="C" alias="c" >
<line text="This is STILL a test."></line>
</narration>
</narrations>
And my XML parsing method is follows:
public HashMap<String, NarrationItem> NarrationMap = new HashMap<String, NarrationItem>();
private void LoadNarrationsXML() {
NarrationItem i = new NarrationItem();
String line;
String s;
try {
// Get the Android-specific compiled XML parser.
XmlResourceParser xmlParser = this.getResources().getXml(R.xml.narrations);
while (xmlParser.getEventType() != XmlResourceParser.END_DOCUMENT) {
if (xmlParser.getEventType() == XmlResourceParser.START_TAG) {
s = xmlParser.getName();
if (s.equals("narration")) {
i.Clear();
i.ID = xmlParser.getAttributeIntValue(null, "id", 0);
i.Name = xmlParser.getAttributeValue(null, "name");
i.Alias = xmlParser.getAttributeValue(null, "alias");
} else if (s.equals("line")) {
line = xmlParser.getAttributeValue(null, "text");
i.Narration.add(line);
}
} else if (xmlParser.getEventType() == XmlResourceParser.END_TAG) {
s = xmlParser.getName();
if (s.equals("narration")) {
NarrationMap.put(i.Alias, i);
}
}
xmlParser.next();
}
xmlParser.close();
} catch (XmlPullParserException xppe) {
Log.e(TAG, "Failure of .getEventType or .next, probably bad file format");
xppe.toString();
} catch (IOException ioe) {
Log.e(TAG, "Unable to read resource file");
ioe.printStackTrace();
}
}
The NarrationItem object is a custom object defined as:
public class NarrationItem {
int ID;
String Name;
String Alias;
ArrayList<String> Narration = new ArrayList<String>();
public NarrationItem() { }
public void LoadNarration(int id, String name, String alias, ArrayList<String> narration) {
ID = id;
Name = name;
Alias = alias;
Narration.addAll(narration);// = narration;
}
public void Clear() {
ID = 0;
Name = "";
Alias = "";
Narration.clear();
}
}//End Narration
If someone could point out the problem I'd be very thankful I have sat here staring at this issue for hours.
A: You're only ever creating one NarrationItem object - you're then using a reference to that object as the value for multiple entries in the map. Don't do that. You need to understand that the map doesn't contain an object as the value - it contains a reference to an object.
You can probably fix this just by creating a new NarrationItem each time instead of calling Clear.
It's not clear how you're looking at the map to see those null values, but if you're using the debugger and looking at the internal data structure, you probably shouldn't really be doing that either - instead, step through the keys, values or entries, i.e. stick within the abstraction that HashMap is meant to support.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Confusing use of synchronized in Java: pattern or anti-pattern? I'm doing a code review for a change in a Java product I don't own. I'm not a Java expert, but I strongly suspect that this is pointless and indicates a fundamental misunderstanding of how synchronization works.
synchronized (this) {
this.notify();
}
But I could be wrong, since Java is not my primary playground. Perhaps there is a reason this is done. If you can enlighten me as to what the developer was thinking, I would appreciate it.
A: If that is all that is in the synchonized block then it is an antipattern, the point of synchronizing is to do something within the block, setting some condition, then call notify or notifyAll to wake up one or more waiting threads.
When you use wait and notify you have to use a condition variable, see this Oracle tutorial:
Note: Always invoke wait inside a loop that tests for the condition being waited for. Don't assume that the interrupt was for the particular condition you were waiting for, or that the condition is still true.
You shouldn't assume you received a notification just because a thread exited from a call to Object#wait, for multiple reasons:
*
*When calling the version of wait that takes a timeout value there's no way to know whether wait ended due to receiving a notification or due to timing out.
*You have to allow for the possibility that a Thread can wake up from waiting without having received a notification (the "spurious wakeup").
*The waiting thread that receives a notification still has to reacquire the lock it gave up when it started waiting, there is no atomic linking of these two events; in the interval between being notified and reacquiring the lock another thread can act and possibly change the state of the system so that the notification is now invalid.
*You can have a case where the notifying thread acts before any thread is waiting so that the notification has no effect. Assuming one thread will enter a wait before the other thread will notify is dangerous, if you're wrong the waiting thread will hang indefinitely.
So a notification by itself is not good enough, you end up guessing about whether a notification happened when the wait/notify API doesn't give you enough information to know what's going on. Even if other work the notifying thread is doing doesn't require synchronization, updating the condition variable does; there should at least be an update of the shared condition variable in the synchronized block.
A: This is perfectly fine. According to the Java 6 Object#notify() api documentation:
This method should only be called by a thread that is the owner of this object's monitor.
A: It certainly is not pointless, you can have another thread that has a reference to the object containing the above code doing
synchronized(foo) {
foo.wait();
}
in order to be woken up when something happens. Though, in many cases it's considered good practice to synchronize on an internal/private lock object instead of this.
However, only doing a .notify() within the synchronization block could be quite wrong - you usually have some work to do and notify when it's done, which in normal cases also needs to be done atomically in regards to other threads. We'd have to see more code to determine whether it really is wrong.
A: This is generally not a anti-pattern, if you still want to use intrinsic locks. Some may regard this as an anti pattern, as the new explicit locks from java.util.concurrent are more fine grained.
But your code is still valid. For instance, such code can be found in a blocking queue, when an blocking operation has succeeded and another waiting thread should be notified. Note however that concurrency issues are highly dependent on the usage and the surrounding code, so your simple snippet is not that meaningful.
A: The Java API documentation for Object.notify() states that the method "should only be called by a thread that is the owner of this object's monitor". So the use could be legitimate depending upon the surrounding context.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Reverse custom django Admin Site urls? Is there a way to reverse URLs added to a custom django AdminSite, for example
class MyAdminSite(AdminSite):
def get_urls(self):
urls = super(MyAdminSite, self).get_urls()
my_urls = patterns('',
url(r'some_view/$',self.admin_view( SomeView.as_view()), name='some_view' ),
)
return my_urls + url
myadmin = MyAdminSite(app_name='my_admin')
url(r'^admin/', include(my_admin.urls)),
How do i reverse some_view
A: alternatively, if you've defined a name for your admin site like so:
class ExplorerAdmin(admin.AdminSite):
def __init__(self, *args, **kwargs):
super(ExplorerAdmin, self).__init__(*args, **kwargs)
self.name = 'explorer_admin'
self.app_name = 'rql'
def get_urls(self):
parent_patterns = super(RQLExplorerAdmin, self).get_urls()
dashboard_patterns = [
url(r'^$', admin.site.admin_view(TemplateView.as_view(template_name='explorer.html')), name="explorer")
]
return dashboard_patterns + parent_patterns
reversing the url would be done by applying namespacing using your custom sites' name, like so:
reverse('explorer_admin:explorer')
A: Try: {% url admin:some_view %}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Android gridview, how to remove the gaps between grid items I am trying to use GridView to achieve a mosaic effect. The grid items are all images, similar to the Gri 2 in the APIDemo sample. The problem is that there are always gaps between the images, even after all the padding and spacing are set to 0. Did I miss some other settings to remove the gap? I want the images right next to each other.
I set the column width as 120dip. Here is my code to set the image width to 120dip:
mTileWidth = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 120, r.getDisplayMetrics());
Is there a problem?
Thanks!
A: This is a very old question and I answer it just to improve my acceptance rate :)
In the end I just calculated the screen width and divided it by the number of columns, and use the result as the width for one item. I want in a row. That fixed the problem. The answer by mmmmm5 perhaps is correct that the gap is the padding added by android, we just need to get around it.
A: If you look at Android's source code for Contacts, a custom GridView class is created. Reviewing quickly, there are settings to paddings, etc. Perhaps, that answers your question
A: There is another working solution. When returning the view from the getView() method in the adapter for the GridView, you have to set layout parameters as follows:
view.setLayoutParams(new GridView.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT,
TableLayout.LayoutParams.MATCH_PARENT));
A: If the padding isn't added in your adapter, look at your XML. Look at android:stretchMode as well as android:verticalSpacing and android:horizontalSpacing.
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="14dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
A: Or even simpler, in the xml of my cell, I put the following parameters on the root view
android:layout_width="match_parent"
android:layout_height="match_parent"
and setup my gridview like that:
<GridView
android:id="@+id/gridview_type"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:stretchMode="columnWidth"
android:numColumns="3"
tools:listitem="@layout/cell_type"
/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I monkey patch a gem that is managed in Bundler? Specifically, I want to point delayed_job at a different table with:
set_table_name "my_table"
I just switched to Bundler from vendoring gems. I used to just change the code in the vendored gem, which was probably stupid. I probably need to do a monkey path for this anyway, I'm just no sure how.
A: The following is the general pattern you can use. It's not going to work as-is, because the point is only to demonstrate the pattern, and because I don't know Delayed::Job's class structure.
# config/initializers/delayed_job_patch.rb
require "delayed_job"
class Delayed::Job
set_table_name "my_table"
end
A: What I would do, is fork the project on github, and then implement a config option for the table name, and then send a pull request back to the original author. In the meantime, I would point bundler at my own git (or company owned) repo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ipython how to execute several history lines In ipython, we can use
_ih[32:39]
To show history lines between 32 and 39. How can I directly execute these history lines?
A: Use the exec statement:
exec(_ih[32:39])
http://docs.python.org/reference/simple_stmts.html#exec
A: You can create a named macro from the lines and execute them:
%macro foo 32-38
foo
This is useful if you want to execute the same set of lines more than once. Also the lines do not need to be sequential or in order:
%macro bar 38 37 32-36 42
A: You can execute code from previous sessions with %recall. See %recall documentation here.
#Execute all code from previous session.
%recall ~1/
#Execute all code from two sessions previous the current session.
%recall ~2/
#Execute lines 1 to 5 from previous session.
%recall ~1/1-5
A: You can edit lines before executing them like so:
edit 1-5
Apparently the syntax changed at some point from the list-notation used in dreynold's answer.
A: I use the list notation:
exec In[34:36]
also, if you use the edit function to edit a chunk, the Out list will have your code in it, so:
exec Out[35]
And my favorite:
edit In[34:38]
because I am a fat-fingered slob who can rarely get it right on the first try.
A: On recent versions of iPython you use the rerun magic-comand:
%rerun 32:39
Documentation on that command: http://ipython.readthedocs.io/en/stable/interactive/magics.html#magic-rerun
A: try %recall,
check doc of recall magic command
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "34"
} |
Q: Declaring JavaScript Variables Efficiently I'm trying to optimize a small web application's use of JavaScript variables. I have about five functions that each produce an Ajax call, and repeatedly make use of a query string. Should I declare the query variable inside of each function, or will it increase efficiency to declare it globally? A very simple example of what I'm talking about is:
Local Declaration
<script type="text/javascript">
function queryOne() {
var queryString = "query arguments";
}
function queryTwo() {
var queryString = "query arguments";
}
</script>
Global Declaration
<script type="text/javascript">
var queryString;
function queryOne() {
queryString = "query arguments";
}
function queryTwo() {
queryString = "query arguments";
}
</script>
Is there are notable efficiency benefit to using the global declaration scheme?
A: Should be declared locally, as any global declaration will take extra time to look for the variable in the local scope and then the global scope, making the global declaration actually slower. Plus a variable declaration might not require a search for the variable name, it can simply just attempt to create a new variable.
Also, if code were added in the future, declaring the variable globally could cause it to be overwritten by other code or conflict.
Actually you might save a little time with a module level variable, if the query string is only assigned to once. However, if you are reassigning the query variable each time the function is called, then you definitely save time making the query variable local to each function.
A: You could enclose it for neatness;
var MyApp = {
queryString: null,
queryOne: function() {
print( this.queryString );
},
queryTwo: function() {
print( this.queryString );
}
}
.
MyApp.queryString = "foo=boob";
.
a = MyApp.queryOne(123);
b = MyApp.queryTwo(456);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android layout: Measure views in order to choose correct TextView font size I am currently working on an Activity that features components with weight. Those components contain text and icons. As far as I know, android does not provide features to scale text according to it's parent view. As a consequence, I need to measure those views and then manually apply my custom font to the TextViews and set an appropriate font size.
I am currently doing it the following way (Which actually works. But I often get 09-30 17:55:14.844: ERROR/ViewRoot(12893): OutOfResourcesException locking surface
) errors and I believe this might be connected to the way I do my layout.
This is one row in the layout (there are several rows)
<RelativeLayout
android:layout_height="0dip"
android:layout_width="fill_parent"
android:layout_weight="0.35"
android:id="@+id/activity_main_row_1">
<View
android:layout_width="6dip"
android:layout_height="fill_parent"
android:background="@color/palette_green"
android:layout_alignParentLeft="true"
/>
<RelativeLayout
android:layout_centerVertical="true"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:paddingLeft="20dip">
<TextView
android:id="@+id/activity_main_row_1_title"
android:text="@string/title_add_expense"
android:textSize="10dip"
android:textColor="@color/palette_grey"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0px">
</TextView>
<TextView
android:id="@+id/activity_main_row_1_sub_title"
android:text="@string/subtitle_add_expense"
android:textSize="10dip"
android:textColor="@color/palette_dark_grey"
android:layout_alignParentLeft="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="0px"
android:layout_below="@+id/activity_main_row_1_title">
</TextView>
</RelativeLayout>
<ImageView
android:id="@+id/activity_main_row_1_bracket"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/icon_bracket_right_grey"
android:paddingLeft="0dip"
android:paddingRight="0dip"
android:paddingTop="24dip"
android:paddingBottom="20dip"
android:layout_alignParentRight="true">
</ImageView>
</RelativeLayout>
This is the way I do the measurements:
in onCreate:
LinearLayout mLayout = (LinearLayout) this.getLayoutInflater().inflate(R.layout.activity_main, null);
mLayout.getViewTreeObserver().addOnGlobalLayoutListener(this);
this.setContentView(mLayout);
In onGlobalLayout:
@Override
public void onGlobalLayout() {
int mRow1Height = mRow1.getHeight();
<omitted>
if(mRow1Height>0) {
TextView row1Title = (TextView) findViewById(R.id.activity_main_row_1_title);
row1Title.setTypeface(mFontProvider.getTypeface());
row1Title.setTextSize((float) ((mRow1Height)*.3));
TextView row1SubTitle = (TextView) findViewById(R.id.activity_main_row_1_sub_title);
row1SubTitle.setTypeface(mFontProvider.getTypeface());
row1SubTitle.setTextSize((float) ((mRow1Height)*.2));
}
Is this the correct way to do what I want to do?
Thanks so much for your advice.
Cheers
A: I found the issue that was causing the OutOfResourcesExceptions. In the onLayout, I set the text for a TextView. This causes the view to be laid out again, resulting in kind of an an infinite loop.
I'd however still be interested in knowing if using addOnGlobalLayoutListener and onLayout is the only way to scale TextViews in respect to their dynamically sized parent views.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I add submenu dropdown to my current wp theme top menu? I have created a new WP Theme and in the header have inserted a top menu / nav ... but it's just 1 level depth.
How do I modify this so that I have show subpages in a dropdown style please?
Here is the current code:
<div class="header_right">
<ul>
<?php wp_list_pages('title_li=&depth=1'); ?>
<li><a href="#" id="signin"></a></li>
</ul>
</div>
Thanks
A: You need to use depth=0 to get the entire list of pages including sub-pages nested in heirarchical li elements. Also, you will have to write corresponding CSS code for the sub-menu pages to appear in drop-down style.
You can take any theme having the same menu style as reference. Twenty Eleven theme has a very simple menu with this functionality and easy to understand CSS code.
A: For your header use: wp_nav_menu();
To get dropdown sub menus that dropdown when hovered over you'll want to add some code to the previous line:
paste-bin adding sub-menu
There's some very helpful advice and useful CSS at Capability Wordpress Help Blog
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android `settings.db` reference? Is there any reference about settings.db database file?
I see mostly obviously variables but there is not enough for confidence.
A: On a rooted device, you can pull the file from /data/data/com.android.providers.settings/databases/settings.db (you will need to do adb root before)
Then you can open it a with a sqlite database explorer:
The names are self-explanatory. If one confuses you, a simple google search should help.
A: There is hardly any reference. You should be using the Settings.System class to be access the system settings in Android. Using the Settings.System class, you are able to both read and write to the system settings.
Checking Mobile Network:
ConnectivityManager nInfo = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
nInfo.getActiveNetworkInfo().isConnectedOrConnecting();
Log.d(tag, "Net avail:"
+ nInfo.getActiveNetworkInfo().isConnectedOrConnecting());
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
Log.d(tag, "Network available:true");
return true;
} else {
Log.d(tag, "Network available:false");
return false;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Setting the default datatype of LINQ to sql datacontext Is there any way of changing the default mapping for LINQ to sql datacontexts? I want to change INT to map to long rather than int every time a new entity is created.
A: Two ways I can think of:
*
*Create a DBML file.
*Find-replace System.Int32 to System.Int64 (easy to create a little command-line app so you just need to double-click it whenever you refresh the DBML).
*Use the DBML file.
Or:
Just hand-code the classes anyway. I actually find it handier to hand-code than DBML - when I make a change I'm likely going to be making a bunch of related changes anyway, so it fits right into how I'm thinking of the change's implications anyway.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to set a this.var from a class inside a function that's in that class? I want to set the this.session variable from within the last this.rpc via this.setSession() but this is 't working for me:
anyone got an answer for me? I'm still learning javascript classes and coming from php classes, it suprises me that this is'nt working.
function glpirpc(host,user,pass){
this.host = host;
this.session = "";
this.user = user;
this.password = pass;
this.setSession = function(s){
this.session = s;
}
this.rpc = function(method,params,callback) {
var args = {};
args.host = this.host;
console.log('session:' + this.session);
if (this.session != ""){
console.log('get session');
this.host += "?session=" + this.session;
}
args.session = _this.session;
args.method = method;
args.params = params;
$.post('glpirpc/',args,function(data){
if (typeof data.error != "undefined"){
alert(data.error);
}else {
callback(data.return)
}
},"json");
}
this.rpc('glpi.doLogin',{
'login_name': this.user,
'login_password': this.password,
},function(data){
this.setSession(data.session)
});
}
A: The strange thing about "methods" in JavaScript is that their this object can be anything or nothing, and its value depends only on how the function is called, not whether it's called from another method. When you do callback(data.return), that's a plain function call, not a method call, so it doesn't get a this object.
Instead do callback.call(this, data.return) so that the callback is invoked with the same this object as the function that called it.
To elaborate a little: when you write something like myobject.mymethod() in JavaScript, two things happen: first the interpreter looks up the mymethod property of myobject, and then calls it with myobject as the context. It's equivalent to writing myobject.mymethod.call(myobject). But when you use a function's call() method, you can specify a different context object — e.g. myobject1.mymethod.call(myobject2), which will find the function via myobject1, but when the function runs, its this will be myobject2.
When you call a plain function, not on an object — callback(data.return) as opposed to someobject.callback(data.return) — its context will be the global window object. And you can't call it with this.callback(data.return) because the function isn't stored as a property of the this object. So instead you use callback.call(this, data.return) to specify that the current function's context (its this) should also be the context in which the callback runs.
A: You can use jQuery.proxy() for this.
this.rpc('glpi.doLogin',{
'login_name': this.user,
'login_password': this.password,
},
$.proxy(function(data) {
this.setSession(data.session)
}, this));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Submitting Repeating InfoPath Table to Sharepoint list in Browser Enabled Form Hopefully you can help. I am working on a Browser Enabled InfoPath 2010 form that lives in a Document Library on a SharePoint site (2007 and 2010). In this form there is a repeating table with data that needs to be captured for reporting purposes. The solution I have chosen is to use the built in SharePoint lists.asmx Web Service to write the lines in the repeating table to a separate list on the sane SharePoint site, in the same site collection. I used the steps here, http://msdn.microsoft.com/en-us/library/cc162745(v=office.12).aspx, as my baseline.
I have gotten everything set up and working when run directly from the InfoPath form client site. The form opens and, on submit, the rows in the repeating table are written to the SharePoint list without any problems. However, once I deploy the form through Central Admin and test, none of the rows in the repeating table are getting written to the list. There are no errors or anything to indicate a problem with the code, and a boolean field used to indicate whether or not a row has been uploaded is set to true.
My first thought is that there is a problem with the permissions somewhere. Maybe when the service is called from client side it passes my credentials but when run from the server through the Document Library it's using something different? Shouldn't it use the credentials that are used to gain access to the SharePoint (which are also my AD credentials)? Is there a way to specify the use of the current users AD credentials when calling the lists.asmx web service in the code?
Anyway, not really sure where else to go with this. Any searching I do comes up with the same how two documentation on submitting to a SharePoint list in general. Any help would be greatly appreciated. Below is the code I am using to accomplish this.
if (MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:ShippingInformation/my:ShipDate", NamespaceManager).Value != "")
{
// If Ship Date is not blank, upload items in Material used to SP List where ForQuote is False
// Quote Number, RMA Number, Ship Date, Unit S/N,
// Create a WebServiceConnection object for submitting
// to the Lists Web service data connection.
WebServiceConnection wsSubmit =
(WebServiceConnection)this.DataConnections["Material Web Service Submit"];
//Create XPathNodeIterator object for the new Material Lines
XPathNodeIterator MaterialLines = this.MainDataSource.CreateNavigator().Select("/my:myFields/my:RepairQuote/my:QuoteLines/my:QuoteLine", NamespaceManager);
int lineCount = 0;
foreach (XPathNavigator NewLines in MaterialLines)
{
lineCount += 1;
if (NewLines.SelectSingleNode(".//my:ForQuote", NamespaceManager).Value == "false" && NewLines.SelectSingleNode(".//my:LineSubmitted", NamespaceManager).Value == "false")
{
// Set the values in the Add List Item Template
// XML file using the values in the new row.
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[@Name='Title']", NamespaceManager).SetValue(NewLines.SelectSingleNode(".//my:lineItem", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[@Name='RMANumber']", NamespaceManager).SetValue(MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:EntitlementContainer/my:RMANumber", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[@Name='UnitSerialNumber']", NamespaceManager).SetValue(MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:EntitlementContainer/my:serialNumber", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[@Name='ShipDate']", NamespaceManager).SetValue(MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:ShippingInformation/my:ShipDate", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[@Name='OrderType']", NamespaceManager).SetValue(MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:RepairQuote/my:orderType", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[@Name='QuoteNumber']", NamespaceManager).SetValue(MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:RepairQuote/my:quoteNumber", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[@Name='LineQuantity']", NamespaceManager).SetValue(NewLines.SelectSingleNode(".//my:lineQuantity", NamespaceManager).Value);
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/Field[@Name='LineNumber']", NamespaceManager).SetValue(lineCount.ToString());
// Set the value of Cmd attribute to "New".
DataSources["AddListItemTemplate"].CreateNavigator().SelectSingleNode("/Batch/Method/@Cmd", NamespaceManager).SetValue("New");
// Submit the new row.
wsSubmit.Execute();
NewLines.SelectSingleNode(".//my:LineSubmitted", NamespaceManager).SetValue("true");
}
}
}
A: I'm unsure why the code doesn't work when you deploy and call the lists web service in code. However I would suggest you to try debugging it to get to the root of the problem:
Step by Step – Debug InfoPath 2010 Forms Deployed on SharePoint 2010 Using Visual Studio 2010
Please try this out and step through it to see if it goes through the code as expected.
A: Well, I am not sure if it is the answer per se, but I believe the problem was related to security on the site. I got around this by using the SharePoint Object Model instead of the web service to create the list items (See http://www.bizsupportonline.net/browserforms/how-to-use-sharepoint-object-model-submit-data-infopath-browser-form-sharepoint-list.htm). With the SharePoint Object Model I am able to use AllowUnsafeUpdates. Also, where it took me quite a bit of time to get the web service set up, including the data connections, CAML file, etc. This way, however, only took a few minutes. Lesson learned, use the SharePoint Object Model if at all possible.
foreach (XPathNavigator NewLines in MaterialLines)
{
lineCount += 1;
if (NewLines.SelectSingleNode(".//my:ForQuote", NamespaceManager).Value == "false" && NewLines.SelectSingleNode(".//my:LineSubmitted", NamespaceManager).Value == "false")
{
using (SPSite site = SPContext.Current.Site)
{
if (site != null)
{
using (SPWeb web = site.OpenWeb())
{
// Turn on AllowUnsafeUpdates on the site
web.AllowUnsafeUpdates = true;
// Update the SharePoint list based on the values
// from the InfoPath form
SPList list = web.GetList("/Lists/InfoPathRtpItems");
if (list != null)
{
SPListItem item = list.Items.Add();
item["Title"] = NewLines.SelectSingleNode(".//my:lineItem", NamespaceManager).Value;
item["RMANumber"] = MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:EntitlementContainer/my:RMANumber", NamespaceManager).Value;
item["UnitSerialNumber"] = MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:EntitlementContainer/my:serialNumber", NamespaceManager).Value;
item["ShipDate"] = MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:ShippingInformation/my:ShipDate", NamespaceManager).Value;
item["OrderType"] = MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:RepairQuote/my:orderType", NamespaceManager).Value;
item["QuoteNumber"] = MainDataSource.CreateNavigator().SelectSingleNode("./my:myFields/my:RepairQuote/my:quoteNumber", NamespaceManager).Value;
item["LineQuantity"] = NewLines.SelectSingleNode(".//my:lineQuantity", NamespaceManager).Value;
item["LineNumber"] = lineCount.ToString();
item.Update();
}
// Turn off AllowUnsafeUpdates on the site
web.AllowUnsafeUpdates = false;
// Close the connection to the site
web.Close();
}
// Close the connection to the site collection
site.Close();
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to deal with classpath conflict In my project, I'm using both glassfish-embedded 3.1.1 and the guava lib... The problem is that glassfish comes with the old implementation of guava (ie google-collections)...
This results in NoSuchMethodError at runtime, for example when using Lists.reverse(), or Sets.newIdentityHashSet() which were introduced later in guava.
I don't find any solution to solve this... (the only one is to manually trash the com/google classes directory in the glassfish jar...)
A: You can overcome this be specifying the below. Read the Delegation section of the Class Loaders chapter.
<class-loader delegate="false" />
Check this SO post for class loading in Java EE apps in general: Java EE class loading standard
A: Glassfish should never have included com.google classes in their own jar. That was an error.
UPDATE[@sly7_7]: It seems like glassfish does not include guava in their own jar anymore, but it depends on the guava artifact instead. This should resolve the problem.
Thanks to @JagWire for pointing this.
A: I was able to make the error go away by using the following Glassfish v4 build:
http://grepcode.com/snapshot/maven.java.net/content/groups/promoted/org.glassfish.main.extras/glassfish-embedded-all/4.0.1-b01
Might be worth taking a look.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Style Select And Multiple Select? How can I style both the <select> HTML tag, and the <select multiple="multiple"> HTML tag while both of the tags reside under a <form> tag? Of course styling within CSS. If someone knows how to accomplish this, may someone give me an example?
Thank you!
Aaron
A: You can use classes fairly easily:
.singleSelect {
width: 200px;
}
.singleMultiple {
width: 300px;
}
<form>
<select class="singleSelect">
<option>Test</option>
</select>'
<br/>
<select class="singleMultiple" multiple="multiple">
<option>Test 1</option>
<option>Test 2</option>
<option>Test 3</option>
</select>
</form>
http://jsfiddle.net/GyxL4/
A more advanced selector may be used on the select[multiple], but beware, legacy browsers (EDIT: apparently only IE6) may not always support the attribute selector, and in the first example below, you're styling every SELECT element on the page (this is called an element selector):
select {
width: 200px;
}
select[multiple] {
width: 300px;
}
See: http://www.w3.org/TR/CSS2/selector.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: jquery get the parent ul of a list item click I am trying to write a simple hover function (please don't suggest another, I have specific needs). I have the hover work so that it will show to the right of the list item that it is hovering. The style of the page shows a left navigation where the ul background looks like a solid block. This means that I need my hover to be to the right of the whole ul, not just the li I am over incase it is a short one. I am trying to get the parent of the li, but I am getting an error this.parent is not a function.
How do I get the parent ul of a li so I can get it's position.
my li has a class of .left-nav-item
this.myhover = function () {
this.xOffset = -10; // x distance from mouse
this.yOffset = 10; // y distance from mouse
$(".left-nav-item").unbind().hover(
function (e) {
this.top = (e.pageY + yOffset);
this.left = (e.pageX + xOffset);
alert(this.title);
this.parent().css('background-color', 'red');
$('body').append('<p id="new">My Hover Text</p>');
$('p#new').css("top", this.top + "px").css("left", this.left + "px").css("position", "absolute").fadeIn("slow");
},
function () {
//$("p#new").fadeOut("slow").remove();
}
).mousemove(
function (e) {
this.top = (e.pageY + yOffset);
this.left = (e.pageX + xOffset);
//$("p#new").css("top", this.top + "px").css("left", this.left + "px");
}
);
};
jQuery(document).ready(function ($) { myhover(); });
A: Try -
$(this).parent().css('background-color', 'red');
parent() is a jQuery function and will only work with a jQuery wrapped element.
A: Your question:
How do I get the parent ul of a li so I can get it's position.
$('your li').closest('ul');
A: $('li.left-nav-item').parent();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: undefined method `new_confirmation_path' Confirmation Module Devise + MongoID I am trying to work with Rails 3.1 + Devise Module :confirmable + MongoID with this template:
https://github.com/RailsApps/rails3-application-templates/raw/master/rails3-mongoid-devise-template.rb
Mi template working fine but now I have generate confirmable views with the next command:
rails generate devise:views confirmable
Generate this:
invoke Devise::Generators::SharedViewsGenerator
create app/views/confirmable/mailer
create app/views/confirmable/mailer/confirmation_instructions.html.erb
create app/views/confirmable/mailer/reset_password_instructions.html.erb
create app/views/confirmable/mailer/unlock_instructions.html.erb
create app/views/confirmable/shared
create app/views/confirmable/shared/_links.erb
invoke form_for
create app/views/confirmable/confirmations
create app/views/confirmable/confirmations/new.html.erb
create app/views/confirmable/passwords
create app/views/confirmable/passwords/edit.html.erb
create app/views/confirmable/passwords/new.html.erb
create app/views/confirmable/registrations
create app/views/confirmable/registrations/edit.html.erb
create app/views/confirmable/registrations/new.html.erb
create app/views/confirmable/sessions
create app/views/confirmable/sessions/new.html.erb
create app/views/confirmable/unlocks
create app/views/confirmable/unlocks/new.html.erb
I catch the next error to refresh the page:
NoMethodError in Devise/sessions#new
undefined method `new_confirmation_path' for #<#<Class:0xb94bb04>:0xb948b20>
11: <% end -%>
12:
13: <%- if devise_mapping.confirmable? && controller_name != 'confirmations' %>
14: <%= link_to "Didn't receive confirmation instructions?", new_confirmation_path(resource_name) %><br />
15: <% end -%>
16:
17: <%- if devise_mapping.lockable? && resource_class.unlock_strategy_enabled?(:email) && controller_name != 'unlocks' %>
Why not working my login, sign_up...etc pages?
A: If you have this problem when installed devise + mongoid + :confirmable module:
!!You must restart the server¡¡
The steps are:
When you have installed devise + mongoid then:
1º enable :confirmable module in your User Model
2º run the command:
rails generate devise:views confirmable
3º Restart the rails server
Regards!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Performing an OR of two Mongoid "any_in" queries If I have two queries that look like:
Store.any_in(:store_id => @user.stores_followed)
Store.any_in(:store_id => @category.stores)
How do I join these into an OR using any_of? I tried this and it doesn't.
I tried
Store.any_of({:store_id.any_in => @user.stores_followed},
{:store_id.any_in => @category.stores})
A: It looks like it isn't full supported in Mongoid, so I had to do:
Store.any_of({"store_id" => { "$in" => @user.stores_followed}}, {"store_id" =>
{"$in" => (:store_id => @category.stores)}})
A: You pass an $or query an array of $in conditions like so:
Store.or( { :store_id.in => @user.stores_followed }, { :store_id.in => @category.stores } )
A: any_in accepts an array of OR values using the $in operator.
ids = @user.stores_followed.map(&:id) + @category.stores.map(&:id)
Store.any_in(:store_id => ids)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Meta tag invalid property attribute I'm trying to change the default thumbnail pic facebook uses when I post my website url on fb. Now I've been on a couple of websites/forums and there is a lot of confusion/differences about it.
Most people say that you should include the following line in the <head></head> tag of your homepage:
<link rel="image_src" href="url to your desired thumbnail image.jpg" />
Now I did that (and so did many other people) and it doesn't work(for others as well). Some other folks on different websites suggested including the following:
<meta name="fb" content="url to your desired thumbnail image.jpg" property="og:image"/>
In ASP.NET (visual studio '10) it says that 'property' is not a valid attribute of 'meta'.
Now what schemas should I declare in my html tags for property to be a 'valid' attribute. I went on some big websites to see their coding, and found the following meta tags declared in the <head> tag:
<meta content="IE=100" http-equiv="X-UA-Compatible">
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
I tried that as well but fb still doesn't use the pic I specified to be used as the thumbnail. My coding and url's are not broken or anything, visual studio debugs it without problems.
Please help...
Thank You
A: Try adding the following <meta> tag into your <head> section:
<meta property="og:image" content="URL_to_your_desired_thumbnail_image.jpg" />
Then, enter the URL of your page into the Facebook URL Linter
For 'property' to be a valid attribute of the <meta> tag, you might have to change your <!DOCTYPE ...>.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to apply function by column to a list of matrices How would I go about applying a function by column to a list of matrices? For example I have a list like below.
[[1]]
[[1]][[1]]
[,1] [,2] [,3]
[1,] "b" "c" "d"
[2,] "y" "y" "y"
[3,] "z" "z" "z"
[[1]][[2]]
[,1] [,2] [,3]
[1,] "b" "b" "c"
[2,] "c" "d" "d"
[3,] "y" "y" "y"
[4,] "z" "z" "z"
[[2]]
[,1] [,2]
[1,] "y" "z"
This works fine:
apply(p[[1]][[1]],2,gen.fmla,y="q")
[[1]]
log(q) ~ b + y + z
<environment: 0x920732c>
[[2]]
log(q) ~ c + y + z
<environment: 0x912e66c>
[[3]]
log(q) ~ d + y + z
<environment: 0x85b608c>
But I can't figure out how to apply it to the list. lapply alone doesn't work as it applies the function to the entire matrix. I was trying to use a combo of apply and lapply, but couldn't figure it out.
A: To get a better answer, you need to supply a reproducible example. For a general answer to your problem, you can use lapply twice. For example:
##Create some data
R> l = list()
R> l[[1]] = matrix(rnorm(10), 2); l[[2]] = matrix(rnorm(10), 2)*10
R> L = list()
R> L[[1]] = l; L[[2]] = l
R> f = function(l) lapply(l, apply, 2, sum)
R> lapply(L, f)
[[1]]
[[1]][[1]]
[1] 1.1923 0.5275 0.4957 0.6848 -0.2776
[[1]][[2]]
[1] -13.984 15.435 -16.362 8.799 4.186
<snip>
Or using the rapply function:
#Gives the same as above
R> rapply(L, function(i) apply(i, 2, sum), how="replace")
A: Your problem is not simply addressed by lapply since it is not a simple list. The first element has two lists each of which has as its first element a matrix. The second element is just a matrix. There is an rapply function, which could be used if you provide a sensible test case of list and function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: django wizard -- How to realize a dynamic form(or formset) in wizard I have asked a similar question yesterday but perhaps it was too concret.
I have read a lot about this on net, but I didn't find any solution.
Here is what I want to realize:
*
*I want to implement a wizard which has 2 steps.
first step---ProductForm
Some fixed fields like Name, Description, etc
Then a dynamic field Picture which can be added by a button, that is to say if the user clicks add another picture, he should see a new Image field shown up
second step---MoreInfoForm
The user finishes the MoreInforForm, then we save the data.
Does anyone have an idea? Thanks in advance!
A: I just answered a similar question here:
django 1.3 wizard alter form_list to change next steps
You need to make two separate forms - a ProductForm and a MoreInfoForm - then you create a view to process these forms.
The view will check whether anything has been POSTed to it (i.e. a form has been submitted) and if so, decide if it needs to provide a new form (in the case of the ProductForm being submitted - i.e. step 1) or carry out a save (in the case that the MoreInfoForm has been submitted - i.e. step 2)
If there is data in the first form that you need to hold onto until the second form has been filled out, you can save this data in a session variable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Twitter Bootstrap on page tabs: not hiding tab content I'm trying to get the twitter on page tabbed content to work. I have the tabs working with switching around active class on the tabs. I've included jquery and the bootstrap-tabs.js but the following code can't seem to get the tabbed content to hide / display as they should. Any help on what may be a simple fix would be appreciated.
<div class="span8">
<ul class="tabs" data-tabs="tabs">
<li class="active"><a href="#2009">2009</a></li>
<li><a href="#2010">2010</a></li>
<li><a href="#2011">2011</a></li>
</ul>
<div class="pill-content">
<div class="active" id="2009">
2009 copy
</div>
<div id="2010">
2010 copy
</div>
<div id="2011">
2011 copy
</div>
</div>
<script>
$(function () {
$('.tabs').tabs()
})
</script>
</div><!-- end span 8 -->
A: The bootstrap example is incomplete - you need class="pill-pane" (or maybe tab-pane) on the tab elements with the ids
<div class="span8">
<ul class="tabs" data-tabs="tabs">
<li class="active"><a href="#2009">2009</a></li>
<li><a href="#2010">2010</a></li>
<li><a href="#2011">2011</a></li>
</ul>
<div class="pill-content">
<div class="active pill-pane" id="2009">
2009 copy
</div>
<div class="pill-pane" id="2010">
2010 copy
</div>
<div class="pill-pane" id="2011">
2011 copy
</div>
</div>
<script>
$(function () {
$('.tabs').tabs()
})
</script>
</div><!-- end span 8 -->
A: If you set the class on the content to class="tab-content" then I think the display:none would work correctly and no need for an inline style.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can top output show more than 100% in %MEM against a process? Can the %MEM value for a process show more than 100% in top output?Is this ever possible?
A: Yes, because the value shown is the percentage of physical memory excluding swap, but a program can use more than this if it also uses swap.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: C++ exceptions in main My class Person has different files as attributes.
class Person {
private:
fstream history;
fstream familyTree;
public:
Person() {
history.open("history.dat");
familyTree.open("tree.dat");
}
}
I need my program to return different values if any of the files couldn't be opened.
If history didn't open, return 1, if familyTree didn't open, return 2.
1) Is using exceptions the only solution for this?
2) Where are the exceptions launched?
3) Is it wrong if I catch exceptions in main?
A: You could throw exceptions in your constructor and catch them in main. Or you could catch the exceptions in your constructor and fix it so that the class can be correctly initialised whatever happens.
To make your class more testable, the constructor should do as little work as possible. I would have two methods:
bool readHistory (std::string fileName)
bool readFamillyTree (std::string fileName)
instead of trying to do that in the constructor. They would return true if the file could be read and was sane. You could have a overloaded constructor that called those methods. As was pointed in the comments, the constructor should return a usable object. I am assuming that those files are not necessary for the object to function. This could be erroneous.
A: There is no need for exceptions here.
bool Person::IsHistoryValid() const
{
return history;
}
bool Person::IsFamilyTreeValid() const
{
return familyTree;
}
int main()
{
Person person;
if (!person.IsHistoryValid())
return 1;
if (!person.IsFamilyTreeValid())
return 2;
// do some work
return 0;
}
Depending on your requirements, catching exceptions in main may be right or wrong. Of course, if you have to return an error code in case of exception, then you have to catch them.
A:
1) Is using exceptions the only solution for this?
No. You can also record the error state in the constructor and have a method that returns it. Or you can do a two phase construction, where the contructor only does the parts that can't fail and you call a second initialization function to complete it.
I think exceptions would be the preferred method. If you are doing things that might need some cleanup if the constructor fails, do them on local variables and copy the results to the member variables at the end.
If main() is the
closest stack call (is that well written?) to where the exceptions are
launched,
2) Is it wrong if I catch exceptions in main?
Absolutely nothing wrong with catching exceptions in main. In fact it's best practice to catch exceptions at the outermost level that can do anything about the error; often that means showing the error and shutting down the program, and main is the perfect place.
A:
1) Is using exceptions the only solution for this?
Certainly not, there are a lot of designs out there that predate the exceptions functionality that use return codes, double initialization, and such techniques. That said, if the construction of a Person requires opening both files, and you cannot do so, then throwing an exception is the preferred way to report it. Think about what it means for your design to be a Person, and to create a default constructed one.
2) Is it wrong if I catch exceptions in main?
No, is not. Plain and simple.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Right way to redirect to list page after successful add Simple question I'm sure but in Symfony 1.4. After I the form is submitted to add what is the best way to automatically go to the list all page?
A: In a typical symfony setting, the general idea would be:
public function executeCreate($request) {
$form = new FooForm();
if ($request->isMethod('post')) {
$form->bind((array) $request->getParameter('foo'));
if ($form->isValid()) {
$form->save();
$this->redirect('@route_name_for_list');
}
}
$this->form = $form;
}
A: Once you have found the name of the route that leads to the list all page, let's call it stuff_index, you can simply do this: $this->redirect('@stuff_index');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Exif data returns string with ? box characters only within javascript I'm fetching exif data using exif_read_data and inserting it into an image alt tag which works fine, but when I fetch that data using javascript (var hovertext = $(this).find('img').attr('alt');) a bunch of weird question mark/box characters appear in the output.. Any ideas?
A: try,
ini_set('exif.encode_unicode', 'UTF-8');
edit: if you haven't set the encoding for your html, then
<meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
edit2:
$exif = exif_read_data('picname.jpg', 0, true);
echo "picname.jpg:<br />\n";
foreach ($exif as $key => $section) {
foreach ($section as $name => $val) {
echo "$key.$name: $val<br />\n";
}
}
Please run this on any picture and provide result for "COMPUTED.UserCommentEncoding:"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Open Source Software For Transcribing Speech in Audio Files Can anyone recommend reliable open source software for transcribing English speech in wav files? The two main programs I've researched are Sphinx and Julius, but I've never been able to get either to work, and the documentation with each on transcribing files is sketchy at best.
I'm developing on 64-bit Ubuntu 10.04, whose repos include sphinx2 and julius, as well as voxforge's julius acoustic modal for English. I'm focussing on transcribing files, instead of directly processing sound from a mic, because I've given up on expecting projects like these to work with Ubuntu's sound system. This isn't a knock against Ubuntu, as I can record sound with my mic perfectly using Audacity, but neither system seems able to access my mic, so I'm hoping I can simply their configuration by just reading from a file.
I first tried Sphinx2, from the Ubuntu package sphinx2-bin. Even though the sample sphinx2-demo seemed to work on transcribing a file, there's virtually no documentation on the configuration, so I'm not sure how I'd customize this to read from an arbitrary wav. The audio file used in the demo is in some undocumented "16k" format, which is indirectly referenced through 2 configuration files. There's a brief blurb describing sphinx2-demo as running sphinx2-batch, but inspecting the script shows it's actually calling sphinx2-continuous. Even worse, the --help docs for each script list about 6 dozen options, and doesn't mention which are required or optional. Overall, the lack of sphinx documentation, and the poor quality of existing documentation is driving me nuts.
I next tried Julius, again from the Ubuntu package, which was surprisingly recent (4.1), considering the version used in Voxforge's quickstart is 3.5. The package seems to include slightly better documentation, and even an example written in Python (/usr/share/doc/julius-voxforge/examples/controlapp). After reading the example's docs, I tried adapting it to read from a file by creating a file filelist.txt containing the text "hello.wav" referring to a file of the same name, containing a recording of someone saying "hello". Placing these in the same directory, I ran:
julius -input file -filelist filelist.txt -C julian.jconf
getting the response:
### read waveform input
Error: adin_file: sampling rate != 16000 (8000)
Error: adin_file: error in parsing wav header at hello.wav
Error: adin_file: failed to read speech data: "hello.wav"
0 files processed
Retrying by specifying absolute filenames for filelist.txt and hello.wav produce the same error.
I also tried the Julius call used in the example, to record directly from a mic:
julius -input mic -C julian.jconf
I called this several times, and the response varied between the error:
Cannot read /dev/dsp
and:
STAT: AD-in thread created
<<< please speak >>>
In the later case, no matter what I say into the mic, nothing happens. I can't tell if it's still unable to read the mic, or if it's reading something, but is simply unable to transcribe the audio.
I'm not sure what to make of this. The errors I'm getting don't leave me with much to go on. Why can't it read a wav? Why can't it read /dev/dsp? Why does it then appear to be able to read /dev/dsp, but not react in any way?
Has anyone else had any success with open source speech recognizers, especially on Linux?
A:
Why can't it read a wav?
It tells you that the file has wrong sampling rate (8000) instead of requested (16000). Sampling rate is very important for speech recognition software.
Why can't it read /dev/dsp?
In recent versions of Ubuntu pulseaudio framework is used instead of OSS. The version you are trying is using OSS so you need to install oss-compatibility package from your distribution to bring OSS support back.
You can try newer Julius which has pulseaudio support
Why does it then appear to be able to read /dev/dsp, but not react in any way?
Audio input doesn't work properly.
Has anyone else had any success with open source speech recognizers,
especially on Linux?
Sure, check this video as an example of what people do with CMUSphinx:
http://www.youtube.com/watch?v=vfaNLIowSyk
I suggest you to revisit CMUSphinx package which is a leading open source speech recognition engine. There are loads of documents on the website, you just need to read them. Remember that speech recognition is a complex area where you can get a great results but you also need to invest your time in understanding the technology. Just like with any other domain.
In short, to transcribe a file with CMUSPhinx you need to do the following 3 simple steps:
*
*Take wav file and resample it to 8khz 16 bit mono file with sox:
sox input.wav -r 8000 -c 1 resampled.wav
*Install pocketsphinx 0.7
apt-get install pocketsphinx
*Decode the file
pocketsphinx_continuous -samprate 8000 -infile resampled.wav
The result will be printed to standard output. To supress the logger, add stderr redirection to /dev/null
pocketsphinx_continuous -infile resampled.wav 2> /dev/null
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Issue with Coffeescript comprehensions and closures I ran into a problem when converting some JavaScript to CoffeeScript. The basic issue is I went from using $.each to CoffeeScript comprehensions and I now have a problem where the last value of the comprehension is being captured in closures. Lets start with the original JavaScript:
function bindKeyboardControls(websocket) {
var moveKeyMap = {
Down: ['down', 's'],
Up: ['up', 'w'],
Left: ['left', 'a'],
Right: ['right', 'd']
};
$.each(moveKeyMap, function (direction, keys) {
$.each(keys, function (_, key) {
$(document).bind('keydown', key, function () { move(websocket, direction); });
});
});
};
Here is my first attempt with CoffeeScript:
bindKeyboardControls = (websocket) ->
moveKeyMap =
Down: ['down', 's']
Up: ['up', 'w']
Left: ['left', 'a']
Right: ['right', 'd']
for direction, keys of moveKeyMap
for key in keys
$(document).bind('keydown', key, -> move(websocket, direction))
null
Why doesn't this work? Well here's the generated JavaScript:
bindKeyboardControls = function(websocket) {
var direction, key, keys, moveKeyMap, _i, _len;
moveKeyMap = {
Down: ['down', 's'],
Up: ['up', 'w'],
Left: ['left', 'a'],
Right: ['right', 'd']
};
for (direction in moveKeyMap) {
keys = moveKeyMap[direction];
for (_i = 0, _len = keys.length; _i < _len; _i++) {
key = keys[_i];
$(document).bind('keydown', key, function() {
return move(websocket, direction);
});
}
}
return null;
};
Do you see how the 'direction' variable is declared at the top of the function? The function that is being passed in to document.bind is creating a closure on that variable, so by the time the function runs, direction will always be equal to the last value ('Right').
Here is a fixed version that is somewhat ugly:
bindKeyboardControls = (websocket) ->
moveKeyMap =
Down: ['down', 's']
Up: ['up', 'w']
Left: ['left', 'a']
Right: ['right', 'd']
for direction, keys of moveKeyMap
for key in keys
((d) -> $(document).bind('keydown', key, -> move(websocket, d)))(direction)
null
I could also just go back to using $.each. So I do have some solutions, but is there a better one?
A: Yes:
for direction, keys of moveKeyMap
for key in keys
do (direction, key) -> $(document).bind('keydown', key, -> move(websocket, d))
That creates and runs an anonymous function that captures the values of direction and key, so that the the bind callback can use them. See my PragProg article A CoffeeScript Intervention for more on this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to store large data source while using jQuery aotocomplete in the front end? If you have 1000k rows of data, it looks like zipcode/city/state, if you type 95101 in the website text field, it will show san jose, ca; and complete the text field autocomplete.
What kind of data structure are you choosing to store the whole zipcode/city/state in united states?
Maybe 1000k rows. If I load the data source to local, it seems like wasting time. If I write the data source in the array of JavaScript, the array is too large, any ideas?
A: Do you mean 1 million rows?
Use a remote datasource to do the search on the server on only return a small number of rows.
eg jQuery autocomplete remote example
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
A: You could use jQuery ui autocomplete with a remote datasource - http://jqueryui.com/demos/autocomplete/#remote
Excerpt from there:
The datasource is a server-side script which returns JSON data, specified via a simple URL
for the source-option. In addition, the minLength-option is set to 2
to avoid queries that would return too many results and the
select-event is used to display some feedback.
Code sample from there:
$(function() {
$( "#birds" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
A: Such a huge amount of data, I recommend you using remote call instead of storing in local array or object. But I believe storing in object is a good option as compared to an array as it creates hash.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CMAKE API - producing an AST from the root CMakeFile I'm toying around with the idea of creating some tools for code analysis. My projects of interest all use cmake and clang++ now.
To start with I need to get my hands on the CMake AST for a certain project. In essence I want to do the following (psuedocode):
CMakeAst & project_ast = CMakeAstBuild("/path/to/the/root/directory/of/a/project");
From the AST I will extract the targets, the (default) compiler switches configured (, the (default) #DEFINE's, the include paths etc. All this information will be required for libClang to build an accurate AST for the targets defined in my project-under-analysis.
So libclang is a clean documented interface to clang. I now need the information for CMake Could someone guide me to getting my own CMake AST producing main program. Any information is welcome.
A c-main and the relevant compile switches in the form of a MakeFile would make my day :D
Edit: My Progress (cmake 2.8.5)
cmakemain.cxx contains the main method and sets up the context for the main engine which seems to be a class cmake which is contained in cmake.h. cmake.h has good documentation.
The build tools seem to build monolithic executable tools, no intermediary library is created. bit messy :/.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: MonoTouch binding not creating partial classes I'm attempting to do what is shown on the MonoTouch binding page and add some methods to a bound class. It says that all I have to do is include these in a partial class defined in a separate file that is included in the generation process with the -s option. The problem is that the generated class is not a partial class and when I run btouch I get the following errors:
$ /Developer/MonoTouch/usr/bin/btouch -v Node.cs -s:Extensions.cs
/Developer/MonoTouch/usr/bin/smcs -unsafe -target:library Node.cs -nowarn:436 -out:/var/folders/cy/g71b7mr91rn4slbpq5cm39140000gn/T/u983s550.k1k/temp.dll -r:/Developer/MonoTouch/usr/lib/btouch/btouch.exe Extensions.cs -r:/Developer/MonoTouch/usr/lib/mono/2.1/monotouch.dll
Node.cs(7,19): error CS0260: Missing partial modifier on declaration of type NodeNameSpace.Node'. Another partial declaration of this type exists
Extensions.cs(5,30): (Location of the symbol related to previous error)
Extensions.cs(5,30): error CS0261: Partial declarations ofNodeNameSpace.Node' must be all classes, all structs or all interfaces
Node.cs(7,19): (Location of the symbol related to previous error)
Extensions.cs(7,29): error CS0106: The modifier public' is not valid for this item
Extensions.cs(10,25): error CS0531:NodeNameSpace.Node.IsExpanded.get': interface members cannot have a definition
Extensions.cs(14,25): error CS0531: `NodeNameSpace.Node.IsExpanded.set': interface members cannot have a definition
Compilation failed: 5 error(s), 0 warnings
btouch: API binding contains errors.
According to the MonoTouch page on binding:
Each class produced by the generator from the API definition file is a partial class
Node.cs
using System;
using MonoTouch.Foundation;
namespace NodeNameSpace
{
[BaseType (typeof (NSObject))]
interface Node
{
[Export ("expanded")]
NSNumber Expanded { get; set; }
}
}
Extensons.cs
using MonoTouch.Foundation;
namespace NodeNameSpace
{
public partial class Node
{
public bool IsExpanded
{
get
{
return Expanded.BoolValue;
}
set
{
Expanded = NSNumber.FromBool(value);
}
}
}
}
A: Looks like that page is out of date. Doing some more searching I found the this post in the forums.
The correct command to compile my example above is:
/Developer/MonoTouch/usr/bin/btouch -v Node.cs --sourceonly genfiles --outdir=gen
followed by:
/Developer/MonoTouch/usr/bin/smcs -out:Node.dll `cat genfiles` Extensions.cs -r:/Developer/MonoTouch/usr/lib/mono/2.1/monotouch.dll -target:library
A: It's a long documentation page, but this should do what you want:
$ /Developer/MonoTouch/usr/bin/btouch Node.cs -x:Extensions.cs
$ ls -l Node.dll
-rwxr-xr-x 1 sebastienpouliot staff 5120 30 Sep 13:30 Node.dll
Your issue was using -s which is used when compiling your interface to a partial class (too early for extensions methods) and to compile the bindings to a .dll.
What you wanted is -x where the source file would only be used for the second compilation (source to .dll). The -s option is most useful for enums since you'll need them in both your interfaces and in the final assembly (.dll).
To get further help do:
/Developer/MonoTouch/usr/bin/btouch --help
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP string to float bug? So, I got this:
$a = "149.45";
var_dump($a);
gives
string(6) "149.45"
now
$b = $a * 100;
var_dump($b);
so far so good:
float(14945)
and now
$i = (int)$b;
var_dump($i);
What the ...?
int(14944)
Tested on PHP 5.2.17 (on CentOS) and PHP 5.3.2-1ubuntu4.9 (On ubuntu).
Can anyone tell me if this is a known bug?
Can anyone test it on a newer PHP version?
EDIT
OK, I got it, float binary representation aproximation error. For my code I already used round().
But why then
$a = 149.45;
$b = 100 * $a;
var_dump($b)
printf('%.10f', $b);
gives
float(14945)
14945.0000000000
? Why that string is not parsed just as 149.45 is parsed?
A: Illustration of what @Jon said:
$a = "149.45";
$b = $a * 100;
var_dump($b);
printf("%.50f", $b);
result
14944.99999999999818101059645414352416992187500000000000000
"14945" is just a string representation of the above number, not that number itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Reading an XML Node only I am having an issue getting the value of an XML, it is loading it in the XML document when i debug, but it is not finding the value or the node i want to access. Here is the xml. The value i want to get is "Active". Now this XML is not a file or anything , is being passed as a string... (can not modify this part) have only access to the class where i can create functions to access it but can not modify the actual code getting the values and passing it as a "xml string"
<Clients>
<BillingCycle>30</BillingCycle>
<Category>1</Category>
<Type>Admin</Type>
<AddressCat>3</AddressCat>
<ZipCodeCat>5</ZipCodeCat>
<ClientManager>
<UserID>5</UserID>
<ZPVal>1</ZPVal>
<DRY1>Test</DRY1>
<Active>1</Active>
</ClientManager>
</Clients>
C# code here
public bool IsActive(int ClientID, int VassID)
{
bool isActive = false;
HelperClass helper = new HelperClass();
XmlDocument xml = new XmlDocument();
//at this point i can see the data was stored in the xml when debugging
xml.LoadXml(helper.GetClientXML(ClientID, VassID));
//have tried the following do not woerk
// XmlNode node = xml.SelectSingleNode ("/Clients/ClientManager/Active/text()");
XmlNode node = xml.SelectSingleNode("Clients/ClientManager/Active");
int isActiveVal = Convert.ToInt32(node.Value);
if (isActiveVal == 1)
{
isActive = true;
}
return isActive;
}
A: Use InnerText instead of Value
A: This line could work:
//XmlNode node = xml.SelectSingleNode ("/Clients/ClientManager/Active/text()");
var activeTextNodes = xml.SelectNodes("/Clients/ClientManager/Active/text()");
... but it will select a set of Active text() values, which you probably don't want.
You could access the InnerText value of the node you found:
XmlNode node = xml.SelectSingleNode("Clients/ClientManager/Active");
int isActiveVal = Convert.ToInt32(node.InnerText);
Or you could access the value of the First Child:
XmlNode node = xml.SelectSingleNode("Clients/ClientManager/Active");
int isActiveVal = Convert.ToInt32(node.FirstChild.Value);
All this being said, you should use int.TryParse instead of Convert.ToInt32 because it won't throw an exception on non-integer data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to make a transparent window with Qt Quick? Is there a way to make the window of a qml application transparent?
I'm looking for a detailed description on how to draw simple shapes with qml while making the window of the application transparent, as well as the background. A working source code demo would be awesome.
A: As of at least Qt 5.3 you don't need anything as elaborate as in the previous answers:
Window {
flags: Qt.ToolTip | Qt.FramelessWindowHint | Qt.WA_TranslucentBackground
color: "#00000000"
Job done. (You might want to change ToolTip. I'm using it because I'm making tooltips.)
A: Here is a simple example:
main.cpp:
#include <QtGui/QApplication>
#include "mainwindow.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
mainwindow.h:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QDeclarativeView>
class MainWindow : public QDeclarativeView
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
};
#endif // MAINWINDOW_H
mainwindow.cpp:
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QDeclarativeView(parent)
{
// transparent background
setAttribute(Qt::WA_TranslucentBackground);
setStyleSheet("background:transparent;");
// no window decorations
setWindowFlags(Qt::FramelessWindowHint);
// set QML file
setSource(QUrl("main.qml"));
}
MainWindow::~MainWindow()
{
}
main.qml
import QtQuick 1.0
Rectangle {
id: root
width: 250
height: 250
// completely transparent background
color: "#00FFFFFF"
border.color: "#F00"
border.width: 2
Rectangle {
id: ball
height: 50; width: 50
x: 100
color: "#990000FF"
radius: height / 2
}
SequentialAnimation {
running: true; loops: Animation.Infinite
NumberAnimation { target: ball; property: "y"; to: root.height - ball.height; duration: 1000; easing.type: Easing.OutBounce }
PauseAnimation { duration: 1000 }
NumberAnimation { target: ball; property: "y"; to: 0; duration: 700 }
PauseAnimation { duration: 1000 }
}
}
transp-qml.pro
QT += core gui declarative
TARGET = transp-qml
TEMPLATE = app
SOURCES += main.cpp\
mainwindow.cpp
HEADERS += mainwindow.h
OTHER_FILES += main.qml
screenshot of result:
A: I'm using Qt 5.3 with both C++ and QML and found that I needed to call QQuickWindow::setDefaultAlphaBuffer. This has to be done before creating the first QQuickWindow, so in C++, not QML. The window color and flags could probably be set in QML, but I opted to put all the code for winow transparency in one place like so:
QQuickView view;
QQuickWindow::setDefaultAlphaBuffer(true);
view.setColor(Qt::transparent);
view.setFlags(m_View.flags() |
static_cast<Qt::WindowFlags>(Qt::WA_TranslucentBackground));
A: I finally found a simple way to draw a couple of red/blue rectangles while leaving the window transparent.
draw_rectangles.qml
import Qt 4.7
Item {
Rectangle {
opacity: 0.5
color: "red"
width: 100; height: 100
Rectangle {
color: "blue"
x: 50; y: 50; width: 100; height: 100
}
}
}
win.cpp:
#include <QApplication>
#include <QDeclarativeView>
#include <QMainWindow>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
QMainWindow window;
QDeclarativeView* v = new QDeclarativeView;
window.setCentralWidget(v);
v->setSource(QUrl::fromLocalFile(("draw_rectangles.qml")));
window.setStyleSheet("background:transparent;");
window.setAttribute(Qt::WA_TranslucentBackground);
window.setWindowFlags(Qt::FramelessWindowHint);
window.show();
return app.exec();
}
win.pro:
TEMPLATE += app
QT += gui declarative
SOURCES += win.cpp
Save these files to the same directory and execute qmake followed by make to compile the application.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: deleting / resetting DOM nodes I have a web application in which you view/explore a 2D network graph.
when you mouseover a node, a request is sent to the server - the server gathers information and sends it back to the client - the client saves all informations in a JS class TooltipGraphListener like this:
var w = new scripts.widget.GraphInfo({
baseURL: this._baseURL,
basePath: 'graphs/' + this._graphName,
path: 'nodes/' + nid,
tooltip: true });
var domNode = w.domNode;
dojo.removeClass(domNode, 'graphInfo');
domNode.setAttribute("id", nid);
this._canvas.containerNode.appendChild(domNode);
dojo.addClass(domNode, 'tooltip');
dojo.style(domNode, "opacity", 0.8);
this._toolTips.push(w);
my problem now is that if I generate a new graph in the web app's widget this line:
var tooltip = dojo.byId(id);
if (tooltip)...
still is true, even if I clear _toolTips (_toolTips = []) or re-initialize the whole class (listener = new TooltipGraphListener()).. the individual tooltips can still be found by dojo.byId(id);
how can I reset/delete all these tooltip domnodes?
A: The GraphInfo class must be appending the tooltip element to the DOM. You have to remove it, or it will always be there, regardless of what happens to your class. The 'byId' method is looking in the DOM for an element with that ID.
If you really must be able to reset the thing you'll have to build a dispose() method into the class, in which it would remove the DOM elements that it added. That or you can just reuse the same DOM element for each instance, assuming it's ok that there can only be 1 showing on the page at a time (since it is a tooltip, I think that is the case).
A: When you clear your tooltips, you'll also have to remove their DOM nodes from the document (I'm sure there's a more dojo way of doing this, but I haven't used that framework):
for (var i = 0; i < this._tooltips.length; i++) {
this._canvas.containerNode.removeChild(this._tooltips[i].domNode);
}
this._tooltips = [];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do you handle shared members when dealing with interfaces? So I did tons and tons of work trying to make an interface for a common set of classes. The idea was to make an interface that each class could use within the set, but ultimately each class is different. Turns out interfaces do not like shared members. What I tried:
Public Interface ISomeInterface
Shared Property Meta() as Object
End Interface
Public Class A
Implements ISomeInterface
Shared Public Property Meta() as Object Implements ISomeInterFace.Meta
'Set/get methods
End Propery
Public Function Haduken() as Object
'perform Haduken
End Function
End Class
Public Class B
Implements ISomeInterface
Shared Public Property Meta() as Object Implements ISomeInterFace.Meta
'Set/get methods
End Propery
Public Function SonicBoom() as Object
'perform sonic boom
End Function
End Class
Obviously, had I done my homework on this, I would have known that shared members can't be use in interfaces. Should I just leave the individual classes completely responsible for handling its shared members? Is there another way to keep coupling down to a minimum with shared members? Theres about 20 something or so classes that will implement a single interface. Thanks in advance.
A: The simplest way to work around this is to have a Private implementation of the interface which simply forwards to the Shared member
Public Shared Property Meta As Object
' Get / Set methods
End Property
Private Property MetaImpl() as Object Implements ISomeInterFace.Meta
Get
return Meta
End Get
Set
Meta = Value
End Set
End Propery
This pattern allows you to maintain the same public facing API and still implement the interface.
A: If the idea is that each implementation of the interface should use its own shared variable, JaredPar's approach is the right one. If the idea is that all users of the interface should see the same shared variable, regardless of what instance they have (if any), the right approach is to create a class with a name similar to the interface, and use a shared member of that class. That is the approach used by e.g. Enumerable<T>.Empty or Comparer<T>.Default.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Float property not working I'm having some issues trying to write CSS to make a box float to the right of my page.
I have a div called #right-box-uploadphoto that is the grey box on this page http://s361608839.websitehome.co.uk/salesboard/After_Login.html
The CSS is this:
#right-box-uploadphoto{
width: 240px;
height: 240px;
background: #e6e6e6;
border: 1px solid #d7d7d7;
margin-left: 15px;
float: right;
}
It's somehow being pushed down. It needs to line up with #page-box2.
Is this not right?
Thanks
A: You placed the div incorrectly on your page. Try adding your div to your mainFrame like:
<div id="mainFrame">
<h2>Set up your Salesboard</h2>
<p>There's only a few steps to go!</p>
<div class="line"></div>
<div id="page-box2">
<div id="step-box-select"><span class="icon-step">1</span> Set Up Your Profile</div>
<div id="step-box-unselect"><span class="icon-step">2</span> Set Up Your Team</div>
<div id="step-box-unselect"><span class="icon-step">3</span> Add Team Member</div>
<br><br>
<form action="" method="get">
</form>
<a href="#" class="upgradebutton">Upgrade</a></div>
<div id="right-box-uploadphoto"></div>
</div>
A: Try putting "right-box-uploadphoto" div into the "mainFrame" div.
<div id="mainFrame">
...
<div id="page-box2"></div>
<div id="right-box-uploadphoto"></div>
</div>
That will do the trick!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to check whether process ended or not with php? I want to check whether process is ended or not with php. Please tell me what is the better way to solve this problem.
I have consider several idea for this, for example:
pattern1:
$res=array();
exec('ps auxww | grep "some.php some_param 1" | grep -v grep', $res);
//if $res is empty, process may have ended.
or
pattern2:
$res = array();
exec('pgrep -fx "some.php some_params 1"', $res);
currently I think pgrep is the better way. but is there any other method?
A: The convenient way is to create a PID file in /tmp on the start of the process, e.g: myprocess.pid. This file contains the process id of the created job. Then your monitoring tool has an easy way to check whether the process runs or don't.
A: If you know the PID of the process (which is a good idea - have it write its pid into a file), then you can check if it is alive with
posix_kill(PID,0)
Which returns TRUE only if the process is alive.
However, this is a bit bogus, as it might return TRUE if some other process has appeared with the same PID. PID reuse is quite likely, especially if the OS was rebooted since the process started.
A better way is to have the process lock a file (with e.g. flock) and then you can see if the lock is still present (by trying to lock the file yourself with FLOCK_NB)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Regex to match pattern "Double-Double;" I have trouble finding a regex matching this pattern:
*
*A numeric (decimal separator can be . or ,), followed by
*a dash -, followed by
*a numeric (decimal separator can be . or ,), followed by
*a semi-column or a space character
This pattern can be repeated one or more time.
The following examples should match the regex:
1-2;
1-2;3-4;5-6;
1,0-2;
1.0-2;
1,0-2.0;
1-2 3-4;
1-2 3,00-4;5.0-6;
The following examples should not match the regex:
1-2
1 2;
1_2;
1-2;3-4
A: Edit updated based on moving of 1 2; to non-match.
This should work:
@"^(\d+([,.]\d+)?-\d+([,.]\d+)?[ ;])+(?<=;)$"
Explanation
^ //Start of the string.
( //Start of group to be repeated. You can also use (?=
\d+ //One or more digits.
([,.]\d+)? //With an optional decimal
- //Separated by a dash
\d+([,.]\d+)? //Same as before.
[ ;] //Terminated by a semi-colon or a space
)+ //One or more of these groups.
(?<=;) //The last char before the end needs to be a semi-colon
$ //End of string.
A: Try this:
@"^([\d.,]+-[\d.,]+[ ;])*[\d.,]+-[\d.,]+;$"
Note that [\d.,]+ accepts some character sequences which wouldn't normally be considered valid "numeric" values such as 00..,.,. You might want to find a better regular expression to match numeric values and substitute it into the regular expression.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WCF Return Type Issue I am using automapper to map a master class to various child classes.
Example: I have a class called VitalStatistics (master class). This class holds all fields for a record.
The company business rules indicate that only certain fields are needed based on the State location.
So, California may not all 20 fields found in the master class and may need only 10 fields instead of the 20. So I use automapper to map the VitalStatis class data to the CAVitalStats class which has only 10 fields. The TXVitalStats class may only have 3 fields. etc..
My web services need to return a type that these classes have in common. E.g. IVitalStatistics interface.
It seems as though the WCF service does not like an interface declared as the return type.
So, how can I get the service to return CAVitalStats or TXVitalStats? Normally if these both were of the same interface type then this would work because they all would be of type IVitalStatistics but the serialization messaging rules appear to have a problem with returning interface types.
I hope this made sense. Thanks
A: If you have CAVitalStats and TXVitalStats both inheriting from the same base class, for instance 'VitalStatsBase', then your service method could return VitalStatsBase.
To make this work with your 2 subclasses you'll need to use the KnownTypeAttribute in your service.
Below is a link describing the KnownTypeAttribute.
http://msdn.microsoft.com/en-us/library/ms730167.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSS Dropdown Menu Disappear in IE My menu looks great in firefox and chrome. But IE. It dissapears. Anybody can help me ?
http://tinyurl.com/6yzd2jc
A: Here's my guess as to what's happening. Could be totally wrong.
The dropdown is supposed to disappear when the user mouses out of the link or the dropdown itself. But the problem is, there's a gap of a few pixels in between the link and the dropdown; this shows up in all browsers; I had trouble with it in Chrome before I even opened IE.
But when I did open it in IE, I saw that the links were even further away from the dropdown menus, so the problem was exacerbated.
If you go back to the CSS and make sure that there's no gap in between the link and the dropdown menu, does that fix the problem?
Edit to actually answer the question
There are a few CSS changes you could quickly make to fix the problem:
*
*Get rid of the height style on #mNav
*Add a <div> with the style clear: both to #topNav, after the <ul>
*Give each ul li a style of height:25px
It's not pretty, but I think that solves it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613148",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to generate scripts from SQL Server 2008 to SQL Server 2008 Express Is it possible to generate scripts from SQL Server 2008 that can then be used in SQL Server Express editions or is it not possible. I read it is not possible, but is there another way.
A: Sure - what are you trying to do??
SQL Server and the Express editions are binary compatible - you could even just create a backup on your "full" SQL Server and restore it on your Express version....
A: unless you are using features that are in Enterprise Edition and up (like data compression, partitioning, etc etc) the scripts should be fine to run on Express edition
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Quartz´s configuration with Oracle How to configure the Quartz's configuration file to work with Oracle. I'm using Quartz.NET 2.0, Oracle 10G and Visual Studio 2010.
I have implemented Quartz 1.0.3 in a project. I have to update the Quartz project to version 2.0, in order to do that i created a Job in a test project and added references to the Quartz's Dlls. The weird is that the Job is working well without install the Quartz service... how is this possible???
A: *
*Run Oracle table creation scripts contained in quartz.net package. I
think the script is under Quartz\database\tables\tables_oracle.sql
*Modify Quartz.Config
quartz.jobStore.tablePrefix = your table prefix , I think default is QRTZ_
quartz.jobStore.dataSource = myDS
quartz.dataSource.myDS.connectionString = your connection string
quartz.dataSource.myDS.provider = OracleClient-20
I think you will be good to go, if you are running quartz as embedded you can number 2 in ypur code.
For more see this tutorial
A: The Oracle database has many options for running scheduled jobs. So maybe you do not really need Quartz for what you want to do. You can use the older DBMS_JOB package or the newer and more sophisticated DBMS_SCHEDULER is also available in 10g.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Transform xorcrypto encryption module to AES encryption module I have been given a sample encryption module which simply xor a key with the packet data and place the result in data field of constructed packet itself....
The code for xoricv module is here.
void
xorcrypto(uint8_t *key, uint32_t keylen,
uint8_t *data, uint32_t datalen)
{
int d, k;
for (d=0, k=0; d < datalen; ++d, k = (k+1)%keylen) {
data[d] ^= key[k];
}
}
Now i need to change the module so that it performed the AES Encryption rather than simple xor operation.
Would you suggest possible transformation i need to do ????
It is a small part of my project and i am stuck in between..
The AES Command I have used on command line for encryption
openssl enc -aes-256-cbc -salt -in file.txt -out file.enc
Daily i am going through plenty of errors when i tried to implement it by my own and i have very limited time so please help me.......
Here is my implementation ...... although i am adding it here in answer column because may be there is small bug in my implementation which i could be able to solve through some valuable suggestions but still If any other way is possible please suggest and provide me some implementation code...
/* u_int8_t ... etc all are typedefs for uint8_t....etc
so don't bother about them */
void xorcrypto(u_int8_t *key, u_int32_t keylen,u_int8_t *data,
u_int32_t datalen)
{
int ch,i,j;
uint8_t modata[100];
FILE *fp,*fr,*fq,*ft;
fp=fopen("key","w");
fputs((char *)key,fp);
fq=fopen("file.txt","w");
fputs((char *)data,fq);
fclose(fp);
fclose(fq);
system("sudo openssl enc -aes-256-cbc -salt -in file.txt -out file.enc -pass file:key");
fr=fopen("file.enc","r");
memset(data,0,sizeof(data));
i=0;
while( (ch=fgetc(fr))==EOF) {
data[i]=ch;
i++;
}
fclose(fr);
system("sudo openssl enc -d -aes-256-cbc -salt -in file.enc
-out file1.txt -pass file:key");
ft=fopen("file1.txt","r");
memset(modata,0,sizeof(modata));
j=0;
while( (ch=fgetc(ft)) != EOF) {
modata[j]=ch;
j++;
}
fclose(ft);
}
Call to function in module is described as -
bool
espcrypto(esp_private *epriv, sendip_data *data, sendip_data *pack)
{
u_int32_t keylen;
u_int8_t *key;
static u_int8_t fakekey;
struct ip_esp_hdr *esp = (struct ip_esp_hdr *)pack->data;
if (!epriv->keylen) { /* This isn't going to be very productive... */
key = &fakekey;
keylen = 1;
} else {
key = (u_int8_t *)epriv->key;
keylen = epriv->keylen;
}
/* Encrypt everything past the ESP header */
xorcrypto(key, keylen,
(u_int8_t *)esp->enc_data,
pack->alloc_len + data->alloc_len -
sizeof(struct ip_esp_hdr));
return TRUE;
}
This is code in the xorcrypto.c file in packet generator tool i am using which is linked during packet construction through command line as -am xorcrypto.so .That is the reason why I was being so lazy.I am first looking for an implementation which can act as proof of concept .Rest all optimizations can be done later.
The output I am getting is - encryption not performed at all the data is still in plain text in packet.
udit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $ cat file.txt
udit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $ cat file.enc
Salted__����
}�#��G�����0����iudit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $ cat file1.txt
udit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $
Why file.txt is null even key file is not updated ???
If any other information needed i will add it here......but please help me getting out of the mesh .
A: This may not even be possible without making some additional changes to your software. It doesn't look like your function allows for the resulting encrypted data to be larger than the unencrypted data, for one, which will be required for RSA.
The key you pass to your function will also be quite different; one side of an RSA key will consist of the modulus and an exponent. The modulus will be a large number (not representable with the normal integer types), and the exponent is typically a large number for one side and a (relatively) small one for the other.
Aside from that, there are a number of issues and difficulties with RSA. You could try to deal with these yourself, but you'd probably be better off using an existing library like OpenSSL. Some of these issues include:
*
*Implementing RSA (with usefully long keys) requires modular arithmetic on very large numbers, far larger than any of the normal integer types. You'd either have to write functions for this, or find a library.
*The data has to be broken into pieces that are shorter than the modulus (part of the key), including whatever padding and such is encrypted along with the data. The length of each piece after encryption will be the length of the modulus. That's why the resulting encrypted data will be longer than the original data (and also padding).
*Avoiding certain vulnerabilities requires additional steps, such as adding random padding into each piece of data and ensuring that the padded data, raised to the exponent from the key, would exceed the modulus (if it weren't done as modular exponentiation).
So first, you'll need to make it possible for your encryption function to return more data than you gave it. Then you should probably look at using an encryption library to do the actual encryption, to save a lot of work and reduce the chances of letting vulnerabilities slip through.
A: Well,
I feel the line :
while( (ch=fgetc(fr))==EOF)
// Also, Similar statements that you have used many times.
You are reading 1 character from the file and comparing that to EOF. That works fine untill you are working with normal text files.
But here you are working with an encrypted file, file.enc which can contain anything at all.
It can even posses EOF character itself as data content.
That means if file has 100 characters and 2nd character is EOF then it will terminate at 2nd character itself.
I feel this as a possible problem.
Remains.. the other problems - I suggest using fprintf() instead of fputs(), these are easy to use and hence avoids unseen bugs. Since you are working on strings instead of characters logically.
Moreover, using these you also get an advantage of string formatting when needed.
Try out and then get back.. :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Silverlight custom navigation window I am developing a Silverlight MVVM app. I have a window with a frame. I have 3 pages, the first for data input, the second for editing the data, and the third for the user to review data and commit changes.
I added 2 buttons, "previous" and "forward", so that the user can navigate.
The "previous"button is going to use the NavigationService.GoBack() method, but I cant figure out how the "next" button is going to know what the next page is.
A: Don't use a navigation application. You'd be much better off with a MVVM framework like Caliburn.Micro and use a shell view to display the content instead of a frame.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inheritance behavior issue I've been reading about inheritance but I still dont have it 100% clear, here goes my question:
I have for example a class full of stuff:
class Something
{
public:
Something();
Something(int A);
Something(Something S);
~Something();
Something& operator=(const Something & s);
Something operator+(const Something & s) const;
// more methods ...
protected:
int A,B,C;
}
All methods implemented somewhere, and now I just want a new class to add one more attribute and maybe one method, but I still want the same behavior as the SuperClass (constructor, destructor, methods, operators), so I do something like this:
class SomethingMore : public Something
{
public:
void OnlyMethodHere();
private:
int D;
}
But I get something like:
undefined reference to SomethingMore::SomethingMore(int)
Is there a ay to tell the compiler to use everything just like it is in the SuperClass or do I have to make a SuperClass::method() in every child's method?
A: You don't have to repeat for methods. but for constructor, you have to define them properly in the sub class. Anyway the code is boiler plate unless you have anything extra.
SomethingMore::SomethingMore(int i_):Something(i_)
{
}
A: In c++0x it is possible to do by:
class BaseClass
{
public:
BaseClass(int iValue);
};
class DerivedClass : public BaseClass
{
public:
using default BaseClass;
};
, but i don't know of any compiler that supports it by now. If you want to keep compatible with older compilers you have to repeat all constructors in derived class like
class BaseClass
{
public:
BaseClass(int iValue);
};
class : public BaseClass
{
public:
DerivedClass(int iValue):BaseClass(iValue){}
};
A: You can obtain the same effect as in this answer, in C++0x with a sort of catch-all constructor:
class SomethingMore
{
public:
.......
template<class... Args>
SomethingMore(Args&&... args) : Something(std::forward<Args>(args...)) {}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: .htaccess and mod-rewrite This is my code in .htaccess:
RewriteEngine On
RewriteRule ^(.*)$ framework/public_html/index.php/$1 [PT,L]
I'm getting "Internal Server Error". What's wrong?
A: Try this:
RewriteCond %{REQUEST_URI} !^/framework/public_html/
RewriteRule ^(.*)$ framework/public_html/index.php/$1/ [PT,L,NC,QSA]
http://www.domain.com/sub/folder/me => [REQUEST_URI] => /sub/folder/me
First, when you want to redirect (.*) it also try to redirect to itself that is why you have a 500 error. so by saying: if it's not (!^) /framework/public_html/ then redirect to this URL.
QSA: Query string append means if you have ?var=1 it will use it and append to the redirected string.
NC: Non Case means capital letters and lower case letters are the same.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Code folding regions in ruby on VIM? I know not everyone like code folding, but as a convert to Rails and a convert to VIM, I want one of the conveniences back that I had in Visual Studio.Net. I want to be able to place arbitrary #region #endregion tags and have VIM fold them for me like everything else.
I have syntax code folding turned on and normal def..end folding works fine, I just want to augment that with #regions.
I did some googling and thought that I could do this in a ruby.vim in my syntaxes folder, but it didn't work, and I don't know enough to debug whether it was bad code that I copied over or if it just "doesn't work that way."
let b:match_words = '\s*#\s*region.*$:\s*#\s*endregion'
This is my only line in syntax/ruby.vim. In fact, the file wasn't there before I started, even though ruby highlighting is working fine. (which also throws big red flags for me - I haven't a clue where the ruby/rails syntax, unless its in the rails.vim plugin, but I can't find it there either.
Can someone lend me a thread so that I can follow it and figure this out?
Thanks
UPDATE:
I found some other code snippets and tried this version instead, which almost gets me there:
syn region vimFoldRegion
\ start="#region"
\ end="#endregion"
\ skip=+"\%(\\"\|[^"]\)\{-}\%("\|$\)\|'[^']\{-}'+
\ transparent fold
\ keepend extend
\ containedin=ALLBUT,@vimNoFold
This lets me fold the region, but all of the code inside the region is shown like its a comment. I've tried different variations of the parameters on the syn, but I'm not grokking it.
A: Vim can fold regions based on markers if you set foldmethod=marker. The default markers are {{{ and }}}, though I'm pretty sure you could override these to be #region and #endregion. The problem is you then lose the ability to fold based on syntax. There's another Stack Overflow question dealing with combining the two fold methods [1], but the conclusion there is that it's not possible to do both simultaneously.
For what it's worth, I find that vim's syntax-based code-folding is horrendously slow for large Ruby files, so you might find yourself wanted to switch to a marker-only fold method if you run into the same problem.
[1] Foldmethod=marker and syntax at the same time?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: bash: line wrapping with fancy PS1 that does positional echo'ing I have something like this in my login script that keeps $foo in the top right of my terminal. It works, but with a caveat. If I type a really long command it doesn't wrap. (Well, it'll wrap if it's more than two lines long, but the 2nd line overwrites the 1st line, if that makes sense.)
Anyone know how I can make bash wrap (i.e. insert newline) at $POS? Or even at $COLUMNS?
trunc_pwd () { # See http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x783.html
local pwdmaxlen=50 # Number of $PWD chars to keep
local trunc_symbol="<" # Prepend to truncated $PWD
if (( ${#PWD} > $pwdmaxlen )); then
local pwdoffset=$(( ${#PWD} - $pwdmaxlen ))
echo "${trunc_symbol}${PWD:$pwdoffset:$pwdmaxlen}"
else
echo ${PWD} | sed "s%^${HOME}%~%g"
fi
}
foo="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
get_pos ()
{
POS=$((COLUMNS-(${#foo}+4)))
}
if [[ ${PS1} ]]; then
PROMPT_COMMAND='get_pos ; echo -ne "\033]0;${USER}@${HOSTNAME%%.*}:$(trunc_pwd)"; echo -ne "\007"'
export PS1="\u@\h \W \$ \[\e[s\]\[\e[1;\$(echo -n \${POS})H\]$foo\[\e[u\]"
fi
A: Bash uses the \[ and \] escapes in the prompt to determine the line length and where to wrap. If you enclose anything that shouldn't affect the line length (the escape sequences, the $foo, etc) with those you should be ok.
I'm not sure why your prompt isn't working (and I don't recognize some of the escape sequences like \e[s, could be you're on something other than a vt100), my attempt works just fine:
PS1='\[\e7\e[0;$((COLUMNS-(${#foo})))H$foo\e8\][\u@\h \W]\$ '
actually re-looking at yours, it might work if you change your PS1 to
PS1="\u@\h \W \$ \[\e[s\e[1;\$(echo -n \${POS})H$foo\e[u\]"
i.e., wrapping \[ ... \] around all the out-of-line stuff.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why does commandButton action listener does not working? I'm using Primefaces components with JSF2.0 and Tomcat 6. The goal is to dynamically create a server components from bean. Just for test I did the next thing:
private Panel editorPanel;
private CommandButton btn;
public void createComponents()
{
this.setEditorPanel(new Panel());
this.getEditorPanel().setRendered(true);
btn = new CommandButton();
btn.setId("btn1");
btn.setRendered(true);
btn.setAjax(true);
btn.setValue("Click!");
btn.addActionListener(new ActionListener()
{
@Override
public void processAction(ActionEvent arg0) throws AbortProcessingException
{
addNewButton();
}
});
this.getEditorPanel().getChildren().add(btn);
}
public void addNewButton()
{
CommandButton btn2 = new CommandButton();
btn2.setRendered(true);
this.getEditorPanel().getChildren().add(btn2);
}
Markup:
<p:panel binding="#{mybean.editorPanel}">
</p:panel>
At the first page load button is rendered. After pressing the button, my bean is recreating due to the request, but breakpoint at "addNewButton" method is never triggered. After that request, the button is disappered.
Bean is marked as @RequestScoped and @ManagedBean(name="mybean"). The other components from markup that are not dynamically rendered can successfully use bean methods.
What I'm doing wrong with this button?
Thanks
EDIT: I know that I can add the button as the previous one in the same method, but the goal is to dynamically add some components.
EDIT 2: I made the separate implementation of ActionListener as the public inner class, and I get the next:
Caused by: java.lang.InstantiationException:web.beans.pages.TemplateEditBean$BtnListener
at java.lang.Class.newInstance0(Unknown Source)
at java.lang.Class.newInstance(Unknown Source)
at javax.faces.component.StateHolderSaver.restore(StateHolderSaver.java:103)
... 90 more
A: Using 2.1.3 version of Mojarra instead 2.0.3 has solved problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In C, is there a difference between a NULL pointer and a pointer that points to 0? If so, what? In C, what is the difference between a NULL pointer and a pointer that points to 0?
A: The ISO/IEC 9899:TC2 states in 6.3.2.3 Pointers
3 An integer constant expression with the value 0, or such an expression
cast to type void *, is called a null pointer constant.55) If a null
pointer constant is converted to a pointer type, the resulting
pointer, called a null pointer, is guaranteed to compare unequal to a
pointer to any object or function
The macro NULL expands to an implementation-defined null pointer constant.
Any two null pointers shall compare equal.
A: Yes there is. The standard dictates that NULL always points to invalid memory. But it does not state that the integer representation of the pointer must be 0. I've never come across an implementation for which NULL was other than 0, but that is not mandated by the standard.
Note that assigning the literal 0 to a pointer does not mean that the pointer assumes the integer representation of 0. It means that the special null pointer value is assigned to the pointer variable.
A: Evaluating the literal 0 in a pointer context is identical to NULL. Whatever bit pattern the compiler uses to represent a NULL pointer is hidden.
A: The old comp.lang.c FAQ has a big section on the null pointer and it's worth a read.
comp.lang.c null pointers
A: The idea is that a NULL pointer should somehow represent a memory area that is invalid.
So since in the lower memory segments the OS code is mapped, the value of 0 has been used (to represent the NULL pointer) since this area in memory does not belong to the user's program but is mapped to the OS code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Backwards Compatible Android/Java Code I'm writing some code that is going to be used by some partners that maintain SDKs. The SDKs are used by developers on Android 1.5 through 2.3.7. My code uses features that are only available on 2.2 and later. How can I write my code so developers using the partner SDKs don't get compile errors on Android < 2.2?
I tried using reflection and avoiding imports / declarations that used classes that weren't available before 2.2, but the code didn't work post 2.2 due to failure to dispatch to methods where I had changed the desired class type to Object.
A: You could try to split up the code into a baseline (Android 1.5) and provide additional JAR(s) for higher API levels, similarly to how the Android compat librabry comes in a Android 1.6-compatible "v4" flavor and a "v11" for Android 3.2 and up.
At some points, you might also be able to take code from AOSP and backport selected 2.2 features. I did this e.g. to be able to use getExternalCacheDir() on API level 7:
private static File getExternalCacheDir(final Context context) {
// return context.getExternalCacheDir(); API level 8
// e.g. "<sdcard>/Android/data/<package_name>/cache/"
final File extCacheDir = new File(Environment.getExternalStorageDirectory(),
"/Android/data/" + context.getApplicationInfo().packageName + "/cache/");
extCacheDir.mkdirs();
return extCacheDir;
}
Reflection-heavy code will be maintenance nightmare -- as much as you want to avoid those red compiler error dongles for your customers/partners, you want to see them instead of some obscure runtime exception caused by outdated constants in your reflection code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Why do I need "out" with a string in C#? I know string is a value type in C#. I understand everything in C# are passed by value.
But if it's a value type anyway there is no need 'out' or 'ref', right?
A: String is a reference type (a class) as others have pointed out. It's just that it's immutable, which makes it sometimes feel like a value type in some ways.
You can pass a string argument by reference or by value, just as with any other parameter. It's worth being absolutely clear about the difference between these two concepts. I have two articles on the topic:
*
*Reference types and value types
*Parameter passing in C#
It's worth becoming really familiar with this topic (and reading articles other than mine, of course) - understanding the difference between reference types and value types is absolutely key in C#, and so is understanding parameter passing (and even what a simple assignment statement means).
A: String is not a value type. It's an immutable sealed reference type.
The MSDN Page on String is probably worth a read.
A: The wrong things you "know" will mess you up.
System.String is immutable, but it is NOT a value type.
Beyond that, ref/out can be used with either value or reference types. They're needed when you want to replace the ENTIRE object. They're not needed if you just want to read from the object. If you want to change members of the object, then ref is needed for a value type but not for a reference type.
From this we conclude that if you just want to read a string, you should pass it by value (the value is a reference to the string content, but it's not linked to the original string variable). But if you want to replace the string with a different one, use ref. And if there isn't any string to begin with, it's first assigned inside the function, use out.
A: You have to distinguish between reference types and passing by reference, as they are quite different things.
A string is a reference type, which means that it's an object allocated on the heap, which you access using a reference.
When you pass something by reference, it's the variable that you are passing, not the value that the variable contains. You pass a variable by reference when you need to change the value of the variable, regardless of whether the value is a value type or if it's a reference to an object.
The default for passing variables is by value, which for a string means that you send a copy of the reference to the string, not a copy of the string data.
Generally parameters are passed by value, it's only in some special situations that you ever need to consider passing a variable by reference. If you want to return a single value (which could alo be a reference) from a method, the return type is used. If you need to return multiple values you can use out or ref, but you can also create an object with multiple properties and return that, so you never need to use out or ref.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: Embed video javascript code from database in PHP This is probably a pretty simple thing. I am testing out several video hosting services where I host the videos and use their embed code to display on my site.
Now this embed code is stored in the database and is associated with each topic. So on a given page there could be 20 topics. So when a user clicks on any topic - using ajax I pull the embed code and display it in a given div.
This works fine for the embed code that uses or like in youtube and other services. But there are others that give you a javascript code to embed like shown below
<script type = "text/javascript" id = "vidyard_embed_code_BAKIQxxxxxxxxxxxx">//To resize this video, please login to your dashboard and edit your player settings
(function() {
var vidyardcontainer = document.createElement("div");
vidyardcontainer.id = 'vidyard_BAxxxxxxxxxxx';
var vidyardcontainer_s = document.getElementById('vidyard_embed_code_BAKIQyVKDjg_FeBoGkxr7A');
vidyardcontainer_s.parentNode.insertBefore(vidyardcontainer, vidyardcontainer_s);
var vidyard = document.createElement('script');
vidyard.type = 'text/javascript';
vidyard.async = false;
vidyard.src = ('https:' == document.location.protocol ? 'https://secure.' : 'http://embed.') + 'vidyard.com/embed/Bxxxxxxxxxxxxx/iframe/?';
var vidyard_s = document.getElementsByTagName('script')[0];
vidyard_s.parentNode.insertBefore(vidyard, vidyard_s);
})(); //embedcodev1.0
</script>
So this type of embed code cos its javascript. Is there anyway to get this working.
Appreciate your input
Thanks
A: JQuery does a lot of crazy stuff with script tags. It's not terribly well documented, but some methods like .html(data) will strip them out. The ajax methods also do some crazy evaluation magic.
This answer may come too late, but at least for the Vidyard case you can use the alternative iframe embed code. Click the checkbox in the embed area that says Using Tumblr, Posterous, or just having trouble embedding? Try our fallback code to get it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I deactivate INFO messages in JBoss? I don't like to see INFO messages in JBoss. Do you know a flag to controll the JBoss output? I would like to deactivate the INFO messages.
A: It depends what you want to do exactly.
*
*If you want to change the default log level you have such possibles:
*
*go to the profile/deploy/jboss-logging.xml and find such line (under root tag, the end of the file)
<level name="${jboss.server.log.threshold:INFO}"/>
You can just change the INFO to WARN or other value. It changes the value permanently. Also check the log level for CONSOLE appender:
<level name="INFO"/>
*you can run JBoss with such the command:
run.sh -Djboss.server.log.threshold=WARN
*You you want to just turn off the console logging, you can just:
*
*comment these line from the root category (also in the profile/deploy/jboss-logging.xml file)
<handler-ref name="CONSOLE"/>
*run JBoss and redirect all output (at least on Linux):
run.sh &> /dev/null
A: Try modifying the {jboss.dir}/jboss-as/server/{server}/conf/jboss-service.xml.
Find the log4j initialization block and modify the "DefaultJBossServerLogThreshold" attribute as per your needs.
A: You have to edit {jboss.dir}/server/{server}/deploy/jboss-logging.xml
Search for a block beginning with this line:
<console-handler name="CONSOLE" autoflush="true" target="System.out">
Then edit the Warning level:
<level name="INFO"/>
The Warning-levels are TRACE,DEBUG,INFO,WARN,ERROR andFATAL (Source: Log4J-PDF and log4j-html)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: When should UIViewController add/remove observers on NSNotificationCenter? If I add an observer to the [NSNotificationCenter defaultCenter] in my viewDidLoad should I be removing it in viewDidUnload?
A: You should remove it in dealloc method.
A: If you need to add these in your initializer, you should remove it in the dealloc method. Ideally, you should only care about these notifications when you are currently onscreen or not.
The viewDid[Appear|Disappear] methods can be called multiple times during the lifetime of a UIViewController. Register for the notification in the viewDidAppear method and unregister it in viewDidDisappear.
A: It seems to me viewDidUnload is the place to put it.
If the notification handler that gets called accesses any of the views managed by the view controller, that will either be an error or will cause the view to get reloaded unnecessarily. If your view is not being shown, then most likely the view controller doesn't need to be notified. If it does, at least check if the view is loaded before you make any changes to it. While the view is not loaded, you might still need to update the state of your view controller, for example change or dirty cached values, but don't update the view until it loads again.
Two, what happens if you don't removeObserver in viewDidUnload, and viewDidLoad gets called again? You call addObserver again. Probably doesn't hurt, the notification center can detect duplicate adds.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Tiny server/client setup - server doesn't respond. All code provided I'm teaching myself Coffeescript/node and, of course, the only way to do this is with TDD. That means I'm also teaching myself vows. There are, I think, at least two problems. One is -- where does the asynchronous code to get the HTTP response lie? And the other is -- why won't the server send me a response back? The console displays "Request sent" but it does not display "Request received."
Here is the test file:
vows = require 'vows'
assert = require 'assert'
EventEmitter = require('events').EventEmitter
Server = require('./web').WebServer
Client = require('../lib/client').Client
Request = require('../lib/request').Request
PORT = 8080
SERVER = new Server PORT
SERVER.start()
CLIENT = new Client PORT, 'localhost'
REQUEST = new Request 'GET', '/'
vows
.describe('Sending a request to the server')
.addBatch
'The request is sent':
topic: ->
CLIENT.transmit(REQUEST, @callback)
return
'The response should be what the server sent back': (err, request) ->
body = ""
request.on 'response', (response) ->
response.on 'data', (chunk) -> body += chunk
assert.equal body, /Ooga/
.export(module)
Here is the WebServer object:
Http = require('http')
exports.WebServer = class WebServer
processRequest = (request, response) ->
console.log 'Request received!'
console.log request
response.writeHead 200, {'Content-Type':'text/plain'} #, 'Content-Length':'6'}
response.write 'Ha-ha!'
response.end
constructor: (@port) ->
@server = Http.createServer processRequest
start: ->
@server.listen @port
stop: ->
@server.close()
Next up is the client code - also very simple.
Http = require 'http'
Request = require('./request').Request
exports.Client = class Client
constructor: (@port, @host) ->
@httpClient = Http.createClient @port, @host
@sentence = "I am a Client"
transmit: (request, callback = null) ->
req = @httpClient.request request.method, request.pathName
req.end
console.log "Request sent!"
if callback
callback(null, req)
#req.on 'response', (res) ->
# callback(null, res)
#request.on 'data', (chunk) -> callback(null, chunk)
#callback(null, request)
And finally, the 'request' object.
exports.Request = class Request
constructor: (@method, @pathName) ->
method: ->
@method
pathName: ->
@pathname
responseBody: ->
@body
setResponseBody: (body) ->
@body = body
appendToResponseBody: (chunk) ->
@body += chunk
All this is so simple that I really can't tell why the server doesn't seem to be working. I'm not even worried, yet, about where the asynchronous code should be to get the information back from the server, but I'd like to figure that out too..
A: Ah, you've made a classic mistake: You wrote
req.end
where you meant
req.end()
So, your request wasn't actually being sent at all, despite your console's claims to the contrary! (I see a response.end in your code as well.)
Incidentally, Vows test code is pretty, but it's also a complex framework with some subtle gotchas. You may want to try something simpler, like nodeunit.
Oh, and if you really hate parentheses, you can write do req.end instead of req.end(), but this isn't a common style.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: AJAX POST Request Only Works Once in Safari 5 I use my own custom AJAX library (I'm not interested in using jQuery, etc.), which is working flawlessly in the following browsers:
*
*Firefox 7
*Chrome 14
*IE 8
*IE 8 (compatibility mode)
Using my custom AJAX library in the aforementioned browsers, I can make as many AJAX requests as I want, in any order, using GET and/or POST methods, and they all work flawlessly. Since a new AJAX object is created for every request (see code below), I can even have more than one AJAX request process simultaneously with success.
However, in Safari 5 an AJAX POST request only passes POST data to the server if it is the absolute first AJAX request to execute. Even if I execute the exact same AJAX POST request twice in a row, the POST data is only passed to the server during the first request. Here is the JavaScript in my custom AJAX library:
if (!Array.indexOf)
{
Array.prototype.indexOf = function(obj) { for (var i = 0; i < this.length; i++) { if (this[i] == obj) { return i; } } return -1; };
}
function ajaxObject()
{
if (window.ActiveXObject)
{
var activexmodes = ["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"];
for (var i = 0; i < activexmodes.length; i++)
{
try
{
return new ActiveXObject(activexmodes[i]);
}
catch (e)
{
}
}
}
else if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
else
{
return false;
}
}
function ajaxRequest(aURI, aContainerId, aPostData, aResponseType, aAvoidBrowserCache)
{
// Initialize
var xmlhttp = new ajaxObject();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if (aResponseType != "eval" && aResponseType != "EVAL")
{
// Show HTML for response
document.getElementById(aContainerId).innerHTML = xmlhttp.responseText;
}
else
{
// Parse & execute JavaScript for response
var responseText = xmlhttp.responseText;
var startPos, endPos;
for (var i = 0; i < responseText.length; i++)
{
if (responseText.substring(i, i + 6) == "<eval>")
{
startPos = i + 6;
break;
}
}
for (var i = startPos; i < responseText.length; i++)
{
if (responseText.substring(i, i + 7) == "</eval>")
{
endPos = i;
break;
}
}
textToEval = responseText.substring(startPos, endPos);
eval(textToEval);
}
}
else
{
try
{
if (xmlhttp.status != 0 && xmlhttp.status != 200)
{
alert('Error ' + xmlhttp.status);
}
}
catch (e)
{
// Handle IE8 debug "unknown error"
}
}
}
if (aAvoidBrowserCache != false)
{
// Combat browser caching:
aURI = aURI + (aURI.indexOf("?") == -1 ? "?" : "&");
theTime = new Date().getTime();
aURI = aURI + theTime + "=" + theTime;
}
// Make request
if (typeof aPostData == "undefined" || aPostData == null || aPostData == "")
{
// GET request
xmlhttp.open("GET", aURI, true);
xmlhttp.send();
}
else
{
// POST request
var parameters = "";
if (aPostData.constructor.toString().indexOf("Array") != -1)
{
// Use parameters passed as array
for (var postCount = 0; postCount < aPostData.length; postCount++)
{
if (parameters != "")
{
parameters = parameters + "&";
}
parameters = parameters + aPostData[postCount][0] + "=" + encodeURIComponent(aPostData[postCount][1]);
}
}
else
{
// Use parameters passed as string
parameters = aPostData;
}
xmlhttp.open("POST", aURI, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(parameters);
}
}
So for example, either of the following AJAX POST requests will pass POST data if they are the absolute first AJAX request (whether GET or POST); otherwise, the POST data is not passed:
ajaxRequest("test.aspx", "", [["name1","value1"],["name2","value2"]], "eval");
or
ajaxRequest("test.aspx", "", "name1=value1&name2=value2", "eval");
I have added debug statements all throughout my AJAX library, and the POST parameters are being created in the "parameters" variable as expected prior to each POST request. I have absolutely no idea why, only in Safari 5 (out of the mentioned browsers), I have this problem. Any ideas?
Thanks in advance!
Jesse
A: The reason the call is failing is because of a bug in Safari when working with Windows Authentication under IIS. Go to the Authentication settings of your website. Right click on Windows Authentication, choose providers and remove Negotiate, leaving NTLM which works fine. I haven't tested Kerberos.
This issue only appears in certain builds of safari.
A: Came here from the thread you mentioned might be a dupe. I never solved our problem, but have you tried a simple page making post requests? With our issue it's a post problem, not an AJAX problem, we're still stumped though.
What version of IIS are you running on the server?
A: I can confirm that the problem seems related to some sort of interaction between Safari & IIS. Luckily, I only develop and test this portion of the code on Windows. I moved it unchanged to a LAMP (Linux/Apache) staging server (prior to moving to our LAMP production server) and the problem went away. I was seeing the problem with Safari 5, IIS 5.1, & an ActiveState Perl 5.6 CGI.
Under RHEL 5, Apache 2.2, & Perl 5.8, it is gone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: android wifi state changed with broadcast receiver If the user has left the app via the back button key and the app contains a broadcast receiver for wifi state changed will a change in the wifi state trigger the 'left' app receiver and resume the app? Or will the receiver only work while the app is visible?
A: If you have registered for the intent-filters in your AndroidManifest.xml, the receiver will be called regardless of whether or not your app is in the foreground or even running. The BroadcastReceiver will be garbage collected the moment onRecieve is done though, thus you are not allowed to do any threading in the BroadcastReceiver. You are limited to starting an activity or binding to a service.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to strip the & symbol from only the URLs in a file? I have a file, index.html, containing data like this:
<li><a href="/battered-fried-chicken-breast-no-skin.html">battered fried chicken breast, no skin</a></li>
<li><a href="/bbq-short-ribs-with-sauce.html">bbq short ribs with sauce</a></li>
<li><a href="/bbq-spareribs-&-sauce-eat-lean-&-fat.html">bbq spareribs & sauce (eat lean & fat)</a></li>
<li><a href="/bbq-spareribs-&-sauce-eat-lean-only.html">bbq spareribs & sauce (eat lean only)</a></li>
I need to strip the & symbols from the URLs, such that "/bbq-spareribs-&-sauce-eat-lean-&-fat.html" becomes "/bbq-spareribs--sauce-eat-lean--fat.html". However, I do not wish to remove the & symbol from the parts of the file which are not URLs, such as the text of the link, bbq spareribs & sauce (eat lean & fat).
How would I accomplish this on a standard Linux install? It doesn't matter to me what specific tool/language is used to achieve the result so long as it works.
A: If you're happy to install BeautifulSoup, this simple Python script may do what you want:
#!/usr/bin/evn python
import sys
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(sys.stdin.read())
for a in soup.findAll("a"):
a["href"] = a["href"].replace("&", "")
print soup
Example usage:
[me@home]$ cat your.html | python amp_remover.py
<li><a href="/battered-fried-chicken-breast-no-skin.html">battered fried chicken breast, no skin</a></li>
<li><a href="/bbq-short-ribs-with-sauce.html">bbq short ribs with sauce</a></li>
<li><a href="/bbq-spareribs--sauce-eat-lean--fat.html">bbq spareribs & sauce (eat lean & fat)</a></li>
<li><a href="/bbq-spareribs--sauce-eat-lean-only.html">bbq spareribs & sauce (eat lean only)</a></li>
Caveat: Since we're regenerating the output HTML based on a parsed representation of it, the formatting may change. Other possible changes include the explicit closing of tags if your markup is not well formed.
I may be wrong, but I suspect most solutions that use a proper XML/HTML parser will result in similar issues. To maintain the file exactly as it is and only remove the offending chars, you will have to end up using regex-based search and remove/replace. Many will advice against parsing XML/HTML with regex except for really trivial patterns. In your case, that may be true, but I'm yet to be convinced.
A: If you are determined to use a simple command-line regex tool, and you know that your URL's are nice, and that the ampersands are used consistently in the text, you could try something like:
$ sed 's/\([^ \t]\)&\([^ \t]\)/\1\2/g' file.html > out.html
This presumes the URL has no whitespace adjacent to an ampersand, and that the ampersands not in the URL are always surrounded by spaces. So this is by no means robust, but it might be simpler than installing Beautiful Soup if you just need this once, and your html is predictable.
A: just for completeness sake an awk-solution. It should be sufficiently stable for
simple tasks.
File:
$ cat file
<li><a href="/battered-fried-chicken-breast-no-skin.html">battered fried chicken breast, no skin</a></li>
<li><a href="/bbq-short-ribs-with-sauce.html">bbq short ribs with sauce</a></li>
<li><a href="/bbq-spareribs-&-sauce-eat-lean-&-fat.html">bbq spareribs & sauce (eat lean & fat)</a></li>
<li><a href="/bbq-spareribs-&-sauce-eat-lean-only.html">bbq spareribs & sauce (eat lean only)</a></li>
Output:
$ awk 'BEGIN{FS=OFS=">"}{for (i=1;i<=NF;i++){if ($i ~ "a href")gsub(/\&/,"",$i)}}1' file
<li><a href="/battered-fried-chicken-breast-no-skin.html">battered fried chicken breast, no skin</a></li>
<li><a href="/bbq-short-ribs-with-sauce.html">bbq short ribs with sauce</a></li>
<li><a href="/bbq-spareribs--sauce-eat-lean--fat.html">bbq spareribs & sauce (eat lean & fat)</a></li>
<li><a href="/bbq-spareribs--sauce-eat-lean-only.html">bbq spareribs & sauce (eat lean only)</a></li>
HTH Chris
A: One route is to use a tool/language that has an XML package. That package would support easy access to the anchor element's href attribute in a programmatic fashion. So, you might have something like:
aElements = doc.getElement('a')
foreach aElement in aElements {
string url = a.getHref()
removeAmpersane ( url )
}
I'm sure that almost all language level tools have packages for this. If you are open to a heavy tool like a language, this will be easy for you. If you just want lower level linux tools, that's beyond my expertise.
A: You could easily use javascript for this:
<head>
<script type="text/javascript">
document.onload = (function (ev) {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
var href = links[i].href.replace(/(&)/, '');
console.log(links[i]);
}
});
</script>
</head>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Configuring one web.config file for different servers Is there a way to configure a web.config file to execute it's rules only if there is a match to a server name?
For example, we have two servers: WebDev (for development) and WebLive (live web server)
On the live server, we have a URL rewrite rule that configures a canonical name, but when we synchronize those sites (thereby copying the web.config file back to the dev) and run it on the development platform, the canonical rule kicks in and send us to the live site instead of keeping us on the development platform. I can exclude the web.config from our synchronization, but was seeking an alternative.
Kinda like...
<apply rule to WebLive>
<rule name="CanonicalHostNameRule1">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="^www\.domain\.org$" negate="true" />
</conditions>
<action type="Redirect" url="http://www.domain.org/{R:1}" />
</rule>
</>
A: In Visual Studio 2010, you now can apply a transformation to your web.config depending on the build configuration.
When creating a web.config, you can expand the file in the solution explorer, and you will see two files:
*
*Web.Debug.Config
*Web.Release.Config
They contains transformation code that can be used to:
*
*Change the connection string
*Remove debugging trace and settings
*Register error pages
link
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery dynamically populating a select option tab I am trying to achieve something like this,
<select id="time" size="1" name="Time" disabled="disabled">
<% foreach (string item in (List<string>)Model.OpenCloseTime[dynamicVariable].AppointmentTimes)
{%>
<option id="<%:item%>" value="<%:item%>">
<%:item%></option>
<%}
%>
</select>
Where dynamicVariable= $('#date').datepicker("getDate");
To break down the issue, getDate is supposed to fetch the value of the weekday from a calendar which needs to help me dynamically populate a select dropdown, based on the data we are getting from the model object day value.
How could I achieve this?
Thanks for the help.
A: I'm not sure what dynamicVariable looks like, but here's how you can populate #time with a Javascript array:
var times = ["Morning", "Afternoon", "Evening"];
for(i in times) {
$("#time").append(
$("<option></option>").attr("value", times[i]).text(times[i])
);
}
Edit to answer your comment:
Concatenate your list:
List<string> items = (List<string>)Model.OpenCloseTime[dynamicVariable].AppointmentTimes;
string itemsStr = string.Join(",", items.toArray());
Print it in your javascript:
var items = "<%:itemStr%>";
Explode the string into a Javascript array:
var items_arr = items.split(",");
Use what I posted above to make the select box:
for(i in items_arr) {
$("#time").append(
$("<option></option>").attr("value", items_arr[i]).text(items_arr[i])
);
}
A: Here is and example of populating a select list using jQuery:
function setCategory(categoryList)
{
var options = '<option value="Select by Category">Select by Category</option>';
for (var i = 0; i < categoryList.length; i++)
{
options += '<option value="' + categoryList[i] + '">' + categoryList[i] + '</option>';
};
$("#categorySelect").html(options);
};
Note, THIS also sets a default text using the first line, which may not be a desire here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613209",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I creating an autocomplete textbox with the "Search" magnifying Glass If I create a textbox in a Firefox with a type of "autocomplete" I am able to get autocomplete working properly. However, the textbox is a intended to be used as search textbox (with autocomplete). Thus, in addition to autocomplete I also want the standard UI used when the textbox has a type of "search." In particular, Firefox shows a magnifying glass that turns into an "X" when the user types into it.
Is there a clean (or, failing that, not so clean) way of accomplishing this?
A: Firefox Searchbar ,the one on right top usually, has type="autocomplete" and has the searchbutton
First: browser.xul of firefox has a toolbaritem which searchbar nested in it.
<toolbaritem id="search-container" title="&searchItem.title;"
align="center" class="chromeclass-toolbar-additional"
flex="100" persist="width" removable="true">
<searchbar id="searchbar" flex="1"/>
</toolbaritem>
searchbar has the following css property in browser.css.
searchbar {
-moz-binding: url("chrome://browser/content/search/search.xml#searchbar");
}
That url in css property brings us to search.xml which has the textbox and the searchbutton is added to textbox in a hbox as far as i can understand.
<xul:textbox class="searchbar-textbox"
anonid="searchbar-textbox"
type="autocomplete"
flex="1"
autocompletepopup="PopupAutoComplete"
autocompletesearch="search-autocomplete"
autocompletesearchparam="searchbar-history"
timeout="250"
maxrows="10"
completeselectedindex="true"
showcommentcolumn="true"
tabscrolling="true"
xbl:inherits="disabled,disableautocomplete,searchengine,src,newlines">
<xul:box>
<xul:button class="searchbar-engine-button"
type="menu"
anonid="searchbar-engine-button">
<xul:image class="searchbar-engine-image" xbl:inherits="src"/>
<xul:image class="searchbar-dropmarker-image"/>
<xul:menupopup class="searchbar-popup"
anonid="searchbar-popup">
<xul:menuseparator/>
<xul:menuitem class="open-engine-manager"
anonid="open-engine-manager"
label="&cmd_engineManager.label;"
oncommand="openManager(event);"/>
</xul:menupopup>
</xul:button>
</xul:box>
<xul:hbox class="search-go-container">
<xul:image class="search-go-button"
anonid="search-go-button"
onclick="handleSearchCommand(event);"
tooltiptext="&searchEndCap.label;" />
</xul:hbox>
</xul:textbox>
Well this is not an total answer, but gives a head start for you or others who may contribute I guess. For further detail you can dig omni.jar in mozilla firefox directory.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How To Align Form Tags Properly? I want to align the input and form elements to the right and have the label informatuion to the left, all while maintaining the label being vertically centered with each input it is aligned up to. I also need some space between each <li> tag per se.
You can view what I am talking and asking about here... http://jsfiddle.net/CCxwF/
A: Try this css instead:
label {display: block; margin: 5px 10px; float: left; width: 200px;}
input, select {float: left; width: 150px;}
ul li {clear: both;}
input.checkbox {width: inherit; margin: 5px 0 0 0;}
change the label closing tag for uncategorized to before the checkbox input and add class checkbox to checkbox
else if you want to keep the label around the checkbox you could use this style:
label {display: block; margin: 5px 10px; float: left; width: 200px; position: relative;}
input, select {float: left; width: 150px;}
ul li {clear: both;}
input.checkbox {width: inherit; margin: 5px 0 0 0;}
A: I've removed the <ul> entirely, setting display: block on the <label>s does the trick just fine.
Example
In this example, each <label> is set to be a block level element, and each <input> or <select> is set to float right inside of it. The black lines are for clarity only (only so you can see what are labels).
A: I personally like using definition lists (although this doesn't vertically align your <label>.
See: http://jsfiddle.net/Wexcode/CCxwF/5/
You might also want to consider adding id attributes to your elements within your forms, and doing label for="element-id"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Disabling third party login in social comment plugin I'm using the social comments plugin in my Facebook app.
In the plugin's documentation it says that the third party login can be disabled in the setting section of the plugin.
How do I enable users to comment using other login providers?
On the settings section of the plugin, you can choose to enable third party login on your comments boxes. Currently this will enable users to comment using a Yahoo!, AOL or Hotmail account.
Since the only section that I could find relating the plugin is the moderation tools, I'm assuming that is the "settings section of the plugin".
Moderation Tools
Here is the screen that is shown when I click under settings for my application:
I have the "Other login providers" option disabled but it is still appearing in the comment box in my application.
Maybe there is a parameter or a method that I can use to achieve this or maybe I didn't find the correct settings section of the plugin.
A: Check to make sure your comment box isn't inheriting any settings from the page itself. When I look at the settings on my comments box there is a section titled "Settings inherited from ...."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Asset Subdirectories in Rails 3.1 I have a Rails 3.1 app with an image:
app/assets/images/icons/button.png
It seems like the image should be served at this URL:
assets/icons/button.png
but if I go to this URL I get a 404. To fix this I created an initializer and added my images/icons subdirectory to the asset path:
Rails.application.assets.append_path "app/assets/images/icons"
However, this does not seem like it can possibly be the recommended way to accomplish this. I'm aware of the require and require_tree directives for JavaScript and CSS assets, is there an equivalent for image assets? How are other people doing this?
A: EDIT: As of Rails 3.2.rc1 this is now fixed! asset_path now generates proper paths when deploying to sub-uri!
For images it just works. Rails packages everything in images/ tree. I personally use them like this (actual code):
CSS:
a#icon-followers{
background: url(<%= asset_data_uri "icons/followers.png" %>) center center no-repeat;
}
(asset_data_uri actually makes the images inline in the CSS file using base64, but that's irrelevant in this case)
No custom configuration required. After precompiling, images from app/assets/icons/ end up in public/assets/icons/.
You can open public/assets/manifest.yml to see how Rails translates the paths to actual files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Converting Bitmap to a vector of unsigned char As the title says, I'm trying to find a method of converting a GDI+ Bitmap to a vector of unsigned chars, any help would be greatly appreciated.
A: Have a look at Bitmap::LockBits. Once you've locked the bits, it should be trivial to copy them to a vector<unsigned char>. Better yet, resize the vector to the required size and let LockBits copy directly to it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: difference between self.up and up in rails migration I have noticed that some tutorials use self.up and self.down for migration methods. I understand that the self keyword indicates the method belongs to the instance only, but do they actually make a difference?
A: This is a change in Rails 3.1 - it used to have to be self.up and self.down, but now there has been a restructuring to allow them to just be up or down, and the associated method "change".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Exporting Facebook Discussions topics On Oct. 31, Facebook is going to remove the "Discussions" app and I would like to know if there is some way to export the topics.
A: The info on the discussions tab is unfortunately not available via the API. You would have to export it manually (copy and paste).
A: There is a new application called Forum for Pages that replaces the discussion tabs and that allows you to automatically re-import all your threads from the old discussion tab: http://www.facebook.com/202980683107053. All your discussions will be backed up in just a few minutes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add new html5 like buttons in website I'm relatively new to this and looking to implement like buttons for videos and articles on a website. I would prefer to get the better functionality from the html5 option over the iframe option. Not sure what I need to do as far as creating the app, getting app ID, and what I need to add to the site from the SDK in addition to the HTML5 code generated on https://developers.facebook.com/docs/reference/plugins/like/ when I put in all the info.
Is there a step by step guide somewhere that I can follow to implement this correctly?
A: Here's Facebook's Open Graph protocol. There's a Getting Started section with all of the info you need. Just follow the instructions and your site should work fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: "Unknown delivery tag" from RabbitMQ when ack'ing a message in a cluster with replicated queues We've been using Rabbit successfully for about a year. Recently have upgraded to v2.6.1, because we want to use clusters with replicated message queues.
My testing has hit a puzzling behavior that smells like a Rabbit bug to me. The test that uncovers this is working with a two-node cluster. Both nodes are running v2.6.1. Both nodes have disk. Both nodes are running on Mac OS, though I doubt this is pertinent.
I'm also running Alice on the node that runs the test. The test uses it to programmatically do a stop_app on one of the nodes, because the test is trying to validate that if the cluster master fails, and a slave is elevated to take its place, that we don't lose messages.
So, the test has a small thread pool, which is given tasks that periodically 1) publish messages, and 2) toggle the state of the Rabbit master node (stopped if running; started if stopped). Other threads are consuming messages from queues.
I'm using publisher confirms, and I'm also acknowledging the messages in the consumers (using autoAck=false for channel.basicConsume()).
When the master node is stopped, I see both the producers and consumers catching ShutdownSignalException. They handle this by attempting to reconnect to the cluster. This works fine. When reconnected, they continue with their business.
Sometimes, what I see is that a consumer has successfully fetched a message from the broker, and is calling channel.basicAck() when it gets that ShutdownSignalException.
Later, when the consumer has reconnected, it again pulls down the same message. (The message bodies are tagged with a UUID, so I know it is the same one.) This time, when the consumer attempts to basicAck() the message, it again gets ShutdownSignalException, but this one has the following text in it: "reply-text=PRECONDITION_FAILED - unknown delivery tag 7".
In fact, that is the same delivery tag that was offered to the consumer by the broker before the master went down and the consumer reconnected.
Googling suggests that this event means that the consumer is attempting to ack the same message more than once.
But, how can this be so? If the first ack succeeded, then the message should have been removed from the broker's queues, and the consumer shouldn't see the same message again.
Yet, if the first ack did not succeed, then the consumer shouldn't be dinged for attempting to re-ack the message.
Anyone seen this before? It smells like a bug in Rabbit's replicated queues to me, but I've still new to Rabbit, and so am willing to believe there's a subtlety here in consuming from a clustered broker that I haven't yet grokked!
Thanks, --Steve
A: I'm not sure if my case matching yours, but I have seen similar "unknown delivery tag" on attempts to ack after reconnect and then the same message arrived again. Initially it looked like a bug to me, but in fact this is expected behavior. Consumer with QOS>1 may have in it's local buffer some messages and delivery tag will be invalid for all o them after reconnect. From another hand, attempt to ack even the current message after reconnect doesn't make any sense, because that message already nacked automatically on connection lost and this is why I got it again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: AJAX/XML/PHP - Comparing results from two queries and displaying them Right now I have one query that returns a list of results and displays them each as links on a page using AJAX. I have another working query that I want to use to compare to the first one, but I'm unsure how to do it exactly (new to AJAX).
What I'm trying to do ultimately is find matches in the two queries' results and format the links (the $("#judgesCompleted").append) that match, with different styles from those that don't.
PHP (xml2.php):
$query = "SELECT Name FROM judges LEFT JOIN $court
ON ($court.JudgeID = judges.JudgeID)
where Month='$month' and Year='$year' order by Name asc;";
$resultID = mysql_query($query, $linkID) or die("Data not found.");
$xml_output = "<?xml version=\"1.0\"?>\n";
$xml_output .= "<entries>\n";
for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
$row = mysql_fetch_assoc($resultID);
$xml_output .= "\t<entry>\n";
$xml_output .= "\t\t<name>" . $row['Name']. "</name>\n";
$xml_output .= "\t</entry>\n";
}
$xml_output .= "</entries>";
echo $xml_output;
AJAX/JS:
$.ajax({
type: "POST",
url: "xml2.php",
data: 'court='+x,
dataType: "xml",
success: parseXml
});
function parseXml(xml)
{
$(xml).find("entry").each(function()
{
$("#judgesCompleted").append('<a href="viewreport.php">'+$(this).find("name").text()+'</a><br />');
});
}
My new query:
$query2 = "SELECT Name FROM judges
LEFT JOIN $court ON ($court.JudgeID = judges.judgeID)
LEFT JOIN users ON ($court.userID = users.userID) WHERE Month='10' AND Year='2011' AND users.type = 'user' ORDER BY Name ASC; "
Hopefully that makes sense.
A: I'd do the heavy lifting in PHP:
*
*Run the first query, save it results into an array (A1)
*Run the second query, save its results into another array (A2)
*(you could probably write it as one query to lighten the DB load if that is a concern)
The first array will have more results than the second, so iterate over A1. On each value, check if it exists in A2. As you go, shuffle the matches into one XML node and the misses into another XML node.
Grab that XML with AJAX and separate back out the two nodes (matches and misses), then go through each one to apply styling as needed.
A: You can try to UNION the 2 queries and implement the compare logic in javascript.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Filter Magento Product collection for products that have a review Hi as per title I want to filter for products that have a approved review.
Any help appreciated.
I have a feeling its based around the rating summary but not sure how to filter for that?
Thanks in advance.
Chris
A: function getReviews() {
$reviews = Mage::getModel('review/review')->getResourceCollection();
$reviews->addStoreFilter( Mage::app()->getStore()->getId() )
->addStatusFilter( Mage_Review_Model_Review::STATUS_APPROVED )
->setDateOrder()
->addRateVotes()
->load();
return $reviews;
}
Source: Here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Evision Argos/Oracle performance I have a report in Evisions Argos that runs in 1-2 minutes on one server and for almost an hour on another. It is the exact same datablock with the exact same code, just running against a different database.
I won't display the script here, I just want to know what kinds of things our Argos Admin should check for (I don't have access to the server, I'm just a DataBlock Designer).
A: Oracle performance tuning is a vast topic. There are people out there who make (very good) livings out of tuning other people's queries. So you really aren't going to get much joy here.
But the general advice is actually pretty obvious: if the same query performs differently in two different environments the cause must be due to some difference between them.
*
*Volumes of data (number of rows)
*Distribution of data (development or test data may have different characteristics from live data)
*Data structures (indexes, materialized views)
*Stale statistics
*Hardware - amount of RAM, quality of IO, size and type of storage.
*Resource contention (more users, different types of users e.g. long running reports)
There are all sorts of tools you can use to diagnose performance problems. These depend on which version of the database you have, which edition you've licensed and also whether you have any of the chargeable options.
But regardless, the first place to start is with the documentation. Find out more.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: If no image, display text? I'm having a problem finding a code that will display text (<?php bloginfo('name'); ?>) when no image has been defined in the img src= (<?php echo get_option('to_logo'); ?>). This works in Firefox, of course, as a simple alt tag. But doesn't cut it in all browsers.
<a class="logo" href="<?php echo get_option('home'); ?>" title="<?php bloginfo('name'); ?>">
<img src="<?php echo get_option('to_logo'); ?>" title="Logo" alt="Logo" />
</a>
A: Wouldn't it be simpler just to do something like:
<a class="logo" href="<?php echo get_option('home'); ?>" title="<?php bloginfo('name'); ?>">
<?php
if (get_option('to_logo') != '') {
?>
<img src="<?php echo get_option('to_logo'); ?>" title="Logo" alt="Logo" />
<?php
} else {
echo bloginfo('name');
}
?>
</a>
A: This looks like WordPress. You can try to first test the image source to see if it is empty:
<a class="logo" href="<?php echo get_option('home'); ?>" title="<?php bloginfo('name'); ?>">
<?=(get_option('to_logo')) ? '<img src="'.get_option('to_logo').'" title="Logo" alt="Logo" />' : 'The alternate text'; ?>
</a>
A: You can try this:
if (get_option('to_logo') == '') {
echo bloginfo('name');
} else {
echo get_option('to_logo');
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how can I get the first element of a XElement how can I get the first element
<outline title="Javascript" text="Javascript"> </outline>
from this XElement
<outline title="Javascript" text="Javascript">
<outline text="j" title="j" type="rss" xmlUrl="http://wwww.Java.com/rss2.xml"/>
</outline>
this is my code
var desireXElement =existXElement.Where(w => (string) w.Attribute("title") == "Javascript").FirstOrDefault();
A: You can't select a node without that node containing its child nodes. Such a "selection" would be equivalent to a mutation. You can create a new XElement that is a copy and then mutate the new one:-
var desireElement = new XElement(existXElement.Where(w => (string)w.Attribute("title") == "Javascript").First());
desireElement.RemoveNodes();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: LINQ vs Stored Procedures vs Inline Queries We are a small team working on a very tight deadline to develop a large web application in .NET. We are using multiple databases (one per client) so our requirements are slightly different than most applications. The databases will only be used for this particular application so it doesn't matter if they are tightly coupled with the application. The main deciding factors are speed of development, long-term maintainability, and security. There are 3 options we are considering:
Option 1 - LINQ to SQL
None of us have any experience with LINQ, but we have been researching it and it seems like a good option and not too difficult to learn. Worth the risk of learning a new method on a tight deadline?
Option 2 - Stored Procedures
Seems like it could be a nightmare to maintain with the multiple database setup (or would it?) and it may slow down development to work in another environment as we don't have a dedicated database developer. Basic CRUD queries would be generated by code generator which is an advantage.
Option 3 - Inline Queries
This method would be the fastest to develop but I know people are generally against hard-coded queries nowadays and I fear we may suffer in the long term with maintainability issues. Basic CRUD queries would be generated by code generator.
Please let me know if there are any factors we are missing. What solution seems the most appropriate for this project?
A: If you have a tight deadline don't try something new. Ask the devs to study Entity Framework at home and in their spare time and try it in next project. Meanwhile do what you know best and have used in past successfully.
Inline queries are not bad if they are decoupled in a DAL assembly.
A: Since @Hasan Khan covered the primary answers regarding SQL. I'm going to throw out a somewhat different answer. Another option is to consider usage of RavenDB, a NoSQL db. It has the concept of Tenant databases inherently baked into it. Which from your requirements it sounds like this is the intended goal.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why would a developer place a forward slash at the start of each relative path? I am examining some code for a friend, and have found that the developer who built his site began each and every relative src, href, and include with a forward slash /.
For example:
src="/assets/js/jquery.js"
I have never seen this before. So my question is, why would a developer place a forward slash / at the start of a relative path?
A: This is to ensure the asset comes from the "root" of the web server.
e.g.
Host is www.example.com
URL becomes www.example.com/assets/js/jquery.js
I do this with project I want to ensure live on their own virtual host.
The issue really comes down to where those assets are being included. For example if the asset is being included from /help/pages/faq then the developer can be sure the path will work correctly when the site is hosted on a non changing host, e.g. example.com.
The issue of using relative paths, 'assets/js/jquery.js' is that if the assets are included from the /help/pages/faqs then the path becomes relative to that starting point, e.g. /help/pages/faqs/assets/js/jquery.js
Hope that helps
A: It's done in order to root the path (making it an absolute path).
It ensures that the path is not relative but read from the root of the site.
This allows one to move a file around and not have to change the links to the different resources.
Using your example:
src="/assets/js/jquery.js"
If the referencing file is in /pages/admin/main.html (for example) using relative paths you would use:
src="../../assets/js/jquery.js"
Suppose you move the file to a child directory. No changes would be needed for with the original rooted path, but the relative one would need to change to:
src="../../../assets/js/jquery.js"
A: Adding on @Oded's answer, the slash makes the URL absolute.
For example:
/foo/bar/baz.css
This translates to:
http://www.example.com/foo/bar/baz.css
But without the slash, things become a bit different:
foo/bar/baz.css
This tells the browser to look in the current folder (not the root folder) for the directory foo and then the subsequent directories and the file.
Also, take for instance this HTML:
<script type="text/javascript" src="foo.js"></script>
If you move the HTML file into another folder, then the script will not load, as foo.js isn't being moved with the HTML file.
But if you use an absolute URL:
<script type="text/javascript" src="/foo.js"></script>
Then the JS file is loaded EXACTLY from http://www.example.com/foo.js no matter where the HTML file is.
A: This is a bit off topic, but if there is any chance that your application will ever be served behind a reverse proxy (eg. using apache2 or nginx) under a sub-path, you should try to avoid absolute paths.
For example, if you reference "/style.css" on https://example.com/, and you tried to hide it behind a reverse proxy at https://proxy.example.com/example/, your absolute reference would break. The browser would make the request to "https://proxy.example.com/style.css" when it should have requested "https://proxy.example.com/example/style.css".
Unintentional absolute paths from a leading forward slash are a nightmare for reverse proxies to deal with.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "77"
} |
Q: Oracle: Aging - 7 Buckets - By Account Report Definition (ARXAGS) Is it possible to get the code file behind a standard Oracle report from a resource other than my IT department?
I only have minimal read-only permissions on our server, and the IT folks here are not willing to share this information with me.
I am trying to write a query similar to the standard report: Aging - 7 Buckets - By Account Report and would like to see the tables/logic that are behind it to point me in the right direction.
Is this data available anywhere? We are on version 11.5.10.2
A: You should be able to easily extract the underlying SQL logic for this very report by simply viewing the concurrent request log file. The log file includes the executed SQL and lexical parameters. I used this approach to migrate this very seeded report to another custom Oracle BI solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MediaWiki anti-bot coding I want to modify MediaWiki handling of user registration to add an anti bot check.
It looks like the addNewAccountInternal() method in the includes/SpecialUserlogin.php file is the right place to do it.
The problem is that nothing I change in that file seems to make any difference. Not even removing that file. I didn't install any kind of cache in the server.
I have already written the client side JavaScript code in the includes/templates/Userlogin.php file and it works as expected.
What am I missing?
A: The same file exists in includes/specials and there the modifications work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MYSQL SELECT WHERE LIKE WITH AES_ENCRYPT How would I perform a Mysql SELECT with WHERE and LIKE serach if field is AES_ENCYPTED?
Example:
SELECT AES_DECRYPT(place,'"+salt+"'),AES_DECRYPT(web_address,'"+salt+"')
FROM access
WHERE place= LIKE '%(AES_ENCRYPT('"+searchStr+"','"+salt+"'))',%')
Basically, perform a search on an encrypted column with the LIKE wildcard on both ends of the $searchStr
A: I have been looking for a simple way to use the SELECT LIKE for an AES_ENCRYPTED field with MySQL. The one that works the best is:
SELECT * FROM table
WHERE CONVERT(AES_DECRYPT(`haystack`,'key') USING utf8) LIKE '%needle%'
I have tested this on MySQL 5 using PHP 5.
This runs very well when processing several thousand rows, but may not be ideal for very large tables due to the decryption and conversion.
This is the basic PHP code:
$key = md5("yourchosenkey".$salt);
$query = "SELECT * FROM ".$tableName." ".
"WHERE CONVERT(AES_DECRYPT(`haystack`,'".$key."') USING utf8) ".
"LIKE '%".addslashes($needle)."%'";
A: You can't search on an encrypted column without first decrypting it.
You'll need to do WHERE AES_DECRYPT(like, salt) LIKE '%something%' but it's going to be quite slow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7613289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.