text stringlengths 8 267k | meta dict |
|---|---|
Q: rails3 model redirect I have a model called User. In the model I want to check if a value is true or false.
If the value is true then break all operations and redirect to a specific page.
How do I do that?
before_create :check_user
def check_user
if User.find_by_email(self.email)
redirect_to root_path
end
end
A: You can't and you never need to redirect form model.
You should do it in controller something like
before_filter :check_user
...
private
def check_user
redirect_to root_path unless User.find_by_email(params[:user][:email])
end
A: before_create :check_user
def check_user
unless User.find_by_email(email).nil?
redirect_to root_path
end
end
See if this does what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to block websites to copy php result in my server? this is my code example:
$('#list').load('/file.php?id=25');
how to block another websites to access and get result from file.php ?
thanks
A: By deleting file.php or by protecting it with a password. There is no other reliable way. If you have a resource publicly accessible on the web, there is always the risk of it being scraped.
The example you show, however, will not work for other sites anyway, because normal Ajax requests can't be cross-domain.
A: Due to the same-origin policy, JavaScript code served in the context of another domain can not access your content.
However, a server-side script can always download the website. What you can do against that is:
*
*Not serve the website in the first place. I'm assuming that's not an option
*Require passwords from trusted users. Note that those users can also store their passwords at a remote server.
*Require CAPTCHAs for each visit. This is bound to annoy your legitimate visitors.
*Require signed hard-/software. Since there is no easy way to do that right now, you'll need every visitor to install custom and/or signed hard- and software. This is not feasible.
A: If you have a login system in place, start a session in file.php and check if the user is logged in - the session cookie will be sent when the Ajax call is made.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript validation -Which one is best (Name or ID ) I have two option of JavaScript validation .Among these which one better to use for validation
Javascript validation based on FIELD NAME
if(document.formname.uname.value=="")
{
alert("Please Enter Username");
document.formname.uname.focus();
return false;
}
Javascript validation based on ID
if(document.getElementById('uname').value=="")
{
alert("Please Enter Username");
document.getElementById('uname').focus();
return false;
}
A: Avoid using ids, but don't access forms that way.
Here are a couple of general rules of thumb:
Get a reference to the form and use that
Don't use globals. This makes code more reusable.
e.g.
function submitHandler (e) {
var myForm = this;
}
document.getElementById('myForm').addEventListener('submit', submitHandler);
Note that addEventListener, while standard, isn't supported by older versions of IE. Use a library to abstract your event binding.
Once you have a reference, use the elements collection
myForm.elements.control …
Where control can be a name or an id. If it is a name and you have multiple controls with the same name (e.g. a checkbox group), then it will return a NodeList you can iterate over.
A: It just depends on how you want to select items in the form. ID is always to be unique for each element whereas name doesn't have to be. So using name, you can select multiple elements quite simply, especially usefull for forms created using javascript with an unknown number of fields.
A: In my opinion the first option with document.fromname.uname is better. Using IDs is like a globale variable. It is better to use the namespace of the form to avoid conflicts.
Also you only have to set the name attribute of the input field instead of name and id.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Google Charts API DataTable Cell Color I'm trying to use the Google Charts API to display a DataTable which has some of its cells coloured depending on their value. The table generates fine, but none of my style properties are applied to the cells. According to the documentation I should be able to set a cell value using the p value:
p [Optional] An object that is a map of custom values applied to the cell. These values can be of any JavaScript type. If your visualisation supports any cell-level properties, it will describe them; otherwise, this property will be ignored. Example: p:{style: 'border: 1px solid green;'}.
I'm passing a Perl generated JSON object to the DataTable constructor. The JSON object looks like this:
{"cols":[{"pattern":"","type":"string","label":"alias","id":""},
{"pattern":"","type":"string","label":"state","id":""},
{"pattern":"","type":"string","label":"server_name","id":""},
{"pattern":"","type":"number","label":"connections","id":""},
{"pattern":"","type":"number","label":"sessions","id":""},
{"pattern":"","type":"number","label":"queues","id":""},
{"pattern":"","type":"number","label":"topics","id":""},
{"pattern":"","type":"number","label":"durables","id":""},
{"pattern":"","type":"number","label":"pending_message","id":""}
],
"rows":[
{"c":[{"v":"live1"},
{"p":{"style":"border: 1px solid green;"},"v":"Active"},
{"v":"serice1"},{"v":"580"},{"v":"1177"},{"v":"632"},{"v":"200"},{"v":"68"},{"v":"69"}
]},
{"c":[
{"v":"live2"},
{"p":{"style":"border: 1px solid green;"},"v":"Active"},
{"v":"service2"},{"v":"68"},{"v":"1481"},{"v":"164"},{"v":"48"},{"v":"4"},{"v":"2592"}
]},
{"c":[
{"v":"uat1"},
{"p":{"style":"border: 1px solid green;"},
"v":"Active"},{"v":"service3"},{"v":"299"},{"v":"1072"},{"v":"305"},{"v":"111"},{"v":"39"},{"v":"17"}]},
{"c":[
{"v":"uat2"},
{"p":{"style":"border: 1px solid green;"},
"v":"Active"},{"v":"service4"},{"v":"115"},{"v":"1755"},{"v":"302"},{"v":"79"},{"v":"9"},{"v":"1"}]
}],
"p":null}
Can any one see what I'm doing wrong, or have an example JSON object structure of a DataTable with style applied to cells or rows?
A: Ok looks like I missed something:
in the dataTable options you have to set 'allowHtml: true'
Then all formatting properties will be accepted, hope this saves someone a bit of digging around, although it is fairly obvious :-s
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Regular expressions in python : don't split when a specific substring is found I found a bug in a regex in one of python-scripts and I need help to solve it.
The problem is that the script splits a string with re.split('(V[A-Z])', string) but I don't want a split if the specific substring SVD is found.
example:
"ACD VU LSF VMSUGH VIJ SVD HJV DVO" -> "ACD ", "U LSF ","MSUGH ", "IJ SVD HJV D", "O"
Is there someone out there that can solve my problem?
A: Hmm...
if 'SVD' not in string:
result = re.split('(V[A-Z])', string)
else:
result = string
A: If I understand your question correctly, you should use lookbehind assertion in regex.
http://docs.python.org/library/re.html
>>>x = 'ACD VU LSF VMSUGH VIJ SVD HJV DVO'
>>>result = re.split('V[A-Z](?<!SVD)', x)
['ACD ', ' LSF ', 'SUGH ', 'J SVD HJV D', '']
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: php error when XML item does not exist I am using PHP to grab an XML feed and display it in my website, the feed is coming from
This NewsReach Blog.
I am using some simple PHP code to get the details as show below:
$feed = new SimpleXMLElement('http://blog.newsreach.co.uk/atom.xml', null, true);
$i = 0;
foreach($feed->entry as $entry)
{
if ($i < 4)
{
$title = mysql_real_escape_string("{$entry->title}");
$summary = mysql_real_escape_string("{$entry->content}");
$summary = strip_tags($summary);
$summary = preg_replace('/\s+?(\S+)?$/', '', substr($summary, 0, 100));
$url = mysql_real_escape_string("{$entry->link[4]['href']}");
$media = $entry->children('http://search.yahoo.com/mrss/');
$attrs = $media->thumbnail[0]->attributes();
$img = $attrs['url'];
}
}
The problem that I have is that the media thumbnail tag does not exist in every blog post which causes an error to appear and stop the XML Grabber from functioning.
I have tired things like:
if ($media == 0)
{
}
else
{
$attrs = $media->thumbnail[0]->attributes();
$img = $attrs['url'];
}
or
if ($media['thumbnail'] == 0)
{
}
else
{
$attrs = $media->thumbnail[0]->attributes();
$img = $attrs['url'];
}
which I had no luck with, I was hoping someone could help me check if the XML Item existed and then process depending on that.
Thanks all
A: You could check if it's set and not empty:
$img = '';
if (!empty($media->thumbnail[0])) {
$attrs = $media->thumbnail[0]->attributes();
$img = $attrs['url'];
}
Remember that $media is an object, you can't access it like an array ($media['thumbnail'] should be $media->thumbnail).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ruby IO#read max length for single read How can i determine the max length IO#read can get in a single read on the current platform?
irb(main):301:0> File.size('C:/large.file') / 1024 / 1024
=> 2145
irb(main):302:0> s = IO.read 'C:/large.file'
IOError: file too big for single read
A: That message comes from io.c, remain_size. It is emitted when the (remaining) size of the file is greater or equal to LONG_MAX. That value depends on the platform your Ruby has been compiled with.
At least in Ruby 1.8.7, the maximum value for Fixnums happens to be just half of that value (-1), so you could get the limit by
2 * 2 ** (1..128).to_a.find { | i | (1 << i).kind_of? Bignum } - 1
You should rather not rely on that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Ruby syntax accept arguments on dynamically generated methods via send How I can pass arguments on dynamically generated methods via send ?
Below I generate on the fly several methods, I want they accept the "row" argument.
The code below generates the methods, but I don't know how let the methods accept the "row" argument.
@sql_columns.each do |attr|
(class << self; self end).send :define_method, attr do
key = @column_mapping[attr].to_s
row[key]
end
end
A: (class << self; self end).send :define_method, attr do |row|
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get tooltips text from C# with PInvoke I'm using PInvoke in C#, trying to read tooltips visible in a window with a known handler, but the apps who's windows I try to inspect in this manner crash with memory access violation errors, or simply don't reveal the tooltip text in the lpszText TOOLINFO member.
I'm calling EnumWindows with a callback and then sending a message to the tooltip window in that function:
public delegate bool CallBackPtr(IntPtr hwnd, IntPtr lParam);
static void Main(string[] args)
{
callBackPtr = new CallBackPtr(Report);
IntPtr hWnd = WindowFromPoint(<mouse coordinates point>);
if (hWnd != IntPtr.Zero)
{
Console.Out.WriteLine("Window with handle " + hWnd +
" and class name " +
getWindowClassName(hWnd));
EnumWindows(callBackPtr, hWnd);
Console.Out.WriteLine();
}
public static bool Report(IntPtr hWnd, IntPtr lParam)
{
String windowClassName = getWindowClassName(hWnd);
if (windowClassName.Contains("tool") &&
GetParent(hWnd) == lParam)
{
string szToolText = new string(' ', 250);
TOOLINFO ti = new TOOLINFO();
ti.cbSize = Marshal.SizeOf(typeof(TOOLINFO));
ti.hwnd = GetParent(hWnd);
ti.uId = hWnd;
ti.lpszText = szToolText;
SendMessage(hWnd, TTM_GETTEXT, (IntPtr)250, ref ti);
Console.WriteLine("Child window handle is " + hWnd + " and class name " + getWindowClassName(hWnd) + " and value " + ti.lpszText);
}
return true;
}
Here's how I defined the TOOLINFO structure:
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
private int _Left;
private int _Top;
private int _Right;
private int _Bottom;
}
struct TOOLINFO
{
public int cbSize;
public int uFlags;
public IntPtr hwnd;
public IntPtr uId;
public RECT rect;
public IntPtr hinst;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpszText;
public IntPtr lParam;
}
the TTM_GETTEXT value
private static UInt32 WM_USER = 0x0400;
private static UInt32 TTM_GETTEXT = (WM_USER + 56);
and the SendMessage overload
[DllImport("user32.dll", CharSet = CharSet.Auto)]
static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, ref TOOLINFO lParam);
So, is there any obvious error that I'm missing in my code, what should I change so that this situation is resolved?
Edit: Here is the whole code, so you could test.
A: You are sending a private message across processes, which requires manual marshaling. Here's another stackoverflow question on the same topic. Better would be to change direction entirely and use Active Accessibility and/or UI Automation, which are designed for this sort of thing.
A: I ended up using UI Automation, as Raymond suggested. AutomationElement, who's Name property value contains the text in case of tooltips, proved to be exactly what the code required. I'm cycling through all the Desktop's child windows, where all the tooltips reside and I only display those that belong to the process that owns the window under the mouse:
public static bool Report(IntPtr hWnd, IntPtr lParam)
{
if (getWindowClassName(hWnd).Contains("tool"))
{
AutomationElement element = AutomationElement.FromHandle(hWnd);
string value = element.Current.Name;
if (value.Length > 0)
{
uint currentWindowProcessId = 0;
GetWindowThreadProcessId(currentWindowHWnd, out currentWindowProcessId);
if (element.Current.ProcessId == currentWindowProcessId)
Console.WriteLine(value);
}
}
return true;
}
static void Main(string[] args)
{
callBackPtr = new CallBackPtr(Report);
do
{
System.Drawing.Point mouse = System.Windows.Forms.Cursor.Position; // use Windows forms mouse code instead of WPF
currentWindowHWnd = WindowFromPoint(mouse);
if (currentWindowHWnd != IntPtr.Zero)
EnumChildWindows((IntPtr)0, callBackPtr, (IntPtr)0);
Thread.Sleep(1000);
}
while (true);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Decoding base64 adds extra spaces I am working in Delphi XE2
I am converting base64 byte array to string using this
TEncoding.UTF7.GetString(byte1)
Then decoding string into byte array using this function
function Base64Decode(const EncodedText: string): TBytes;
var
DecodedStm: TBytesStream;
Decoder: TIdDecoderMIME;
begin
Decoder := TIdDecoderMIME.Create(nil);
try
DecodedStm := TBytesStream.Create;
try
Decoder.DecodeBegin(DecodedStm);
Decoder.Decode(EncodedText);
Decoder.DecodeEnd;
Result := DecodedStm.Bytes;
finally
DecodedStm.Free;
end;
finally
Decoder.Free;
end;
end;
But input string length is 400 and after decode its byte array length is 8192.
Somewhere it is adding extra spaces... any suggestion as what I'm doing wrong?
Edit...
this is base64 of my data send from c# through tcp to delphi XE2 app
string length = 400
TVpQAAIAAAAEAA8A//8AALgAAAAAAAAAQAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAALoQAA4ftAnNIbgBTM0hkJBUaGlzIHByb2dyYW0gbXVzdCBiZSBydW4gdW5kZXIgV2luMzINCiQ3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFBFAABMAQgAGV5CKgAAAAAAAAAA4ACOgQsBAhkArAoAAMQCAAAAAAAwugoA
i receive TBytes in my delphi app when i convert TBytes to string following comes
Tbytes to UTF-7 string
string length = 401
TVpQAAIAAAAEAA8A//8AALgAAAAAAAAAQAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAALoQAA4ftAnNIbgBTM0hkJBUaGlzIHByb2dyYW0gbXVzdCBiZSBydW4gdW5kZXIgV2luMzINCiQ3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA‘AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFBFAABMAQgAGV5CKgAAAAAAAAAA4ACOgQsBAhkArAoAAMQCAAAAAAAwugoA
TByte to UTF-8 String
string length= 0 ( ZERO)
TByte to ANSI String
string length= 401
TVpQAAIAAAAEAA8A//8AALgAAAAAAAAAQAAaAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAALoQAA4ftAnNIbgBTM0hkJBUaGlzIHByb2dyYW0gbXVzdCBiZSBydW4gdW5kZXIgV2luMzINCiQ3AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA‘AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFBFAABMAQgAGV5CKgAAAAAAAAAA4ACOgQsBAhkArAoAAMQCAAAAAAAwugoA
there is 1 extra bit is comming in between but i dont know why it is comming.
kindly advice am i doing any thing wrong.
A: You can add one line to get the length you are expecting:
function Base64Decode(const EncodedText: string): TBytes;
var
DecodedStm: TBytesStream;
Decoder: TIdDecoderMIME;
begin
Decoder := TIdDecoderMIME.Create(nil);
try
DecodedStm := TBytesStream.Create;
try
Decoder.DecodeBegin(DecodedStm);
Decoder.Decode(EncodedText);
Decoder.DecodeEnd;
Result := DecodedStm.Bytes;
SetLength(Result, DecodedStm.Size); // add this line
finally
DecodedStm.Free;
end;
finally
Decoder.Free;
end;
end;
A: While it is a very bad idea to mix UTF7 encoding with Base64 decoding, you should use the built-in functions EncodeBase64 and DecodeBase64 found in Soap.EncdDecd.pas.
A: First and foremost, why are you involving UTF-7 at all? Base64 is a 7-bit encoding that uses only ASCII characters. Converting base64 to/from UTF-7 is an unnecessary operation. If you have a TBytes that contains base64-encoded character octets, then you can simply copy the TBytes directly into an AnsiString without doing any decoding at all:
var
byte1: TBytes;
s: AnsiString;
SetString(s, PAnsiChar(byte1), Length(byte));
Or use Indy's BytesToStringRaw() function:
var
byte1: TBytes;
s: String;
s := BytesToStringRaw(byte1);
Either way, once you have a base64-encoded string, you can eliminate your custom Base64Decode() function completely by using the TIdDecoderMIME.DecodeBytes() method instead:
var
decoded: TBytes;
decoded := TIdDecoderMIME.DecodeBytes(s);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Haskell list comprehension to map I am new to haskell . I was wondering If I can do the following thing using just map and concat ?
[ (x,y+z) | x<-[1..10], y<-[1..x], z<-[1..y] ]
A: Yes:
concat $ concat $ map (\x -> map (\y -> map (\z -> (x,y+z)) [1..y]) [1..x]) [1..10]
Although the official translation uses concatMap:
concatMap (\x -> concatMap (\y -> concatMap (\z -> [(x,y+z)]) [1..y]) [1..x]) [1..10]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Get post value from a select tag PHP Hey I need to get the gender selected from a select tag
and then store that value as a variable in php, here's some relevant snippets of both
the register.php form and the register_process.php file
register.php
<form action="register_process.php" method="post">
<table>
<tr>
<td>Username (to be used for login and display name)</td>
<td><input type="text" name="username" id="username" onclick="check()"/></td>
<td id="username_check"></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" id="password" onclick="check()"/></td>
<td id="password_check"></td>
</tr>
<tr>
<td>Password (Re-Enter)</td>
<td><input type="password" name="repassword" id="repassword" onclick="check()"/></td>
<td id="repassword_check"></td>
</tr>
<tr>
<td>Email Address</td>
<td><input type="text" name="email" id="email" onclick="check()"/></td>
<td id="email_check"></td>
</tr>
<tr>
<td>Email Address (Re-Enter)</td>
<td><input type="text" name="reemail" id="reemail" onclick="check()"/></td>
<td id="reemail_check"></td>
</tr>
<tr>
<td>Gender</td>
<td>
<select name="gender">
<option value="1">Male</option>
<option value="2">Female</option>
</select>
</td>
<td></td>
</tr>
<tr>
<td>I agree to the terms and conditions</td>
<td><input type="checkbox" name="tos" id="tos" /></td>
<td id="tos_check"></td>
</tr>
<tr>
<td id="valid" colspan="3"></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Register" /></td>
</tr>
<tr>
<td colspan="3"><a href="login.php">Cancel</a></td>
</tr>
</table>
</form>
there is a ton of javascript I have omitted from this that does very basic validation
register_process.php
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
?>
<?php
$connection = mysql_connect(HOST, USERNAME, PASSWORD);
if(!$connection)
{
die("Database connection failed: " . mysql_error());
}
$db_select = mysql_select_db(DATABASE, $connection);
if(!$db_select)
{
die("Database selection failed: " . mysql_error());
}
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$repassword = mysql_real_escape_string($_POST['repassword']);
$email = mysql_real_escape_string($_POST['email']);
$reemail = mysql_real_escape_string($_POST['reemail']);
$gender = $_POST['gender'];
$tos = mysql_real_escape_string($_POST['tos']); // not being checked yet
$errors = 0;
$success = 0;
// USERNAME CHECK
if (preg_match('/^[a-z\d_]{5,20}$/i', $username))
{
$user_query = "SELECT * FROM users WHERE user_name = '$username' OR login_name = '$username' LIMIT 1";
$result=mysql_query($user_query);
$count=mysql_num_rows($result);
if($count==0)
{
echo "username is available <br/>";
$success++;
echo "<br/>1 Passed<br/>";
}
else
{
echo "sorry, that username already exist";
$errors++;
echo "<br/>1 Passed<br/>";
}
}
else
{
echo "You either need to enter a username, or you have entered a username in an incorrect format.";
$errors++;
echo "<br/>1 Passed<br/>";
}
// PASSWORD CHECK
if(preg_match('/^[a-z\d_]{5,20}$/i', $password))
{
// password is between 5-10 characters, alpha-numeric (a-z, A-Z, 0-9) and underscores
if($password === $repassword)
{
// password is identical
$success++;
echo "<br/>2 Passed<br/>";
}
else
{
// passwords do not match
$errors++;
echo "<br/>2 Passed<br/>";
}
}
else
{
echo "Password failed validation";
$errors++;
}
// EMAIL CHECK
if (eregi('^[a-zA-Z0-9._-]+@[a-zA-Z0-9._-]+\.([a-zA-Z]{2,4})$',$email))
{
// user@email.com passes
// 1@1.com passes
// -@_.com passes
//
echo "<br/> email is ok";
if($email === $reemail)
{
// email addresses match
$success++;
echo "<br/>3 Passed<br/>";
}
else
{
// email address does not match
echo "<br/>3 Passed<br/>";
$errors++;
}
}
else
{
echo "email validation failed <br/>";
$errors++;
echo $email;
}
// Here is the problem, I can't seem to evaluate the correct value,
// When I echo out $gender I get nothing, So theres either an issue
// in the html form OR in the way I use $gender = $_POST['gender'];
if($gender == 1 || $gender == "1" || $gender == '1')
{
echo "male selected";
}
else
{
echo "female selected";
}
?>
what am I missing here guys?,
I have been hunting around
google to find an answer with no success.
heres the error php is giving me:
"Notice: Undefined index: gender in register_process.php on line 22"
Everything else in the form IS working fine, there are no other issues
A: Your mistake is this:
/>
Don't close your form tag way up there - you need to close it after the select.
BTW xhtml is dead, don't use it (it has been superseded by html5). Use plain HTML and don't close tags that don't need it.
A: Because of error in your HTML syntax.
Change:
<form action="register_process.php" method="post" />
To:
<form action="register_process.php" method="post">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how can i bind business object of c# in crystal or rdlc report? First let me tell you one thing, I have never worked with any sort of reporting yet. I have read all the related question and answer on this topic. But could not find any concrete solution.
My problem is I have a very simple report to make where I have to show a row from a view from the database. In order to have that row, I have created a business object (entity). that entity is holding my row perfectly. I have tried crystal report and rdlc report as well. But at the end I will choose only one. So I have a crystal report in my solution. In my aspx form I have taken a report-viewer. but I don know how to make these three things work together, i.e. the report, the report viewer and the object or entity that is holding the information.
Now the code goes here
the name of the crystal report is FormSaleMoneyReceipt.rpt
my aspx page is
<form id="form1" runat="server">
<asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>
<div id = "SearchPlace">
<label for ="">Candidate ID:</label><asp:TextBox runat = "server" ID = "txtCandidateId"></asp:TextBox>
<label for ="">Form SL#:</label><asp:TextBox runat = "server" ID = "txtFormSl"></asp:TextBox>
<asp:Button runat = "server" ID = "btnShowReport" Text = "Show Report"
onclick="btnShowReport_Click" />
</div>
<div id = "ReportViewrHolder">
<CR:CrystalReportViewer ID="CrystalReportViewerMRN" runat="server" AutoDataBind="true" />
</div>
</form>
My code behind file is
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnShowReport_Click(object sender, EventArgs e)
{
int candidateId = 0;
string formSl = txtFormSl.Text;
ViewFormSaleMoneyReceiptEntity formSaleMoneyReceiptEntity = new ViewFormSaleMoneyReceiptEntity();
if(txtCandidateId.Text != "")
{
candidateId = Convert.ToInt32(candidateId);
formSaleMoneyReceiptEntity = ViewFormSaleMoneyReceipt_DAO.GetMoneyReceiptByID(candidateId);
//CrystalReportViewerMRN.ReportSource = formSaleMoneyReceiptEntity;
}
if(txtFormSl.Text!="")
{
formSaleMoneyReceiptEntity = ViewFormSaleMoneyReceipt_DAO.GetMoneyReceiptByFormSL(formSl);
//CrystalReportViewerMRN.ReportSource = formSaleMoneyReceiptEntity;
}
}
please, please give me a solution, I am desperately in need of the solution. Thank you all the smart tech geeks in advance.
A: You have to create a ReportSource object and assign that to your report, as described here.
CrystalReportViewerMRN.ReportSource = myReportSource;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Wow addon failing to work with array I'm trying to create a simple addon for world of warcraft which records my kills.
I've already got'n quite far except there is a problem with the writing of a lua array.
The code I have so far
local CharacterDefaults = {
kills = {},
totalkills = 0
}
local killDefaults = {
DBtimeofday = 0,
DBplayer = 0,
DBenemyname = 0,
DBenemyid = 0,
DBzone = 0,
DBkilltype = 0
}
The next piece is inside a event which checks for overkill
if not KillCount then
KillCount = CharacterDefaults
end
if not KillCount.totalkills then
KillCount.totalkills = 0
end
KillCount.enemy[KillCount.totalkills] = destName
KillCount.kills[KillCount.totalkills] = killDefaults
KillCount.kills[KillCount.totalkills].DBtimeofday = stamp
KillCount.kills[KillCount.totalkills].DBzone = zone
KillCount.kills[KillCount.totalkills].DBkilltype = killtype
KillCount.kills[KillCount.totalkills].DBenemyid = unitId
KillCount.kills[KillCount.totalkills].DBenemyname = destName
KillCount.kills[KillCount.totalkills].DBplayer = playerName
KillCount.totalkills = KillCount.totalkills + 1
Ofcourse there's more code but this is the only important code (as far as I know).
If I look at this I would expect that for every new kill a new array part is made and the values are entered. However, for each kill I make in world of warcraft, every single item already in it will get the results of the last kill.
The lua variables saved file:
KillCount = {
["kills"] = {
{
["DBplayer"] = "MyName",
["DBzone"] = "Blackrock Depths",
["DBkilltype"] = 0,
["DBenemyname"] = "Grim Patron",
["DBenemyid"] = 9545,
["DBtimeofday"] = "11-09-22 10:45:23",
}, -- [1]
{
["DBplayer"] = "MyName",
["DBzone"] = "Blackrock Depths",
["DBkilltype"] = 0,
["DBenemyname"] = "Grim Patron",
["DBenemyid"] = 9545,
["DBtimeofday"] = "11-09-22 10:45:23",
}, -- [2]
[0] = {
["DBplayer"] = "MyName",
["DBzone"] = "Blackrock Depths",
["DBkilltype"] = 0,
["DBenemyname"] = "Grim Patron",
["DBenemyid"] = 9545,
["DBtimeofday"] = "11-09-22 10:45:23",
},
},
["totalkills"] = 3,
}
as you can see the [0] is the only one to be properly writen. Am I doing something wrong?
A: The problem is here:
KillCount.kills[KillCount.totalkills] = killDefaults
Everytime you kill, you're pointing KillCount.kills[KillCount.totalkills] to killDefaults then modifying killDefaults. The problem is, you are using the same killDefaults every time. So when you udpate the values of killDefaults later, it affects every reference to killDefaults that you have already created.
Try something like:
function GetDefaultKills()
return {
DBtimeofday = 0,
DBplayer = 0,
DBenemyname = 0,
DBenemyid = 0,
DBzone = 0,
DBkilltype = 0
};
end
KillCount.kills[KillCount.totalkills] = GetDefaultKills()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why is my Binding not working? This is silverlight code - but I guess that this will be same in WPF -
I have this simple classes
public Class A1
{
string str1;
public string Str_1
{
return str1;
}
}
public Class B1
{
A1 a1;
public A1 A_1
{
return a1;
}
}
I assume that B1::A1.str1 have the value "my string".
Now in the XAML I have this
<Grid x:Name="LayoutRoot" DataContext="B1">
<StackPanel>
<TextBox Text="{Binding ElementName=A1, Path=Str_1, Mode=TwoWay}"/>
</StackPanel>
</Grid>
In the the code ( xaml.cs ) i writing in the constructor this
LayoutRoot.DataContext = this;
( the B1 object is part of the xaml.cs file and the B1 is also not null and A1 is not null )
But ==> this is not working ... and the text of the textbox is not update with the text that is in A1 object.
A: You are using element binding but A1 is not a named element in the Xaml page.
You want Text={Binding Path=A_1.Str_1}
This means that it points to the Str_1 property of the A_1 property of the data context (your code behind class).
Please note that TwoWay is pointless here as you have no setters on your properties.
To do this properly (assuming your values will change and be required) you need to implement setters on your A_1 and Str_1 properties and implement INotifyPropertyChanged on both your class A1 & B1.
A: You can say Text={Binding Path=A_1.Str_1, Mode=TwoWay} I think that should work.
Also if you want to do two-way binding you need to implement INotifyPropertyChanged to let WPF know it has to refresh the UI after you updated the value in code.
GJ
A: Firstly your class B1 must implement INotifyPropertyChanged like this.
Then you should make a property proxy in your B1 class like this:
public string Str_1
{
get
{
return a1.str1;
}
set
{
a1.str1 = value;
this.RaisePropertyChanged("Str_1"); // INotifyPropertyChanged implementation method
}
}
And finally update your binding:
<TextBox Text="{Binding Path=Str_1}"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google map problem when hide and then toggle I have a google map in my page. I set a button with
.slideToggle()
functionality to show/hide the with the map and it do so.
The problem is that I want to hide the map by default.
If I use the display:none on the css, than after toggle up (show) the map,
I don't see the markers that I put in it. Also, the map area seems much smaller than the area of its div.
All of this doesn't happen if I load the page showing the map (display:block).
How can I start with hiding the map, and still be able to see it after toggle it?
A: For others who still have this problem on api v3 use google.maps.event.trigger(your_map_name, 'resize'); which is equivalent to checkResize() method from api v2.
A: Your Google maps initialization should be in a function, if it's not make sure it is.
Then you can only initialize the map after you toggle it, this will also make sure it doesn't get loaded if the user doesn't wish to see it.
function init_maps(){
// google maps api goes here
}
var init = false;
$('.show_map').click(){
if(!init){
init_maps();
init = true;
}
$('.map').slideToggle();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sort an array with respect to the Date in iphone sdk I have a tableview with values loaded from a web service. Which contains date value, here is how it looks like :
"Title":"Title1",
"StartDate":"9\/15\/2011 12:00:00 AM",
"EndDate":"10\/15\/2011 12:00:00 AM".
I have done formatting using NSDateFormatter, I got the output as:
theDate: |09/22/2011|
theTime: |14:09:30 PM|
Now I need to sort the Title in the tableview with respect to the corresponding dates of each title. How can I implement that? Please share your ideas...
And I need to implement this function on a button action, that is the sorting function should be performed on a button action.
Thank you...
A: NSSortDescriptor* nameSorter = [[NSSortDescriptor alloc] initWithKey:@"startDate" ascending:NO];
NSMutableArray *temp = [yourArray mutableCopy];
[temp sortUsingDescriptors:[NSArray arrayWithObject:nameSorter]];
yourArray = temp;
[self.tableView reloadData];
The same goes with titles as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Parameterized LIKE clause in SQL statement using Dapper I want to perform the following query using Dapper, which currently doesn't return expected results (I think it must be treating the @pName param as literal text within the single quotes?):
var q = "SELECT * FROM Users WHERE Name LIKE '@pName%'";
@pName is the param I assign a value to upon executing the query.
Things work if I just build the SQL like:
var q = "SELECT * FROM Users WHERE Name LIKE '" + name + "%'";
.. but I would prefer to use a param if possible.
I am executing the query using the following code:
o = _cn.Query<User>(q, new { pName = new DbString { Value = name, IsFixedLength = false, Length = 25, IsAnsi = true } }).ToList();
How do I got about this using Dapper?
A: SELECT * FROM Users WHERE Name LIKE @pName + '%'
A: I would like to add here another possible solution:
var results = cn.Query("SELECT * FROM Table WHERE Column LIKE @value", new { value = value + "%" });
The wildcard is inside the string var itself, and then we reference that var in the SQL. Applies to any wildcard pattern you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: The keyword of class and interface at header file in Objective-c
Possible Duplicate:
@class vs. #import
I am new to Objective-c, I have seen an example look likes:
#import <UIKit/UIKit.h>
@class MapKitSampleViewController;
@interface MapKitSampleAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
MapKitSampleViewController *viewController;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet MapKitSampleViewController *viewController;
@end
The above code is stored at "MapKitSampleAppDelegate.h" file, I want to ask what is the meaning of line 3 "@class MapKitSampleViewController;"? Can we change it to #import "MapKitSampleViewController.h"?
A:
I want to ask what is the meaning of line 3
"MapKitSampleViewController"? Can we change it to #import
"MapKitSampleViewController.h"?
Yes.
@class keyword is a "forward declaration". What you are telling the compiler is that this class is going to be used in this class, but the header import for it will be elsewhere.
Most likely if you look in the .m file, you will find that the #import "MapKitSampleViewController.h" will be there.
Why?
The reason why this was implemented (I think, anyway), is to prevent circular imports. Imagine a scenario where the following happens:
Class1.h
#import Class2.h
Class2.h
#import Class1.h
Now, if I'm not wrong, what happens here is that during compilation, it will repeatedly import both header and bad things happen. The @class keyword is meant to prevent this from happening, because the import for those files will happen in the .m files, not in the .h files.
BTW this is a duplicate of @class vs. #import
So you will likely find more in-depth discourse on this topic at that question.
A: Yes you can change it but this will increase the compilation time and will bring you no benefits.
The "@class MapKitSampleViewController;" is a forward declaration see http://en.wikipedia.org/wiki/Forward_declaration
When using forward declaration you have to take care that you can use the forward declared class name only for type references.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Change which view opens first (Xcode)
Possible Duplicate:
How to change the default View Controller that is loaded when app launches?
So if I made an app and a certain view opens first by default, and decide I want to change which view opens first, how would I do that?
A: That is controlled in the method in your AppDelegate.m file (or whatever the title of your app delegate file is) called didFinishLaunchingWithOptions. For example, in a tab bar app I've created it looks like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
// Add the tab bar controller's current view as a subview of the window
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
All you have to do is change the value of the self.window.rootViewController. For example, let's say you want a MapViewController to become the first page to open. You could do something like this:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
// Add the tab bar controller's current view as a subview of the window
MapViewController *mvc = [[MapViewController alloc]initWithNibName:@"MapViewController" bundle:nil]; //Allocate the View Controller
self.window.rootViewController = mvc; //Set the view controller
[self.window makeKeyAndVisible];
[mvc release]; //Release the memory
return YES;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512107",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Reading Windows file attributes from Linux (FAT or NTFS file system) Is there any quick and dirty way to read the Windows file attributes from a FAT/NTFS partition, from Linux? For example, to check if a file is read only, system, hidden, etc.
And without uncommon libraries (such as linking with Wine).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: codeigniter ActiveRecord where statement issue is have this statement and i want to make it by the Active Records way in codeigniter
DELETE FROM TABLE
(col1 = value AND col2 = value2 ) OR (col1 = value2 AND col2 = value );
A: CodeIgniter Active Record is impractical for mixing AND's and OR's within a query.
You will likely need to construct some of the query manually, e.g. something along the lines of:
$this->db->where("col1 = $value AND col2 = $value2");
$this->db->or_where("col1 = $value2 AND col2 = $value");
Alternately, in your example where there are only two specific columns and two values, the following idea should also work:
$this->db->where_in('col1', array($value, $value2));
$this->db->where_in('col2', array($value, $value2));
$this->db->where('col1 != col2');
A: Try this:
$this->db->where('col1', $value1);
$this->db->where('col2', $value2);
$this->db->delete($table);
A: That's not the goal of active record. As name suggest active record object instance is tied to a single row in a table. If you want to do this in "active record way" you have to retrieve all the records you have to delete the database, mark them as deleted and commit changes witch is overkill. Best you can do is to get connection instance from codeignither and execute query manually.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL on CSV using HSQLDB JDBC Driver I have a pregenerated CSV file on which I need to run SQL queries. I've been looking at different open source solutions (e.g. CsvJdbc, xlSQL etc) but haven't really found anything satisfactory.
CsvJdbc couldn't recognize ORDER BY, GROUP BY etc
xlSQL only runs on XLS files, not CSV (or I haven't been able to get it to run with CSV. Anybody know how?). Plus it's not in development or supported anymore.
I read somewhere that HSQLDB supports querying on CSV files, but I haven't been able to work it correctly. Here's what I've done till now:
If I create a CSV File using HSQLDB, then it's able to execute queries successfully. Here's the code for that:
String driver = "org.hsqldb.jdbcDriver";
Driver d = (Driver) Class.forName(driver).newInstance();
String protocol = "jdbc:hsqldb:file";
final String url = "jdbc:hsqldb:file:/C:/Users/varun.achar/Documents";
final StringBuilder createTable = new StringBuilder();
createTable.append("CREATE TEXT TABLE currency (");
createTable.append("id INT PRIMARY KEY, name VARCHAR)");
final StringBuilder linkTable = new StringBuilder();
linkTable.append("SET TABLE currency SOURCE ");
linkTable.append("\"/currencies.csv");
linkTable.append(";ignore_first=true;all_quoted=true\"");
Connection conn = DriverManager.getConnection(url, "sa", "");
Statement stm = conn.createStatement();
stm.execute(createTable.toString());
stm.execute(linkTable.toString());
ResultSet resultSet = stm.executeQuery("SELECT * FROM CURRENCY");
if (resultSet != null) {
while (resultSet.next()) {
System.out.println("CURRENCY = " + resultSet.getString(2));
}
}
conn.close();
But the same thing doesn't work when I delete the file and run it again! I get the error
Table already exists: CURRENCY in statement [CREATE TEXT TABLE currency]
Also, If I have a pre-existing csv file ( the formatting is correct since I was able to run a simple select statement using CsvJDBC) then I get the error
Table not found: RMS in statement [SET TABLE rms]
Code for this
final StringBuilder linkTable = new StringBuilder();
linkTable.append("SET TABLE rms SOURCE ");
linkTable.append("\"C:/myreports/temp/user/1316083232009/rms.csv");
linkTable.append(";ignore_first=true;all_quoted=true\"");
Driver d = (Driver) Class.forName(driver).newInstance();
System.out.println("Driver was successfully loaded.");
String protocol = "jdbc:hsqldb:file";
String database = "C:\\myreports\\temp\\user\\1316083232009\\rms.csv";
String url = protocol + ":" + database;
con = DriverManager.getConnection(url);
stm = con.createStatement();
stm.execute(linkTable.toString());
resultSet = stm.executeQuery(testSQLStatement());
if (resultSet != null) {
while (resultSet.next()) {
System.out.println("FULL NAME = "+ resultSet.getString("usr_FULL_NAME"));
}
}
Can somebody throw some light on this?
Thanks
A: A single HSQLDB database can have many tables, including several TEXT tables. It seems you think there must be one database per each text table, which is not the case.
The database path is not a directory. It is not a CSV file either. In your first example you should specify a database name such as this:
final String url = "jdbc:hsqldb:file:/C:/Users/varun.achar/Documents/mydb";
The same in your second example.
The database consists of a few files beginning with the names you sepcified. In this example, you will have mydb.properties, mydb.script, etc.
The CREATE TEXT TABLE ... statement creates the metadata for the table. This table metadata is persisted in the database.
The first example will then work. If you delete the CSV file, then open the database, the 'CREATE TEXT TABLE' statement is still stored in the database, therefore it complains when you attempt to create the same table again.
If you have a preexisting CVS file, you still need to start with CREATE TEXT TABLE ..., then link it with the CVS using the SET TABLE statement, the same way as the first example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: (Vibrating TextView) Configure attributes for custom views I just created class VibratingTextView. I intend to create a whole library of widgets so I want to do it the right way.
The xml for this View:
<sherif.android.textview.VibratingTextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:text="outToRight" >
</sherif.android.textview.VibratingTextView>
Notice it has android:orientation and android:text. It accepts the attributes of a TextView and of a LinearLayout. The class itself extends LinearLayout.
My problem is in the xml editor of eclipse. When the user types android:, eclipse's intellisense gives the user the options available in this namespace.
In my case, it is giving the attributes of LinearLayout so, for example, Text and TextSize do not appear.
Is there a way to make them appear (using the android namespace)?
If not, should I create my own namespace with attributes that I define? or is there a way to import the android's attributes and make them in sherif's attributes?
Keep in mind that I am creating a TextView in the constructor of my class using the attributes passed. It is working fine and all the attributes for the TextView are being set correctly.
Since I will create many other widgets, I might need my own namespace but what is the best practice? For example, I want to create alwaysVibrate attribute. It will be something like sherif:alwaysVibrate="true". I want my library to be includable and eclipse to show the attributes of my namespace: I use the usual way using attr.xml?
A: I recently faced the exact same problem. Here are my custom attribute declarations in attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="NumberPicker">
<attr name="rangeStart" format="integer|reference" />
<attr name="rangeEnd" format="integer|reference" />
<attr name="speed" format="integer|reference" />
<attr name="current" format="integer|reference" />
<attr name="android:orientation" />
</declare-styleable>
</resources>
You can reuse the android attributes but you can't teach them to suggest different values. In fact you can't even teach eclipse to suggest your custom attribute definitions (at least at this date of post, I would love to see that feature in future).
Everything else you would want to know about defining custom attributes is in the question:
Declaring a custom android UI element using XML.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Non-editable text paste target Users need to be able to paste the contents of an Excel spreadsheet into a grid in my flex application.
I have implemented this using a TextArea with a change event handler that parses the text the the user pastes - splitting it up by newlines and tabs - and adding it to the ArrayCollection that is bound to the grid.
However, it makes no sense for users to be able to manually enter text into the TextArea. How can I prevent them from doing so?
Or: would it make more sense to create my own component that implements IFocusManagerComponent?
A: [Updated]
A bit messy, please cleanup the code before use:
<fx:Script>
<![CDATA[
protected function keyDownEvent(e:KeyboardEvent):void
{
e.preventDefault();
switch(e.keyCode)
{
case Keyboard.V:
if (e.ctrlKey)
{
ta.text += "Some dummy " + "\n" +
"text pasted in this text area";
ta.text += "\n[Keyboard Used to paste]";
}
break;
default:
e.preventDefault();
}
}
protected function onCreationComplete(event:Event):void
{
ta.addEventListener(KeyboardEvent.KEY_DOWN, keyDownEvent);
}
]]>
</fx:Script>
<s:Label text="Press CTRL[V] to see the action"/>
<s:TextArea id="ta"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: initSql property and DriverManagerDataSource I configured the following DriverManagerDataSource for my junits
<bean id="myDS"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${ds.driver}"/>
<property name="url" value="${ds.url}"/>
<property name="username" value="${ds.username}"/>
<property name="password" value="${ds.password}"/>
</bean>
Now I want to add the initSql property to make the DS execute an sql command at connection creation time. I tried the following configuration but it doesn't work.
<bean id="myDS"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${ds.driver}"/>
<property name="url" value="${ds.url}"/>
<property name="username" value="${ds.username}"/>
<property name="password" value="${ds.password}"/>
<property name="connectionProperties">
<props>
<prop key="initSql">select set_limit(0.1)</prop>
</props>
</property>
</bean>
How to add the initSql property on a DriverManagerDataSource ?
A: You can take a look at DBCP basic datasource, that supports specifying a set of sqls to be executed at the time of creation of connections.
The DriverManagerDatasource is not recommended to be used for deployment as it doesn't do any connection pooling. It is better to use DBCP or CP30.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL Trigger deleting from multiple tables I have 2 tables with relation in between. table one is holding groups with groupid. table 2 is holding the relation between the 2 groups.
table 1
GroupId, Name, Description, .......
table 2
MasterGroupId, SubGroupId, sequenceNumber
When preforming a deletion of a group out of table 1 all of the related groups has to be deleted to.
this includes the subgroups under the group and there subgroups recursive.
example of the data in both tables before delete
Table Tbl_TemplateListGroup
GroupId |Name |Description |TemplateListId
100 | Group 1 | NULL | 6
101 | Group 2 | NULL | 6
102 | Group 11 | NULL | 6
103 | Group 12 | NULL | 6
104 | Group 13 | NULL | 6
105 | Group 131 | NULL | 6
106 | Group 1311 | NULL | 6
107 | Group111 | NULL | 6
Table Tbl_TemplateListGroupGroup
Master | Sub SequenceNumber
Group | Group
Id | Id
100 | 102 | 1
100 | 103 | 2
100 | 104 | 3
102 | 107 | 1
104 | 105 | 1
105 | 106 | 1
example of data after delete
Table Tbl_TemplateListGroup
GroupId |Name |Description |TemplateListId
100 |Group 1 | |6
101 |Group 2 | |6
102 |Group 11 | |6
103 |Group 12 | |6
107 |Group111 | |6
Tabel Tbl_TemplateListGroupGroup
Master Sub SequenceNumber
Group Group
Id Id
100 |102 |1
100 |103 |2
102 |107 |1
the delete statement
delete from tbl_TemplateListGroup where GroupId = 104
The trigger is now :
CREATE TRIGGER TR_TemplateListGroupDelGroup
on Tbl_TemplateListGroup
INSTEAD OF DELETE
AS
BEGIN
SET NOCOUNT ON;
BEGIN
SELECT GroupId INTO tmpTbl FROM Tbl_TemplateListGroup
WHERE GroupId in (SELECT SubGroupId FROM Tbl_TemplateListGroupGroup
WHERE MasterGroupId in ( select d.GroupId from deleted d ))
DELETE FROM Tbl_TemplateListGroupGroup
WHERE SubGroupId in ( select d.GroupId from deleted d )
DELETE FROM Tbl_TemplateListGroupGroup
WHERE MasterGroupId in ( select d.GroupId from deleted d )
DELETE FROM Tbl_TemplateListGroup
WHERE GroupId in ( select d.GroupId from deleted d )
DELETE FROM Tbl_TemplateListGroup
WHERE GroupId in (select GroupId FROM tmpTbl)
DROP TABLE tmpTbl;
END
END
this is not working for 2 reasons
*
*The user has no create table rights so he can't create a temp table. ( is there an other way to get that data).
*I think that the group with groupid 105 is restricting the delete because the trigger was working (in sa mode) before I have added that item with its relation.
For now I delete both tables and fill them again with the correct data. I would like to solve that in the DB.
A: Unfortunately, because there are two tables involved, a temp table will still be required. Something like:
CREATE TABLE #GroupIDs (ID int)
;WITH Closure AS (
SELECT GroupId from deleted
UNION ALL
SELECT SubGroupId from Tbl_TemplateListGroupGroup lgg inner join Closure c on lgg.MasterGroupId = c.GroupId
)
INSERT INTO #GroupIDs (ID) SELECT GroupID from Closure
DELETE FROM Tbl_TemplateListGroupGroup where MasterGroupID in (select ID from #GroupIDs)
DELETE FROM Tbl_TemplateListGroup where GroupID in (select ID from #GroupsIDs)
This uses a Recursive Common Table Expression to compute the closure over the subgroup table. These are available from SQL Server 2005 onwards.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Does calling a delegate defined with a signature (e.g.) Func type excecute synchronously in ASP.NET? On first examination it appears that it does. A quick examination of the call stack shows that the method passed to the delegate is executed as one would expect. However....
In calling the delegate in a "click event" and trying to modify controls (e.g. visibility, binding, updating update panels) nothing happens (In fact for an explicit call to an UpdatePanel.Update an exception is thrown saying that the method can not be called after Render - for all intents and purposes though, Im perceivably NOT at that stage in the page lifecycle, but rather in a control event - invariably handled as a postback event, always before Render, to my best knowledge.).
However... When returning to the call site and executing the same code (just after the delegate call) that I tried to execute (from within the method called by the delegate) to affect changes on various controls, it works.
What could be going on?
EDIT
Framework code:
IModalWorkflowItem
{
void ExecuteWorkflow();
.....
}
public abstract class BaseModalWorkflow : IModalWorkflowItem
{
....
protected Func<String, IMinervaValidator , Boolean>_action;
....
/// <summary>
/// Using the properties (if necessary) perform the action
/// required on completion of modal workflow
/// </summary>
/// <returns></returns>;
protected abstract Boolean PerformAction(PropertyBag properties);
}
Creation of object passing in lambda as anonymous method...
new ModalWorkflowUserGroupAction(ModalPopupExtender_UserPrompt,
Session,
(x, y) =>
{
if (UserGroupManager.UserAccessToUserGroup(membershipID,
CurrentUserGroup.UserGroupID, false))
{
BindUserList();
Actual call:
/// <summary>
/// Call the next action in the modal workflow.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void ExpandingButton_ModalConfirmContinue_Click
(Object sender, EventArgs e)
{
if (CurrentModalWorkFlowItem != null)
{
CurrentModalWorkFlowItem.ExecuteWorkflow();
A: Yes, calling any delegate occurs synchronously, in any .NET program type. This sort of thing doesn't suddenly change just because you happen to be using ASP.NET.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to solve this PHP Ajax Arabic Characters Encoding issue? I develop a web site using PHP and I connect to Sybase database using PHP ODBC functions.
There is a web page related to the Customers in order to input their data to confirm a service provided in the web site.
I use Ajax to get the Customer Data from the database in case that the customer enters an ID that exists in the database as I do the query to get his data like Number,Name,Mobile,Email and I concatenate these data so that I make it one string using a seperator character like * then I divide the string using substr() function in the Javascript file when Ajax is operated and the result is returned. I assign the values returned to the text boxes displayed in the web page.
This scenario goes perfect even some data is missed in the customer record being sent.
My problem is that the database has two languages for the text stored in it : English and Arabic.
It goes perfect with English but when the customer data is Arabic, the Javascript acts as there is no data at all or it encodes it to strange characters that could not be read.
How I can solve that as I checked all matters related to the langauage and character encoding and using UTF-8 and Windows-1256 and also using the encoding conversion functions in PHP and Javascript Files and making sure of the file encoding itself.
Generally I use Windows-1256 to display the Arabic well in my php web pages as if I use UTF-8 the Arabic dynamic data coming from the database could not be displayed well but the Arabic static data written directly in the web page are ok.
Any help is appreciated and thanks in advance .....
A: Well,
First: Add by the beginning of HTML page
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
second:
if you are using AJAX encode data using encodeURIComponent
Third:
First line of your PHP page should be
header('Content-Type: text/html; charset=utf-8');
and decode the data sent to PHP using urldecode
also,if you are using oracle as DB use, the following connection string: $connect=oci_connect($UserName,$Password,$db_name,'AL32UTF8')
Regards,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I swap a jndi datasource lookup to an in memory database for intergration testing? I'm using Spring and Hibernate and want to do some intergration testing with DBUnit. In my application-context.xml I currently specify a datasource via jndi-lookup which reads the jndi-name from a properties file:
<jee:jndi-lookup id="dataSource"
jndi-name="${datasource.myapp.jndi}"
cache="true"
resource-ref="true"
proxy-interface="javax.sql.DataSource" />
I'd like to swap this out to an in memory database (hsqldb, h2 etc) for integration testing by just supplying a new properties file, is this possible? Or should I just use a different application-context.xml for the integration testing?
A: You can either have separate application contexts for prod and test or specify a default data source for the JNDI data source that should be used if the lookup fails. Then don't have a JNDI data source configured on your integration test environment. Spring will automatically fail over to the in-memory source when the lookup fails.
A: This is why Spring 3.1 introduced profiles: http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/
Upgrade application to 3.1 or use different configs for integrations tests.
A: Move the datasource bean definition to a separate config file (infrastructure-config.xml), create another version of it called test-infrastructure-config.xml in which you can define a datasource either using the jdbc:embedded-database tag
<jdbc:embedded-database type="hsql">
<!-- in case you want to populate database, list the sql script files here -->
<jdbc:script location=".."/>
<jdbc:script location=".."/>
</jdbc:embedded-database>
Once you do this you specify the main application-context.xml and test-infrastructure-config.xml for out of conatiner testing and with the infrastructure-config.xml for deployment.
A: Use a @Bean to define your datasource. In that method you can use conditional logic to determine the environment and either do the JNDI lookup or connect to your in-memory DB.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Pass Arguments to Timertask Run Method I have a method and I want it to be scheduled for execution in later times. The scheduling time and method's arguments depend on user inputs.
I already have tried Timers, but I have a question.
How could It be possible to pass arguments to Java TimerTask run method ?
TimerTask timert = new TimerTask()
{
@Override
public void run()
{
//do something
}
}
A: You will need to extend the TimerTask and create a constructor and/or setter fields.. Then set the values you want before scheduling the TimerTask for execution.
A: You can write you own class which extends from TimerTask class and you can override run method.
class MyTimerTask extends TimerTask {
String param;
public MyTimerTask(String param) {
this.param = param;
}
@Override
public void run() {
// You can do anything you want with param
}
}
A: It's not possible to change the signature of the run() method.
However, you may create a subclass of TimerTask and give it some kind of initialize-method. Then you can call the new method with the arguments you want, save them as fields in your subclass and then reference those initialized fields in the run()-method:
abstract class MyTimerTask extends TimerTask
{
protected String myArg = null;
public void init(String arg)
{
myArg = arg;
}
}
...
MyTimerTask timert = new MyTimerTask()
{
@Override
public void run()
{
//do something
System.out.println(myArg);
}
}
...
timert.init("Hello World!");
new Thread(timert).start();
Make sure to set the fields' visibilities to protected, because private fields are not visible to (anonymous) subclasses of MyTimerTask. And don't forget to check if your fields have been initialized in the run() method.
A: The only way to do this is to create your own class that extends TimerTask and pass arguments to its constructor or call its setters. So, the task will "know" its arguments from the moment of its creation.
Moreover if it provides setters you can modify the task configuration even later, after the task has been already scheduled.
A: class thr extends TimerTask{
@Override
public void run(){
System.out.println("task executed task executed .........." );
}
class service {
private Timer t;
public void start(int delay){
Timer timer=new Timer();
thr task =new thr();
timer.schedule(task, delay);
this.t=timer;
}
public void stop(){
System.out.println("Cancelling the task scheduller ");
this.t.cancel();
}
}
public class task1 {
public static void main(String[] args) {
service sv=new service();
sv.start(1000);
System.out.println("This will check the asynchronous behaviour ");
System.out.println("This will check the asynchronous behaviour ");
System.out.println("This will check the asynchronous behaviour ");
System.out.println("This will check the asynchronous behaviour ");
System.out.println("This will check the asynchronous behaviour ");
sv.stop();
}
}
the code above works fine to schedule and reschedule the task you can set and reset the task with a timer function
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Simple way for removing all non word characters I'd like to remove all characters from string, using most simple way.
For example
from "a,sd3 31ds" to "asdds"
I cad do it something like this:
"a,sd3 31ds".gsub(/\W/, "").gsub(/\d/,"")
# => "asdds"
but it looks a little bit awkward. Maybe it is possible to merge these rexegs in one?
A: You can do this with the regex "OR".
"205h2n0bn r0".gsub(/\W|\d/, "")
will do the trick :)
A: What about
"a,sd3 31ds".gsub(/\W|\d/,"")
You can always join regular expressions by | to express an "or".
A: You can try this regex:
\P{L}
not Unicode letter, but I don't know, does Ruby support this class.
A: A non regex solution:
"a,sd3 31ds".delete('^A-Za-z')
A: "a,sd3 31ds".gsub(/(\W|\d)/, "")
A: I would go for the regexp /[\W\d]+/. It is potentially faster than e.g. /(\W|\d)/.
require 'benchmark'
N = 500_000
Regexps = [ "(\\W|\\d)", "(\\W|\\d)+", "(?:\\W|\\d)", "(?:\\W|\\d)+",
"\\W|\\d", "[\\W\\d]", "[\\W\\d]+" ]
Benchmark.bm(15) do |x|
Regexps.each do | re_str |
re = Regexp.new(re_str)
x.report("/#{re_str}/:") { N.times { "a,sd3 31ds".gsub(re, "") }}
end
end
gives (with ruby 2.0.0p195 [x64-mingw32])
user system total real
/(\W|\d)/: 1.950000 0.000000 1.950000 ( 1.951437)
/(\W|\d)+/: 1.794000 0.000000 1.794000 ( 1.787569)
/(?:\W|\d)/: 1.857000 0.000000 1.857000 ( 1.855515)
/(?:\W|\d)+/: 1.638000 0.000000 1.638000 ( 1.626698)
/\W|\d/: 1.856000 0.000000 1.856000 ( 1.865506)
/[\W\d]/: 1.732000 0.000000 1.732000 ( 1.754596)
/[\W\d]+/: 1.622000 0.000000 1.622000 ( 1.617705)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: jsTree do ajax request for every parent expanding i'm using jsTree with json as the datasource from the server.
Why the jsTree do ajax request on every click on a node and even if the node doesn't have children the node is getting filled with children from the server(it takes the root data!).
How can I prevent that behavior?
A: script:
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$(function () {
$("#treeview").jstree({
"json_data": {
"ajax": {
"url": "/Tree/Tree"
}
},
"plugins": ["themes", "json_data"]
});
});
});
</script>
server side:
public class TreeController : Controller
{
//
// GET: /Tree/
public ActionResult Tree()
{
return Json(new jsTreeModel
{
data = "Parent",
att = new JsTreeAttribute { id = 1 },
state = "closed",
children = new List<jsTreeModel> { new jsTreeModel { data = "Child", att = new JsTreeAttribute { id = 1 }, state = "closed" } }
}, JsonRequestBehavior.AllowGet);
}
}
public class jsTreeModel
{
public string data { get; set; }
public JsTreeAttribute att { get; set; }
public string state { get; set; }
public List<jsTreeModel> children { get; set; }
}
public class JsTreeAttribute
{
public int id { get; set; }
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SpecFlow, Webdriver and Mocks - is it possible? The question in short is that we are stumbling upon BDD definitions that more or less require different states - which leads to the necessity for a mock of sorts for ASP.NET/MVC - I know of none, which is why I ask here
Details:
We are developing a project in ASP.NET (MVC3/Razor engine) and are using SpecFlow to drive our development.
We quite often stumble into situations where we need the webpage under test to perform in a certain manner so that we can verify the behavior, i.e:
Scenario: Should render alternatively when backend system is down
Given that the backend system is down
And there are no channels for the page to display
When I inspect the webpage under test
Then the page renderes an alternative html indicating that there is a problem
For a unit test, this is less of an issue - run mock on the controller bit, and verify that it delivers the correct results, however, for a SpecFlow test, this is more or less requiring alternate configurations.
So it is possible at all, or - are there some known software patterns for developing webpages using BDD that I've missed?
A: Even when using SpecFlow, you can still use a mocking framework. What I would do is use the [BeforeScenario] attribute to set up the mocks for the test e.g.
[BeforeScenario]
public void BeforeShouldRenderAlternatively()
{
// Do mock setups.
}
This SO question might come in handy for you also.
A: You could use Deleporter
Deleporter is a little .NET library that teleports arbitrary delegates into an ASP.NET application in some other process (e.g., hosted in IIS) and runs them there.
It lets you delve into a remote ASP.NET application’s internals without any special cooperation from the remote app, and then you can do any of the following:
*
*Cross-process mocking, by combining it with any mocking tool. For example, you could inject a temporary mock database or simulate the passing of time (e.g., if your integration tests want to specify what happens after 30 days or whatever)
*Test different configurations, by writing to static properties in the remote ASP.NET appdomain or using the ConfigurationManager API to edit its entries.
*Run teardown or cleanup logic such as flushing caches. For example, recently I needed to restore a SQL database to a known state after each test in the suite. The trouble was that ASP.NET connection pool was still holding open connections on the old database, causing connection errors. I resolved this easily by using Deleporter to issue a SqlConnection.ClearAllPools() command in the remote appdomain – the ASP.NET app under test didn’t need to know anything about it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What does the below comparison means? Could any one explain why NOVALIDATE is written their and why alpha betwnn two ":" and "[]"
ALTER TABLE CUSTOMERS
ADD CONSTRAINT cust_f_name
CHECK(REGEXP_LIKE(cust_first_name,'[[:alpha:]]'))NOVALIDATE ;
and what does
REGEXP_LIKE(cust_first_name,'^[0-9]')
and
REGEXP_LIKE(cust_first_name,'^A-Z')
means ? is that numbers not allowed?
A: These are regular expressions, used in Oracle as a table constraint.
*
*[:alpha:] matches any character from the alpha POSIX class; that is, alphabetic characters (a-z and A-Z).
*The ^, in the context of ^[0-9], means look from the beginning of the string. [0-9] is the class of numbers (i.e., 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9)
*^A-Z means negate the class A-Z; so it would match anything that didn't contain an upper case alphabetic character.
NOVALIDATE means that, once the constraint is added to the table CUSTOMERS, Oracle will not check that any current entries violate the constraint and only apply it to newly inserted records.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Run Time Error (exit status 1) when submitting puzzle in Python I have python 2.7 installed on my windows computer. I'm trying to email a puzzle answer to Spotify, which is running Python 2.6.6. When I submit my *.py source code, I'm getting the following error:
Run Time Error
Exited, exit status: 1
I only have "import sys". I've run tons of stress tests - possible inputs are 1 ≤ m ≤ 10 000 lines, I've tested with 1 million+ values with zero problems. I've tried printing with print & sys.stdout.write.
When I send in dummie test code (I run my full algorithm but only print garbage instead of my answer - ie, print "test!"), I get the expected "Wrong Answer" back.
I have no idea where to start debugging - any tips/help at all?
Thanks!
-Sam
A: I got the same error. As I see it's not python output but just an answer from spotify bot that your program threw an exception in some tests. Maybe the real output isn't shown to prevent debugging using the bot.
When you print dummy data fist test fails and you get 'Wrong Answer'.
When you print real output first test may pass but next throw an exception and you get 'Run Time Error'.
I fixed one defect with possible exception in my script and Run Time Error went away.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Diazo add unwanted html header into json response I have a blank Plone 4.1 site with only collective.quickupload installed. The upload portlet worked fine until I install plone.app.theming and apply my theme. The files were still uploaded, but the web client got "Failed" status.
Inspecting the ajax response from server I found that they were wrapped by html header.
The old response (before install diazo & apply my theme) was simply
{"success":true}
The new response (after install diazo and apply my theme) was being wrapped by a html tag:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"><body><p>{"success":true}</p></body></html>
I've pasted my rule.xml file here (nothing special, there is only one rule conditioned by css:if-content="#visual-portal-wrapper"): http://pastebin.com/SaK13Fni
What should I do to work around this ?
Thanks
A: To avoid this behavior you have to add an exception in your rules.xml that specify to not apply your theme to your specific view , like this:
<notheme if-path="myjson_view"/>
edit:
I've tried with one of my diazo themes and a json view and I didn't have your issue. So I think the problem is either in your rules.xml or in your json view. You should try one of these two way:
*
*change your rules.xml this way:
<rules
xmlns="http://namespaces.plone.org/diazo"
xmlns:css="http://namespaces.plone.org/diazo/css"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- Prevent theme usage in zmi-->
<rules css:if-content="#visual-portal-wrapper">
<theme href="index.html" />
</rules>
*have you already specified the "Content-type" of the output in
your json view? Like this:
self.request.response.setHeader("Content-type","application/json")
return json_data
If not, that's probably the problem.
A: Watch out for using Chrome inspector... it adds the html head and pre tags around your json when you inspect it...it's not actually there if you look at view:source of the page (old school)...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: how to add jde components plugin in an eclipse I need to add jde component plugin in an blackberry eclipse.I have already used the following link in my eclipse:
http://www.blackberry.com/go/eclipseUpdate/3.5/java
But am getting the error as:
'installing software' has encountered a problem.An error occurred while collecting items to be installed.
Please tell me the solution.
A: That happened with me so many times that I stopped using that update site. Instead, try downloading the component package directly from:
http://us.blackberry.com/developers/javaappdev/javadevenv.jsp
A: The answer may be simple: Perhaps Windows installs it's updates (and only one installation process can be run at one time), or some other installations or processes may interrupting you.
Try just restart you system and retry your installation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem while creating a Left function in PostgreSQL I am trying to create a Left function in PostgreSQL as under
CREATE OR REPLACE FUNCTION LEFT(text, integer) RETURNS text
AS 'SELECT SUBSTR($1,$2);'
LANGUAGE SQL IMMUTABLE;
It got compiled fine. Now when I am invoking it as under
select LEFT(',a,b,c',2)
I am getting the output as ,a
when the expected output is a,b,c
If I run SELECT SUBSTR(',a,b,c' , 2) it works as expected .
Please help me out in identifying the mistake
Thanks
A: LEFT function already exists in pg_catalog. So try a different function name or run
SELECT public.LEFT(',a,b,c' , 2)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mouseover not working in ie6 I am using below code to call a div on hover,it is working fine on ie7+,ff and chrome, but not in ie6.
<div class="business-bottom-content" onMouseOver="javascript:this.className='business-bottom-content-hover';" onMouseOut="javascript:this.className='business-bottom-content'">
A: I'm not sure if it applies to onMouseOver as well, but :hover in CSS only works for a elements in IE6.
As for what you are trying to do, I would also recommend using :hover in CSS instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Viewing typedef replacement Can anyone tell me, how can I see the typedef replacement string.
Actually we could see the preprocessor replacement using cc -E filename.c . So like that I want to see the typedef replacement.
A: This (and also the -E) depends on the compiler you are using.
That said, I doubt this is possible with any compiler. Contrary to macros, typedefs are not just text replacements.
Please note also that the output of a potential typedef expanding program is not necessarily valid C code, e.g. instances the same struct will become incompatible.
A: typedefs are not macros.
-E is a preprocessor stage in compilation and you will be able to see only MACRO replacements.
#define A int *
typedef int *B;
Now this means wherever 'A' appears, it will be replaced by 'int *' - plain string replacement
However B is synonymous to saying 'int *'
So when I type :
A c, d;
B e, f;
The -E stage will show you that the following replacement has taken place :
int *c, d;
B e, f;
So :
c is of type 'int *'
d is of type 'int'
e is of type B (synonymous to saying e is of type 'int *')
f is of type B (synonymous to saying f is of type 'int *')
HTH
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Resque with Redis To Go can't work as expectation I need to use Resque to enqueue my jobs on Heroku.
As it's my first time to use it, I follow the instruction on this site:Resque with Redis To Go.
When I run the command:
$ rake resque:work QUEUE=*
the terminal shows:
rake aborted!
Please install the yajl-ruby or json gem
(See full trace by running task with --trace)
I had installed both yajl-ruby and json gem after I got the error; however, it didn't work.
If I ignore the problem and enter "rails s" to start the server.
It shows:
/Library/Ruby/Gems/1.8/gems/resque-1.19.0/lib/resque/helpers.rb:6: Please install the yajl-ruby or json gem (RuntimeError)
from /Library/Ruby/Gems/1.8/gems/resque-1.19.0/lib/resque.rb:10:in `require'
from /Library/Ruby/Gems/1.8/gems/resque-1.19.0/lib/resque.rb:10
from /Library/Ruby/Gems/1.8/gems/bundler-1.0.18/lib/bundler/runtime.rb:68:in `require'
from /Library/Ruby/Gems/1.8/gems/bundler-1.0.18/lib/bundler/runtime.rb:68:in `require'
from /Library/Ruby/Gems/1.8/gems/bundler-1.0.18/lib/bundler/runtime.rb:66:in `each'
from /Library/Ruby/Gems/1.8/gems/bundler-1.0.18/lib/bundler/runtime.rb:66:in `require'
from /Library/Ruby/Gems/1.8/gems/bundler-1.0.18/lib/bundler/runtime.rb:55:in `each'
from /Library/Ruby/Gems/1.8/gems/bundler-1.0.18/lib/bundler/runtime.rb:55:in `require'
from /Library/Ruby/Gems/1.8/gems/bundler-1.0.18/lib/bundler.rb:120:in `require'
from /Users/Brian/Documents/cookie-monster/config/application.rb:7
from /Library/Ruby/Gems/1.8/gems/railties-3.0.5/lib/rails/commands.rb:28:in `require'
from /Library/Ruby/Gems/1.8/gems/railties-3.0.5/lib/rails/commands.rb:28
from /Library/Ruby/Gems/1.8/gems/railties-3.0.5/lib/rails/commands.rb:27:in `tap'
from /Library/Ruby/Gems/1.8/gems/railties-3.0.5/lib/rails/commands.rb:27
from script/rails:6:in `require'
from script/rails:6
I guess it's a problem of my environment, but I don't know how to solve it.
Please help me, thanks!!
mikhailov ask me to paste my Gemfile and Gemfile.lock.
Here it is:
Gemfile:
source 'http://rubygems.org'
gem 'rails', '3.0.5'
gem 'sqlite3-ruby', :require => 'sqlite3'
gem 'redis'
gem 'SystemTimer'
Gemfile.lock:
GEM
remote: http://rubygems.org/
specs:
abstract (1.0.0)
actionmailer (3.0.5)
actionpack (= 3.0.5)
mail (~> 2.2.15)
actionpack (3.0.5)
activemodel (= 3.0.5)
activesupport (= 3.0.5)
builder (~> 2.1.2)
erubis (~> 2.6.6)
i18n (~> 0.4)
rack (~> 1.2.1)
rack-mount (~> 0.6.13)
rack-test (~> 0.5.7)
tzinfo (~> 0.3.23)
activemodel (3.0.5)
activesupport (= 3.0.5)
builder (~> 2.1.2)
i18n (~> 0.4)
activerecord (3.0.5)
activemodel (= 3.0.5)
activesupport (= 3.0.5)
arel (~> 2.0.2)
tzinfo (~> 0.3.23)
activeresource (3.0.5)
activemodel (= 3.0.5)
activesupport (= 3.0.5)
activesupport (3.0.5)
arel (2.0.9)
builder (2.1.2)
erubis (2.6.6)
abstract (>= 1.0.0)
i18n (0.5.0)
mail (2.2.15)
activesupport (>= 2.3.6)
i18n (>= 0.4.0)
mime-types (~> 1.16)
treetop (~> 1.4.8)
mime-types (1.16)
polyglot (0.3.1)
rack (1.2.2)
rack-mount (0.6.14)
rack (>= 1.0.0)
rack-test (0.5.7)
rack (>= 1.0)
rails (3.0.5)
actionmailer (= 3.0.5)
actionpack (= 3.0.5)
activerecord (= 3.0.5)
activeresource (= 3.0.5)
activesupport (= 3.0.5)
bundler (~> 1.0)
railties (= 3.0.5)
railties (3.0.5)
actionpack (= 3.0.5)
activesupport (= 3.0.5)
rake (>= 0.8.7)
thor (~> 0.14.4)
rake (0.9.2)
redis (2.2.2)
sqlite3-ruby (1.2.4)
thor (0.14.6)
treetop (1.4.9)
polyglot (>= 0.3.1)
tzinfo (0.3.25)
PLATFORMS
ruby
DEPENDENCIES
rails (= 3.0.5)
redis
sqlite3-ruby
A: You still should use/try:
bundle exec rake resque:work QUEUE=*
A: Resque has dependence on 'json' gem, so just add it into Gemfile:
gem 'json'
then Bundler pick the appropriate version to resolve dependencies
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to output warnings to the console during a build in Xcode? How do I output custom warnings to the console in Xcode? I want to do this to remind myself that I'm in a particular build mode.
I tried #warning "Hello World" but I don't see it in the console.
Any suggestions?
Edit:
I don't want to use NSLog because I am already using it to log a bunch of stuff so when I use NSLog for warnings, it is difficult to see all the warnings.
A: #warning directive
The #warning directive is to see the message on the compiler. This is very handy to know that something must be changed before deploying or simply to remember to change a piece of code that can be improved (but you don't have the time to do so now). (go to View -> Navigators -> Show Issue Navigator on your project and you will the see the list of warnings). These messages will not appear on the console.
The Apple System Log facility
What you want is to show a warning to the console while the app is running and here is where The Apple System Log facility comes to the rescue.
You have 8 logging levels:
*
*0 Emergency.
*1 Alert
*2 Critical
*3 Error
*4 Warning
*5 Notice
*6 Info
*7 Debug
Code sample:
#include <asl.h>
...
asl_log(NULL, NULL, ASL_LEVEL_INFO, "Hello World!");
Since I was in the same situation than you once, and to make things simple, I use this wrapper https://github.com/MikeWeller/MWLogging in all my projects so my debug errors won't show when I send my App to the App Store but other critical error will.
Update: Now with Swift I use this debug log framework https://github.com/DaveWoodCom/XCGLogger
A: You can use NSLog
In state of your warning use something like:
NSLog(@"Hello World");
Or you can use the standard C printf function:
printf("Hello World");
If you want to be printed on stderr you can use fprintf redirected to stderr.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CSS Border redundancy removal I often find myself into this:
.class {
border-top:1px dashed #0000000;
border-bottom:1px dashed #0000000;
}
Is there a way to one-line that?
I tried this but doenst' work:
.class {
border:1px 0 dashed #0000000;
}
A: No but you could make it simpler to maintain by using:
.my_class {
border: 1px dashed #000;
border-right: none;
border-left: none;
}
That what you only need to change one line.
A: You can use properties for every "side" (top, right, bottom, left) for each single border property, in your case:
.class{
border-color: #000;
border-width: 1px 0;
border-style: dashed;
}
Note that you can specify every property for every side, for example:
.class{
border-color: #000 green blue yellow;
border-width: 1px 2px 3px 4px;
border-style: dashed solid dotted solid;
}
A: Nope, there's no one-liner for that in pure CSS - you can use the border shorthand only for all four sides at once.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a way to pass template arguments to a function on an object when the object type is a template argument? To illustrate:
struct MyFunc {
template <size_t N>
void doIt() {
cout << N << endl;
}
};
template <typename Func>
struct Pass123ToTemplateFunc {
static void pass(Func f) {
f.doIt<123>(); // <-- Error on compile; is there a way to express this?
}
};
int main() {
Pass123ToTemplateFunc<MyFunc>::pass(MyFunc());
return 0;
}
This is pretty much purely a syntax curiosity; is there a way in the language to express this without passing arguments to the doIt function itself? If not, it's no big deal and I'm already well aware of ways I can gracefully work around it, so no need to provide alternative solutions. (I'll accept "no" as an answer, in other words, if that's the truth. :-P)
A: You have to tell the compiler that doIt will be a template:
f.template doIt<123>();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Is c lib a static in c++ program? I have a c lib, algo.lib, which I need to call in my c++ program. I realise that the variables in algo.lib is static, which creates problem for my c++ program, when I call algo.lib multiple times, or use threads to call algo.lib concurrently.
For example, in algo.lib, there is a int a which is initiall set to 0. When I call algo.lib the first time, a will be set to 1000. But when I call algo.lib another time, I want the variables in algo.lib to be in the initial state, that is, a = 0 and not a = 1000.
Is it possible to make algo.lib to become object-oriented, so that when I call its function, it is created as an object and is set to its initial state? And after finish running algo.lib, this object is destroyed?
A: Yes, it is possible. If you rewrite it. If you only have the binary - then you cannot change this behavior. You can solve it by creating a separate executable that will do what you want with it and then exit, and pass the results back to the main program through some IPC. Basically - wrap it with your own implementation that will effectively initialize the library for each separate call.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Custom list adapter for ListView or ListFragments How can we define Custom ListAdapter(like ArrayAdapter or IconicAdapter) for ListView in activity? How can we do the same for ListFragments? any example or links will be appreciated.Thanks.
A: A ListFragment holds a ListView, so there is really no difference. You just call getListView() to get a reference and then you can set an adapter as usual.
A: In my ListFragment onActivityCreated I set the adapter and notify.
The adapter is custom, which inflates a customview. The contents of the text view never show up.
public class MyAdapter extends BaseAdapter {
String[] items;
public MyAdapter(String[] url) {
items = url;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getActivity()).inflate(
R.layout.itemwithimage, null);
}
TextView txt = (TextView) convertView
.findViewById(R.id.listtextView);
txt.setText(items[position]);
Log.d(TAG, "string " + items[position]);
return convertView;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public Object getItem(int position) {
return items[position];
}
@Override
public int getCount() {
if (items == null)
return 0;
return items.length;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Restoring an extracted sub-matrix after necessary modification into the original matrix from which it is extracted using Matlab I have a huge 2D matrix.
After extracting as many as possible sub-matrices of size 8*8 from this 2D matrix, i made certain necessary modifications in the sub-matrices.
Now i want to re-constitute the original 2D matrix by replacing the extracted sub-matrices with the corresponding new modified sub-matrices.
The positions of each of the elements in both the extracted sub matrix as well as the corresponding new modified sub matrix should be the same in the original 2D matrix.
How can i do this using Matlab?
Thank you.
A: % let's generate a big 100x100 matrix
big_matrix = rand(100, 100);
% the indices of an exemplary small matrix
sm_x = 20:27;
sm_y = 20:27
% the small matrix
small_matrix = big_matrix(sm_x:sm_y);
% let's modify the small matrix - replace this line with your own code
small_matrix(small_matrix > 0.5) = 1;
% let's write the modified small matrix back to the original position
big_matrix(sm_x:sm_y) = small_matrix;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: What was the anticipated use of the reserved parameter on CoInitialize Its been about 16 years now since it was created and I still don't know why there was a reserved parameter in the CoInitialize method. Does anyone know (or is able to make an intelligent guess about) why this parameter was added and what the anticipated use was?
A: This is actually not for future use, but for backward compatibility. Read: Why was the ability to specify an allocator during CoInitialize removed from the system? by @Larry Osterman, who actually hangs around here occasionally...
In short: that argument used to allow you to specify a custom allocator. But since that feature has been misused, it was deprecated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android NDK - connect() blocks system I'm facing a wierd problem something can not explain ;)
now i'm developing client program working on the android phone.
this app connects remote server and does something.
core library which's made in C++ (NDK) and Android UI works fine when using WIFI mode
but system freezes when 3G data mode.
i got where this freezing causes, it was in connect() function.
the wierd thing is socket is already set NON-BLOCK mode before connect() line.
m_nSock = socket(AF_INET, SOCK_STREAM, 0);
if (m_nSock <= 0)
{
close(m_nSock);
return -1;
}
flags = fcntl(m_nSock, F_GETFL, 0);
fcntl(m_nSock, F_SETFL, flags | O_NONBLOCK);
struct sockaddr_in AddrClient;
memset(&AddrClient, 0x00, sizeof(AddrClient));
AddrClient.sin_family = AF_INET;
AddrClient.sin_addr.s_addr = inet_addr(szIP);
AddrClient.sin_port = htons(nPort);
nRet = connect(m_nSock, (struct sockaddr*)&AddrClient, sizeof(AddrClient));
blocking takes always about 21 seconds. (it may show default time is used somewhere in the kernel, i think.) how can i fix this? what should i search for?
any suggestion is welcome.
thanks in advance.
A: Try these changes:
put socket to non-blocking mode:
dword mode = 1;
ioctl(socket, FIONBIO, &mode);
back to blocking mode:
mode = 0;
ioctl(socket, FIONBIO, &mode);
This is how it works for me to set blocking mode
A: Your blocking code doesn't look right - you should be using F_SETFL as the command to set the flags. So:
int flags = fcntl(sock, F_GETFL);
fcntl(sock, F_SETFL, flags | O_NONBLOCK);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Multiples threads in FTP download: give each its own connection Vs. have them share one connection In an application that downloads several files from an FTP server, it uses threads, ie. 5, to do its deed, and each one has its own connection (Apache Commons FTPClient.connect(url)).
Will it be the same if the connection is shared instead? Is the ability to download files simultaneously be affected? Does the number of connections also dictate how well the app can maximize bandwidth (like maybe because an FTP server configure a bandwidth limit per connection it accepts, if there is such a thing)?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Calculating and correcting bit errors using Hidden Markov Model in C++ I am a student and new to C++. It would be great if somebody could help me write a program. Here is what it is suppose to do;
1- generates a Pseudo Random Bit Sequence (PN9 or PN15) 9 or 15 bit length.
2- saves the bit sequence from step 1 into a bit array/buffer and displays the array.
3- calculates the transition probabilities for
1. 0 --> 0
2. 0 --> 1
3. 1 --> 0
4. 1 --> 1
4- asks the user to input a bit sequence
5- introduces some noise.. i.e. flips some of the input bits
6- calculates and corrects the BIT errors based on the transition probabilities calculated in step-3
can any body guide or share his work with me on this?
A: You'll probably find many of the functions in the GNU Scientific Library (GSL) useful for your work. Apart from that, you'll have to do some work and then ask a specific question to get guidance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ignored retain property in Class method i've a Class method like this:
+(CCScene *) sceneWithMovie:(NSString*)movieName level:(NSString*)levelName hudLevel:(NSString*)hudName
{
bbsScene* scene = (bbsScene*)[super sceneWithMovie:movieName level:levelName];
ScenePage* hudLayer = (ScenePage*)scene.layer;
UTLOG(@"---> %p RETAIN COUNT: %d",hudLayer.hudLoader,[hudLayer.hudLoader retainCount]);
TouchLevelHelperLoader* loader = [[TouchLevelHelperLoader alloc]initWithContentOfFile:hudName];
hudLayer.hudLoader = loader;
UTLOG(@"---> %p RETAIN COUNT: %d",hudLayer.hudLoader,[hudLayer.hudLoader retainCount]);
[loader release];
UTLOG(@"---> %p RETAIN COUNT: %d",hudLayer.hudLoader,[hudLayer.hudLoader retainCount]);
[hudLayer.hudLoader addSpritesToLayer:hudLayer];
NSInteger sceneNumber = [[[[self class]description] stringByReplacingOccurrencesOfString:@"Scene" withString:@""]intValue];
[hudLayer loadTextPage:sceneNumber fromFile:SCENE_TEXT_FILE];
// return the scene
return scene;
}
The output is:
2011-09-22 10:53:28.477 MP NO VID[598:207] ---> 0x0 RETAIN COUNT: 0
2011-09-22 10:53:28.490 MP NO VID[598:207] ---> 0x64af820 RETAIN COUNT: 2
2011-09-22 10:53:28.491 MP NO VID[598:207] ---> 0x64af820 RETAIN COUNT: 2
When i release loader the data is lost as if i don't call hudLayer.hudLoader = loader;
Obviously i set:
@property(nonatomic,retain)TouchLevelHelperLoader* hudLoader;
Any ideas? Maybe the class mothod (+) is the problem?
A: You shouldn't rely on the retainCount property.
It is not very reliable because you never know what is done behind the scene.
For example when using Class Clusters like NSString, there are so many things that are done internally in the NSString class that retainCount can't have a real meaning for you. For some cases like NSTimers & so on, objets are also released by the RunLoop (when scheduled on this runloop) but if you don't know it, it is not trivial...
Obviously these two examples (class clusters and runloop retention) are not what you are having here, but what I'm saying here is that the retainCount property is not something that you should rely on to check if you have a leak.
Moreover, if you have the Garbage Collector activated for your project, release is a NO-OP (because that's the GC itself that will manage and release the instance)
Actually, the use of retainCount is prohibited since Xcode4 when you use ARC in your project.
To check if you have leaks in your code, use the Static Analyser ("Build & Analyse" from Xcode Build menu) and/or Instruments "Leaks" tool.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I load data conditionally using sqlldr in oracle I have a txt file as follows. 1st machine_no,2nd emp_no, 3rd shift_type (1 for entry,3 for exit), 4th work_date, 4th is time.
001,0000000021,01,2011/06/21,06:50,
001,0000000026,01,2011/06/21,14:00,
001,0000000018,01,2011/06/21,07:00,
001,0000000021,03,2011/06/21,14:00,
001,0000000018,03,2011/06/21,16:50,
001,0000000026,03,2011/06/21,16:55,
I want to load data in the table. The field time1 to have time if
time_type is 1 and the field time2 to have time if time_type is
3. Please let me know how I can have this in the control file.
Thanks in advance for your help..Macky.
Below is the txt file and table in oracle.
The table as follows:
desc data_trans;
Name Null? Type
------------------------------- -------- ----
MACHIAN VARCHAR2(4)
YEAR NUMBER(4)
MONTH VARCHAR2(2)
WDAY VARCHAR2(2)
TIME1 VARCHAR2(5)
TIME2 VARCHAR2(5)
TIME3 VARCHAR2(2)
SHIFT_NO NUMBER(1)
TIME_TYPE NUMBER(1)
WORK_DATE DATE
EMP_NO VARCHAR2(10)
A: Why don't you use an external table to read this file and then you can simply SELECT from it and perform any conditional transformation you want to easily in SQL.
N.B. There are a few assumptions, you seem to interchange "time_type" with what seems to be "shift_type" and there are table columns that are not present in your data file etc.
-- Create the Oracle directory
CREATE OR REPLACE DIRECTORY file_dir AS '<physical-server-directory-path>';
-- Grant privs on the directory
GRANT READ, WRITE ON DIRECTORY file_dir TO <username>;
-- Create the external table
CREATE TABLE ext_data_table
(machine_no VARCHAR2(4),
emp VARCHAR2(10),
shift_type VARCHAR2(2),
work_date VARCHAR2(10),
time VARCHAR2(5)
)
ORGANIZATION EXTERNAL (
DEFAULT DIRECTORY file_dir
ACCESS PARAMETERS(RECORDS DELIMITED BY NEWLINE
BADFILE file_dir :'file.bad'
LOGFILE file_dir :'file.log'
DISCARDFILE file_dir :'file.dsc'
FIELDS TERMINATED BY ','
(
machine_no CHAR(4),
emp CHAR(10),
shift_type CHAR(2),
work_date CHAR(10),
time CHAR(5)
)
LOCATION (
FILE_DIR:'<filename>'
)
)
NOPARALLEL;
-- Insert (and transform) your file data
INSERT INTO data_trans
(machian,
year,
month,
wday,
time1,
time2,
time3,
shift_no,
time_type,
work_date,
emp_no)
SELECT machine_no, -- machian
SUBSTR(work_date, 1, 4), -- year
SUBSTR(work_date, 6, 2), -- month
SUBSTR(work_date, 9, 2), -- wday
(CASE TO_NUMBER(shift_type)
WHEN 1
THEN time
ELSE NULL
END), -- time1
(CASE TO_NUMBER(shift_type)
WHEN 3
THEN time
ELSE NULL
END), -- time2
NULL, -- time3 (You don't specify)
NULL, -- shift_no (You don't specify)
TO_NUMBER(shift_type), -- time_type
TO_DATE(work_date, 'YYYY/MM/DD'), -- work_date
emp -- emp_no
FROM ext_data_table;
From the info given this is a close approximation.
Hope it helps.
A: This is not possible in SQL*Loader. Use an External Table, then copy it into your real table using the decode function to pivot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can i cast an Object in mobiaccess? I am playing around with mobiaccess framework, but i am stuck when i try to cast an Object to Integer.
Is it possible to cast in mobiaccess?
I tried to below code but it does not work:
var i:Integer = (Integer) objectClass;
A: You can use the square bracket "[]" like this:
var i:Integer = [Integer] objectClass;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: App that stays in front of other apps I need to write an app for testing purposes, which shall stay in foreground regardless which other application is currently activated. That means i need to allocate a small area of the screen that shall be usable for my app. Does somebody know a way how to achieve this?
A: Sounds like you want to to create something like statusbar. I'm not sure if you can do that without using some internal android API(for which you'd need to recompile android and build your own custom ROM).
Now you can look at what android does when it creates status bar here http://www.google.com/codesearch#uX1GffpyOZk/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarService.java check the addStatusBarView method. There some internal stuff there like WindowManagerImpl. You might be able to achieve something like this by using dialog or regular activity and using getWindow() to get its window and setFlags to mess with its flags in order to make them behave more like status bar. I'm not sure if this would give any results..
If you don't have a lot of info to display maybe it would be much easier to use notification in the status bar..
A: Look at this thread it looks like a similar problem was addressed there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how do i call function of other's open source propriotery project in my project in C Suppose you have a software written in C say XYZ. The software XYZ is an open source proprietary software.
So I can have the source of the software. I can use the software but I can not modify XYZ's files.
Suppose I am writing my own software say ABC. And that software uses some of functionalities provided by XYZ.
Now there is function in source code of XYZ say "static int get_val( int index ) ".
I want to use the function get_val(), so what should i do?
How should I call the function??
A: You shouldn't. The static keyword makes the function local to it's translation unit (source file, more or less), which means it can not be called from other translation units.
Well of course you can, but it may not be a good idea.
There's two ways of making the function available:
*
*Export it from the module by removing the static keyword and adding it to the api header file. This will of course involve changing the original source.
*#include the file into your own source file, thus effectively making it part of your own translation unit. Depending on what other dependencies this file may have, this may or may not be a viable option. I would be very wary of doing this, but it is an option.
A: Build a shared library (DLL or .so) from XYZ. Chances are that there is a shared library already available.
Link your code i.e. ABC with XYZ and you can start using the functions exposed by XYZ in your program.
All open source software come with very good readme and instructions which will help you use the software. Start checking from those guides.
A: If the XYZ project is open source
*
*add the source files of the XYZ project to your own and compile all together
*if you change something in the XYZ project, consider sending a message to the maintainers of the project with your changes: they might like what you did and incorporate into a future version
If the project is proprietary, you don't have the source code. A function defined as static ... is not visible in other translation units, so you don't call it at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: java XPath api reference The java standard tutorial http://download.oracle.com/javase/tutorial/jaxp/xslt/xpath.html explains the XPath standard itself but not the java api for XPath. I need:
1) I know XPath syntax, that is how to reference /person/dateofbirth element. What is the java api to select this node and get its text content?
2) can I obtain DOM objects via XPath?
3) is somewhere an official tutorial to the api and not to the xpath itself?
The real question is the 3rd point since the issue is having official and first-hand information as a base.
A: Check these articles, they explain parsing a xml document using XPath api in Java.
http://www.ibm.com/developerworks/library/x-javaxpathapi/index.html
http://onjava.com/pub/a/onjava/2005/01/12/xpath.html
http://www.javaworld.com/javaworld/jw-09-2000/jw-0908-xpath.html
I am not sure if a official tutorial for the API exists.
A: That tutorial is about XSLT and th use of XPath in that context. I guess the most "official" documentation of the XPath API is this:
http://download.oracle.com/javase/6/docs/api/index.html?javax/xml/xpath/package-summary.html
It is really very simple.
A: If you prefer a simpler API, have a look at XPathAPI library.
It is easier to use than the regular Java API and has no dependencies. It also supports List<Node> while the native Java API supports only the non-generic NodeList.
Examples:
Node user = XPathAPI.selectSingleNode(doc, "//user[@id='{}']", userID);
List<String> titles = XPathAPI.selectNodeListAsStrings(doc, "//title");
List<Node> friends =
XPathAPI.selectListOfNodes(doc, "//user[@id='{}']/friend", userID);
(Disclaimer: I'm the author of the library.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: HTML source indentation for ckeditor When you add some code to a ckeditor in HTML view and then change to WYSIWYG view and come back, almost all HTML tags have been modified and have loose the indentation. Is there any way to prevent this behaviour? (parameter, plugin, hard code...)
For example:
<div class="former input">
<span class="big horizontal">
<label for="test">Hi world</label>
<input class="medium free" id="test" name="test" type="text" />
</span>
</div>
Becomes:
<div class="former input">
<span class="big horizontal"><label for="test">Hi world</label><input class="medium free" id="test" name="test" type="text" /></span></div>
A: Here's a link to a page in the developer's guide:
Output Formatting
It explains how to control the layout of the HTML code that is output by the editor and has an example that sets the formatting for the <p> tag.
Try using the <p> tag example as a template and set the formatting for the <span>, <label> and <input> tags using the same approach.
writer.setRules( 'span',
writer.setRules( 'label',
writer.setRules( 'input',
Be Well,
Joe
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Silverlight Binding To A User Control Within A DataTemplate In Silverlight, I have a DataTemplate which is bound to an object which contains a property which holds a UserControl.
Within the DataTemplate, I want to bind to the property which holds the UserControl so that the UserControl is displayed as part of the DataTemplate.
At the moment, I am using an ItemsControl and binding the ItemsSource to the property containing the UserControl and this is working, however, the UserControl is not filling the available space and this is making me wonder whether there is a better way of doing this.
Thanks for any help.
Martyn.
EDIT: As requested some XAML:
<DataTemplate x:Key="ContentTemplate">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="1*"/>
</Grid.RowDefinitions>
<TextBlock Text="Large Content" Grid.Row="0"/>
<ItemsControl ItemsSource="{Binding Contents}" Grid.Row="1" MinHeight="200" MinWidth="300" VerticalAlignment="Stretch" HorizontalAlignment="Stretch"/>
</Grid>
</DataTemplate>
Where, the Contents property being bound to is as follows:
private UserControl _contents;
public UserControl Contents
{
get {return _contents;}
set
{
_contents = value;
NotifyPropertyChanged("Contents");
}
}
A: Don't know why you're using an ItemsControl to show the content, maybe if you try it with a ContentControl.
<ContentControl Content="{Binding Contents}" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" ...
Note the the properties HorizontalContentAlignment and VerticalContentAlignment, these properties sets the alignament of the control content, so if you set them to "Stretch" then the content should fit all the available space.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JOOMLA : template overrides for plugin i'm doing a gallery plugin for joomla, someone told me to use template overrides, i really don't know what the hell is this, and why i need to use it for my gallery plugin? i did googling and found this article useful Joomla template override , but still i am not able understand why i need this, and how to do this for my gallery plugin 'cause the example i found is for modules, your help will be much appreciated.
A: If you are simply trying to insert some content (a gallery) into the output via a plugin, template overrides are not what you need. Template overrides would allow you to modify the output of a component or a module, but not to insert a functionality like a gallery. You simply want to create a plugin that acts on onContentPrepare.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512270",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Windows Phone7 How to Play 3gp video? I am using this code,
String video="http://bitcast-in.bitgravity.com/divum/espn/j2me/260811_Nojo-does-a-Maria.3gp";
mediaplayer.Source = new Uri(video);
mediaplayer.Play();
In layout:
<MediaElement x:Name="mediaplayer"/>
video is not streaming.Please anyone help me.
A: http://msdn.microsoft.com/en-us/library/ff462087(v=vs.92).aspx
Try out this msdn link. u will get idea about media playback...
A: 3GP isn't supported on Windows Phone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Packaging a jre with my application My application contains an c++ exe file which invokes a java program using JNI, thus requiring jvm.dll. However, I want my application to ship with its own embedded jre but after I copy the jre6 folder found in JAVA_HOME and added it to my installer, it fails to run the program(Error occurred during initialization of VM Unable to load native library: Can't find dependent libraries), when I use dependency walker on jvm.dll, it says that it can't find gpsvc.dll, IEShims.dll and sysntfy.dll. After I tried copying those dlls to the same folder as jvm.dll, dependency walker tells me that gpsvc.dll andsysntfy.dll is 64 bit where it should be x86. Problem is, those were the only dlls on my system, what should I do?
A: The Java virtual machine consists of much more than just jvm.dll. You'll need to redistribute the whole JVM package and install that on a user's machine instead of just adding jvm.dll to your own application.
It will probably be much easier to require your users to download and install the JVM themselves before installing your application. If you really want to redistribute the JVM with your application, you'll need to find documentation on Oracle's website on what the exact license for that is and on how to do it. Look at this paragraph of the JDK 6 readme, for example.
It's not as simple as copying jvm.dll and other libraries that it depends on.
A: You may download the required dll's from the appropriate sites, i.e. from this one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Parsing String to JsonObject using GSON gives IllegalStateException: This is not a JSON Object I have the following code:
JsonParser parser = new JsonParser();
System.out.println("gson.toJson: " + gson.toJson(roomList));
JsonObject json2 = parser.parse("{\"b\":\"c\"}").getAsJsonObject();
System.out.println("json2: " + json2);
JsonObject json = parser.parse(gson.toJson(roomList)).getAsJsonObject();
System.out.println("json: " + json);
It gives me the following output:
gson.toJson: [{"id":"8a3d16bb328c9ba201328c9ba5db0000","roomID":9411,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328b9f3a01328b9f3bb80000","roomID":1309,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328ba09101328ba09edd0000","roomID":1304,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bb8af640000","roomID":4383,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd271fe0001","roomID":5000,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd2e0e30002","roomID":2485,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd3087b0003","roomID":6175,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd35a840004","roomID":3750,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd366250005","roomID":370,"numberOfUsers":4,"roomType":"BigTwo"},{"id":"402881e4328bb83601328bd3807d0006","roomID":9477,"numberOfUsers":4,"roomType":"BigTwo"}]
json2: {"b":"c"}
java.lang.IllegalStateException: This is not a JSON Object.
Can someone please help me parse my Json string to JsonObject? I have checked in http://jsonlint.com/ that my json is valid though.
A: This should give you some basic idea.
ArrayList<String> roomTypes = new ArrayList<String>();
JSONArray jsonArray = new JSONArray(jsonString);
for(int i =0; i<jsonArray.length(); i++){
roomTypes.add(jsonArray.getJSONObject(i).getString("roomType"));
}
A: It's because due to the JSON structure..
I have to put it into a JSONObject first, like so
JsonObject jsonObj = new JsonObject();
jsonObj.addProperty(ServerConstants.JSONoutput, gson.toJson(roomList));
Then I would deserialize like
List<RoomData> roomList = gson.fromJson(jsonObj.get(CardGameConstants.JSONoutput).toString(), listType);
for (RoomData roomData : roomList) {
System.out.println(roomData.getRoomID());
}
A: The problem with the code is that roomList is not a JsonObject as evident in the printed output. It's actually a JsonArray.
To fix the code, call .getAsJsonArray() (instead of .getAsJsonObject())
JsonParser parser = new JsonParser();
System.out.println("gson.toJson: " + gson.toJson(roomList));
JsonObject json2 = parser.parse("{\"b\":\"c\"}").getAsJsonObject();
System.out.println("json2: " + json2);
JsonArray json = parser.parse(gson.toJson(roomList)).getAsJsonArray();
System.out.println("json: " + json);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: OpenVAS fails to respond with more than 8192 bytes I'm requesting a HTML report from an OpenVAS server the following way:
<?xml version="1.0" encoding="utf-8"?>
<commands><authenticate><credentials><username>***</username><password>***</password></credentials></authenticate><get_reports report_id="454a3397-b8a4-408e-9f55-f08972765d30" format_id="b993b6f5-f9fb-4e6e-9c94-dd46c00e058d"/></commands>
However when I read the response I receive only 8192 bytes, which happens not to hold all the HTML code. Is this is a hardcoded limit? How do I get around it?
A: I have found a similar issue. The cause was related to running
openvas-mkcert-client -n admin -i
Note the trailing -i, this is what causes the break. I have found no solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Merge multiple checkbox value in one list in a GET url In our web application (django based, with solr backend) we have some checkboxes with multiple choices allowed. Problem is my url is getting longer (we're using GET method)
Something like
?what=&where=&within=any&rooms=any&rooms=any&baths=any&baths=any&sqrft=&sqrft=&price=&price=&property-type=any&date=any
is it possible to merge the repeated ones in one list comma separated?
?what=&where=&within=any&rooms=any,any&baths=any,any&sqrft=any,any&price=any,any&type=any&date=any
they are all ranges [min,max] so it would be good (i guess) to keep them grouped togheter.
thanks in advance
A: Things you can do:
1) Prepare the shorthand querystring using Javascript and then parse it on the server
2) When the user submits a URL with a long querystring, redirect them to a URL with a short querystring
3) Do a combination of 1 and 2. If the user has Javascript enabled, do 1, otherwise do 2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: The same Makefile succeeded in Ubuntu 10.04 LTS but failed in Angstrom on Beagle Board I tried to compile chardev.c from this tutorial using the following Makefile:
obj-m := chardev.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
default :
$(MAKE) -C $(KDIR) M=$(PWD) modules
I got the correct output and it is working fine while I make in Ubuntu 10.04 LTC:
make -C /lib/modules/2.6.32-33-generic-pae/build M=/home/noge/Desktop/driver- tutorial/IOCTL_example/ioctl_eclipse modules
make[1]: Entering directory `/usr/src/linux-headers-2.6.32-33-generic-pae'
Building modules, stage 2.
MODPOST 1 modules
LD [M] /home/noge/Desktop/driver-tutorial/IOCTL_example/ioctl_eclipse/chardev.ko
make[1]: Leaving directory `/usr/src/linux-headers-2.6.32-33-generic-pae'
However, when I transfer the same files to BeagleBoard that is running Angstrom, and did a make CROSS_COMPILE=arm-angstrom-linux-gnueabi-, I got the following error:
root@beagleboard:~/Desktop/noge/C-tutorials/hello_world# make CROSS_COMPILE=
arm-angstrom-linux-gnueabi-
make -C /lib/modules/2.6.32/build M=/home/root/Desktop/noge/C-tutorials/hels
make[1]: Entering directory `/usr/src/linux-2.6.32/2.6_kernel'
Makefile:1448: *** mixed implicit and normal rules. Stop.
make[1]: Leaving directory `/usr/src/linux-2.6.32/2.6_kernel'
make: *** [default] Error 2
I'm not sure if this is the cause, but I noticed the version of make is different for the Ubuntu and Angstrom:
Angstrom's version:
GNU Make 3.82
Built for arm-angstrom-linux-gnueabi
Ubuntu's version:
GNU Make 3.81
This program built for i486-pc-linux-gnu
In short, why the error while doing make in Beagle Board running Anstrom?
Thanks for any help..!
Update:
The content of the Makefile near line 1448:
1447 # Modules
1448 / %/: prepare scripts FORCE
1449 $(Q)$(MAKE) KBUILD_MODULES=$(if $(CONFIG_MODULES),1) \
1450 $(build)=$(build-dir)
1451 %.ko: prepare scripts FORCE
1452 $(Q)$(MAKE) KBUILD_MODULES=$(if $(CONFIG_MODULES),1) \
1453 $(build)=$(build-dir) $(@:.ko=.o)
1454 $(Q)$(MAKE) -f $(srctree)/scripts/Makefile.modpost
I did a check on my kernel version and I got:Linux beagleboard 2.6.32 #3 PREEMPT Thu Jun 23 09:56:19 CEST 2011 armv7l GNU/Linux, but the kernel source I got from here is of version 2.6.22.18.
Is it possible for getting the wrong kernel source code that is causing this ?
A: I'm fairly sure your Makefile is not at fault here, but there might be a rule name collision. What is at line 1448 of /usr/src/linux-2.6.32/2.6_kernel/Makefile ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java read unsigned int, store, and write it back I need to read an unsigned int from a quicktime file, and write it back to another quicktime file.
Currently I read the unsigned int into a Long but while writing it back I never managed to write the exact number back in 4 bytes as unsigned int. The long has the correct value that I need to write back.
(eg 3289763894 or 370500)
I am unable to even read the write a number smaller then Integer.MAX_VALUE (eg 2997).
I am using the following methods to write the value back
public void writeUInt32(long uint32,DataOutputStream stream) throws IOException {
writeUInt16((int) (uint32 & 0xffff0000) >> 16,stream);
writeUInt16((int) uint32 & 0x0000ffff,stream);
}
public void writeUInt16(int uint16,DataOutputStream stream) throws IOException {
writeUInt8(uint16 >> 8, stream);
writeUInt8(uint16, stream);
}
public void writeUInt8(int uint8,DataOutputStream stream) throws IOException {
stream.write(uint8 & 0xFF);
}
Any help would be appreciated.
A: Just write your long casted to int. I checked:
PipedOutputStream pipeOut = new PipedOutputStream ();
PipedInputStream pipeIn = new PipedInputStream (pipeOut);
DataOutputStream os = new DataOutputStream (pipeOut);
long uInt = 0xff1ffffdL;
System.out.println ("" + uInt + " vs " + ((int) uInt));
os.writeInt ((int) uInt);
for (int i = 0; i < 4; i++) System.out.println (pipeIn.read ());
uInt = 0x000ffffdL;
System.out.println ("" + uInt + " vs " + ((int) uInt));
os.writeInt ((int) uInt);
for (int i = 0; i < 4; i++) System.out.println (pipeIn.read ());
Output is4280287229 vs -14680067
255
31
255
253
1048573 vs 1048573
0
15
255
253as expected
A: If you only want to read, store and rewrite it, then you can just use int.
More general: as long as you do not interpret the bits you can just read, store and write them without caring about the intended interpretation of the bits.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Data is Null. This method or property cannot be called on Null values if (!string.IsNullOrEmpty(rd.GetString(2)))
{
StrBcc = rd.GetString(2);
}
Error: System.Data.SqlTypes.SqlNullValueException: Data is Null. This
method or property cannot be called on Null values.
A: If your values can be NULL then using SqlTypes instead can be a safer solution as they all implement INullable:
StrBcc = rd.GetSqlString(2);
or if you like extension methods:
public static class DataReaderExtensions
{
public static T GetValueOrNull<T>(this SqlDataReader reader, int ordinal) where T : class
{
return !reader.IsDBNull(ordinal) ? reader.GetFieldValue<T>(ordinal) : null;
}
public static T? GetValueOrNullable<T>(this SqlDataReader reader, int ordinal) where T : struct
{
if (reader.IsDBNull(ordinal)) return null;
return reader.GetFieldValue<T>(ordinal);
}
}
A: My solution was to create an extension method:
static class DataReaderExtensions
{
public static string GetStringNullCheck(this IDataReader reader, int ordinal)
{
return reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal);
}
}
So I can use it as:
StrBcc = rd.GetStringNullCheck(2);
A: You should use
if (!rd.IsDBNull(2))
StrBcc = rd.GetString(2);
That's because when you use string.IsNullOrEmpty(x) you are telling your app that x is a string, while is a database null value, which is different from a string whose value is null.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: How to quantize image color from RGB 24 bit to RGB 6 bit (64 colors)? I'm trying to deploy BIC algorithm (border/interior pixel classify) and using PIL (python imaging library) to process image . But i don't know how to quantize RGB color from 24bit (8bit per color) to 6 bit (2bit per color) by using PIL .
Anyone can tell me how to do it by PIL or another python library such as Opencv , pythonmagick...?
A: the PIL ImageOps posterize (scroll down to posterize) function should do this for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: PHP - Dealing with POST and header include Say I have a form where the user can sign in, and when the user fills out the form it posts back to the same page, checks for errors with the username and password, and logs the suer in if all is swell. At the moment I'm doing this by loading the form under this condition:
if($_SERVER['REQUEST_METHOD'] != 'POST') {
and if this isn't true then check for errors and log in etc.
The problem is that this all happens in signin.php. At the top of signin.php I am including header.php and connect.php, which do exactly what their names suggest. When I post back to the page the changes in sign in status are not shown in the header file (there is a userbar in this file, similar in nature to the one on this site). The sign in works, but I have to navigate to a different page for the header to show 'signed in' instead of 'sign in/register' or whatever.
Have I gone about this in the wrong way, or is there just something I need to add to make my header update? Cheers.
P.S: I am pretty new to php so something not too complicated would be preferable please.
A: You probably need to redirect (using header()) after the POST code happens:
if($_SERVER['REQUEST_METHOD'] != 'POST') {
..
}
else {
..
header('Location: ' . basename($_SERVER['REQUEST_URI']));
exit;
}
A: there are 2 problems with your setup violating very basic yet strict rules of the web-development
*
*There ought to be redirect after any POST request. Can be done as shown in the other answer.
*There must be no HTML shown before all logic is done. So, your header.php should be called AFTER form checking, not before it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: One dropdownlist depending on the other I develop a php web page that contains two dropdownlists (select tags) as one of them used to display the car types like Toyota, Nissan, Chevrolet and so on.
Toyota
Nissan
Chevrolet
The other should be used to display the car models like Toyota Camry, Toyota Corrolla, Toyota Cressida, Toyota Eco and son on depeding on the Car Type selected from the first dropdownlist.
I use PHP as a development language plus Sybase as database and I connect to it using ODBC.
I use Windows-1256 as Character Encoding as my displayed data is Arabic.
I try to use Ajax to implement that but I do not know how as I used Ajax before to return one value only but in this case I need to reply with some database records in the following format:-
15 "Toyota Camry"
16 "Toyota Corrolla"
17 "Toyota Cressida"
18 "Toyota Eco"
plus that the data is sent in arabic not in English as listed above so the list may be as the following:-
15 "تويوتا كامري"
16 "تويوتا كرولا"
17 "تويوتا كرسيدا"
18 "تويوتا إيكو"
how I can do that using Ajax and make sure that the Arabic text will be displayed well?
I wait your answer and help and Thanks in advance .....
My Code is written in the following to make things more clear and be useful for others and to get the right answer:
The first file
showCarData.php File (Saved as ANSI PHP File)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256" />
<script src="js/jquery-1.3.2.min.js" type="text/javascript" /></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#selectCarType').change(function ()
{
$('#selectCarModel option').remove();
$.ajax(
{
url: "getCarModels.php",
dataType: 'json',
data: { CarType: $('#selectCarType').val() },
async: true,
success: function(result)
{
//var x = eval(result);
$.each(result, function(key, value) { $('#selectCarModel').append('<option value="' + key + '">' + value + '</option>'); } );
}
});
$('#selectCarModel').show();
});
});
</script>
</head>
<body>
<select id="selectCarType">
<option value="0" selected="selected">select car type</option>
<?php
//Connecting To The Database and getting $conn Variable
$conn = odbc_connect("database","username","password");
//Connection Check
if (!$conn)
{
echo "Database Connection Error: " . $conn;
}
$sqlCarTypes = "SELECT DISTINCT CarTypeID AS CarTypeCode, CarTypeDesc AS CarTypeName FROM tableCarTypes ORDER BY CarTypeDesc ASC";
$rsCarTypes = odbc_exec($conn,$sqlCarTypes);
if (!$rsCarTypes)
{
echo "<option class='CarType' value='n' >Not Available</option>";
}
else
{
while ( odbc_fetch_row($rsCarTypes) )
{
//Assigning The Database Result Set Rows To User-Defined Varaiables
$CarTypeCode = odbc_result($rsCarTypes,"CarTypeCode");
$CarTypeName = odbc_result($rsCarTypes,"CarTypeName");
//Creating the options
echo '<option class="CarType" style="color:#060;" value="'. $CarTypeCode . '"';
echo '>' . $CarTypeName . '</option>' . "\n";
}
}
odbc_close($conn);
?>
</select>
<select id="selectCarModel">
<option value="0" selected="selected">select car model</option>
</select>
</body>
</html>
and the other file is
getCarModels.php File (Saved as ANSI PHP File)
<?PHP
//determine the Characterset
header('Content-Type: text/html; charset=windows-1256');
//Recieve CarType variable
$CarType = $_GET['CarType'];
// initialize an array that will hold the rows
$result = array();
if ($CarType != Null)
{
//Connecting To The Database and getting $conn Variable
$conn = odbc_connect("database","username","password");
//Connection Check
if (!$conn)
{
echo "Database Connection Error: " . $conn;
}
$sqlCarModels = "SELECT DISTINCT CarModelID AS CarModelCode, CarModelDesc AS CarModelName FROM tableCarTypes WHERE CarTypeID='$CarType' ORDER BY CarModelDesc ASC ";
$rsCarModels = odbc_exec($conn,$sqlCarModels);
if ( $rsCarModels )
{
while ( odbc_fetch_row($rsCarModels) )
{
$CarModelCode = odbc_result($rsCarModels,"CarModelCode");
$CarModelName = odbc_result($rsCarModels,"CarModelName");
$CarModelName = utf8_encode($CarModelName);
$result [$CarModelCode] = $CarModelName;
}
}
else
{
echo "No Data";
}
odbc_close($conn);
}
//send the result in json encoding
echo json_encode($result);
?>
I hope this clear what I asked about and that any one could help me finding where is the error or the thing I miss to get the output in a proper format instead of the strange symbols and characters that could not be read as it shows in the second dropdown list.
Thanks in advance
A: What I do in such scenario is the following:
*
*I construct the first dropdownlist on the server, with PHP while over the car categories from the database, for example. I place the id of the category as a value of the option. The resulting HTML should look something like this:
<select id="cars-categories">
<option value="1">Toyota</option>
<option value="2">Nissan</option>
<option value="3">Chevrolet</option>
...
</select>
*Then on the page, with JavaScript, I listen for onchange event of the select and when occurs send the category id to the server
*PHP code on the server picks the category id and makes a SELECT your_cols FROM product_table WHERE cat_id = $_GET['id']. Send the result as JSON with json_encode
*Finally, parse the returned data with JavaScritp and fill the model dropdownlist.
Here is what the client script basically can look like:
<script type="text/javascript">
$(document).ready(function() {
$('#cars-categories').change(function () {
$('#car-models option').remove();
$.ajax({
url: "get_data.php",
dataType: 'json',
data: { category: $('#cars-categories').val() },
async: true,
success: function(json){
$.each(json, function(key, value){
$('#car-models').append('<option value="' + value.id + '">' + value.name + '</option>');
});
}
});
$('#car-models').show();
});
});
</script>
Encoding shouldn't be an issue.
EDIT: As requested by the author of the question, here is a simple way to get all the rows from the DB query and to send them back to the page as JSON encoded string.
<?php
// connect to DB
...
// initialize an array that will hold the rows
$rows = array();
// sanitize the category id. since it is an int, it is safest just to cast it to an integer
$cat_id = (int)$_GET['category'];
$result = mysql_query("SELECT id, name FROM `models` WHERE cat_id = $cat_id");
while($row = mysql_fetch_assoc()){
$rows[] = $row;
}
// do a regular print out. It is not going to the screen but will be returned as JavaScript object
echo json_encode($rows);
// you have to exit the script (or at least should not print anything else)
exit;
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I insert a variable containing a backslash in sed? Please see these simple commands:
$ echo $tmp
UY\U[_
$ echo "a" | sed "s|a|${tmp}|g"
UY[_
The \U is eaten. Other backslashes won't survive either.
How can I make the above command work as expected?
A: If it's only backslash that is "eaten" by sed and escaping just that is enough, then try:
echo "a" | sed "s|a|${tmp//\\/\\\\}|g"
Confusing enough for you? \\ represents a single \ since it needs to be escaped in the shell too.
The inital // is similar to the g modifier in s/foo/bar/g, if you only want the first occurring pattern to be replaced, skip it.
The docs about ${parameter/pattern/string} is available here: http://www.gnu.org/s/bash/manual/bash.html#Shell-Parameter-Expansion
Edit: Depending on what you want to do, you might be better of not using sed for this actually.
$ tmp="UY\U[_"
$ in="a"
$ echo ${in//a/$tmp}
UY\U[_
A: You could reparse $tmp itself through sed
echo "a" | sed "s|a|$(echo ${tmp} | sed 's|\\|\\\\|g')|g"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JQuery resizable snap to other resizable objects' borders? I wonder why they didn't develope JQuery resizable with option to snap the resizing object to others (instead of snapping to grid) like draggable ? Does anyone know such a plugin to achieve this ?
Thanks.
A: Think this should do the trick:
https://github.com/polomoshnov/jQuery-UI-Resizable-Snap-extension
A: For me this javascript add-on provided didn't work, maybe because it's some years outdated. Instead I found a simpliest solution that uses only an original attribute from the JQuery-UI's library.
On the dialog you want to snap, just make something like:
$('.your-dialog-filter').dialog().parents('.ui-dialog').draggable('option', 'snap', true);
Simple like this.
More info and demo: https://jqueryui.com/draggable/#snap-to
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Proving language properties I am taking a course on the formal foundations of programming, one of things we have covered is proving certain properties of languages, i have done most of the work, but I am stuck on these two questions, as I have no idea how to prove them.
they are as follows:
A ^ (B ^ C) = (A ^ B) ^ C (which I believe is the associative rule)
A ^ (B U C) = (A ^ B) U ( A ^ C) (Distribution rule)
In these examples i have used the ^ to mean concatenation
A: First
A^B is all the words x such that there is v in A and w in B such that x = vw
let's prove A^(B^C) is included into (A^B)^C
The A^(B^C) is all the words x such that there is v in A and w in B^C
such that x=vw
and w = lm where l is in B and m is in C then x=vlm
x=(vl)m =v(lm) since vl is in A^B qnd m is in C then x is in (A^B)^C.
then A^(B^C) is included into (A^B)^C.
Same proof for inverse inclusion
then A^(B^C) =(A^B)^C
Second:
x in B U C if and only if x is in B or x is in C.
first inclusion:
if x in A ^ (B U C)
then x = vw where v in A and w in B or C
Then x is in A^B or A^C
then x is in (A ^ B) U ( A ^ C)
second inclusion
if x is in (A ^ B) U ( A ^ C)
then x = vw with v in A and w in B or x =vw with with v in A and w in
C
then since v is always is A
then x = vw where v in A and w in B or C
x in A ^ (B U C)
Therefore A ^ (B U C) = (A ^ B) U ( A ^ C)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Do I need to re-retrieve data when paging using asp:GridView I have a .aspx search screen that displays the results of the search in an asp:GridView component. There can be up to approx 1000 records returned by the search. I want to implememt paging on the grid so that only 15 records are displayed at any one time and the user can page through the results.
I am retrieving the records by passing search parameters to a WCF service which returns a List of particular entity objects. I create a Datatable and insert one DataRow per entity object from the List. I then bind the grid view to the Datatable.
This is how my grid is defined in the .aspx page:
<asp:GridView ID="gridCat" runat="server" AutoGenerateColumns="False" DataKeyNames="CatalogueID"
HeaderStyle-CssClass="fieldHeading" RowStyle-CssClass="fieldContent"
AlternatingRowStyle-CssClass="alternateFieldContent" Width="100%"
AllowPaging="True" AllowSorting="True" AutoGenerateDeleteButton="True"
PageSize="15">
and I also have this method in the code behind (.aspx.vb file):
Sub GridPagingAction(ByVal sender As Object, ByVal e As GridViewPageEventArgs) Handles gridCat.PageIndexChanging
gridCat.PageIndex = e.NewPageIndex
gridCat.DataBind()
gridCat.Visible = True
End Sub
My problem is this: the first page is rendered correctly i.e. the first 15 records are displayed correctly. However, when I navigate to page 2 in the grid, the GridPagingAction method is hit on the server but nothing is displayed in the grid - it is just blank.
I think the reason this is happening is because the Datatable no longer exists on the server when the request for the second page hits the server - is that right? And the asp:GridView, when it is rendering the first page of results, only takes the first 15 records from the Datatble and sends them back to the browser. So when the request for the second page comes in the other records (i.e. records 16 - 1000) don't exist anywhere - is all that correct?
If so, what's the best solution - I can't see how to implement paging without having to do one of the following:
*
*re-perform the search each time the user uses the paging option;
*saving the search results on the Session after the first Search retrieving them each time the user uses the paging option;
*manually inserting the Search results into ViewState and retrieving them each time the user uses the paging option.
Is there a better way to do this (or am I doing it wrong)? If not, which of the 3 options do you think is the best? I'm leaning towards option 2 as I don't think option 1 is performant and I don't want to be sending loads of unnecessary data back to the browser as per option 3.
A: All you said is correct. You could either use ViewState or the Session to keep hold of the data on client- or server-side, but if you really have that many records, it might be a good idea to only collect the data you actually need.
So if you want to show records 1 to 10, you perform a query against the database and only fetch those ten records. If you want to show the next ten, you perform another query with the according parameters.
This will improve your performance and memory usage significantly, IF calling your DB is not overly expensive.
This article might give you a start on how to do this:
http://dotnetslackers.com/articles/gridview/Optimized-Paging-and-Sorting-in-ASP-NET-GridView.aspx
If you want an easy solution without any additional efforts, I would query all the records on each postback (your option #1).
If you want the best performing solution with not much overhead, use the custom paging.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512316",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Perl trapping Ctrl-C (sigint) in bash I'm reading How do we capture CTRL ^ C - Perl Monks, but I cannot seem to get the right info to help with my problem.
The thing is - I have an infinite loop, and 'multiline' printout to terminal (I'm aware I'll be told to use ncurses instead - but for short scripts, I'm more comfortable writing a bunch of printfs). I'd like to trap Ctrl-C in such a way, that the script will terminate only after this multiline printout has finished.
The script is (Ubuntu Linux 11.04):
#!/usr/bin/env perl
use strict;
use warnings;
use Time::HiRes;
binmode(STDIN); # just in case
binmode(STDOUT); # just in case
# to properly capture Ctrl-C - so we have all lines printed out
# unfortunately, none of this works:
my $toexit = 0;
$SIG{'INT'} = sub {print "EEEEE"; $toexit=1; };
#~ $SIG{INT} = sub {print "EEEEE"; $toexit=1; };
#~ sub REAPER { # http://www.perlmonks.org/?node_id=436492
#~ my $waitedpid = wait;
#~ # loathe sysV: it makes us not only reinstate
#~ # the handler, but place it after the wait
#~ $SIG{CHLD} = \&REAPER;
#~ print "OOOOO";
#~ }
#~ $SIG{CHLD} = \&REAPER;
#~ $SIG{'INT'} = 'IGNORE';
# main
# http://stackoverflow.com/questions/14118/how-can-i-test-stdin-without-blocking-in-perl
use IO::Select;
my $fsin = IO::Select->new();
$fsin->add(\*STDIN);
my ($cnt, $string);
$cnt=0;
$string = "";
while (1) {
$string = ""; # also, re-initialize
if ($fsin->can_read(0)) { # 0 timeout
$string = <STDIN>;
}
$cnt += length($string);
printf "cnt: %10d\n", $cnt;
printf "cntA: %10d\n", $cnt+1;
printf "cntB: %10d\n", $cnt+2;
print "\033[3A"; # in bash - go three lines up
print "\033[1;35m"; # in bash - add some color
if ($toexit) { die "Exiting\n" ; } ;
}
Now, if I run this, and I press Ctrl-C, I either get something like this (note, the _ indicates position of terminal cursor after script has terminated):
MYPROMPT$ ./test.pl
cnEEEEEcnt: 0
MYPROMPT$ _
cntB: 2
Exiting
or:
MYPROMPT$ ./test.pl
cncnt: 0
MYPROMPT$ _
cntB: 2
Exiting
... however, I'd like to get:
MYPROMPT$ ./test.pl
cncnt: 0
cntA: 1
cntB: 2
Exiting
MYPROMPT$ _
Obviously, handlers are running - but not quite in the timing (or order) I expect them to. Can someone clarify how do I fix this, so I get the output I want?
Many thanks in advance for any answers,
Cheers!
A: Hmmm... seems solution was easier than I thought :) Basically, the check for "trapped exit" should run after the lines are printed - but before the characters for "go three lines up" are printed; that is, that section should be:
printf "cnt: %10d\n", $cnt;
printf "cntA: %10d\n", $cnt+1;
printf "cntB: %10d\n", $cnt+2;
if ($toexit) { die "Exiting\n" ; } ;
print "\033[3A"; # in bash - go three lines up
print "\033[1;35m"; # in bash - add some color
... and then the output upon Ctrl-C seems to be like:
MYPROMPT$ ./test.pl
cnt: 0
^CcntA: 1
cntB: 2
Exiting
MYPROMPT$ _
Well, hope this may help someone,
Cheers!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Oracle - count() in same line i'm new user here, and i think that this is amazing!!!
I need a little help:
i do this, but don't work like i want! (count(countOfCat) is no Good!)
select count(countOfCat) as "Cat", count(countOfDog) as "dog", count(countOfHorse) as "horse", 0 as "duck", 0 as "Mouse"
from animal
where Birthdate in
(...
-- i think not important
...
)
and ( species= 'cat' or species= 'dog' or species= 'horse')
group by species
i'm want to receive like this
Cat Dog Horse Duck mouse
------- ------- ------- ------ -------
1234 2345 3456 0 0
...
I need that all count are in the same row.
I can't utilize this
noGood- Cat Dog Horse Duck mouse
noGood- ----- ------ -------- ------- -------
noGood- 1234 0 0 0 0
noGood- 0 2345 0 0 0
noGood- 0 0 3456 0 0
Thank you for yout time!
Da!
A: select sum(case when species = 'cat' then 1 else 0 end) as "Cat",
sum(case when species = 'dog' then 1 else 0 end) as "Dog",
sum(case when species = 'horse' then 1 else 0 end) as "Horse",
0 as "duck",
0 as "Mouse"
from animal
where species in ('cat', 'dog', 'horse')
A: I too think amazing that you're new here. :D
select
(select count(*) from animal a where a.species = 'cat') as Cat,
(select count(*) from animal a where a.species = 'horse') as Horse,
(select count(*) from animal a where a.species = 'duck') as Duck
from
dual
NB: dual is a system table that always has a single row. It is very convenient for tricks like this.
A: Very simple.
All you need to do is remove the group by clause :D
select count(countOfCat) as "Cat", count(countOfDog) as "dog", count(countOfHorse) as "horse", 0 as "duck", 0 as "Mouse"
from animal
where Birthdate in
(...
-- i think not important
...
)
and ( species= 'cat' or species= 'dog' or species= 'horse')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Explanation of this LINQ expression I would be grateful if someone could explain this following LINQ expression:
Endpoint adapter = (from adap in this
where
(endpointName == DEFAULT_ENDPOINT_NAME && adap.IsDefault) ||
(endpointName != DEFAULT_ENDPOINT_NAME && adap.Name == endpointName)
select adap).FirstOrDefault();
I can pretty much get the gist of this, I just need help with the from adap in this section. I would've expected this would be selecting from the current class - but I can't find anything within the current class that's a collection. Could you point me to where the data is likely to be coming from, adap?
A: The class the code resides in implements IEnumerable<T> or IQueryable<T> as that is needed for it be to able to call the IEnumerable.Where or IQueryable.Where method.
A: This is a query expression. The C# compiler basically translates it to:
Endpoint adapter = this.Where(adap => (endpointName == DEFAULT_ENDPOINT_NAME &&
adap.IsDefault) ||
(endpointName != DEFAULT_ENDPOINT_NAME &&
adap.Name == endpointName))
.FirstOrDefault();
It's likely (but not required) that Where is an extension method call - probably Enumerable.Where or Queryable.Where. If you could show us the declaration of the type this call resides in, it would make it clearer.
Basically once you've applied the "pre-processor" step, it should be clearer what's going on. In particular, if you type:
this.Where
into Visual Studio and hover over "Where", what does it show?
EDIT: Now we know that you're deriving from List<Endpoint> (which I'd frankly advise against, to be honest - favour composition over inheritance; deriving from List<T> is almost always a bad idea), it's really calling Enumerable.Where.
A: Your class implements IEnumerable<T> so you can select from this I would say.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Immediately starting new UIViewController from a viewcontroller When the UIViewController starts, I want to start another UIViewController immediately.
This doesn't work:
-(void) awakeFromNib {
UIViewController *newcontroller = [[[UIViewController alloc] init] autorelease];
...
[self presentModalViewController:newcontroller animated:YES];
}
In order for this to work, I have to do afterDelay for a method, like so:
-(void) awakeFromNib {
[self performSelector:@selector(startNewController) withObject:nil afterDelay:0.5];
[super init];
}
-(void) startNewController {
UIViewController *newcontroller = [[[UIViewController alloc] init] autorelease];
...
}
Is it possible to get it to work without delay?
A: Call startNewController in your viewDidAppear method instead, that happens because your viewController is not totally loaded when you try to present the modal viewController, so that's why it works when you wait.
A: Practically, you should not plan your application architecture which forces you to do such implementations. Though, I can understand there are times where you have no way out..
I'd say:
best solution for your case is to call your controller from
viewDidAppear
or
viewWillAppear
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem with aspnet_regsql.exe i wrote a website with asp.net 4 and sql server 2008. But my host sql version is 2005 so i get script from my database in sqlserver 2008 and convert it to 2005. Then i import .sql file that is exported from 2008 iin sqlserver 2005 and retrieve it. Then i make a back up with sqlserver 2005 and upload it on my host. Now i have one problem:
I used aspnet_regsql.exe to create the database schema.
But when i want to login to my website it throws following error:
The 'System.Web.Security.SqlMembershipProvider' requires a database
schema compatible with schema version '1'. However, the current
database schema is not compatible with this version. You may need to
either install a compatible schema with aspnet_regsql.exe (available
in the framework installation directory), or upgrade the provider to a
newer version.
What is the problem?
A: Which version of ASP.NET is your published website using? It looks like it might be different than what you're using in development.
The version info is configured on a per-AppPool basis in IIS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: HOw to access the hidden value set in cshtml from controller? Can i have something like this in my cshtml
@Html.hiddenfor(model => model.name , "passname")
In controller :
i want to access this modal.name which will be having the value i set i.e "passname"
A: 2 ways:
1 - your model has to have this property that it can pass to HiddenFor. For example
class
class PageModel{
public string HiddenFieldValue{get;set;}
public string Name {get;set;}
}
in cshtml
@model PageModel
...
@Html.hiddenfor(model => model.name, model.HiddenFieldValue)
in controller
public ViewResult MyPage(){
return View(new PageModel(){
HiddenFieldValue = "Hello World!";
});
}
2nd way: pass in through ViewBag/ViewData.
in controller
public ViewResult MyPage(){
ViewBag.HiddenFieldValue = "Hello World!";
return View();
}
in cshtml
@model PageModel
...
@Html.hiddenfor(model => model.name, ViewBag.HiddenFieldValue)
A: The value for the hidden field will be send together with all the other POST data (if your form uses a POST).
So you can:
*
*Add a property "passname" to the model that you use to retrieve the data.
*Create an argument named "passname" on the action that handles the post.
*Add a FormCollection to the argement (on the action that handles the post), and retrieve the value from there.
*Get it from the Request using Request.Form["passname"] or event Request["passname"]
// Example 1
public class MyModel {
// other properties
public string passname { get; set; }
}
public class MyController : Controller {
[HttpPost]
public ActionResult MyAction(MyModel data) {
}
}
// Example 2
public class MyController : Controller {
[HttpPost]
public ActionResult MyAction(string passname) {
}
}
// Example 3
public class MyController : Controller {
[HttpPost]
public ActionResult MyAction(FormCollection data) {
var passname = data["passname"];
}
}
// Example 4
public class MyController : Controller {
[HttpPost]
public ActionResult MyAction() {
var passname = Request.Form["passname"];
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how can i hide a title in a Ext.formPanel how can i hide in runtime the title of panel??
this is my code:
{
xtype: 'panel',
id: 'pnlAllCenter',
border: false,
layout: {
align: 'stretch',
type: 'vbox'
},
title: '<center>Main Application</center>'
}
now in runtime i need to hide this title!
(i need something like this Ext.getCmp('pnlAllCenter').title.remove();)
thanks!!
A: You're quite close...
Ext.getCmp('pnlAllCenter').getHeader().hide();
EDIT
To completely remove the header use
Ext.getCmp('pnlAllCenter').getHeader().destroy();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: One-to-one mapping confusion Why is it that a lot of people are referring to One-to-One when I am sure they are referring to Many-to-one?
For instance, if you have two tables;
Inventory (InventoryID)
Item (ItemID, InventoryFK)
There is no one-to-one mapping here as far as I can tell. It's "Many items to one inventory".
Now, let's assume that there would be only one item per inventory. In this case, my colleagues would start calling it a "one-to-one". Am I correct in pointing out that it's still a many-to-one relationship? When I try to explain this to them they don't seem to understand.
I believe a proper one-to-one mapping to be something like this:
Person (Column: PersonID, Name)
PersonAddress (Column: PersonID, StreetName, StreetNumber)
Here you'd have two tables, sharing the exact same PK.
Assuming my assumptions are correct, why are so many people abusing the term "one-to-one"?
A: The one-to-many and one-to-one relation are implemented in a slightly different way.
One-to-many
Object (objectId) ObjectCharacteristics(charId,objectId)
One-to-one
The order of the table is not important:
Husband (husbandId) Wife(wifeId,husbandId) + unique constraint on husbandId
N.B. One-to-many relation is also a one-to-one relation in the order way. The ObjectCharacteristics has one and only one object.
But you are right the relationship is a concept that does not depend upon the specific data in your database but only on the structure of it.
A: I agree these terms are much abused. But who of us isn't guilty? Without knowing the constraints involved, your example of what you believe to be a one-to-one relationship could be a one-to-zero-or-one relationship (hint: the presence of a foreign key does not imply the presence of actual referencing values).
Chris Date wrote a very thorough analysis of the situation in his paper All for One, One for All.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Disable AutoSelect in AutoCompleteBox in WP7? Is there any way to disable the AutoSelect in the AutoCompleteBox in WP7? What happens now is that each time when I write something and it is listed in the search suggestions, the logic runs. This is not what I want, because the user would only like to do the actual search when clicking on a suggestion, the enter key or the search button. So, my question is: How is it possible to disable this?
How it is done now:
In the xaml file, showing the AutoCompleteBox and binds it to key up and selectionchanged:
<toolkit:AutoCompleteBox x:Name="AutoCompleteBox" FilterMode="None" ItemsSource="{Binding SearchSuggestion}" KeyUp="AutoCompleteBoxKeyUp" MinimumPrefixLength="3">
<i:Interaction.Triggers>
<i:EventTrigger EventName="KeyUp">
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding TextBoxKeyUpCommand, Mode=OneWay}" CommandParameter="{Binding Text, ElementName=AutoCompleteBox}"/>
</i:EventTrigger>
<i:EventTrigger EventName="SelectionChanged">
<GalaSoft_MvvmLight_Command:EventToCommand x:Name="TextBoxSelectionChanged" Command="{Binding TextBoxSelectionChangedCommand, Mode=OneWay}" CommandParameter="{Binding Text, ElementName=AutoCompleteBox}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</toolkit:AutoCompleteBox>
In xaml.cs I listen to the keyup event and send a message to the viewmodel:
private void AutoCompleteBoxKeyUp(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
Messenger.Default.Send(new ViewModelMessage { Action = ViewModelMessage.ACTION_EXECUTE, Text = AutoCompleteBox.Text });
Pivot.Focus();
}
}
In the ViewModel:
private void TextBoxKeyUp(string string)
{
_string = string;
}
private void TextBoxSelectionChanged(string string)
{
_string = string;
}
private void ReceiveMessage(ViewModelMessage message)
{
switch (message.Action)
{
case ViewModelMessage.ACTION_EXECUTE:
_string = message.Text;
break;
}
}
The problem seems to be that the SelectionChanged event is raised when I click on the drop down, but also when i type in something that is listed in the drop down. Hope someone can help :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512333",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there any program like LINQPad for Java? (Not a duplicate!)
Possible Duplicate:
Is there any program like LINQPad for Java?
My question is similar to Is there any program like LINQPad for Java?, but not the same.
Like the author of the original question, I am not interested in the database quering capabilities provided by LinqPad.
What I am looking for is a desktop utility to run short java code snippets. I am not interested in any web based solutions, so groovy web console is out of the question.
(Showing Java byte code is a bonus, but not a must)
Thanks.
A: This can be done using Eclipse scrapbook pages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: ProducerConsumer problem I am trying to translate the scenario below using threads.
procA {
while (TRUE) {
update(x);
retrieve(y);
}
}
procB {
while (TRUE) {
retrieve(x);
update(y);
}
}
Have written the code for this which I have provided below:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#define WORK_SIZE 10
pthread_mutex_t work_mutex;
int wa1[WORK_SIZE];
int wa2[WORK_SIZE];
void *funA(void *);
void *funB(void *);
int main(){
pthread_t tid1,tid2;
if(pthread_create(&tid1,NULL,funA,(void *)wa1))
perror("pthread_create");
if(pthread_create(&tid2,NULL,funB,(void *)wa2))
perror("pthread_create");
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
return 0;
}
void *funA(void *ptr){
int *x=ptr;
int i=0,j,num;
//sleep(1);
while(i<=10){
num=rand();
*x=num;
x+1;
j=*wa2;
printf("A: %d\n",j);
wa2+1;
i++;
}
return NULL;
}
void * funB(void *ptr){
int *y=ptr;
int a=0,b,num;
while(a<=10){
num=rand();
b=*wa1;
printf("B: %d\n",b);
wa1+1;
*y=num;
y+1;
a++;
}
return NULL;
}
I am required to implement MUTEX but that will come later into the picture. For now as my per my understanding, both the threads should in progress simultaneously and hence the address pointed by *wa1 and *wa2 should be getting updated simultaneously. It seems I am missing something because of which the output getting generated is :
Included infinite loop. Updated o/p depicted below(only a part of the output)
A: 1258442020
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
A: 803738656
B: 1317969989
A: 803738656
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
A: 1251276256
B: 1851766329
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
B: 455345464
Seems like after the infinite loop, a context switch happens but I am still not clear on the output. The random function should generate a new number but rather the same number is getting repeated. Any suggestions please and how can this be termed as a producer -consumer problem How can I implement this problem is a better manner than the one I have implemented
thanks.
A: The ten iteration are just so few that they are handled before a context switch can happen, so you wouldn't see any concurrency. I'm sorry that I can't really tell anything from your code because it lacks indentation, comments and good variable names.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to find coordinates of an element relative to browser window I want coordinates of an element relative to the browser window. So if an element is at top-left corner of browser can I get it's coordinates as x=0, y=0. How to achieve this ?
A: I think you could use this script or use jquery offset()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Moving/Dressing mesh in 3D engine (iPhone) I'm new in 3D games developing so I have kinda dummy question - how to move a mesh in 3D engine (under moving I mean a walking animation). And how to dress some skin on it?
What I have:
*
*open source 3D OpenGL engine - NinevehGL http://nineveh.gl/. It's super easy to load a mesh
to. I' pretty sure it will be awesome engine when it will be released!
*a mesh model of the human.
http://www.2shared.com/file/RTBEvSbf/female.html (it's mesh of a
female that I downloaded from some open source web site..)
*found a
web site from which I can download skeleton animation in
formats:
dao (COLLADA) , XML , BVH (?) - http://www.animeeple.com/details/bcd6ac4b-ebc9-465e-9233-ed0220387fb9
*what I stuck on (see attached image)
So, how can I join all these things and make simple game when dressed human will walk forward and backward?
A: The problem is difficult to answer, because it would require knowledge of the engine's API. Also you can't just stick a skeletal animation onto some mesh. You need some connection between both, a process called rigging, in which you add "bones" (also called armatures) to the mesh. This is an artistic process, done in a 3D modeller. Then you need to implement a skeletal animation system, which is a far too complex task to answer in a single Stackoverflow answer (it involves animation curve evaluation, quaternion interpolation, skinning matrices, etc.).
You should break down your question into smaller pieces.
A: I'm a BETA Tester for Nineveh Engine.
Currently, the engine does not support bones/skeleton animation. This will be a part of their next release version which is upcoming in next 4-8 months.
Future (Roadmap)
Version 0.9.3 : Q4 2011 - Q1 2012
Bones, Rigging and Mesh's Animations.
Mesh Morph.
You might want to checkout http://nineveh.gl/docs/changelog/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Javascript: Height reduces on multiple clicks ? tried animating a dropdown,worked.But,the height of the element reduces if i keep clicking on it -- finally becomes 0px !!.. not sure why this is happening.
HeightChangePersist -- funciton to increase the height(via steps -- works fine)
when you click on click here!!,it works fine the 1st time but clicking on it more times reduces the height(gradually) -- unexpected and unwanted -- please do tell me where i'm going wrong!!..
Kindly help,javascript beginner.
Here's the code --
<html>
<style type="text/css">
.box{
width: 300px;
overflow: hidden;
background: rgba(0,0,0,.5);
color: white;
margin-top: 2px;
}
.hide{
display: none;
}
</style>
<script type="text/javascript" >
function heightChangePersist(elem,startHeight,endHeight,steps,intervals,powr) {
if (elem.heightChangePersist) window.clearInterval(elem.heightChangePersist);
var currStep = 0;
elem.heightChangePersist = window.setInterval(
function() {
elem.currHeight = easeInOut(startHeight,endHeight,steps,currStep,powr);
elem.style.height = elem.currHeight+"px";
currStep++;
if (currStep > steps) window.clearInterval(elem.heightChangePersist);
}
,intervals)
}
function easeInOut(minValue,maxValue,totalSteps,currStep,powr) {
var delta = maxValue - minValue;
var stepp = minValue+(Math.pow(((1 / totalSteps)*currStep),powr)*delta);
return Math.ceil(stepp);
}
function invoke(){
var box1=document. getElementById('box1');
var box2=document. getElementById('box2');
box1.style.display='block';
box2.style.display='block';
heightChangePersist(box1,0,box1.offsetHeight,30,30,.5);
heightChangePersist(box2,0,box2.offsetHeight,30,30,.5);
}
</script>
<div class="box" onclick="invoke()">
click Here!!
</div>
<div id="box2" class="box hide">
This is a test done to check the animation of a particular item.Hoping it works and i hope to be successful in this trial..!!
</div>
<div id="box1" class="box hide">
This is a test done to check the animation of a particular
item.Hoping it works and i hope to be successful in this trial..!!This is a test done
to check the animation of a particular item.Hoping it works and i hope to be successful in this trial
..!!This is a test done to check the animation of a particular item.Hoping it works
and i hope to be successful in this trial..!!
</div>
The heightChangePersist -- Something which i picked up from http://www.hesido.com/web.php?page=javascriptanimation
A: This is because you called the heightChangePersist function again when the previous heightChangePersist still not completed.
I modified your code, and the problem resolved:
<html>
<style type="text/css">
.box{
width: 300px;
overflow: hidden;
background: rgba(0,0,0,.5);
color: black;
margin-top: 2px;
}
.hide{
display: none;
}
</style>
<script type="text/javascript" >
function heightChangePersist(elem,startHeight,endHeight,steps,intervals,powr) {
if (elem.heightChangePersist) window.clearInterval(elem.heightChangePersist);
var currStep = 0;
completeFlag++;
elem.heightChangePersist = window.setInterval(
function() {
elem.currHeight = easeInOut(startHeight,endHeight,steps,currStep,powr);
elem.style.height = elem.currHeight+"px";
currStep++;
if (currStep > steps){
window.clearInterval(elem.heightChangePersist);
completeFlag--;
}
}
,intervals)
}
function easeInOut(minValue,maxValue,totalSteps,currStep,powr) {
var delta = maxValue - minValue;
var stepp = minValue+(Math.pow(((1 / totalSteps)*currStep),powr)*delta);
return Math.ceil(stepp);
}
var completeFlag = 0;
function invoke(){
if(completeFlag==0){
var box1=document. getElementById('box1');
var box2=document. getElementById('box2');
box1.style.display='block';
box2.style.display='block';
heightChangePersist(box1,0,box1.offsetHeight,30,30,.5);
heightChangePersist(box2,0,box2.offsetHeight,30,30,.5);
}
}
</script>
<div class="box" onclick="invoke()">
click Here!!
</div>
<div id="box2" class="box hide">
This is a test done to check the animation of a particular item.Hoping it works and i hope to be successful in this trial..!!
</div>
<div id="box1" class="box hide">
This is a test done to check the animation of a particular
item.Hoping it works and i hope to be successful in this trial..!!This is a test done
to check the animation of a particular item.Hoping it works and i hope to be successful in this trial
..!!This is a test done to check the animation of a particular item.Hoping it works
and i hope to be successful in this trial..!!
</div>
Take note on the completeFlag.
A: It's because it call all the times you click 'click me' the event invoke. So it can't finish the interval and then the animation.
If you disable it before start your animation and re-enable it when animation is over it works :)
<html>
<style type="text/css">
.box{
width: 300px;
overflow: hidden;
background: rgba(0,0,0,.5);
color: white;
margin-top: 2px;
}
.hide{
display: none;
}
</style>
<script type="text/javascript" >
function heightChangePersist(elem,startHeight,endHeight,steps,intervals,powr) {
if (elem.heightChangePersist) window.clearInterval(elem.heightChangePersist);
var currStep = 0;
var a = document.getElementById('button');
a.onclick = null;
elem.heightChangePersist = window.setInterval(
function() {
elem.currHeight = easeInOut(startHeight,endHeight,steps,currStep,powr);
elem.style.height = elem.currHeight+"px";
currStep++;
if (currStep > steps) {
window.clearInterval(elem.heightChangePersist);
a.onclick = function onclick(event) { invoke() };
}
}
,intervals)
;
}
function easeInOut(minValue,maxValue,totalSteps,currStep,powr) {
var delta = maxValue - minValue;
var stepp = minValue+(Math.pow(((1 / totalSteps)*currStep),powr)*delta);
return Math.ceil(stepp);
}
function invoke(){
var box1=document. getElementById('box1');
var box2=document. getElementById('box2');
box1.style.display='block';
box2.style.display='block';
heightChangePersist(box1,0,box1.offsetHeight,30,30,.5);
heightChangePersist(box2,0,box2.offsetHeight,30,30,.5);
}
</script>
<div id="button" class="box" onclick="invoke()">
click Here!!
</div>
<div id="box2" class="box hide">
This is a test done to check the animation of a particular item.Hoping it works and i hope to be successful in this trial..!!
</div>
<div id="box1" class="box hide">
This is a test done to check the animation of a particular
item.Hoping it works and i hope to be successful in this trial..!!This is a test done
to check the animation of a particular item.Hoping it works and i hope to be successful in this trial
..!!This is a test done to check the animation of a particular item.Hoping it works
and i hope to be successful in this trial..!!
</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to write a UT for a Runnable java class which has an infinite loop in run()? I have a java class like below. Its job is monitor a file, if that file's size does not change at certain interval, it will raise alert.
I'd like to write two UTs for it.
1.Simulates the file size keeps unchanges.
2.Simulate file size keeps changes for a while. After that file size will change.
The UT will verify alerter.alert() or alerter.harmless() is really invoked when condition is or isn't met. I mocked Alerter and passed it to Task's constructor. But how to control the timing for run()? I know timing for multi-thread cannot be controlled accurately. I just would like to know what is the best practice to write ut for this kind of class. If possible, please write a test sample.
You can regard that "some condition" as checking if a specified file's size changes at a certain interval. If not changed, some condition will be true.
class Task implements Runnable{
Alerter alerter;
boolean stop=false;
public Task(Alerter alerter){
this.alerter=alerter;
}
public void run() {
while (!stop){
if (some condition){
alerter.alert();
} else{
alerter.harmless();
}
Thread.sleep(5000);
}
}
public synchronized void stop(){
stop=true;
}
}
I'm thinking of writing uts like below. But I don't think it is good enough.
@Test
public void testRunWithFeed() {
Alerter mockAlerter=mock(Alerter.class);
Task task=new Task(mockAlerter);
Thread thread =new Thread(task);
thread.start();
try {
Thread.sleep(1000); // give Task.run() a change to run
} catch (InterruptedException e) {
e.printStackTrace();
}
task.stop();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
verify(mockAlerter,atLeastOnce()).alert();
verify(mockAlerter,never()).harmless();
}
@Test
public void testRunNoFeed() {
Alerter mockAlerter=mock(Alerter.class);
Task task=new Task(mockAlerter);
Thread thread =new Thread(task);
thread.start();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
changeFileSize();
try {
Thread.sleep(6000); //because every 5000ms file size will be checked once in run()
} catch (InterruptedException e) {
e.printStackTrace();
}
task.stop();
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
verify(mockAlerter,atLeastOnce()).alert();
verify(mockAlerter,atLeastOnce()).harmless();
}
Thanks in advance.
A: I think that you should not call sleep() and obviously should not call stop in your test.
If you task runs and is expected to terminate calling join() is enough: your main thread will wait until the worker thread is done. Then you will verify the result.
And yet another tip. You should prevent your test from being stuck. Both JUnit and TestNG have annotations that define the test timeout. If timeout is expired the test will be killed by framework and will fail automatically.
For example for JUnit it is the attribute timout: @Test(timeout=3000) means 3 seconds.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Why doesn't my JFrame show up? I'm trying to make a solved sudoku puzzle show up in a window with 81 boxes. I did this:
import java.awt.GridLayout;
import java.awt.*;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class GraphicSolver extends JFrame {
GraphicSolver(int[][] spelplan) {
Panel panel = new Panel(new GridLayout(9,9));
for(int i=9;i<9;i++){
for(int x=0;x<9;x++){
panel.add(new JLabel(""+spelplan[i][x]));
}
}
Frame frame = new Frame();
frame.add(panel);
frame.setVisible(true);
}
}
However, it only gives me an empty window without any numbers. I'd be pleased if someone could point me in the right direction.
A: The outer loop should start at zero:
for(int i=0;i<9;i++){
A: Try calling frame.pack (), this will pack all the components into the frame to be displayed after computing the correct size with the panels. Also, follow the fix suggested by @trashgod above will solve the fact that no panels were added, and the fix by @Ashkan Aryan will make your code a bit more reasonable (although it should work without it, but then there is no point in inheriting from JFrame).
The code below works for me:
GraphicSolver(int[][] spelplan) {
Panel panel = new Panel(new GridLayout(9,9));
for(int i=0;i<9;i++){
for(int x=0;x<9;x++){
panel.add(new JLabel(""+spelplan[i][x]));
}
}
this.add(panel);
this.pack ();
this.setVisible(true);
}
A: You seem to have two Frames. 1 is the JFrame (the class GrpahicSolver itself) and the other a frame that you are creating within it.
I suggest you replace frame.addPanel() with this.addPanel() and it should work.
A:
import java.awt.GridLayout;
import javax.swing.*;
public class GraphicSolver {
GraphicSolver(int[][] spelplan) {
// presumes each array 'row' is the same length
JPanel panel = new JPanel(new GridLayout(
spelplan.length,
spelplan[0].length,
8,
4));
for(int i=0;i<spelplan.length;i++){
for(int x=0;x<spelplan[i].length;x++){
panel.add(new JLabel(""+spelplan[i][x]));
}
}
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
int[][] plan = new int[4][7];
for (int x=0; x<plan.length; x++) {
for (int y=0; y<plan[x].length; y++) {
plan[x][y] = (x*10)+y;
}
}
new GraphicSolver(plan);
}
});
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Add View to a Fragment Dynamically in Android? Is it possible to add a View to a Fragment dynamically? If it is, how can i do that?
A:
Is it possible to add a View to a Fragment dynamically?
Yes.
If it is, how can i do that?
The same way you would add a View anywhere else: call addView() on the View's parent container.
A: HomeFragment frag = new HomeFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragLogin, frag);
ft.setCustomAnimations(R.anim.right_in, R.anim.right_out);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.commit();
Here,R.id.fragLogin is the id of your first fragment which you have declared in your activities xml and HomeFragment is your second Fragment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512369",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Can DBIx::Class be used with stored procedures instead of tables? The access to read from the db has been given to me via mssql stored procedures that return result sets rather than tables or views. But I want to be able to read the data using ORM.
I tried to use DBIx::Class::ResultSource::View to do the procedure call (e.g. EXEC my_stored_proc ?) as a custom query but this didn't work because it tried to convert the procedure call into a select statement.
Does anyone have another suggestion?
A: No, there is no reasonable way to execute a stored procedure in the context of DBIx::Class.
As far as I can tell, the closest thing to a workaround is "using the ORM" to get a database handle, which is weak soup:
my @results = $schema->storage->dbh_do(sub{
my ($storage, $dbh, @args) = @_;
my $sth = $dbh->prepare('call storedProcNameFooBar()');
my @data;
$sth->execute();
while( my $row = $sth->fetchrow_hashref){
push @data, $row;
}
return @data;
},());
[ see details at
http://metacpan.org/pod/DBIx::Class::Storage::DBI#dbh_do ]
...as you get none of the benefits of an ORM for your trouble.
A: You can use register_source
package My::Schema::User;
use base qw/DBIx::Class/;
# ->load_components, ->table, ->add_columns, etc.
# Make a new ResultSource based on the User class
my $source = __PACKAGE__->result_source_instance();
my $new_source = $source->new( $source );
$new_source->source_name( 'UserFriendsComplex' );
# Hand in your query as a scalar reference
# It will be added as a sub-select after FROM,
# so pay attention to the surrounding brackets!
$new_source->name( \<<SQL );
( SELECT u.* FROM user u
INNER JOIN user_friends f ON u.id = f.user_id
WHERE f.friend_user_id = ?
UNION
SELECT u.* FROM user u
INNER JOIN user_friends f ON u.id = f.friend_user_id
WHERE f.user_id = ? )
SQL
# Finally, register your new ResultSource with your Schema
My::Schema->register_source( 'UserFriendsComplex' => $new_source );
To call with parameters do the following
my $friends = [ $schema->resultset( 'UserFriendsComplex' )->search( {
+},
{
bind => [ 12345, 12345 ]
}
) ];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to stop the timer function after the object has been shot? I am making a simple target shooting game.I have a countdownTimer inside the label and an object that blinks in a random position inside the panel. Every time I click on the object,. the object's timer stops which makes that object stop too, but the countdown timer doesn't and that is my problem. I want the countdown timer should stop also.
Could someone help me about this matter?
Here's the code :
private void starting()
{
new Timer(TIMER_PERIOD, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
if (count++ < MAX_COUNT)
{
String text = "Time remaining: (" + (MAX_COUNT - count) + ") seconds left";
setCountDownLabelText(text);
Date date = new Date();
setCountDownPanelText(date);
}
else
{
((Timer) e.getSource()).stop();
randomTimer.stop();
JOptionPane.showMessageDialog(null, "Game Over");
System.exit(0);
}
}
}).start();
}
A: It strikes me that you don't understand the code at all, that you are unaware of the anonymous class created that is extending Timer, which (if you'd seen the documentation) has a function stop() which does what you ask.
You need to store a reference to the Timer.
private javax.swing.Timer timer;
private void starting() {
timer = new Timer(TIMER_PERIOD, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
// do stuff
// stop the timer
timer.stop();
// do other stuff
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512377",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: accessing operator overloading of class which is wrapped by std::shared_ptr the idea is that I want a class which is wrapped by std::shared_ptr, can still be used
just like they weren't a pointer, for example the operator= which was defined in my class
can still be used after my class is wrapped by std::shared_ptr.
for example
template <class Ty> class shared_ptr_proxy : public std::shared_ptr<Ty> {
public:
template<class Other> shared_ptr_proxy& operator=(const Other& rhs)
{
(*this->get()) = rhs;
return *this;
}
template<class Other> explicit shared_ptr_proxy(Other * ptr)
: std::shared_ptr<Ty>(ptr){};
};
// usage :
shared_ptr_proxy<float> obj = shared_ptr_proxy<float>(new float);
obj = 3.14;
its work, but is there a way that i don't need to create shared_ptr_proxy or
inheriting a class from std::shared_ptr ?
and
if I do like this, is there a caveat that i should take care of?
A: It depends on what you want the proxy for. A full proxy might make it look entirely like you had the value, so you'd provide the conversion operators.
In such case, it might not be a good idea to inherit from shared_ptr, though, because you might be inheriting functions that you want to rely on the implicit conversions instead.
Compare how sorting orders the items:
#include <memory>
#include <vector>
#include <algorithm>
#include <iostream>
template <class Ty> class shared_ptr_proxy {
std::shared_ptr<Ty> ptr;
public:
template<class Other> explicit shared_ptr_proxy(Other * p)
: ptr(std::shared_ptr<Ty>(p)){};
template<class Other> shared_ptr_proxy& operator=(const Other& other)
{
*ptr = other;
return *this;
}
operator Ty& () { return *ptr; }
operator const Ty& () const { return *ptr; }
};
int main()
{
std::vector<shared_ptr_proxy<int> > vec {
shared_ptr_proxy<int>(new int(10)),
shared_ptr_proxy<int>(new int(11)),
shared_ptr_proxy<int>(new int(9))
};
vec.back() = 8; //use assignment
std::sort(vec.begin(), vec.end()); //sort based on integer (not pointer) comparison
for (unsigned i = 0; i != vec.size(); ++i) {
std::cout << vec[i] << ' '; //output stored values
}
}
#include <memory>
#include <vector>
#include <algorithm>
#include <iostream>
template <class Ty> class shared_ptr_proxy : public std::shared_ptr<Ty> {
public:
template<class Other> explicit shared_ptr_proxy(Other * p)
: std::shared_ptr<Ty>(p){};
template<class Other> shared_ptr_proxy& operator=(const Other& other)
{
*this->get()= other;
return *this;
}
operator Ty& () { return *this->get(); }
operator const Ty& () const { return *this->get(); }
};
int main()
{
std::vector<shared_ptr_proxy<int> > vec {
shared_ptr_proxy<int>(new int(10)),
shared_ptr_proxy<int>(new int(11)),
shared_ptr_proxy<int>(new int(9))
};
vec.back() = 8; //the only thing that works
std::sort(vec.begin(), vec.end()); //sort based on pointer values
for (unsigned i = 0; i != vec.size(); ++i) {
std::cout << vec[i] << ' '; //outputs addresses
}
}
A: operator= must be a member of the class that you're overloading. So no, you can't really do that non-intrusively.
A: No, you can't do this transparently, and it would probably be quite confusing if you could.
A: Sorry, I don't think you can get away without inheriting or a custom wrapper, you can not overload operator = outside the definition of shared_ptr, and inheritance is not recommended in this case due to the nature of shared_ptr. However if you write a custom wrapper you can make it generic enough that it works for every type.
It is only possible in C++11, and even there it is difficult. You need decltype and std::declval for deducing the return type of the operator, and rvalue references and std::forward to forward the parameters perfectly. See this question and its answers for examples.
And as mentioned in that question, I have a pointer wrapper class implemented: http://frigocoder.dyndns.org/svn/Frigo/Lang/ref
However it has some differences compared to what you want:
*
*Both operator = (ref&) and operator = (ref&&) only copies pointers. However, due to this and the proxied copy constructor, the implicit operator = (const T&) does a copy construction and a pointer copy instead of assignment or taking the address. This is a conscious choice of mine, assignment can create problems if the object is shared, and taking pointer from a stack allocated object is unsafe.
*Taking the return type of compound assignment operators like operator += does not work due to an unimplemented feature of GCC. This is no problem since they are reinterpreted: x += y calls x = (x + y), doing a copy/move construction and a pointer copy. This is also a conscious choice of mine, to keep the shared object unchanged.
*Garbage collected with Boehm GC instead of reference counted. This is also a conscious choice of mine, reference counting is a pretty bad alternative to garbage collection.
A: Dereference shared pointer:
std::shared_ptr<float> obj(new float);
*obj = 3.14;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Album name gets corrupted when characters are Japanese Please let me know the maximum number of "Album Name".
Now I'm developing Photo Upload app with Graph API.
When creating an album, the album name gets corrupted if the number of Japanese characters exceeds 21.
Below is the example of this issue.
e.g.
Input:
あいうえおかきくけこあいうえおかきくけこあい
Registered Album Name:
あいうえおかきくけこあいうえおかきくけこあ��
Note that the same issue occurs if more than 21 Korean or Chinese characters are set as Album Name.
A: It would appear that there is a length limit on this field. Guessing that they're using UTF-8, it would be a limit of 64 bytes, rather than a integral number of characters.
Facebook appear to be truncating the string at that number of bytes, regardless of whether that byte limit happens to align with a character boundary or not. This kind of misbehaviour is unfortunately common in languages that don't handle text strings as Unicode characters natively. In your case the last い takes up three bytes, but there's only room for two, so you get left with two trailing bytes that don't form a valid UTF-8 sequence, hence ��.
To stop this happening you'd have to do their job for them and impose the length limit in a Unicode-clean way. One way to do this would be to encode to UTF-8 yourself, do the truncation, and convert back to characters ignoring the invalid end bytes. eg in Python:
>>> print u'あいうえおかきくけこあいうえおかきくけこあい'.encode('utf-8')[:64].decode('utf-8', 'ignore')
あいうえおかきくけこあいうえおかきくけこあ
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: mysql limiting join I've done a few searches on this subject but non of the solutions seem to work so perhaps my requirement is slightly different.
Basically I have a "content" table and a "file_screenshots" table. Each row in the "file_screenshots" table has a "screenshot_content_id" column. I want to select from the "content" table, join the "file_screenshots" table but only select a maximum of 5 screenshots for any single piece of content.
If this isn't possible i'm happy to use two queries, but again i'm not sure how to limit the results to only receiving 5 screenshots per piece of content.
Here is an example query:
SELECT * FROM content
LEFT JOIN file_screenshots
ON file_screenshots.screenshot_content_id = content.content_id
WHERE content_type_id = 4
A: Assuming you have some sort of unique id column in your file_screenshots table, this should work for you:
SELECT
c.*,
fs.*
FROM
content c
JOIN
file_screenshots fs
ON (fs.screenshot_content_id = c.content_id)
LEFT JOIN
file_screenshots fs2
ON (fs2.screenshot_content_id = c.content_id AND fs2.id < fs.id)
GROUP BY
fs.id
HAVING
COUNT(*) < 5
ORDER BY c.content_id, fs.id
I've named the id column id. Rename it if neccessary.
If you want the 5 screenshots with the highest id, reverse the fs2.id vs. fs.id comparison.
ON (fs2.screenshot_content_id = c.content_id AND fs2.id > fs.id)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Regex (?:[,\\. ]*(&|and) ?) is not matching ', and " Regex (?:[,\\. ]*(&|and) ?) is not matching ", and ". But when i change the matcher to (?:[,\\.] ?(&|and) ?) the pattern ", and " is getting matched. What is causing pblm?
When i remove the space from [,\\. ]* it seems working. I simply dnt understand.
A: I can find the match even with the space. It would be helpful if you can post the exact code.
Pattern p = Pattern.compile("(?:[,\\. ]*(&|and) ?)");
Matcher matcher = p.matcher(", and ");
System.out.println("Match? " + matcher.find());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: facet dynamic fields with apache solr I have defined dynamic field in ApacheSolr:
I use it to store products features like: color_feature, diameter_feature, material_feature and so on. Number of those fields are not constant becouse products are changing.
Is it possible to get facet result for all those dynamic fields with the same query or do I need to write always all fields in a query like ... facet.field=color_feature&facet.field=diameter_feature&facet.field=material_feature&facet.field=...
A: Solr currently does not support wildcards in the facet.field parameter.
So *_feature won't work for you.
May want to check on this - https://issues.apache.org/jira/browse/SOLR-247
If you don't want to pass parameters, you can easily add these to your request handler defaults.
The qt=requesthandler in request would always include these facets.
A: I was in a similar situation when working on an e-commerce platform. Each item had static fields (Price, Name, Category) that easily mapped to SOLR's schema.xml, but each item could also have a dynamic amount of variations.
For example, a t-shirt in the store could have Color (Black, White, Red, etc.) and Size (Small, Medium, etc.) attributes, whereas a candle in the same store could have a Scent (Pumpkin, Vanilla, etc.) variation. Essentially, this is an entity-attribute-value (EAV) relational database design used to describe some features of the product.
Since the schema.xml file in SOLR is flat from the perspective of faceting, I worked around it by munging the variations into a single multi-valued field ...
<field
name="variation"
type="string"
indexed="true"
stored="true"
required="false"
multiValued="true" />
... shoving data from the database into these fields as Color|Black, Size|Small, and Scent|Pumpkin ...
<doc>
<field name="id">ITEM-J-WHITE-M</field>
<field name="itemgroup.identity">2</field>
<field name="name">Original Jock</field>
<field name="type">ITEM</field>
<field name="variation">Color|White</field>
<field name="variation">Size|Medium</field>
</doc>
<doc>
<field name="id">ITEM-J-WHITE-L</field>
<field name="itemgroup.identity">2</field>
<field name="name">Original Jock</field>
<field name="type">ITEM</field>
<field name="variation">Color|White</field>
<field name="variation">Size|Large</field>
</doc>
<doc>
<field name="id">ITEM-J-WHITE-XL</field>
<field name="itemgroup.identity">2</field>
<field name="name">Original Jock</field>
<field name="type">ITEM</field>
<field name="variation">Color|White</field>
<field name="variation">Size|Extra Large</field>
</doc>
... so that when I tell SOLR to facet, then I get results that look like ...
<lst name="facet_counts">
<lst name="facet_queries"/>
<lst name="facet_fields">
<lst name="variation">
<int name="Color|White">2</int>
<int name="Size|Extra Large">2</int>
<int name="Size|Large">2</int>
<int name="Size|Medium">2</int>
<int name="Size|Small">2</int>
<int name="Color|Black">1</int>
</lst>
</lst>
<lst name="facet_dates"/>
<lst name="facet_ranges"/>
</lst>
... so that my code that parses these results to display to the user can just split on my | delimiter (assuming that neither my keys nor values will have a | in them) and then group by the keys ...
Color
White (2)
Black (1)
Size
Extra Large (2)
Large (2)
Medium (2)
Small (2)
... which is good enough for government work.
One disadvantage of doing it this way is that you'll lose the ability to do range facets on this EAV data, but in my case, that didn't apply (the Price field applying to all items and thus being defined in schema.xml so that it can be faceted in the usual way).
Hope this helps someone!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.