text
stringlengths 8
267k
| meta
dict |
---|---|
Q: What is a boolean flag I'm taking a course in Visual Basic 2010 and I'm trying to get a grasp on this new term called a flag. I kind of understand that it has something to do with a boolean condition. I don't quite understand what a flag is. I see references to it using the term flag. I understand it has something to do when a boolean, a condition triggers a flag. But what is the flag. How do you identify it? Can somebody give me an example.
A: In general, "Flag" is just another term for a true/false condition.
It may have more specific meanings in more specific contexts. For instance, a CPU may keep "arithmetic flags", each one indicating a true/false condition resulting from the previous arithmetic operation. For instance, if the previous operation was an "ADD", then the flags would indicate whether the result of the add was zero, less than zero, or greater than zero.
I believe the term comes from flags used to signal a go/no go condition, like, a railroad flagman indicating whether or not it is safe for the train to proceed.
A: You hear this quite a bit with BOOL being a 'Flag' since there are only 2 outcomes either TRUE or FALSE. Using BOOL in your decision making processes is an easy way to 'flag' a certain outcome if the condition is met.
An example could be:
if ($x == TRUE) {
// DO THIS
{
else {
//Flag not tripped, DO THIS
}
A: You can use this with bitwise operations. It can be used to pack 32 booleans into one integer. Here's a sample:
Dim flags As Integer
Const ADMINISTRATOR = 1
Const USER = 2
Const BLUE = 4
Const RED = 8
flags = ADMINISTRATOR or BLUE
If flags and ADMINISTRATOR then
' Do something since the person is an admin
End If
The ors add flags and ands check if the flag is set.
Now we can check up to 32 booleans for this one variable. Great for storing in a database. You can use bigger datatypes, like a long to store more.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to test for nth-child using Modernizr? I'm trying to use modernizr to test for :nth-child browser support but I'm not sure how to do it, I found this one http://jsfiddle.net/laustdeleuran/3rEVe/ which tests for :last-child but I don't know how to change it to detect :nth-child (I was also thinking about using it like that since I believe that browsers that don't support :last-child don't support :nth-child either but I'm not sure)
Can you guys help me? Thanks in advance!
A: I remember there was a Modernizr selectors plugin that tested for selectors support, but I can't find it right now. You can take a look at this: http://javascript.nwbox.com/CSSSupport/ which is similar.
A: You can also use Selectivizr to add CSS3 selector support to unsupported browsers
A: I just wrote a function to detect the :nth-child support for you
function isNthChildSupported(){
var result = false,
test = document.createElement('ul'),
style = document.createElement('style');
test.setAttribute('id', 'nth-child-test');
style.setAttribute('type', 'text/css');
style.setAttribute('rel', 'stylesheet');
style.setAttribute('id', 'nth-child-test-style');
style.innerHTML = "#nth-child-test li:nth-child(even){height:10px;}";
for(var i=0; i<3; i++){
test.appendChild(document.createElement('li'));
}
document.body.appendChild(test);
document.head.appendChild(style);
if(document.getElementById('nth-child-test').getElementsByTagName('li')[1].offsetHeight == 10) {result = true;}
document.body.removeChild(document.getElementById('nth-child-test'));
document.head.removeChild(document.getElementById('nth-child-test-style'));
return result;
}
Usage:
isNthChildSupported() ? console.log('yes nth child is supported') : console.log('no nth child is NOT supported');
You can see this works in action here
http://jsbin.com/epuxus/15
Also There is a difference between jQuery :nth-child and CSS :nth-child.
jQuery :nth-child is supported in any browser jQuery supports but CSS :nth-child is supported in IE9, Chrome, Safari and Firefox
A: Mohsen, thank you for your decision.
If someone needs to jQuery:
function test(){
var result = false,
test = $('<ul id="nth-child-test"><li/><li/><li/></ul>').appendTo($('body')),
style = $('<style type="text/css">#nth-child-test li:nth-child(even){height:10px;}</style>').appendTo($('head'));
if(test.children('li').eq(1).height() == 10)
result = true;
test.remove();
style.remove();
return result;
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: OnTouch locations tablets vs. phone I made a particle system that was designed for a tablet.. particles follow finger movement etc. anyways.. I implemented the gyroscope so when you tilt the tablet whatever direction.. all the particles fall to that direction. In the manifest I locked it down to landscape view.
So then I loaded it up on a Samsung Intercept. When I moved that screen around nothing was going in the correct direction at all.. So what I did to fix the situation is
if (width<800) // My tablet width is obviously 800 phone is much less
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
else
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
this fixes my problem.. but I'm unsure if this is for all phones? My samsung intercept is only for development and it's a POS IMO. Is it the phone or is this just how it works..
A: Some devices have a natural orientation of portrait and some have a natural orientation of landscape. This will affect the default sensor coordinate system for the device. Take a look at this post from the Android Developers blog for more details and solutions: http://android-developers.blogspot.com/2010/09/one-screen-turn-deserves-another.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL View - Combine multiple rows into 1 row I am trying to make a new view using in MSSql 2008 from three tables:
Table 1 has customer id and transaction id
Table 1
CustomerID TransactionID
1 1
1 2
Table 2 has Purchases Transaction and Products ID
TransactionID ProductID
1 x
2 y
Table 3 has Products Names
ProductID Name
1 x
2 y
I view I would like to make should show
CustomerID Product Name
1 x, y
When I use the following query:
SELECT table1. CustomerID, table3.Name
FROM table1 LEFT OUTER JOIN
Table2 ON table2. TransactionID = table1.VisitId LEFT OUTER JOIN
Table3 ON table2. ProductID = Table3. ProductID
GROUP BY table1. CustomerID, table3.Name
I get
CustomerID Product Name
1 x
1 y
Thanks in Advance
A: One way to do this is to use a user defined function, something like:
SELECT table1.CustomerID, dbo.BuildStringOfCustomerProductNames(table1.CustomerID)
FROM table1
And create a user defined function like: dbo.BuildStringOfCustomerProductNames
that takes a customerid as input.
Inside there, you can run a query to loop through the table 2 and table 3 joined records to make a string, and return that.
Off hand I can't think of any other simple way to do it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Find links in page and run it through custom function function link_it($text)
{
$text= preg_replace("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a href=\"$3\" target=\"_blank\">$3</a>", $text);
$text= preg_replace("/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\" target=\"_blank\">$3</a>", $text);
$text= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"mailto:$2@$3\" target=\"_blank\">$2@$3</a>", $text);
return($text);
}
That's the working code.
I'm working on a new function
function shorturl2full($url)
{
echo 'URL IS: ' . $url;
return "FULLLINK";
}
The idea is to take the url and return it back. Later going to work on turning it in to the full url. So like t.co will be full url they will see.
$text= preg_replace("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", "$1$2<a href=\"$3\" target=\"_blank\">" . shorturl2full("$3") . "</a>", $text);
$text= preg_replace("/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/is", "$1$2<a href=\"http://$3\" target=\"_blank\">" . shorturl2full("$3") . "</a>", $text);
$text= preg_replace("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", "$1<a href=\"mailto:$2@$3\" target=\"_blank\">$2@$3</a>", $text);
return($text);
}
Is my bad try at it.
So if you click the link it should use the original but the one you see should be the output of shorturl2full
So like <a href="t.co">FULLLINK</a>
I want to attempt to write the shorturl2full function on my own and i think i have a very great idea on how to do it. The problem is in the link_it function... It needs to pass the url to the shorturl2full function and display what ever it returned.
A: You can use preg_replace_callback instead of preg_replace http://nz.php.net/manual/en/function.preg-replace-callback.php
function link_it($text)
{
$text= preg_replace_callback("/(^|[\n ])([\w]*?)((ht|f)tp(s)?:\/\/[\w]+[^ \,\"\n\r\t<]*)/is", 'shorturl2full', $text);
$text= preg_replace_callback("/(^|[\n ])([\w]*?)((www|ftp)\.[^ \,\"\t\n\r<]*)/is", 'shorturl2full', $text);
$text= preg_replace_callback("/(^|[\n ])([a-z0-9&\-_\.]+?)@([\w\-]+\.([\w\-\.]+)+)/i", 'shorturl2full', $text);
return($text);
}
function shorturl2full($url)
{
$fullLink = 'FULLLINK';
// $url[0] is the complete match
//... you code to find the full link
return '<a href="' . $url[0] . '">' . $fullLink . '</a>';
}
Hope this helps
A: In a previous answer I have shown a function called make_clickable which has an optional callback parameter which get's applied to each URI if set:
make_clickable($text, 'shorturl2full');
Maybe it's helpful or gives some ideas at least.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP-CLI Sudo Execution I am running a cli-script, that requires a exec('sudo ...'); call. I know it is not safe on the web, but how can it be done in cli? The script is executed by a user known as "btcdbit", who is in the sudoers file.
A: In my experience setting the NOPASSWD option doesn't always work and even if it does it seems unsafe. Seems to me that a better approach - if you're able to use it - would involve using phpseclib to do sudo through SSH. eg.
<?php
include('Net/SSH2.php');
$sftp = new Net_SSH2('www.domain.tld');
$sftp->login('username', 'password');
echo $sftp->read('username@username:~$');
$sftp->write("sudo ls -la\n");
$output = $sftp->read('#Password:|username@username:~\$#', NET_SSH2_READ_REGEX);
echo $output;
if (preg_match('#Password:#', $lines)) {
$ssh->write("password\n");
echo $sftp->read('username@username:~$');
}
?>
The website "sudo in php" elaborates
A: So long as btcdbit is in sudoers for the program that you want it to be able to run, you should be able to use any of the PHP functions like exec or system to run it. Make sure that you use the NOPASSWD option in sudoers (see http://www.ducea.com/2006/06/18/linux-tips-password-usage-in-sudo-passwd-nopasswd/ for example) if you don't want it to get caught up asking btcdbit for a password.
A: It should be just as simple as exec('/usr/bin/sudo {script}').
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: c# picturebox point to filesystem i have a picture box in my win forms app. the question is, how can i make the image load from a directory within that application,
for example, i have a program and it lies under Debug directory. Now i have an image located under Debug/source/images/logo.png. I dont want to make use of resources file (embedded within the assembly)
How can i point it towards that path, instead of getting the image/picture from the local resources file.
A: There are a number of ways to do this, you can use the ImageLocation property or the Load method to specify the path just take a look at the documentation here
A: Try this
String.Format(@"{0}\myDesiredPath\MyFile.MyExtension",System.Reflection.Assembly.GetExecutingAssembly().Location);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Interface php results with jQuery I have quite some experience with php, but I am very new to using jQuery.
I am hoping someone can give me some example code (preferably) or point me in the right direction for which jQuery functions I need to use, essentially, what I want to do is for a user to submit a form in php and then for the results of that form submit to be displayed on the same page using jQuery (I assume).
Like I said I have very little experience with jQuery, and none doing something like this. So any help is appreciated.
A: You might want to check out the jQuery form plugin.
http://jquery.malsup.com/form/
The site has loads of examples too.
A: Well, this answer is not really targeted at the newbie, but if you really want to dig into writing your own custom a PHP/JQuery interface you might want to try something like this:
*
*use ajax function name as a php pseudo function name
*implement jquery and let php echo the output.
*this can be useful if you want to only write your code in php only
*not really practical but it works some 90% of the time.
Note sure if there's any library out there that does this implementation but I do have some
sample implementation which I use on some custom development projects, maybe you might find
some of the insights useful if you are really into writing your own code.
See the following code snippet
<?php
function js_start(){
return '<script type="text/javascript">';
}
function js_add_jquery($version='1.4.2'){
return '<script src="https://ajax.googleapis.com/ajax/libs/jquery/'.$version.'/jquery.min.js"></script>';
}
function js_ajax($url, $data, $success){
return "
$.ajax({
url: '$url',
data: '$data',
success: $success
});";
}
function js_end(){
return '</script>';
}
//Example usage:
// where success is behaviour you want executed on success
$success =
"function(data) {
$('#page').html(data);
}";
echo js_add_jquery(); // default version 1.4.2 is used here
echo js_start();
echo js_ajax('test.php', 'name=John&surname=Doe', $success);
echo js_end();
?>
A: You could place a function on a button that checks for values in input fields and then writes them out in another area.
Your question is a bit ambiguous.
Resources:
http://api.jquery.com/val/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Model.find(:all, :conditions ...) on one field for one key-value from a hash? I have a table of email messages like so:
create_table :emails do |t|
t.string :emailMessageId
t.datetime :date
t.string :subject
t.string :gmailMessageId
t.string :gmailThreadId
t.string :from_hash, :default => nil
t.text :to_hash, :default => nil
t.text :cc_hash, :default => nil
t.integer :contact_id
The email.rb model file says:
class Email < ActiveRecord::Base
serialize :from_hash, Hash
serialize :to_hash, Array
serialize :cc_hash, Array
end
Imagine that
:to_hash = {"name" => "john", "email" => "[email protected]"}
or an array of hashes
:to_hash = [ {"name" => "john", "email" => "[email protected]"}, {"name" => "bob", "email" => "[email protected]"} ]
As an example, here is Email.first
#<Email id: 1, emailMessageId: "357", date: "2011-10-03 00:39:00", subject: nil,
gmailMessageId: nil, gmailThreadId: nil, from_hash: {"name"=>"melanie",
"email"=>"[email protected]"}, to_hash: [{"name"=>"michie", "email"=>"[email protected]"},
{"name"=>"clarisa", "email"=>"[email protected]"}], cc_hash: [{"name"=>"john",
"email"=>"[email protected]"}, {"name"=>"alex", "email"=>"[email protected]"}], contact_id: 1,
created_at: "2011-10-03 00:39:00", updated_at: "2011-10-03 00:39:00">
Further imagine that my database has thousands of such records, and I want to pull all records keyed on :to_hash["email"]. In other words, I want to be able to find all records in the Email model that contain the email "[email protected]" despite the fact that the email value is within an array of hashes. How do I do this?
I tried variations on:
hash = {"name" => "john", "email" => "[email protected]"}
Email.find(:all, :conditions => ["to_hash = ?", hash]) # returns the following error
ActiveRecord::StatementInvalid: SQLite3::SQLException: near ",": syntax error: SELECT "emails".* FROM "emails" WHERE (to_hash = '---
- name
- john
','---
- email
- [email protected]
')
I also tried:
email = "[email protected]"
Email.find(:all, :conditions => ["to_hash = ?", email])
# => [], which is not an error, but not what I want either!
And finally:
email = "[email protected]"
Email.find(:all, :conditions => ["to_hash['name'] = ?", email])
# which, as expected, gave me a syntax error...
ActiveRecord::StatementInvalid: SQLite3::SQLException: near "['name']": syntax error: SELECT
"emails".* FROM "emails" WHERE (to_hash['name'] = '[email protected]')
A: The simple answer is;
if you need to query something, you shouldn't serialize it.
Saying that, I think the answer is just
Email.all(:conditions => ["to_hash LIKE '%email: ?%'", "[email protected]"])
If you look at the database contents this should satisfy you.
But going forward you should look for a better solution.
Serialization is great for storing structured data that you never need to use in a sql query,
but just gets in the way if you do.
If you really need this kind of freeform data structure, I suggest you look at using MongoDB and Mongoid.
However, within the usual Rails world, I'd suggest the following;
class Email
has_many :email_recipients
def to_hash
email_recipients.map do |recipient|
{"name" => recipient.name, "email" => recipient.email}
end
end
end
class EmailRecipient
# with columns
# email_id
# name
# email
belongs_to :email
end
A: One possible way to do this with just regular Ruby is to use the select method and let ActiveRecord take care of deserialization.
emale = "[email protected]"
Email.find(:all).select { |m| m[:to_hash]["email"] === emale }
Another possible solution is to serialize the search hash and match the serialized hash exactly how it is saved in the database. This requires that the hash has all attributes, not just the e-mail. Some useful links to the code that makes this happen available here. You'll see that ActiveRecord uses YAML for serialization by default, so something like this could work.
search_hash = {"name" => "john", "email" => "[email protected]"}
encoder = ActiveRecord::Coders::YAMLColumn.new(Hash)
search_string = encoder.dump(search_hash)
Email.find(:all, :conditions => ["to_hash = ?", search_string])
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error applying image style dynamically, why? attrs.xml:
<declare-styleable name="AppTheme">
<attr name="actionbarCompatLogoStyle" format="reference" />
</declare-styleable>
styles.xml:
<style name="Theme.MyApp" parent="android:style/Theme.Light">
<item name="actionbarCompatLogoStyle">@style/ActionBarCompatLogo</item>
</style>
<style name="ActionBarCompatLogo">
<item name="android:layout_width">30dp</item><!-- original image is huge -->
<item name="android:layout_height">30dp</item>
<item name="android:src">@drawable/app_logo</item>
</style>
Problem: if I use this, image dimensions won't work (huge image):
ImageButton logo = new ImageButton(context, null, R.attr.actionbarCompatLogoStyle);
If I use this, it works (tiny image, which is what I want):
<ImageView style="@style/ActionBarCompatLogo"></ImageView>
Why?
A: Any attribute prefixed with layout_ is part of a LayoutParams object. LayoutParams are special arguments to the parent view about how it should lay out the child view. The type of LayoutParams you set on a view is dependent on what type of ViewGroup you are adding it to. Each container view type can be different and so can the LayoutParams. layout_weight is specific to LinearLayout, layout_below is for RelativeLayout, etc. layout_width and layout_height are part of the base ViewGroup LayoutParams.
The takeaway from this is that LayoutParams are not parsed by the view's constructor, they're parsed by another step that your code above isn't doing. (The LayoutInflater involves the parent ViewGroup's generateLayoutParams method.)
Since LayoutParams are dependent on the intended parent of the View it's not recommended to put LayoutParams in styles. It mostly works when you are inflating views from layout XML but it has other implications similar to the edge case you've found here and requires you to be aware of them. For example, a style may specify layout_weight for a LinearLayout but if a view with that style is added to a RelativeLayout instead it will not behave as expected since RelativeLayout does not support layout_weight.
A: As far as I know it's not possible to apply styles to specific views programmatically, only via XML.
What you can do is to set a theme on your activity inside the onCreate() method. Consult this question: android dynamically change style at runtime
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Best way to show navigation details for more than one destination I am working on a navigation program for the Android, and one feature is to allow you to enter several destinations, and it will show directions on how to get from point A to point B to point C.
My difficulty is showing the details, as I am not certain the best choices to use.
Basically what I want to do is to show the top level detail, so you can see going to Point B and how many miles/minutes is estimated, but if there are several of these listed, as TextView components, would it be a simple move to the right to show all the details of that part of the trip, and move the left to show the top view of each destination?
I hope this makes sense, basically, I want to just show the address/travel time/distance to each waypoint, but then give the user an intuitive way to see the details of that part of the trip.
I am developing this for Android 2.3, btw.
A: I personally prefer using the google maps treeview listing on the journey details and the estimated time listed as the heading of the treeview.
But i do understand that you would like to change the destination view details such that each journey details are listed on the right.
like
Point A to B blah,blah,blah
blah,blah,blah
Point B to C blah,blah,blah
For this i suggest you make a custom view so that you will have more flexibility in designing the layout according to your needs
I hope this answers your question, btw i am only a junior android developer..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Expression for summing all the entries of a logical matrices expressions in Matlab? To sum all the elements in a matrix you usually do
A = sum ( B(:) );
which is nice and short. However assume that we have a logical expression like this
B = B == 6
and we want to sum the elements of all the entries, then smartest way seems to be to do
A = sum ( sum ( B == 6 ) )
or
B = B == 6;
A = sum( B(:) );
Both are kind of ugly. So I was wondering is there a nicer expression?
A = sum ( (B == 6)(:) );
Would be nice but doesn't work.
A: So what is so nasty about the simple solution...
A = sum(B(:) == 6);
A: Not that I recommend this, but as was shown previously, you can actually do something like:
%# A = sum ( (B == 6)(:) )
A = sum( subsref(B == 6, struct('type','()', 'subs',{{':'}})) )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630432",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: wxPython and windows 7 taskbar For brevity's sake: I'm trying to implement this with wxPython, but I'm struggling to fit that code into a script based on wxPython.
My simple PyQt test code works fine. Here it is:
from PyQt4 import QtGui
from threading import Thread
import time
import sys
import comtypes.client as cc
import comtypes.gen.TaskbarLib as tbl
TBPF_NOPROGRESS = 0
TBPF_INDETERMINATE = 0x1
TBPF_NORMAL = 0x2
TBPF_ERROR = 0x4
TBPF_PAUSED = 0x8
cc.GetModule("taskbar.tlb")
taskbar = cc.CreateObject("{56FDF344-FD6D-11d0-958A-006097C9A090}", interface=tbl.ITaskbarList3)
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self, parent)
self.setWindowTitle("Test")
self.progress_bar = QtGui.QProgressBar(self)
self.setCentralWidget(self.progress_bar)
self.progress_bar.setRange(0, 100)
self.progress = 0
self.show()
thread = Thread(target=self.counter)
thread.setDaemon(True)
thread.start()
def counter(self):
while True:
self.progress += 1
if self.progress > 100:
self.progress = 0
time.sleep(.2)
self.progress_bar.setValue(self.progress)
taskbar.HrInit()
hWnd = self.winId()
taskbar.SetProgressState(hWnd, TBPF_ERROR)
taskbar.SetProgressValue(hWnd, self.progress, 100)
app = QtGui.QApplication(sys.argv)
ui = MainWindow()
sys.exit(app.exec_())
But, when I try to execute the wxPython counterpart, the taskbar doesn't work as expected. Here's the wxPython code:
import wx
import time
import comtypes.client as cc
import comtypes.gen.TaskbarLib as tbl
from threading import Thread
TBPF_NOPROGRESS = 0
TBPF_INDETERMINATE = 0x1
TBPF_NORMAL = 0x2
TBPF_ERROR = 0x4
TBPF_PAUSED = 0x8
cc.GetModule("taskbar.tlb")
taskbar = cc.CreateObject("{56FDF344-FD6D-11d0-958A-006097C9A090}", interface=tbl.ITaskbarList3)
class MainWindow(wx.Frame):
def __init__(self, parent, ID, title):
wx.Frame.__init__(self, parent, ID, title)
self.panel = wx.Panel(self)
self.gauge = wx.Gauge(self.panel)
self.gauge.SetValue(0)
self.progress = 0
self.Show()
thread = Thread(target=self.counter)
thread.setDaemon(True)
thread.start()
def counter(self):
while True:
self.progress += 1
if self.progress > 100:
self.progress = 0
time.sleep(.2)
self.gauge.SetValue(self.progress)
taskbar.HrInit()
hWnd = self.GetHandle()
taskbar.SetProgressState(hWnd, TBPF_ERROR)
taskbar.SetProgressValue(hWnd, self.progress, 100)
app = wx.PySimpleApp()
frame = MainWindow(None, wx.ID_ANY, "Test")
app.SetTopWindow(frame)
app.MainLoop()
In particular I think the issue is due to the wxWindow window handle (hWnd) method, that differ from its Qt equivalent, the former returning an integer and the latter a "sip.voidptr object".
The problem is that I already wrote the whole code (1200+ lines) with wxPython, thus i can't re-write it to use Qt (not to talk about the different licenses).
What do you think about it? Should I give up?
Thanks a lot in advance :)
EDIT
Thanks to Robert O'Connor, now it works. However, I still can't get why GetHandle returns an integer while winId returns an object. In the .idl file the argument hwnd is declared as long in all the function definitions. Maybe this is a simple question too ;) Any Ideas?
A: On the following line:
hWnd = self.panel.GetId()
You want to use GetHandle() instead of GetId().
Edit: This was originally posted as a comment, but I suppose it would be more appropriate for me to repost as an answer.
Regarding the edit to your question: If it now works I guess there isn't a problem anymore ;) Okay, seriously though..
Ints and Longs are unified in Python and if I had to guess comtypes might be doing some coercion in the background. I don't know if it's necessary to worry about such details when dealing with comtypes in general, but it doesn't seem to matter much in this case.
Now I have no experience with PyQT, but in Python you can define special methods on objects such as __int__ and __long__ to emulate, well, Ints and Longs. If I had to guess, the object you're getting in PyQT defines one of those methods.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I make a picker appear to spin around multiple times? I am trying to make a picker appear to spin around multiple times before landing on a particular row. I have tried using for and do while loops. I have even tried calling multiple methods in succession, but each time, the picker only appears to reload once even though I am telling it to reload multiple times before finally landing on a selected row like this:
int newValue = random() % [self.inputNames count];
[payPicker selectRow:newValue inComponent:0 animated:YES];
[payPicker reloadComponent:0];
NSDate *future = [NSDate dateWithTimeIntervalSinceNow: 2.0 ];
[NSThread sleepUntilDate:future];
newValue = random() % [self.inputNames count];
[payPicker selectRow:newValue inComponent:0 animated:YES];
[payPicker reloadComponent:0];
[NSThread sleepUntilDate:future];
I do the above about three or four times and each time the picker only appears to reload once and goes to the final selected row. Is there something special I have to do or is it possible at all to make the picker appear to spin around and around? If I could even get it to jump randomly between the row choices before landing on one, I would be fine with that.
Thanks!!
A: Don't sleep the UI thread. No animation will start until you exit this method, after all your sleeping. So return from the method with the first request for the picker to animate. Do subsequent picker animation requests in timer callbacks after the previous picker animation has finished. Rinse and repeat as necessary.
The way other apps do this is by not using a real picker at all, but overlaying the picker control with an animated image sequence which just happens to look like a picker spinning. Then remove the fake animation to show an identical looking but real picker underneath. The advantage of your own animated cartoon is that you can make the fake picker spin in ways that a real picker can't.
A: Perhaps you could try selecting random rows before selecting your actual row. For example, if you want to select row 0, select rows in the following order - 9, 2, 15, 0. I don't think picker view will rotate if it is already on the row it is supposed to go to.
Also, you should select the rows every time after your pickerView:didSelectRow:inComponent: method hits.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java using compareTo with an array of strings I was wondering if the compareTo method looks at just the length of the strings or if it looks at each character of the string?
and if it does just look at the length how would i be able to compare two elements in an array of strings to see which element is bigger.
What im trying to do is write a method that recursively looks at the right side of the array, the middle, and the left and returns the index of the longest string in the array.
i have it working fine, the only problem is when there are two strings of the same length, it returns the first one.
Just clarifying how the compareTo method looks at the strings would help me solve this problem i think
how do strings of numbers compare lexographically? would 17 be bigger than 15?
A: compareTo for strings is done lexicographically. (or alphabetically) It doesn't compare the lengths of the strings.
A is less than B if A is alphabetically before B.
If you want to compare the length of a string, you can get the length from the .length() method and compare it as an integer.
EDIT:
Lexicographically is done by the ASCII/UNICODE values.
So in your example, 17 is bigger than 15. Because the 1 is the same (a tie), and 7 has a higher ASCII/UNICODE value than 5.
A: compareTo will compare both the alphabetical (lexicographical) order of the strings.
See the documentation here.
A:
I was wondering if the compareTo method looks at just the length of the strings or if it looks at each character of the string?
It (potentially) looks at each character in the string. It certainly does not just look at the length.
and if it does just look at the length how would i be able to compare two elements in an array of strings to see which element is bigger.
It doesn't, so this question is moot.
What im trying to do is write a method that recursively looks at the right side of the array, the middle, and the left and returns the index of the longest string in the array.
i have it working fine, the only problem is when there are two strings of the same length, it returns the first one.
We'd need to see your code to understand what is actually going wrong, but it is most likely not caused by some strangeness in the semantics of String.compareTo(String)
how do strings of numbers compare lexographically? would 17 be bigger than 15?
Yes it does compare strings lexicographically. Yes "17" would be bigger than "15". (But "17" would be greater than "15" if you compared the strings numerically too. On the other hand "7" is lexicographically greater than "13" but numerically less than it.)
Perhaps you need to read up on what "lexicographical order" means; Wikipedia summarizes it as:
"In mathematics, the lexicographic or lexicographical order, (also known as lexical order, dictionary order, alphabetical order or lexicographic(al) product), is a generalization of the way the alphabetical order of words is based on the alphabetical order of letters."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Custom scroll bar behavior in Javascript? I'd like to reproduce an effect similar to this page: http://artofflightmovie.com/ where the vertical scrollbar controls the progression of the browser "viewport" over a pre-defined path.
I am thinking the easiest way of going about this is through the use of javascript to read the scroll bar value and position background elements accordingly.
Is it possible to obtain the vertical scroll bar value in Javascript? Am I approaching this design wrong?
A:
Is it possible to obtain the vertical scroll bar value in Javascript?
var scrollTop = document.documentElement.scrollTop || window.pageYOffset;
Am I approaching this design wrong?
It seems like a valid approach.
A: I would think that you'd want to:
*
*Create an element with the desired scrollbar
*Hook up an event handler for scroll events
*Write logic in that event handler for how you guide your main page depending upon the scroll position you get in the event handler
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: On a Group, how can I retrieve the dates on which a member was added and by whom? I'm able to read the stream from a group but I'm particularly looking for the posts where it's mentioned that so-and-so has been "added by" a member and on which date. Eg:
John Smith and 12 other members were added by Alexander John.
Unlike · · Unfollow Post · Saturday at 4:02pm
Unfortunately, I can't seem to extract the above info using 'method'=>'fql.query' on the stream table. Even if I manage to find the Ids of these "added by" posts, when I run it as a query, i get an empty array. For example:
$sql = "SELECT post_id, permalink, created_time, updated_time, actor_id, message, attachment, likes, comments FROM stream WHERE gid=$gid AND (post_id='243493399035757' OR post_id='243503932368037')";
If this info shows up on a Group's stream, then it has to be coming from somewhere, right? So, does anyone know how I can get/extract these "added by" posts using FB's API or otherwise??
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Microsoft OLE DB Provider for SQL Server error '80040e14' Stored procedure, and using ADO to connect, i'm having problems with the quotes however..
x = "text'"
If instr(x,"'") then x=replace(x,"'","''")
'x = "text''" at this point
Set Rs = Server.Createobject("adodb.recordset")
Rs.Open "Select_SP @name='" & x & "'"
I thought i was doing this right.. But I guess not, because i'm getting this error:
Microsoft OLE DB Provider for SQL Server error '80040e14'
SELECT ID from Table where Name='text''
Shouldn't it be
Name = 'text'''
Why isn't SQL recognizing the double quotes using ADO?
The Select_SP Uses something like this:
SET @sql = 'SELECT ID from Table where Name='''+@name+''''
Exec(@sql)
Do I have this SP written correctly?
A: The short answer is, don't call procedures the way you're doing it. Use a Command instead. This is from memory, since I don't have a Windows system in front of me at the moment, but it should work:
Dim cmd
Set cmd = Server.CreateObject("ADODB.Command")
Set Cmd.ActiveConnection = myConnectionVariableHere
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "Select_SP"
'Note: if the above two lines don't work, replace them with the following
'cmd.CommandType = adCmdText
'cmd.CommandText = "Select_CP @name=?"
cmd.Parameters.Append cmd.CreateParameter("name", adVarChar, adParamInput, len(x), x)
Rs.Open cmd
Now, all that said, I can't tell you why your procedure is giving that particular output since you're not showing us the code for it. But I'm fairly certain ADO isn't going to convert a pair of single quotes into a double quote - not sure why you'd expect it to.
Edit after seeing the OP's edit. Don't execute SQL that way unless you absolutely have to. You will only give yourself grief. I don't know what database you're using and that procedure syntax doesn't look familiar, but in Oracle you could write something like:
PROCEDURE sql_test(MyName IN VARCHAR2, MyCursor OUT SYS_REFCURSOR) IS
BEGIN
OPEN MyCursor FOR SELECT id FROM some_table WHERE name = MyName;
END;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Custom ActionResult to return View = Model is ReadOnly I've got a snippet of code in a custom ActionResult
VB.NET Version
Dim result As New ViewResult()
result.Model= data ## Property Model is ReadOnly
Return result
C# Version
ViewResult result = new ViewResult();
result.Model = data; // Property Model is ReadOnly
return result;
How do I properly return a View from within a custom ActionResult that can also include the model?
A: Setting
result.ViewData.Model = data;
Should help you. In fact, get ViewResultBase.Model is implemented as
public object Model
{
get {
return ViewData.Model;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: change struct-object state I would like to change the state of the objects andre and blastoise, adding a new property(attribute/state) to the object... the name of this new property I want to add is "tax". I tryed the code below but didnt work out... help me plz:
(def andre {:owner "Andre" :type "car" :cur-speed 101 :license-plate "ABC"})
(def blastoise {:owner "Blastoise" :type "truck" :cur-speed 120 :license-plate "XYZ"})
(def car-tax[andre blastoise])
(defn calculate-car-tax [v]
(for [element v]
(if (> (element :cur-speed) 100) (dosync (alter element tax :20)))
)
)
(calculate-car-tax car-tax)
A: try
(assoc andre :tax 20)
From the docs:
user=> (doc assoc)
-------------------------
clojure.core/assoc
([map key val] [map key val & kvs])
assoc[iate]. When applied to a map, returns a new map of the
same (hashed/sorted) type, that contains the mapping of key(s) to
val(s). When applied to a vector, returns a new vector that
contains val at index. Note - index must be <= (count vector).
nil
user=>
Edit to include function:
(defn calculate-car-tax [v]
(for [element v]
(if (> (element :cur-speed) 100)
(dosync (assoc element :tax 20)))))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Many Booleans On Two Tables Using Rails 2.1 and Mysql.
I have a corporation model, which has_many companies
And of course the company model, which belongs_to corporation
I need to add quite a few boolean columns to these two tables, but this feels really wrong. Each table will have the same booleans, and we would be checking first the company to see if it's true, and then corporation. So, the options I can see are these:
*
*Add the boolean values to each table. I suppose this is simplest but feels really redundant.
*Create an extra table called something like "boolean_options", which would belong_to company and corporation. Each boolean is added to this table, and then connect to the appropriate model(s).
*Use something like the has_many_booleans gem, which means I add one column (boolean) to each table and handle the data in my code. This seems like it would be the least obvious solution, but feels more elegant to me, especially when it comes time to add more booleans to these tables.
What is the best way to handle booleans that will appear across multiple tables?
A: The answer may depend more on your overall concept than anything else. For each true/false bit of data, ask yourself how closely linked it is to the essence of the model. How often will each bit be referenced in model instances, or used in searches. Those that are closely linked may belong in the model; the ones that are less so may be better grouped in other tables.
Example: In the real world, a corporation is a type of company and shares many of the Company attributes; these attributes could be stored in the Company table, perhaps with an is_a_corporation flag.
Where corporations have unique attributes, such as the ability to own companies, these functions and attributes should be in the Corporation model.
Booleans as Bits: I don't think there is anything wrong with having many boolean attributes in a model, but I agree that it seems inelegant to have all those boolean columns in the table. I checked out the has_many_booleans gem, which does offer some interesting opportunities for simulating bitwise operations and masks which, coming from the world of embedded software, makes a lot of sense to me.
Checking around, I discovered that Postgresql (my db of choice) offers the bitstring datatype and provides a plethora of actual bitwise operations on as many bits as you want, using just one column for all your booleans, which seems incredibly cool to me. The downside is you'd have to configure the column and and perform the operations in native SQL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Callback at certain times during audio playback Is it possible to play an audio file from the user's ipod library and have a callback occur whenever the player reaches a certain time point ? I need it to be very accurate, so simply using methods like currentPlaybackTime might not be enough because float equality is inaccurate. I could use the A - B < Epsilon float check, but is there a better, more accurate way of achieving this?
A: If you can target iOS 4.0 or hight, try using AVPlayer. Then you will be able to use
- (id)addBoundaryTimeObserverForTimes:(NSArray *)times queue:(dispatch_queue_t)queue usingBlock:(void (^)(void))block
which takes an array of NSValues for CMTimes and will run the contents of the block each time one of the boundary times is hit. (Beware of some behavior like, if you pause the audio file inside of the block, the callback will fire again when you unpause it).
Since CMTime is not a float, I think this will be more accurate than checking for the currentTime repeatedly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android, Handler's error This is a bit weird, but I have no idea where the problem is.
In my onCreate() I have this code:
GameRunningNotesTimer().start();
and then out of onCreate I have this code:
Thread GameRunningNotesTimer = new Thread(new Runnable() {
public void run() {
int sleepingTime;
try {
if (r_settings.getGameOver() == 0) {
sleepingTime = 1000 - (r_settings.getInternalLevel() * 100);
if (r_settings.getInternalLevel() == 0) {
Thread.sleep(1000);
} else {
if (sleepingTime <= 399)
{
sleepingTime = 350;
}
Thread.sleep(sleepingTime);
}
if (r_settings.getGameOver() == 1){ gameOver(); }
myHandler2.sendEmptyMessage(0);
} // End of if (r_settings.getGameOver()
} catch (Exception e) { Log.e("MUSIC!!!!!", "Error in activity", e); }
}// End of run
}); // End of GameRunningNotesTimer()
final Handler myHandler2 = new Handler() {
@Override
public void handleMessage(Message msg) {
//text2.setText(""+item[0]);
int z = 1;
if (r_settings.getGameStarted() == true)
{
changeNoteFromTimer();
} else {
startingCountdown(z);
}
} // end of handleMessage()
};
but this GameRunningNotesTimer().start(); is underlined in red (in Eclipse) and when I mouseover it it says: The method GameRunningNotesTimer() is undefined for the type GameScr
What am I doing wrong? another thread/handler in the same class is not giving me this problem.
Thanks!
A: It should be GameRunningNotesTimer.start(); not GameRunningNotesTimer().start();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VideoView with Cookies (or Headers) I am trying to use android.widget.VideoView to stream content.
I need to ensure that when using setVideoURI(Uri) that VideoView will include Cookies from prior HttpClient calls.
I see in the source that there is setVideoUri(Uri,Headers) but this has a @hide JavaDoc annotation and won't compile.
So, any way to pass cookies or headers with the HTTP requests made by VideoView?
A: Extract classes VideoView and Metadata from SDK.
Then, you will be able to call setVideoURI(Uri uri, Map<String, String> headers) on your own VideoView class.
Note that metadata are not extracted because mp.getMetadata(MediaPlayer.METADATA_ALL, MediaPlayer.BYPASS_METADATA_FILTER) is not accessible but you can try with MediaMetadataRetriever
VideoView
import java.io.IOException;
import java.util.Map;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.MediaController;
import android.widget.MediaController.MediaPlayerControl;
/**
* Displays a video file. The VideoView class can load images from various sources (such as resources or content
* providers), takes care of computing its measurement from the video so that it can be used in any layout manager, and
* provides various display options such as scaling and tinting.
*/
public class VideoView extends SurfaceView implements MediaPlayerControl {
private String TAG = "VideoView";
// settable by the client
private Uri mUri;
private Map<String, String> mHeaders;
private int mDuration;
// all possible internal states
private static final int STATE_ERROR = - 1;
private static final int STATE_IDLE = 0;
private static final int STATE_PREPARING = 1;
private static final int STATE_PREPARED = 2;
private static final int STATE_PLAYING = 3;
private static final int STATE_PAUSED = 4;
private static final int STATE_PLAYBACK_COMPLETED = 5;
// mCurrentState is a VideoView object's current state.
// mTargetState is the state that a method caller intends to reach.
// For instance, regardless the VideoView object's current state,
// calling pause() intends to bring the object to a target state
// of STATE_PAUSED.
private int mCurrentState = STATE_IDLE;
private int mTargetState = STATE_IDLE;
// All the stuff we need for playing and showing a video
private SurfaceHolder mSurfaceHolder = null;
private MediaPlayer mMediaPlayer = null;
private int mVideoWidth;
private int mVideoHeight;
private int mSurfaceWidth;
private int mSurfaceHeight;
private MediaController mMediaController;
private OnCompletionListener mOnCompletionListener;
private MediaPlayer.OnPreparedListener mOnPreparedListener;
private int mCurrentBufferPercentage;
private OnErrorListener mOnErrorListener;
private int mSeekWhenPrepared; // recording the seek position while preparing
private boolean mCanPause;
private boolean mCanSeekBack;
private boolean mCanSeekForward;
public VideoView(Context context) {
super(context);
initVideoView();
}
public VideoView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
initVideoView();
}
public VideoView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initVideoView();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Log.i("@@@@", "onMeasure");
int width = getDefaultSize(mVideoWidth, widthMeasureSpec);
int height = getDefaultSize(mVideoHeight, heightMeasureSpec);
if(mVideoWidth > 0 && mVideoHeight > 0) {
if(mVideoWidth * height > width * mVideoHeight) {
// Log.i("@@@", "image too tall, correcting");
height = width * mVideoHeight / mVideoWidth;
} else if(mVideoWidth * height < width * mVideoHeight) {
// Log.i("@@@", "image too wide, correcting");
width = height * mVideoWidth / mVideoHeight;
} else {
// Log.i("@@@", "aspect ratio is correct: " +
// width+"/"+height+"="+
// mVideoWidth+"/"+mVideoHeight);
}
}
// Log.i("@@@@@@@@@@", "setting size: " + width + 'x' + height);
setMeasuredDimension(width, height);
}
@Override
public void onInitializeAccessibilityEvent(AccessibilityEvent event) {
super.onInitializeAccessibilityEvent(event);
event.setClassName(VideoView.class.getName());
}
@Override
public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo info) {
super.onInitializeAccessibilityNodeInfo(info);
info.setClassName(VideoView.class.getName());
}
public int resolveAdjustedSize(int desiredSize, int measureSpec) {
int result = desiredSize;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
switch(specMode) {
case MeasureSpec.UNSPECIFIED:
/*
* Parent says we can be as big as we want. Just don't be larger than max size imposed on ourselves.
*/
result = desiredSize;
break;
case MeasureSpec.AT_MOST:
/*
* Parent says we can be as big as we want, up to specSize. Don't be larger than specSize, and don't be
* larger than the max size imposed on ourselves.
*/
result = Math.min(desiredSize, specSize);
break;
case MeasureSpec.EXACTLY:
// No choice. Do what we are told.
result = specSize;
break;
}
return result;
}
private void initVideoView() {
mVideoWidth = 0;
mVideoHeight = 0;
getHolder().addCallback(mSHCallback);
getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
}
public void setVideoPath(String path) {
setVideoURI(Uri.parse(path));
}
public void setVideoURI(Uri uri) {
setVideoURI(uri, null);
}
/**
* @hide
*/
public void setVideoURI(Uri uri, Map<String, String> headers) {
mUri = uri;
mHeaders = headers;
mSeekWhenPrepared = 0;
openVideo();
requestLayout();
invalidate();
}
public void stopPlayback() {
if(mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;
mTargetState = STATE_IDLE;
}
}
private void openVideo() {
if(mUri == null || mSurfaceHolder == null) {
// not ready for playback just yet, will try again later
return;
}
// Tell the music playback service to pause
// TODO: these constants need to be published somewhere in the framework.
Intent i = new Intent("com.android.music.musicservicecommand");
i.putExtra("command", "pause");
getContext().sendBroadcast(i);
// we shouldn't clear the target state, because somebody might have
// called start() previously
release(false);
try {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnPreparedListener(mPreparedListener);
mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
mDuration = - 1;
mMediaPlayer.setOnCompletionListener(mCompletionListener);
mMediaPlayer.setOnErrorListener(mErrorListener);
mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
mCurrentBufferPercentage = 0;
mMediaPlayer.setDataSource(getContext(), mUri, mHeaders);
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mMediaPlayer.setScreenOnWhilePlaying(true);
mMediaPlayer.prepareAsync();
// we don't set the target state here either, but preserve the
// target state that was there before.
mCurrentState = STATE_PREPARING;
attachMediaController();
} catch(IOException ex) {
Log.w(TAG, "Unable to open content: " + mUri, ex);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
return;
} catch(IllegalArgumentException ex) {
Log.w(TAG, "Unable to open content: " + mUri, ex);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
mErrorListener.onError(mMediaPlayer, MediaPlayer.MEDIA_ERROR_UNKNOWN, 0);
return;
}
}
public void setMediaController(MediaController controller) {
if(mMediaController != null) {
mMediaController.hide();
}
mMediaController = controller;
attachMediaController();
}
private void attachMediaController() {
if(mMediaPlayer != null && mMediaController != null) {
mMediaController.setMediaPlayer(this);
View anchorView = this.getParent() instanceof View ? (View)this.getParent() : this;
mMediaController.setAnchorView(anchorView);
mMediaController.setEnabled(isInPlaybackState());
}
}
MediaPlayer.OnVideoSizeChangedListener mSizeChangedListener = new MediaPlayer.OnVideoSizeChangedListener() {
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
if(mVideoWidth != 0 && mVideoHeight != 0) {
getHolder().setFixedSize(mVideoWidth, mVideoHeight);
}
}
};
MediaPlayer.OnPreparedListener mPreparedListener = new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
mCurrentState = STATE_PREPARED;
// Get the capabilities of the player for this stream
// -_- where is the method ?
// Metadata data = mp.getMetadata(MediaPlayer.METADATA_ALL, MediaPlayer.BYPASS_METADATA_FILTER);
// use MediaMetadataRetriever to retrieve metadata
Metadata data = null;
if(data != null) {
mCanPause = ! data.has(Metadata.PAUSE_AVAILABLE) || data.getBoolean(Metadata.PAUSE_AVAILABLE);
mCanSeekBack = ! data.has(Metadata.SEEK_BACKWARD_AVAILABLE) || data.getBoolean(Metadata.SEEK_BACKWARD_AVAILABLE);
mCanSeekForward = ! data.has(Metadata.SEEK_FORWARD_AVAILABLE) || data.getBoolean(Metadata.SEEK_FORWARD_AVAILABLE);
} else {
mCanPause = mCanSeekBack = mCanSeekForward = true;
}
if(mOnPreparedListener != null) {
mOnPreparedListener.onPrepared(mMediaPlayer);
}
if(mMediaController != null) {
mMediaController.setEnabled(true);
}
mVideoWidth = mp.getVideoWidth();
mVideoHeight = mp.getVideoHeight();
int seekToPosition = mSeekWhenPrepared; // mSeekWhenPrepared may be changed after seekTo() call
if(seekToPosition != 0) {
seekTo(seekToPosition);
}
if(mVideoWidth != 0 && mVideoHeight != 0) {
// Log.i("@@@@", "video size: " + mVideoWidth +"/"+ mVideoHeight);
getHolder().setFixedSize(mVideoWidth, mVideoHeight);
if(mSurfaceWidth == mVideoWidth && mSurfaceHeight == mVideoHeight) {
// We didn't actually change the size (it was already at the size
// we need), so we won't get a "surface changed" callback, so
// start the video here instead of in the callback.
if(mTargetState == STATE_PLAYING) {
start();
if(mMediaController != null) {
mMediaController.show();
}
} else if( ! isPlaying() && (seekToPosition != 0 || getCurrentPosition() > 0)) {
if(mMediaController != null) {
// Show the media controls when we're paused into a video and make 'em stick.
mMediaController.show(0);
}
}
}
} else {
// We don't know the video size yet, but should start anyway.
// The video size might be reported to us later.
if(mTargetState == STATE_PLAYING) {
start();
}
}
}
};
private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mCurrentState = STATE_PLAYBACK_COMPLETED;
mTargetState = STATE_PLAYBACK_COMPLETED;
if(mMediaController != null) {
mMediaController.hide();
}
if(mOnCompletionListener != null) {
mOnCompletionListener.onCompletion(mMediaPlayer);
}
}
};
private MediaPlayer.OnErrorListener mErrorListener = new MediaPlayer.OnErrorListener() {
public boolean onError(MediaPlayer mp, int framework_err, int impl_err) {
Log.d(TAG, "Error: " + framework_err + "," + impl_err);
mCurrentState = STATE_ERROR;
mTargetState = STATE_ERROR;
if(mMediaController != null) {
mMediaController.hide();
}
/* If an error handler has been supplied, use it and finish. */
if(mOnErrorListener != null) {
if(mOnErrorListener.onError(mMediaPlayer, framework_err, impl_err)) {
return true;
}
}
/*
* Otherwise, pop up an error dialog so the user knows that something bad has happened. Only try and pop up
* the dialog if we're attached to a window. When we're going away and no longer have a window, don't bother
* showing the user an error.
*/
if(getWindowToken() != null) {
Resources r = getContext().getResources();
int messageId;
if(framework_err == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
messageId = R.string.VideoView_error_text_invalid_progressive_playback;
} else {
messageId = R.string.VideoView_error_text_unknown;
}
new AlertDialog.Builder(getContext()).setMessage(messageId).setPositiveButton(R.string.VideoView_error_button, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/*
* If we get here, there is no onError listener, so at least inform them that the video is over.
*/
if(mOnCompletionListener != null) {
mOnCompletionListener.onCompletion(mMediaPlayer);
}
}
}).setCancelable(false).show();
}
return true;
}
};
private MediaPlayer.OnBufferingUpdateListener mBufferingUpdateListener = new MediaPlayer.OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
mCurrentBufferPercentage = percent;
}
};
/**
* Register a callback to be invoked when the media file is loaded and ready to go.
*
* @param l The callback that will be run
*/
public void setOnPreparedListener(MediaPlayer.OnPreparedListener l) {
mOnPreparedListener = l;
}
/**
* Register a callback to be invoked when the end of a media file has been reached during playback.
*
* @param l The callback that will be run
*/
public void setOnCompletionListener(OnCompletionListener l) {
mOnCompletionListener = l;
}
/**
* Register a callback to be invoked when an error occurs during playback or setup. If no listener is specified, or
* if the listener returned false, VideoView will inform the user of any errors.
*
* @param l The callback that will be run
*/
public void setOnErrorListener(OnErrorListener l) {
mOnErrorListener = l;
}
SurfaceHolder.Callback mSHCallback = new SurfaceHolder.Callback() {
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
mSurfaceWidth = w;
mSurfaceHeight = h;
boolean isValidState = (mTargetState == STATE_PLAYING);
boolean hasValidSize = (mVideoWidth == w && mVideoHeight == h);
if(mMediaPlayer != null && isValidState && hasValidSize) {
if(mSeekWhenPrepared != 0) {
seekTo(mSeekWhenPrepared);
}
start();
}
}
public void surfaceCreated(SurfaceHolder holder) {
mSurfaceHolder = holder;
openVideo();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// after we return from this we can't use the surface any more
mSurfaceHolder = null;
if(mMediaController != null)
mMediaController.hide();
release(true);
}
};
/*
* release the media player in any state
*/
private void release(boolean cleartargetstate) {
if(mMediaPlayer != null) {
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;
if(cleartargetstate) {
mTargetState = STATE_IDLE;
}
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if(isInPlaybackState() && mMediaController != null) {
toggleMediaControlsVisiblity();
}
return false;
}
@Override
public boolean onTrackballEvent(MotionEvent ev) {
if(isInPlaybackState() && mMediaController != null) {
toggleMediaControlsVisiblity();
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean isKeyCodeSupported = keyCode != KeyEvent.KEYCODE_BACK && keyCode != KeyEvent.KEYCODE_VOLUME_UP
&& keyCode != KeyEvent.KEYCODE_VOLUME_DOWN && keyCode != KeyEvent.KEYCODE_VOLUME_MUTE && keyCode != KeyEvent.KEYCODE_MENU
&& keyCode != KeyEvent.KEYCODE_CALL && keyCode != KeyEvent.KEYCODE_ENDCALL;
if(isInPlaybackState() && isKeyCodeSupported && mMediaController != null) {
if(keyCode == KeyEvent.KEYCODE_HEADSETHOOK || keyCode == KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE) {
if(mMediaPlayer.isPlaying()) {
pause();
mMediaController.show();
} else {
start();
mMediaController.hide();
}
return true;
} else if(keyCode == KeyEvent.KEYCODE_MEDIA_PLAY) {
if( ! mMediaPlayer.isPlaying()) {
start();
mMediaController.hide();
}
return true;
} else if(keyCode == KeyEvent.KEYCODE_MEDIA_STOP || keyCode == KeyEvent.KEYCODE_MEDIA_PAUSE) {
if(mMediaPlayer.isPlaying()) {
pause();
mMediaController.show();
}
return true;
} else {
toggleMediaControlsVisiblity();
}
}
return super.onKeyDown(keyCode, event);
}
private void toggleMediaControlsVisiblity() {
if(mMediaController.isShowing()) {
mMediaController.hide();
} else {
mMediaController.show();
}
}
public void start() {
if(isInPlaybackState()) {
mMediaPlayer.start();
mCurrentState = STATE_PLAYING;
}
mTargetState = STATE_PLAYING;
}
public void pause() {
if(isInPlaybackState()) {
if(mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
mCurrentState = STATE_PAUSED;
}
}
mTargetState = STATE_PAUSED;
}
public void suspend() {
release(false);
}
public void resume() {
openVideo();
}
// cache duration as mDuration for faster access
public int getDuration() {
if(isInPlaybackState()) {
if(mDuration > 0) {
return mDuration;
}
mDuration = mMediaPlayer.getDuration();
return mDuration;
}
mDuration = - 1;
return mDuration;
}
public int getCurrentPosition() {
if(isInPlaybackState()) {
return mMediaPlayer.getCurrentPosition();
}
return 0;
}
public void seekTo(int msec) {
if(isInPlaybackState()) {
mMediaPlayer.seekTo(msec);
mSeekWhenPrepared = 0;
} else {
mSeekWhenPrepared = msec;
}
}
public boolean isPlaying() {
return isInPlaybackState() && mMediaPlayer.isPlaying();
}
public int getBufferPercentage() {
if(mMediaPlayer != null) {
return mCurrentBufferPercentage;
}
return 0;
}
private boolean isInPlaybackState() {
return (mMediaPlayer != null && mCurrentState != STATE_ERROR && mCurrentState != STATE_IDLE && mCurrentState != STATE_PREPARING);
}
public boolean canPause() {
return mCanPause;
}
public boolean canSeekBackward() {
return mCanSeekBack;
}
public boolean canSeekForward() {
return mCanSeekForward;
}
}
A: I had the same issue. You can manually set the header object, or any other private feild for that matter, using a class called Field (click for API DOC).
VideoView videoView = (VideoView) fl.findViewById(R.id.vidAttachmentPreview);
videoView.setVideoURI("http://youURL.com");
try {
Field field = VideoView.class.getDeclaredField("mHeaders");
field.setAccessible(true);
field.set(videoView, headerHashMap);
} catch (Exception e) {
e.printStackTrace();
}
// the rest is just standard VideoView stuff
MediaController mc = new MediaController(LoopThreadActivity.this);
mc.setAnchorView(videoView);
videoView.setMediaController(mc);
videoView.start();
I've tested this and it works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How to make code using Value[T : Numeric] more “flexible” like the “unboxed” counterparts? If I have code like 5 * 5.0 the result gets converted to the most accurate type, Double.
But this doesn't seem to work with code like
case class Value[T : Numeric](value: T) {
type This = Value[T]
def +(m: This) = Value[T](implicitly[Numeric[T]].plus(value, m.value))
...
}
implicit def numToValue[T : Numeric](v: T) = Value[T](v)
Is there a way to make things like someIntValue + double work, where someIntValue is Value[Int] and double is Double?
PS: Sorry for the far less-than-perfect title. I'm thankful for suggestions for better wording ...
A: You can do this (with a lot of busywork) by creating implicit operators:
abstract class Arith[A,B,C] {
def +(a: A, b: B): C
def -(a: A, b: B): C
def *(a: A, b: B): C
def /(a: A, b: B): C
}
implicit object ArithIntLong extends Arith[Int,Long,Long] {
def +(a: Int, b: Long) = a+b
def -(a: Int, b: Long) = a-b
def *(a: Int, b: Long) = a*b
def /(a: Int, b: Long) = a/b
}
...
def f[A,B,C](a: A, b: B)(implicit arith: Arith[A,B,C]) = arith.*(a,b)
scala> f(5,10L)
res46: Long = 50
but you really have to do more than that, since you need a Numeric equivalent for A and B alone, and the asymmetric operations need to be defined both ways. And it's not really practical to specialize given that there are three types involved.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How do I implement a datatype, like a stack, in assembly? I need to implement a custom data structure in assembly. Preferably, it needs to be dynamic. Something like a linked list in C++/Java where each element points to the next element. Please note that the size of each element may vary.
How can I do this?
A: The same you would in C. Assembly has functions and address spaces. Start with the basics: what functions does your stack need to have? Put the actual datastructures aside and focus on the big picture.
All you need is a function to push() and a function to pop(), a place to stick these items in the memory, and a counter to tell you how much of that space you've used up.
Oh, you should probably review your data structures before starting, as in neither C++ nor Java (or any other language, as a matter of fact) does an object pushed onto a stack point to the next object on the stack. That's called a linked list.
A: Try implementing your data structure using C and then look at the assembly generated. For your memory needs, however, it might require some more careful considerations (such as using non-volatile vs. volatile memory for storage for the varying sized elements).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Confused with fork() I am having a difficult time understanding what the fork() command does under different scenarios. Here is some sample code from my book:
int main() {
int a = 12;
int b = 9;
int fid = fork();
if (fid == 0) {
a++;
}
else {
wait(NULL);
b = b - 5;
}
printf("program exit. a = %d, b = %d\n", a, b);
return 0;
}
Can someone walk me through what the fork() command is doing in this case and perhaps give some more examples to clarify?
A: *
*a is set to 12, b is set to 9.
*fork is called, we now have two processes.
*The parent gets the PID of the child, and goes to the else clause. The child gets 0, and goes to the if clause.
*The parent waits for the child to finish.
*The child increments its copy of a. So a is now 13 in the child and 12 in the parent.
*The child exits, outputting 13 and 9.
*The parent subtracts 5 from its copy of b, so b is now 4 in the parent.
*The parent exits, outputting 12 and 4.
Note that the exact order of execution of the child and parent after fork is not guaranteed, but it doesn't change the results because the parent waits for the child to finish before it does anything.
Also, note that having both processes exit normally is bad practice. When one process exits normally, it runs cleanup handlers that can confuse the other process, for example by changing the file position on shared file descriptions, causing data corruption.
A: When you call fork(), the entire process including all memory/variables etc... are duplicated.
So after the fork call, each process has it's own copy of a and b which start as 12 and 9 respectively.
Process 0, will increment it's own copy of a. Process 1 will decrement (by 5) it's own copy of b.
So they should print:
Process 0: a = 13, b = 9
Process 1: a = 12, b = 4
A: [main]
a = 12
b = 9
fork()
|
|
+--------------+--------------+
| |
| |
[parent] [child]
fid = 1234 fid = 0
wait(NULL) a++
... printf("a = 13, b = 9");
... return 0
... <exit>
b = b - 5
printf("a = 12, b = 4");
return 0
<exit>
After fork() executes there are two copies of the program. Each process gets its own copies of the variables, so there are now two a's, two b's, etc. The only difference between the two programs is the value returned from fork(): in the child process fork() returns 0; in the parent process it returns the PID of the child.
The child process increments a, prints the values of a and b, and exits.
The parent process first waits for the child process to terminate. Only after the child has finished does it continue on, subtracting 5 from b, printing out a and b, and then exiting.
The wait(NULL) ensures that the child process's printout always comes before the parent's, so you will always get the same output in a reliable order. Without it you wouldn't be able to depend on the order of the two printouts. They would be the same messages, just in an unpredictable order.
A: Its o/p would be
Parent :: a=12 , b=4
Child :: a=13 , b=9
as both process execute simultaneously but both have different copies of local variables a,b
so local var. affected by one process will not be visible to another process as both are working on their own copies
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: UI Stress Testing on Android is there a way for me to do a sort of UI Stress test, similar to that of monkey runner.
I want my stress tester to click randomly on the screen until something is prompted.
however, i want to be able to detect if a dialog box comes up, then i want to put in some values, or if there is a prompt for me to upload something, i'll upload a random picture. Monkey runner does not have the functionality of knowing what dialog boxes come up right? This stress tester that i am trying to configure has to be a one size fits all stress tester.
A: The monkey itself doesn't know what your UI is showing, but your app does. You might find the isUserAMonkey API useful. While its existence has been a source of amusement for many, it exists for these cases where you want your app to behave differently for a monkey than for a real user.
A: Take a look at robotium. It also supports black-box UI testing of Android applications.
A: This is how you could try to do this with testobject.com:
The function randomInput(...) is invoking the Exerciser Monkey. It's not completely bullet-proof, but might do the trick in your case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Convert two matrices into a list using apply I have two matrix with the same number of columns, but with different number of rows:
a <- cbind(runif(5), runif(5))
b <- cbind(runif(8), runif(8))
I want to associate these in a same list, so that the first columns of a and b are associated with each other, and so on:
my_result <- list(list(a[,1], b[,1]), list(a[,2], b[,2]))
So the result would look like this:
> print(my_result)
[[1]]
[[1]][[1]]
[1] 0.9440956 0.7259602 0.7804068 0.7115368 0.2771190
[[1]][[2]]
[1] 0.4155642 0.1535414 0.6983123 0.7578231 0.2126765 0.6753884 0.8160817
[8] 0.6548915
[[2]]
[[2]][[1]]
[1] 0.7343330 0.7751599 0.4463870 0.6926663 0.9692621
[[2]][[2]]
[1] 0.5708726 0.1234482 0.2875474 0.4760349 0.2027653 0.5142006 0.4788264
[8] 0.7935544
I can't figure how to do that without a for loop, but I'm pretty sure some *pply magic could be used here.
Any directions would be much appreciated.
A: I'm not sure how general a solution you're looking for (arbitrary number of matrices, ability to pass a list of matrices, etc.) but this works for your specific example:
lapply(1:2,function(i){list(a[,i],b[,i])})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to validate only show me geometric shapes smaller than a JFrame I can make a program to enter a series of values of geometric figures to show me in a JFrame.
It happens all the figures showing they want to see in the JFrame, but I have to validate that these figures appear to me entirely in the JFrame is not the case when the coordinates are very large.
I was looking online and found nothing.
I thought that "if" but never finished, because each number and the radio that I have to enter a validation.
I wondered if there was a reserved word in java that allows me to display only the data that is smaller than the JFrame.
Thank you for your response.
A: There are many methods you can use in the Shape class. E.g. getBounds() and contains(double x, double y)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I install this service_wrapper for mongrel/rails on my windows server? I have been given the unpleasant task of installing a Rails 3 app I have written on Windows Server 2008 (definitely not my choice - was promised a linux server but I.T. pulled the rug out at the last minute so please don't suggest a change in environment as a solution).
I followed the instructions on this blog post (with a few minor modifications) and now actually have my app up and running under Windows/IIS (proxying mongrel) after a great deal of frustration. The only thing remaining is to get mongrel running as a service.
Unfortunately the mongrel gem has not been kept up-to-date for Rails 3 and while I can get the app running under mongrel at the command line I am unable to use mongrel_service to get the app running as a service.
The solution to this appears to be to use the service_wrapper project on github which has been mentioned in this previous question. The project is not yet complete but apparently functional but comes without documentation/binaries. I have looked through the source-code and don't really understand what is it/how it works so was wondering if someone can point me in the right direction (or, even better, walk me through how) to get this installed.
So close, yet still so far.....
A: Alright I have this worked out (with a little help from luislavena himself - thanks).
Download service_wrapper-0.1.0-win32.zip from https://github.com/luislavena/service_wrapper/downloads and extract service_wrapper.exe from bin/. I extracted it to C:\service_wrapper.
Next set up a configuration file. I used the hello example and modified it for my app then placed it in the C:\service_wrapper directory.
; Service section, it will be the only section read by service_wrapper
[service]
; Provide full path to executable to avoid issues when executable path was not
; added to system PATH.
executable = C:\Ruby192\bin\ruby.exe
; Provide there the arguments you will pass to executable from the command line
arguments = C:\railsapp\script\rails s -e production
; Which directory will be used when invoking executable.
; Provide a full path to the directory (not to a file)
directory = C:\railsapp
; Optionally specify a logfile where both STDOUT and STDERR of executable will
; be redirected.
; Please note that full path is also required.
logfile = C:\railsapp\log\service_wrapper.log
Now just create the service with
sc create railsapp binPath= "C:\service_wrapper\service_wrapper.exe C:\service_wrapper\service_wrapper.conf" start= auto
(watch for the spaces after binPath= and start=. It won't work without them)
Then start it with
net start railsapp
And you're home and hosed!
A: I ought to contribute due to this article. For config of using bundle exec, use the following:
Note that I am setting up rubyCAS! it's a great OpenCAS authentication mechanism!!!
; Service section, it will be the only section read by service_wrapper
[service]
; Provide full path to executable to avoid issues when executable path was not
; added to system PATH.
executable = C:\Ruby\bin\ruby.exe
; Provide there the arguments you will pass to executable from the command line
arguments = D:\rubycas-server bundle exec rackup -s mongrel -p 11011
; Which directory will be used when invoking executable.
; Provide a full path to the directory (not to a file)
directory = D:\rubycas-server
; Optionally specify a logfile where both STDOUT and STDERR of executable will
; be redirected.
; Please note that full path is also required.
logfile = D:\rubycas-server\log\service_wrapper.log
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: list / string in python I'm trying to parse tweets data.
My data shape is as follows:
59593936 3061025991 null null <d>2009-08-01 00:00:37</d> <s><a href="http://help.twitter.com/index.php?pg=kb.page&id=75" rel="nofollow">txt</a></s> <t>honda just recalled 440k accords...traffic around here is gonna be light...win!!</t> ajc8587 15 24 158 -18000 0 0 <n>adrienne conner</n> <ud>2009-07-23 21:27:10</ud> <t>eastern time (us & canada)</t> <l>ga</l>
22020233 3061032620 null null <d>2009-08-01 00:01:03</d> <s><a href="http://alexking.org/projects/wordpress" rel="nofollow">twitter tools</a></s> <t>new blog post: honda recalls 440k cars over airbag risk http://bit.ly/2wsma</t> madcitywi 294 290 9098 -21600 0 0 <n>madcity</n> <ud>2009-02-26 15:25:04</ud> <t>central time (us & canada)</t> <l>madison, wi</l>
I want to get the total numbers of tweets and the numbers of keyword related tweets. I prepared the keywords in text file. In addition, I wanna get the tweet text contents, total number of tweets which contain mention(@), retweet(RT), and URL (I wanna save every URL in other file).
So, I coded like this.
import time
import os
total_tweet_count = 0
related_tweet_count = 0
rt_count = 0
mention_count = 0
URLs = {}
def get_keywords(filepath, mode):
with open(filepath, mode) as f:
for line in f:
yield line.split().lower()
for line in open('/nas/minsu/2009_06.txt'):
tweet = line.strip().lower()
total_tweet_count += 1
with open('./related_tweets.txt', 'a') as save_file_1:
keywords = get_keywords('./related_keywords.txt', 'r')
if keywords in line:
text = line.split('<t>')[1].split('</t>')[0]
if 'http://' in text:
try:
url = text.split('http://')[1].split()[0]
url = 'http://' + url
if url not in URLs:
URLs[url] = []
URLs[url].append('\t' + text)
save_file_3 = open('./URLs_in_related_tweets.txt', 'a')
print >> save_file_3, URLs
except:
pass
if '@' in text:
mention_count +=1
if 'RT' in text:
rt_count += 1
related_tweet_count += 1
print >> save_file_1, text
save_file_2 = open('./info_related_tweets.txt', 'w')
print >> save_file_2, str(total_tweet_count) + '\t' + srt(related_tweet_count) + '\t' + str(mention_count) + '\t' + str(rt_count)
save_file_1.close()
save_file_2.close()
save_file_3.close()
Following is the sample keywords
Depression
Placebo
X-rays
X-ray
HIV
Blood preasure
Flu
Fever
Oral Health
Antibiotics
Diabetes
Mellitus
Genetic disorders
I think my code has many problem, but the first error is as follows:
line 23, in <module>
if keywords in line:
TypeError: 'in <string>' requires string as left operand, not generator
I coded "def ..." part. I think it has a problem. When I try "print keywords" under line (keywords = get_keywords('./related_keywords.txt', 'r')), it gives something strange numbers not words.... . Please help me out!
A: Maybe change if keywords in line: to use a regular expression match instead. For example, something like:
import re
...
keywords = "|".join(get_keywords('./related_keywords.txt', 'r'))
matcher = re.compile(keywords)
if matcher.match(line):
text = ...
... And changed get_keywords to something like this instead:
def get_keywords(filepath, mode):
keywords = []
with open(filepath, mode) as f:
for line in f:
sp = line.split()
for w in sp:
keywords.append(w.lower())
return keywords
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Closing a prettyPhoto lightbox from inside iframe Would like to run some Javascript in the iFrame which changes the height and width of the prettyPhoto lightbox window that it is in.
This is an example of lightbox in action:
http://www.no-margin-for-errors.com/projects/prettyphoto-jquery-lightbox-clone/
http://jsfiddle.net/txchou/GBmTL/
This is how to close the window:
window.parent.$.prettyPhoto.close();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: I can not get rid of a underline text I got this code:
<div class="class1"><a href="http://nvm/">text</a></div>
CSS code of class1 is following:
.class1 {
text-decoration: none;
}
The output looks on, until I move the mouse over the div. The text is underlined then.
Sure, I've tried a lot of methods like:
.class1:hover {
text-decoration: none;
}
I've also tried to add a !important attribute, but still without expected results. :/
I've also used firebug to debug the HTML & CSS code, and I can't find any class with attribute text-decoration: underline;.
I know this is such a silly question, but I'm out of ideas.
A: You should set the text-decoration property to none for the a element inside of .class1, since that is the element that contains the text (and likely the element that you are hovering on).
For example:
.class1 a (all a tags whose ancestor is .class1)
OR
.class1 > a (all a tags whose parent is .class1)
A: If you're setting a global <a> property elsewhere, you'll need to specifically override the <a> tags for that class.
.class1 a { text-decoration: none; }
and
.class1 a:hover {text-decoration: none; }
depending on if you have a global hover defined too
A: div.class1 a { Properties:values}
Would be a good practice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Indexing arrays in matlab from 0 For the math class I'm taking, I have to write a program to compute the FFT of a function. We have been given the code in class. I'm having problems entering the code in matlab because the index starts at 0. This is the code given in class:
Input: q,N,f(k)
Output: d(k)
sigma(0) = 0
for r = 0 to q-1
for k = 0 to (2^r)-1
sigma((2^r)+k) = sigma(k) + 2^(q-1-k)
end
end
for k = 0 to N-1
d(k) = f(sigma(k))/N
end
for r = 0 to q-1
M = 2^r
Theta = e^(-i*pi()/M)
for k = 0 to M-1
for j = 0 to 2^(q-1-r)-1
x = theta^(k)*d(2*j*M+k)-x
d(2*j*m+k) = d(2*j*M+k)+x
end
end
end
Normally this would not be hard to implement but, the indicies are throwing me off. How do I write this code starting the loops at index 1 instead of 0(the program has to be written in Matlab)? Normally I would just manually calculate the first term(0 term) and put it outside the loop and then, shift the loop by one index. This problem however is not that simple. Thanks.
A: Just add one whenever you're indexing into an array. For example:
sigma((2^r)+k+1) = sigma(k+1) + 2^(q-1-k)
Also, use 1i when you mean sqrt(-1) since it's clearer, safer, since you can overwrite the meaning of i or j accidentally, and faster.
A: i would do every array index as "i array index" and then immediately change array index to be i array index - 1. you can then use array index for the mathematical portion and i*array index* to index specified arrays.
example:
instead of
for i = 0:n
sum = sum + i*array(i);
end
i would do
for ii = 1:n+1
i = ii-1;
sum = sum + i*array(ii);
end
EDIT: incredibly stupid typo: ii should go from 1:n+1 - that was the entire point of my change!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Program Crash - probably a memory retain misuse I have an array of Objective-C objects that is to be sorted on a field of the object. I use a simple selection sort since the array is small. The sort works and the correct data is in the array, but after adding about 3 or 4 objects to the array and resorting each time it crashes.
Any help would be appreciated. The error is EXC_BAD_ACCESS Thanks in advance. The code follows:
TopTenDataClass *temp1 = [[TopTenDataClass alloc] init];
TopTenDataClass *temp2 = [[TopTenDataClass alloc] init];
for (int i = 0; i < [topTenDataArray count]; i++)
{
int minIndex = i;
for (int j = i; j < [topTenDataArray count]; j++)
{
temp1 = [topTenDataArray objectAtIndex:minIndex];
temp2 = [topTenDataArray objectAtIndex:j];
if ( temp2.timeInSeconds < temp1.timeInSeconds)
minIndex = j;
}
[topTenDataArray exchangeObjectAtIndex:minIndex withObjectAtIndex:i];
}
[temp2 release]; [temp1 release];
A: The issue is that inside of your loop you are changing the values of temp1 and temp2. When you release them after the loop completes, you are not releasing the objects that you created before the loop started. Instead you are attempting to release some other object that you did not alloc/init (in this part of the code). Probably that is what is causing your crash.
I'd suggest trying something like:
TopTenDataClass *temp1 = nil;
TopTenDataClass *temp2 = nil;
for (int i = 0; i < [topTenDataArray count]; i++)
{
int minIndex = i;
for (int j = i; j < [topTenDataArray count]; j++)
{
temp1 = [topTenDataArray objectAtIndex:minIndex];
temp2 = [topTenDataArray objectAtIndex:j];
if ( temp2.timeInSeconds < temp1.timeInSeconds)
minIndex = j;
}
[topTenDataArray exchangeObjectAtIndex:minIndex withObjectAtIndex:i];
}
You don't need to assign a new object instance to temp1 and temp2 before the loop, because you just overwrite their values inside your loop.
Do also note that if topTenDataArray has only a single element in it your code will call [topTenDataArray exchangeObjectAtIndex:0 withObjectAtIndex:0], which may also be a problem (the API docs don't say that you can't exchange an object with itself, but they don't say that you can, either).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630528",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Explanation of JetBoy example for dev.android.com? I have developed many applications for desktop or web in java, but never for android.
What little I have practiced with was weird because I am used to SWING. Since it uses .xml files for applications I was wondering if you needed this also in games?
For example there is a a good example at http://developer.android.com/resources/samples/JetBoy/index.html. I was hoping someone could explain two things for me.
*
*How is the image drawn to the screen?
*How do you listen for user input? (Eg. Clicks, drawing, swiping, ect...)
I have made games on the desktop so you don't have to get in depth, but I found it hard to understand the code. (What I was suppose to do special for android.)
(Another way to put it:)
I guess basically what I am asking is how to I draw an image that will in turn listen to clicks and such without adding a button? Or do I need to add an invisible button? Then if I did have to add a button how would I listen for swiping and drawing?
Also I saw some methods like doDraw(), but did not see where they were putting the image so it would appear on the android device.
A: JetBoy is rather complicated for a beginner, check these simple examples which are based on the same principles as JetBoy: How can I use the animation framework inside the canvas?
Everything is done by drawing bitmaps on the view's canvas and an event which detects when and where the sreen was touched.
A: I think this will tell you everything you need to know, in a comprehensive, 31 part series detailing the creation of Light Racer 3d for Android.
A: If you are not going to use any Game Engine ,
basically you extend android.view.SurfaceHolder
and then overide these methods,
public boolean onTouchEvent(MotionEvent event)
protected void onDraw(Canvas canvas)
go through
these articles.It teaches everything you need from the scratch
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Action/Func vs Methods, what's the point? I know how to use Action and Func in .NET, but every single time I start to, the exact same solution can be achieved with a regular old Method that I call instead.
This excludes when an Action or Func is used as an argument for something I don't control, like LINQ's .Where.
So basically my question is...why do these exist? What do they give me extra and new that a simple Method doesn't?
A: I use them to create an array of functions. For instance, I may have a ComboBox full of actions that could be taken. I populate the ComboBox with items of a class or structure:
public class ComboBoxAction
{
private string text;
private Action method;
public ComboBoxAction(string text, Action method)
{
this.text = text;
this.method = method;
}
public override string ToString()
{
return this.text;
}
public void Go()
{
this.method();
}
}
Then when someone selects an item, I can call the action.
CType(ComboBox1.SelectedItem, ComboBoxAction).Go()
This is far easier than having a Select statement determine which method to call based on the ComboBox's text.
A: I think other answers here talk about what an Action/Func is and its use. I will try to answer how to choose between Action/Func and method. The differences first:
1) From a raw performance point of view, delegates are slower compared to direct method calls, but it's so insignificant that worrying about it is a bad practice.
2) Methods can have overloads (same function names with different signatures) but not Action/Func delegates since they are declared as variables and by C# rules you cant have two variables with the same name in a given scope.
bool IsIt() { return 1 > 2; }
bool IsIt(int i) { return i > 2; } //legal
Func<bool> IsIt = () => 1 > 2;
Func<int, bool> IsIt = i => i > 2; //illegal, duplicate variable naming
3) Consequently, Action/Func are reassignable and can point to any function, while methods once compiled remain to be the same forever. It is semantically wrong to use Func/Action if the method it points to never changes during run time.
bool IsIt() { return 1 > 2; } //always returns false
Func<bool> IsIt = () => 1 > 2;
IsIt = () => 2 > 1; //output of IsIt depends on the function it points to.
4) You can specify ref/out parameters for normal methods. For eg, you can have
bool IsIt(out string p1, ref int p2) { return 1 > 2; } //legal
Func<out string, ref int, bool> IsIt; //illegal
5) You cannot introduce new generic type parameter for Action/Func (they are generic already btw, but the type arguments can only be a known type or types specified in the parent method or class), unlike methods.
bool IsIt<A, R>() { return 1 > 2; } //legal
Func<bool> IsIt<A, R> = () => 1 > 2; //illegal
6) Methods can have optional parameters, not Action/Func.
bool IsIt(string p1 = "xyz") { return 1 > 2; } //legal
Func<string, bool> IsIt = (p1 = "xyz") => 1 > 2; //illegal
7) You can have params keyword for parameters of a method, not so with Action/Func.
bool IsIt(params string[] p1) { return 1 > 2; } //legal
Func<params string[], bool> IsIt = p1 => 1 > 2; //illegal
8) Intellisense plays well with parameter names of methods (and accordingly you have cool XML documentation available for methods), not so with Action/Func. So as far as readability is concerned, regular methods win.
9) Action/Func have a parameter limit of 16 (not that you can't define your own ones with more) but methods support more than you will ever need.
As to when to use which, I would consider the following:
*
*When you are forced to use one based on any of the above points, then you anyway have no other choice. Point 3 is the most compelling I find upon which you will have to base your decision.
*In most normal cases, a regular method is the way to go. It's the standard way of refactoring a set of common functionality in C# and VB.NET world.
*As a rule of thumb, if the function is more than a line, I prefer a method.
*If the function has no relevance outside a specific method and the function is too trivial, like a simple selector (Func<S, T>) or a predicate (Func<bool>) I would prefer Action/Func. For eg,
public static string GetTimeStamp()
{
Func<DateTime, string> f = dt => humanReadable
? dt.ToShortTimeString()
: dt.ToLongTimeString();
return f(DateTime.Now);
}
*There could be situations where Action/Func makes more sense. For instance if you have to build a heavy expression and compile a delegate, its worth doing it only once and caching the compiled delegate.
public static class Cache<T>
{
public static readonly Func<T> Get = GetImpl();
static Func<T> GetImpl()
{
//some expensive operation here, and return a compiled delegate
}
}
instead of
public static class Cache<T>
{
public static T Get()
{
//build expression, compile delegate and invoke the delegate
}
}
In the first case when you call Get, GetImpl is executed only once, where as in the second case, (expensive) Get will be called every time.
Not to forget anonymous method itself will have certain limits unrelated to Func/Action, making the use little different. Also see this for a related question.
A: There's plenty of cases where a Func can help where a Method wouldn't.
public void DoThing(MyClass foo, Func<MyClass, string> func)
{
foo.DoSomething;
var result = func(foo);
foo.DoStringThing(result);
}
So you can specify a different Func whenever you call this method - the DoThing method doesn't need to know what's being done, just that whatever it is will return a string.
You can do this without using the Func keyword by using the delegate keyword instead; it works much the same way.
A: One great use of action and func are when we need to perform some operation (before or after a method), irrespective of what the method is. For example, we need to retry the method 10 times if exception occurs.
Consider the following method – its return type is generic. So it can be applied on func with any return type.
public static T ExecuteMultipleAttempts<T>(Func<T> inputMethod, Action additionalTask, int wait, int numOfTimes)
{
var funcResult = default(T);
int counter = 0;
while (counter < numOfTimes)
{
try
{
counter++;
funcResult = inputMethod();
//If no exception so far, the next line will break the loop.
break;
}
catch (Exception ex)
{
if (counter >= numOfTimes)
{
//If already exceeded the number of attemps, throw exception
throw;
}
else
{
Thread.Sleep(wait);
}
if (additionalTask != null)
{
additionalTask();
}
}
}
return funcResult;
}
A: Action and Func are framework-provided Delegate types. Delegates allow functions to be treated like variables, meaning that you can (among other things) pass them from method to method. If you have ever programmed in C++, you can think of Delegates as function pointers that are restricted by the signature of the method they refer to.
Action and Func specifically are generic delegates (meaning they take type parameters) with some of the most common signatures- almost any method in most programs can be represented using one or the other of those two, saving people a lot of time manually defining delegates like we did in .net prior to version 2. In fact, when I see code like this in a project, I can usually safely assume that the project was migrated from .net 1.1:
// This defines a delegate (a type that represents a function)
// but usages could easily be replaced with System.Action<String>
delegate void SomeApplicationSpecificName(String someArgument);
I'd recommend that you look into delegates some more. They are a hugely powerful feature of the C# language.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "42"
} |
Q: RESTful Web URI Design for Single/Multiple Resource GET
Possible Duplicate:
Rest URL design - multiple resources in one http call
I have looked for answers on this site and the net, but haven't quite figured out the best way to approach this problem.
As an example, say I have the following REST API
Single resource REST API is straightforward:
/car/{id} --> get car by an id
Multiple resource get for a list of cars:
/cars;ids={id1,id2,id3 etc} --> get list of cars by ids
/cars;list-id={listId};count=5 --> get cars defined by a list id saved
in the cloud
/cars;relatives={id};count=5 --> get cars that are related to the car
specified by id
A list-id can specify an arbitrary list of elements to return. /cars will just return cars defined in that list.
Note: the matrix params relatives, ids, and list-id cannot all be used in a single GET request. E.g if ids and list-id both appear, then ids will take priority.
Question: Should this be redesigned? And if so, how? Thanks.
A: What if you view a car as a list ID with just one car? A list ID could then refer to one car or multiple cars. For this to work a list ID and a car ID have to share the same 'domain'. One doesn't take priority over the other because they are actually the same thing - a list of cars.
GET /car/{id} could be one car or a list of cars.
GET /car/{id}/related would return a list of those cars related to the list of cars in the car ID. But this list would have no ID of it's own (yet).
POST /car/{id}/related would return a list ID for the list of cars. That could then be used with GET /car/{id} to return the same list of cars that was also retrieved indirectly with GET /car/{id}/related.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630539",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Run Servlet Without POST or GET I am new to servlets, and would like to follow the Model2 paradigm by keeping all my "code" in servlets, and html/beans in jsp pages. But, is there a way to run a servlet when I access a jsp page without using a form submission. For example, I have a login page. If the user logs in and then somehow goes back to the login page I want to check for the existance of their session and automatically move them on to their welcome page. This is one real world example, but it seems it would come in handy to run code without having to submit a form for a multitude of reasons.
A: you dont have to submit a form to invoke a servlet. All you have to do is have the browser hit the url that is mapped to the servlet. That could happen when submitting a form, clicking a link, invoking an xhr, using curl or wget from the command line, etc.
Also, keeping all code in servlets is not good design. Your servlets should handle incoming requests, invoke business logic implemented in separate classes (for good modularity and testing purposes), and return the appropriate response.
A: If I recall correctly, in Model2, the user never navigates to (JSP) pages - only controllers (servlets). Trying to access a lower layer of code (a servlet) direcltly from a view (the page) is a violation of MVC/Model2.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: delphi standalone webservice returns http error when consumed through php I'm pretty new in WS programming.
I created WS (that I picked the base from http://www.digicoast.com/delphi_soap_standalone.html) using delphi-7
When I consumed it through XAMPP php nusoap that is installed to my PC, it worked well and I got the requested result.
But when I consumed it through php nusoap on my web hosting, it returned nothing.
When I put debug in the php codes, it says: HTTP Error: Couldn't open socket connection to server. Error(110): Connection timed out.
Here is my php codes:
<?php
require_once('../lib/nusoap.php');
$aparams = 'kode_query='.'TRIPS_ALL'.'&'.
'kode_user='.$username.'&'.
'kode_id='.$uid;
$client = new nuSoap_Client('http://110.139.181.78:9696/wsdl/IVSoftWS');
$xml_data = $client->call('GetXMLDataTable',$aparams);
echo '<h2>Debug</h2>';
echo '<pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
echo '<h2>Error</h2>';
echo '<pre>' . htmlspecialchars($client->getError(), ENT_QUOTES) . '</pre>';
?>
Info: my web hosting using php 5.2.9, while my XAMPP using php 5.3.1
Question: How can I get the same result through web hosting php codes?
Any helps are really appreciated.
A: Have you checked the firewall settings? The server seems to run on port 9696, this port needs to be opened on the server (more precise: the server which runs the Delphi 7 web service server app) for incoming connections.
To verify, you can use a web browser (or wget) from a different computer, and try to open the service URL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630545",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can Gstreamer be used server-side to stream audio to multiple clients on demand? I'm working on an audio mixing program (DAW) web app, and considering using Python and Python Gstreamer for the backend. I understand that I can contain the audio tracks of a single music project in a gst.Pipeline bin, but playback also appears to be controlled by this Pipeline.
Is it possible to create several "views" into the Pipeline representing the project? So that more than one client can grab an audio stream of this Pipeline at will, with the ability to do time seek?
If there is a better platform/library out there to use, I'd appreciate advice on that too. I'd prefer sticking to Python though, because my team members are already researching Python for other parts of this project.
Thanks very much!
A: You might want to look at Flumotion (www.flumotion.org). It is a python based streaming server using GStreamer, you might be able to get implementation ideas from that in terms of how you do your application. It relies heavily on the python library Twisted for its network handling.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: using a new path with execve to run ls command I am trying to use execve to run the ls command. Currently I'm running it with the following arguments:
execve(args[0], args, env_args)
//args looks like {"ls", "-l", "-a", NULL}
//env_args looks like {"PATH=/bin", "USER=me", NULL}
What I expected this to do was run the ls command using my new env_args meaning that it would look up ls in my PATH. However, this code actually doesn't do anything and when I run the code it just returns to my command prompt without output.
Using the same args[] I was using execvp and ls worked and searched my current path.
Can you tell me what I am doing wrong?
What I am trying to do is write my own shell program where I can create and export my own environment and have exec use the environment I have defined in a char**. Essentially I am writing my own functions to operate on env_args to add and remove vars and when I call exec i want to be able to call exec on {"ls", "-l", NULL} and have it look down my new environments path variable for a valid program called ls. I hope this explains what I am doing a little better. I don't think the extern environ var will work for me in this case.
A: The execve() function does not look at PATH; for that, you need execvp(). Your program was failing to execute ls, and apparently you don't report failures to execute a program after the execve(). Note that members of the exec*() family of functions only return on error.
You'd get the result you expected (more or less) if you ran the program with /bin as your current directory (because ./ls - aka ls - would then exist).
You need to provide the pathname of the executable in the first argument to execve(), after finding it using an appropriate PATH setting.
Or continue to use execvp(), but set the variable environ to your new environment. Note that environ is unique among POSIX global variables in that is it not declared in any header.
extern char **environ;
environ = env_args;
execvp(args[0], &args[0]);
You don't need to save the old value and restore it; you're in the child process and switching its environment won't affect the main program (shell).
This seems to work as I'd expect - and demonstrates that the original code behaves as I'd expect.
#include <stdio.h>
#include <unistd.h>
extern char **environ;
int main(void)
{
char *args[] = { "ls", "-l", "-a", NULL };
char *env_args[] = { "PATH=/bin", "USER=me", NULL };
execve(args[0], args, env_args);
fprintf(stderr, "Oops!\n");
environ = env_args;
execvp(args[0], &args[0]);
fprintf(stderr, "Oops again!\n");
return -1;
}
I get an 'Oops!' followed by the listing of my directory. When I create an executable ls in my current directory:
#!/bin/sh
echo "Haha!"
then I don't get the 'Oops!' and do get the 'Haha!'.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Multi-line button labels Is there an easy way to have two lines of button.text where you specify each line individually? Also, there seem to be large margins on the buttons so the text font needs to be quite small to fit. Is there a way to allow the text to use more of the button area?
A: The way I would do a two-line text implementation is:
Dim t1,t2 As String
t1="This is line one"
t2="This is line two"
...
MyButton.Text = t1 & CRLF & t2
The CRLF performs a Carriage Return and Line feed thus splitting the text up
I can't help with the padding issue though. Have you tried changing the font size?
MyButton.TextSize=9
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to pass List of class to List of Interface? I have a function like this:
DoSomething(List<IMyInterface>)
IMyInterface is an interface and MyClass is a class implementing this interface
Class MyClass:IMyInterface
I call DoSomething(List<MyClass>) and it looks it doesn't work.
How could I pass the list of a class to a list of the interface of the class as function's parameter? Thanks!
A: If your code is simply iterating over the sequence inside the method (not adding, removing, or accessing by index), change your method to one of the following
DoSomething(IEnumerable<IMyInterface> sequence)
DoSomething<T>(IEnumerable<T> sequence) where T : IMyInterface
The IEnumerable<> interface is covariant (as of .NET 4) (first option). Or you could use the latter signature if using C# 3.
Otherwise, if you need indexed operations, convert the list prior to passing it. In the invocation, you might have
// invocation using existing method signature
DoSomething(yourList.Cast<IMyInterface>().ToList());
// or updating method signature to make it generic
DoSomething<T>(IList<T> list) where T : IMyInterface
What the latter signature would allow you to do is to also support adds or removes to the list (visible at the callsite), and it would also let you use the list without first copying it.
Even still, if all you do is iterate over the list in a loop, I would favor a method acceping IEnumerable<>.
A: This is not safe in general because Lists are mutable. Suppose you pass someone a reference to a List<MyClass> as a List<IMyInterface>, then they do:
void Foo(List<IMyInterface> list)
{
IMyInterface x = new MyOtherClassWhichAlsoImplementsIMyInterface();
list.Add(x);
}
Now your List<MyClass> contains an instance of a class that is not a MyClass. This would violate type safety. (As other answers noted, you can avoid this problem by passing only the IEnumerable<> interface of List, which provides read-only access and so is safe).
For more details, see Using Variance in Interfaces for Generic Collections on MSDN. See also a good summary of covariance and contravariance and various C# features that support it.
A: If you only need to go through the list, declare the method with an IEnumerable. If you want to add elements to the list, what you're asking isn't typesafe and might not be allowed in C# as a result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: RVM after_cd Hook I'm trying to use the RVM hooks to run a command after I cd into a directory with my rails app.
The contents of my ~/.rvm/hooks/after_cd is:
echo "Now using $rvm_ruby_string"
The contents of my ~/.rvm/hooks/after_use is:
echo "Now using $rvm_ruby_string"
When I do $rmv use 1.9.2 I see my echo, but when I cd into the rails root directory for my app I don't get any echo.
Am I using the after_cd hook wrong?
$rvm -v says:
rvm 1.0.8 by Wayne E. Seguin ([email protected]) [http://rvm.beginrescueend.com/]
A: First you need to understand how rvm overwrite your system's default cd command.
Here's the answer explains this well.
In short, rvm defines a function like this in .rvm/script/cd
cd(){
builtin cd $* #run system cd
source after_cd_hooks #run hook scripts
}
And you can find this line if you look into how this cd() defined.
__rvm_project_rvmrc && __rvm_after_cd || true
__rvm_project_rvmrc is the function to check if .rvmrc exists in the directory you change into.
So the hook scripts will only be sourced when .rvmrc exists in your project root.
So create your .rvmrc and try the cd again. Good Luck!
> /path/to/app/root/.rvmrc
cd /path/to/app/root
My rvm version:
rvm -v
rvm 1.23.14 (stable) by Wayne E. Seguin <[email protected]>, Michal Papis <[email protected]> [https://rvm.io/]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: ArrayList in java, only doing an action once For some reason, I'm drawing a blank on this one. I have an ArrayList that contains CDs (some of them identical in name) and I want to print a String that tells how many I have of each CD. For example, a string that says "You have: (1) AlbumOne, (2) AlbumTwo, (1) AlbumThree" etc. The CDs are not sorted. How can I do this?
A: One way to do it is to loop thru the array, and use a map that uses the objects as keys and the values as counts. So
Map<YourObject, Integer> counter ...
As you loop thru the array, do a get on the counter for the current object in the array. If you get null, initialize the value at that bucket in the map to be 1. If you have a value, increment it. Then you can loop over the map to get your readout.
Note that if you use a Hashmap, your objects have to implement the hashcode and equals method properly. You don't have to use your object, if it has keys or some other distinguishing field, the keys in your map can be that...
A: //aggregate details
Map<String, Integer> albumCounts = new HashMap<String, Integer>();
for (String album : albums) {
Integer count = albumCounts.get(album);
if (count == null) {
count = 0;
}
albumCounts.put(album, count + 1);
}
//print stats
System.out.println("You have:");
for (String album : albums) {
System.out.println("(" + albumCounts.get(album) + ") " + album);
}
A: Don't get confused about the Map. Use of Map is appropriate to solve such a problem (as you have posted) So please visit this link (tutorial) and read/learn about Map.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails 3: adding a yes/no "recommended" option to user posts I'm new to rails and I'm working on a simple app where users create posts with content, hehehe. But since I'm real new I'm having some confusion. When users create a post I want them to have a 'recommended option' yes/no which defaults on the no. So if a user wants to recommend a post he simply selects the yes radio button before he submits the form. I already have the user and post model working to create a post with a title and body. The model relationship is users has_many posts, and posts belongs_to user.
I'd like to keep it really simple and just add a 'recommended' attribute to the post model, using no/yes radio buttons which default to no. I'm confused about the rails form helpers and how to add a yes/no attribute to my post migration. Then how would I select an array of the posts which are recommended by a specific @user?
Thanks a lot!
A: in the migration:
def self.up
add_column :posts, :is_recommended, :boolean, :default => false
add_column :posts, :message, :text
end
posts_controller.rb:
#rails 2 way:
@recommended_posts = Post.find(:all, :conditions => {:is_recommended => true, :user_id => params[:user_id]})
#rails 3 way:
@recommended_posts = Post.where(:is_recommended => true, :user_id => params[:user_id])
views/posts/new.html.erb: (using check_box rather than radio_button)
<% form_for(@post) do |f| %>
<p>
<%= f.label :message %><br />
<%= f.text_area :message %>
</p>
<p>
<%= f.label 'Recommend' %><br />
<%= f.check_box :is_recommended %>
</p>
<% end %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Normalizing histograms? What is normalizing histograms? When and why would I use it? What are its advantages?
I don't understand the concept at all- when I try to apply it to my histogram, when I use back projection, I don't get any results.
Could someone give me a non-technical explanation of normalization?
I am using OpenCV
PS: Don't send me to wikipedia- I don't understand the Wikipedia Page
Thanks
A: It's very simple, actually. A normalized histogram is one in which the sum of the frequencies is exactly 1. Therefore, if you express each frequency as a percentage of the total, you get a normalized histogram.
What is the use of a normalized histogram? Well, if you studied probability and/or statistics, you might know that one property required for a function to be a probability distribution for a random variable is that the total area under the curve is 1. That's for continuous-variable functions. For discrete functions, the requirements is that the sum of all values of the function is 1. So a normalized histogram can be thought of a probability distribution function which shows how probable each of the values of your random variable is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inserting form values with spaces into mysql 4.1 I'm trying to insert form data into a MySQL 4.1 DB. The problem I'm having is form fields that include spaces get truncated before insertion. The POST variables are complete, spaces and all. Just being cut off somewhere. For instance, "South Lake Tahoe" is inserted simply as "South". Zip codes and telephone numbers with dashes are also fine. The site I'm working on is hosted by Yahoo Small Business, and they're still using MySQL 4.1. I don't know if that is the problem, but I do know I never had issues doing this with MySQL 5+. The user fills out a form to add a new member. Upon Submit, the form data is POSTED to another page for processing:
$k = array();
$v = array();
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$result = mysql_query("SELECT * FROM members WHERE first_name='$first_name' AND last_name='$last_name'");
if(mysql_num_rows($result)>0){
mysql_free_result($result);
exit("Duplicate User in Database");
}
mysql_free_result($result);
array_pop($_POST);//Don't need the Submit value
foreach($_POST as $key=>$value){
array_push($k, "$key");
array_push($v, "$value");
}
$fields = implode(", ", $k);
$values = array();
foreach($v as $key=>$value){
array_push($values, '"'.$value.'"');
}
$values_string = implode(", ", $values);
$result = mysql_query("INSERT INTO members($fields) VALUES($values_string)");
I'm sure there are better ways of doing this, but I'm still on the way up the learning curve. Please point out any obvious flaws in my thinking.
Any suggestions are greatly appreciated.
EDIT: The field types in MySQL are correct and long enough. For example, the field for City is set as VARCHAR(30).
Thanks much,
Mark
A: <?php
// Remember to always escape user input before you use them in queries.
$first_name = mysql_real_escape_string($_POST['first_name']);
$last_name = mysql_real_escape_string($_POST['last_name']);
$result = mysql_query("SELECT * FROM members WHERE first_name='$first_name' AND last_name='$last_name'");
if (mysql_num_rows($result) > 0) {
mysql_free_result($result);
exit("Duplicate User in Database");
}
mysql_free_result($result);
// I removed your loop around $_POST as it was a security risk,
// and could also become non-working. (What would happen if the order
// of the $_POST keys were changed?)
// Also the code become clearer this way.
$result = mysql_query("INSERT INTO members(first_name, last_name) VALUES('$first_name', '$last_name')");
A: This code is horrifically insecure - you're taking user-supplied values and plopping them directly into your SQL statements without any sanitization. You should call http://php.net/manual/en/function.mysql-real-escape-string.php on anything you insert into a query this way (parameterized queries with PDO are even better).
You also make some assumptions, such as $_POST always being ordered a certain way (is that guaranteed?) and that you have exactly as many elements in your form as you have fields in your table, and that they're named identically. The code as it's written is the kind of thing a lot of beginning programmers do - it feels efficient, right? But in the end it's a bad idea. Just be explicit and list out the fields - e.g.
$field1 = $_POST['field1'];
$field2 = $_POST['field2'];
$sql = "insert into mytable (field1, field2) values ('" . mysql_real_escape_string($field1) . "', '" . mysql_real_escape_string(field2) . "')";
mysql_query($sql);
I haven't touched on why stuff would cut off at the first space, as this would imply that your code as you have it presented is salvageable. It's not. I get the feeling that reworking it as I described above might make that problem go away.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to fix syntax to nest functions in mathematica? I wanted to try to make a rule to do norm squared integrals. For example, instead of the following:
Integrate[ Conjugate[Exp[-\[Beta] Abs[x]]] Exp[-\[Beta] Abs[x]],
{x, -Infinity, Infinity}]
I tried creating a function to do so, but require the function to take a function:
Clear[complexNorm, g, x]
complexNorm[ g_[ x_ ] ] := Integrate[ Conjugate[g[x]] * g[x],
{x, -Infinity, Infinity}]
v = complexNorm[ Exp[ - \[Beta] Abs[x]]] // Trace
Mathematica doesn't have any trouble doing the first integral, but the final result of the trace when my helper function is used, shows just:
complexNorm[E^(-\[Beta] Abs[x])]
with no evaluation of the desired integral?
The syntax closely follows an example I found in http://www.mathprogramming-intro.org/download/MathProgrammingIntro.pdf [page 155], but it doesn't work for me.
A: The reason why your expression doesn't evaluate to what you expect is because complexNorm is expecting a pattern of the form f_[x_]. It returned what you put in because it couldn't pattern match what you gave it. If you still want to use your function, you can modify it to the following:
complexNorm[g_] := Integrate[ Conjugate[g] * g, {x, -Infinity, Infinity}]
Notice that you're just matching with anything now. Then, you just call it as complexNorm[expr]. This requires expr to have x in it somewhere though, or you'll get all kinds of funny business.
Also, can't you just use Abs[x]^2 for the norm squared? Abs[x] usually gives you a result of the form Sqrt[Conjugate[x] x].
That way you can just write:
complexNorm[g_] := Integrate[Abs[g]^2, {x, -Infinity, Infinity}]
Since you're doing quantum mechanics, you may find the following some nice syntatic sugar to use:
\[LeftAngleBracket] f_ \[RightAngleBracket] :=
Integrate[Abs[f]^2, {x, -\[Infinity], \[Infinity]}]
That way you can write your expectation values exactly as you would expect them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630571",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Git push everything to new origin I deleted my previous git origin, and created a new one. I did git add . and git commit. But it will update changes, how do i push everything into the new origin
A: (works with git 1.8.4)
If you want to push all branches at once:
git push <URL> --all
To push all the tags:
git push <URL> --tags
A: git remote add origin <address>
git push origin <branchname>
A: git push new_remote_name branch_name
A: Hmmmm I just did this. I am not sure if you did exactly the same but I had a different method.
I setup a bare repo on "newserver" (using ssh). Had the full clone of the repo on my laptop.
I then did:
git remote set-url origin "newservers url"
git push origin master
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
} |
Q: how to use UITableViews for multiple datasets I am currently playing around with a navigational based app. Where I want to allow the user to construct a search query by selecting one of several different uitableview cells when touched leads them to a sub uitableview where I will display the data for the user to select.
each cell will load the same subview however it will load it with different datasets. I am wanting to know an appropriate way of handling the transition of data (when the user selects the cell from the subveiw how can I control which cell that data should be sent back to?
I am thinking about passing the subview the Indexpath of the mainviews selected cell.. then passing it back to when the subview is poped from the stack so that it knows where the data needs to be.. is that the best solution? or is their another way of doing this?
A: Yes, give the subview a property for the indexPath of main view's selected cell. Set this property in the main view's didSelectCell method before pushing the subview.
Once you pass that indexPath back to the main view with you data, you can use
[self cellForRowAtIndexPath:indexPath]
to access the correct cell.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I find the minimum/maximum values to use with Root Solvers? I want to use the root solvers (ex: BrentSolver) in Commons Math to find roots for polynomial functions, but they all seem to require using an initial estimate for minimum/maximum, where the function has different signals.
So how do I go about doing this? I know I can compute f(x) for points inside whatever interval I have in mind, but if my Interval is too big, do I still do that? How big should the step be between every attempt? Isn't there a better way to do this?
A: I think what they want is a starting interval to search in. The min and max values define the region where you think the roots are.
I don't know what you mean by "interval too big". It won't be +/- infinity; you must have some region of interest to start with.
Run it once; see what you get. Try a few other intervals to see if you can find a true global min/max.
It's not possible to use numerical methods as a complete black box. You have to know something about your function and how the methods work. Use them as an iterative tool to learn something about your function of interest.
A: You might try the Durand-Kerner-Weierstrass method as an estimate or check. A Java implementation is shown here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to manage (create/delete) Email addresses programmatically? I am building a web application that will also allow my users to register/transfer a domain and manage email addresses through my application. However, I'm not exactly sure how to do that yet. I think there are services with APIs that will allow me to register domain names. However, working with DNS, MX records, email addresses and running an email server is something I've never done before. What do I need to know about automating this process of managing email accounts, and what sorts of solutions already exist?
A: for the email address part, have a look at How to communicate with a mail server through a web application
the dns part is pretty much the same, but you need a dns authoritative server with a database backend, such as powerdns (database configuration docs)
if you don't want to run the dns servers yourself, powerdns also offers hosting with API access
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Learning C++ & STL by doing game programming project? I've been coding with c++ for last 3 years, mostly my work revolved around using other libraries such as QT. I recently realized that for a guy who has been coding for 3+ years I dont really know much C++, cause I dont know much about Templates or STL or Boost.
To remedy it I decided that I shall learn new C++ feature and STL, then I stumbled on this excellent thread Learning C++ using a template. Which basically says that I should learn STL before anything else.
Now game programming is something I wanted to do from my undergrad days, I even wrote one flight simulator game for my project, but after some time it was discontinued.
My question is should I go on and try to make an opengl game, or try some text based game to learn C++. Would learning opengl be so hard an effort that it would distract me from actually learning C++. Also if not does somebody has some other idea ?
A: The STL and Boost are used in almost every C++ program, you don't need to go to the videogames domain just to learn that... Videogame programming is a very complex application domain. Nevertheless, if game programming is what you enjoy the most, go for it. I'd recommend starting with SDL instead of OpenGL, it's a higher level API. Another thing I recommend, start making a simpler game, like a Tetris clone for instance, and then move on to more complex types of game. A page I highly recommend for your game programming needs is GameDev.net
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Graph API search pages and applications using php-sdk I am looking for -
*
*Sample on how to use graph api search pages to get me started.
*Does the api include applications in the search?
*Do i need an access token to use this feature, i did not see in the docs?
A: this sample assumes you have php-sdk 3.1.1 installed. and are using a form to submit the search to current page. url format sample.com/?qs=search+facebook
$q = urlencode($_GET['qs']);
if(!$_GET['qs']){
$q = urlencode($_POST['qs']);
if(!$_POST['qs']){
$q = "facebook";
}
}
$MEsearch = $facebook->api('/search?q='.$q.'&type=page&limit=100');
foreach ($MEsearch as $key=>$value) {
foreach ($value as $fkey=>$fvalue) {
$pagename = $fvalue[name];
$pageid = $fvalue[id];
$pagecategory = $fvalue[category];
echo ''.$pagename.' '.$pagecategory.'';
}
}
A: Here is what I've been doing with Ajax. Make a php file (fbAuth.php, in this example), first :
require_once("fb_sdk/src/facebook.php"); //Path to FB SDK
$facebook = new Facebook(array(
'appId' => 'yourappid',
'secret' => 'yourappsecret',
));
$query = urlencode('searchterm');
$type = 'post';
$ret = $facebook->api('/search?q='.$query.'&type='.$type);
echo json_encode($ret);
And then, using jQuery :
function fb_fetchPosts(){
$.ajax({
url: "fbAuth.php",
type: "POST",
datatype: "json",
success: fb_success
});
}
function fb_success(posts){
posts = $.parseJSON(posts);
//Do stuff here
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630616",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: keyboard event as3 not working This was something that had me banging my head for 2 hours before I figured it out.
I decided to post it here, to help others not pull their hair out :).
Essentially the bug was I was not receiving the keyboard event from within my flash builder environment (The same bug/issue is visible with adobe flash cs5). I set the stage.focus = stage, did not help. I added other event listeners (mouse_down, frame_enter) which worked fine, I added MovieClip children and listened for events on those children, still the same issue.
package
{
public class Test extends Sprite
{
public function Test()
{
this.addEventListener(Event.ADDED_TO_STAGE,init);
}
public function init(stage:Stage):void
{
this.removeEventListener(Event.ADDED_TO_STAGE,init);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
}
private function keyPressed(e:KeyboardEvent):void
{
trace("keyPressed");
}
private function keyReleased(e:KeyboardEvent):void
{
trace("keyReleased");
}
}
}
A: Using keyboard commands requires listening to keyboard events. This process is identical to the process for listening to any other event in AS3. You need to use the addEventListener() method to register with a KeyboardEvent. However, unlike other objects, due to the fact that the keyboard is not necessary attached to any specific object in the project, the Keyboard Event is usually registered with the stage. In the code below, the stage object registers for a keyboard event to be triggered each time a keyboard key is pressed down.
Unlike in AS2, in AS3 Keyboard events are not global. They are issued to the stage, and they bubble through the display list to whatever display object has focus.
package
{
import flash.display.*;
import flash.events.*;
public class Test extends Sprite
{
public function Test()
{
init();
}
public function init():void
{
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
}
private function keyPressed(e:KeyboardEvent):void
{
trace("keyPressed");
}
private function keyReleased(e:KeyboardEvent):void
{
trace("keyReleased");
}
}
}
A: public function init(stage:Stage):void
ADDED_TO_STAGE is a `listener Event` not a stage instance.
so instead of stage:Stage use event:Event.
and u needs to import needed classes.
A: Marked the line that changed. Your code doesnt compile btw, check for error logs.
package {
import flash.display.Sprite; /// changed line
import flash.events.Event; /// changed line
import flash.events.KeyboardEvent; /// changed line
public class Test extends Sprite
{
public function Test()
{
this.addEventListener(Event.ADDED_TO_STAGE,init);
/* i like it this way
stage ? init(null) : addEventListener(Event.ADDED_TO_STAGE,init);
*/
}
public function init(e:Event):void /// changed line
{
this.removeEventListener(Event.ADDED_TO_STAGE,init);
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressed);
stage.addEventListener(KeyboardEvent.KEY_UP, keyReleased);
}
private function keyPressed(e:KeyboardEvent):void
{
trace("keyPressed");
}
private function keyReleased(e:KeyboardEvent):void
{
trace("keyReleased");
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: display tag sorting duplicate the last action performed on the page I have display tag like this.
<display:table class="displayTable" id="orgList"
name="${sessionScope.organisationArray}" requestURI="" pagesize="13"
defaultsort="1" sort="list">
<display:column property="organisationName"
title="Organisation Name" sortable="true" headerClass="sortable"/>
<display:column property="description" title="Description" />
</display:table>
I got the ArrayList of the data from Session.
The problem is whenever I click to sort the Organisation Name column, it automatically performs the last action. For example, I add a new organistation, then I back to the list. And I click to sort, then adding of a new organisation perform again.
When I check the URL on the sortable column, it is pointing to the last action (Add action ) URL. If last action is delete, it is pointing to Delete action. Second time click on sortable column is OK, it works well.
But just first time straight back from another action, sorting is duplication the same action.
How can I overcome this problem?
Thanks ahead.
A: Finally I fix it just by adding requestURI="blahblah.action" which is an action just to display all the list.
Thanks to the following link: coderanch.com/t/53098/Struts/display-tag-sorting-Struts Thanks.
please check this link for detail info.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630622",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Odd behavior when binding a click to two elements in jQuery I have two images with the title "Show Options". I want to assign a click event to both of them and I want the clicks to print different statements.
console.log($('img[title*=\"Show\"]'));
$('img[title*=\"Show\"]').each(function(index, value){
switch(index){
case 0:
console.log('object');
$(this).live('click', function(e) {
console.log('object clicked');
});
break;
case 1:
console.log('record');
$(this).live('click', function(e) {
console.log('record clicked');
});
break;
}
});
ODD BEHAVIOR
*
*object and record are printed so I know there are 2 elements.
*When I click on the image that is associated with object, record is printed.
*When I click on the image that is associated with record, nothing is printed.
I am not sure how I can resolve this.
A: The purpose of the .live method is to allow you to specify event handlers on DOM objects that may change, or do not yet exist. This works because in fact no handler is attached at all. Instead, a pre-existing handler at the root of the document looks through all of the selectors registered with .live() to determine if any of them is a match.
In your example, you are passing in a DOM object directly, and not a jQuery selector. So, what's probably happening (although, I'm not sure) is that it's trying to attach live events to selectors created by stringifying the DOM objects, which can lead to strange, unexpected results.
If you're trying to attach events to a single DOM object that will not change, just use the .bind() function.
If you really needed to use live, you could restructure the code so that you specify selectors that match the elements. For example:
var selector = 'img[title*=\"Show\"]';
$(selector).each(function(index, value){
switch(index){
case 0:
console.log('object');
$(selector+":eq(0)").live('click', function(e) {
console.log('object clicked');
});
break;
case 1:
console.log('record');
$(selector+":eq(1)").live('click', function(e) {
console.log('record clicked');
});
break;
}
});
In general, this is a very bad pattern, and there are much more eloquent ways to do things. However, it is in theory possible to make this pattern work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630623",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java regex to find a sequence of characters in a string I would like to find out if my string has = & & sequence in it. If yes then I would like to encode second &. How using java regex can I find it?
My string is something like this:
a=cat&b=dog&cat&c=monkey
Thanks
Chaitanya
A: Like Mosty and Ted suggested, perhaps the best way to go at this is by detecting and escaping the '&'.
However, if you want a single regex to do the work for you, here it is:
String s = "a=cat&b=dog&cat&c=monkey";
s = s.replaceAll("&(?=[^=]*&)", "&");
System.out.println(s);
A: Why don't you just split it?
First split it by "&", then take the second element
A: You can use this format:
if (string.contains("=&&"))
{
// do something
}
else
{
// do something else
}
I don't know what you mean by "encode the &" though. Could you clarify?
A: It would be easier to escape the & in the values before forming the concatenated name-value pair string. But given an already-encoded string, I think a variant of Mosty's suggestion might work best:
String escapeAmpersands(String nvp) {
StringBuilder sb = new StringBuilder();
String[] pairs = nvp.split("&");
if (pairs[0].indexOf('=') < 0) {
// Maybe do something smarter with "a&b=cat&c=dog"?
throw new Exception("Can't handle names with '&'");
}
sb.append(pairs[0]);
for (int i = 1; i < pairs.length; ++i) {
String pair = pairs[i];
sb.append(pair.indexOf('=') < 0 ? "&" : "&");
sb.append(pair);
}
return sb.toString();
}
This is likely to be faster than regular trying to do this with regular expressions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630624",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WCF http activation without IIS Is it possible to enable HTTP components for WCF without installing IIS. When i try to enable the HTTP components on windows server 2008 it forces me to enable the web server components.
Is there a workaround by not installing webserver.
(any solution other than self hosting or windows service)
thanks
Ben
A: WCF services can be hosted in any managed .NET application, not only IIS. You can either host it inside a windows service, or create a standard .NET executable to host the service (self-hosting). You can configure your end point to http eventhough the WCF is hosted outside IIS.
Check this article for more insight:
Hosting and Consuming WCF Services
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630626",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JSONCPP Amalgamated link errors I am trying to use the amalgamated version of jsoncpp(the latest version), but it is producing unresolved external symbol link errors. The code I am using is
#include <json/json.h>
int main(){
Json::Value root;
return 0;
}
and it is giving me the error
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Json::Value::~Value(void)" (??1Value@Json@@QAE@XZ) referenced in function _main
1>main.obj : error LNK2019: unresolved external symbol "public: __thiscall Json::Value::Value(enum Json::ValueType)" (??0Value@Json@@QAE@W4ValueType@1@@Z) referenced in function _main
A: Probably you didn't include the JSONCPPs *.cpp file into your project (they have to be compiled and linked). If the library gets compiled to a static library, you have to tell the linker what to link.
A: I got this when trying to link x86 version of JsonCpp in my x64 build. I did not notice that Vcpkg behaves as if VCPKG_DEFAULT_TRIPLET=x86-windows was defined, unless it's told otherwise.
I saw the following entry in the build log when that was happening
C:\Tools\vcpkg\installed\x86-windows\debug\lib\jsoncpp.lib : warning LNK4272: library machine type 'x86' conflicts with target machine type 'x64' [C:\projects\qpid-proton\BLD\cpp\qpid-proton-cpp.vcxproj]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630629",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Convert string to long in excel macro How can I convert string to long in excel macro. CLng is giving me type mismatch error
Dim wStr As String
Dim w As Long
wStr = "=RAND() * 0.3 + 0.35"
w = CLng(wStr)
A: Try the formula for w below.
w = CLng(Evaluate(wStr))
Or forget trying to use an "Excel formula", and go straight to VBA with with its random function counterpart
w = CLng(Rnd() * 0.3 + 0.35)
A: The root cause of your error is that CDbl expects a numeric value or a string that looks like a number. the string "=RAND() * 0.3 + 0.35" itself does not look like a number, even though it will evaluate to a number.
What are you actually trying to achieve here?
If its to get a long integer result from the formula =RAND() * 0.3 + 0.35, use
Dim w as Long
w = Rnd() * 0.3 + 0.35
If its to emulate a cell formula use
Dim w as Long
w = Application.Evaluate("=RAND() * 0.3 + 0.35")
As to the formula itself, why this construct? It will return Single in the range [0.35, 0.65) which when rounded to a Long will return 0 or 1 at 50% probability of each.
Why not use
w = Rnd()
or
w = Application.Evaluate("=RAND()")
or
w = Application.WorksheetFunction.RandBetween(0, 1)
or is there some other reason I've missed?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Opening Window mobile 6 professional emulator I make a window mobile application using ms visual studio 2005 professional.
*
*Could I run this application in emulator without installing Visual
Studio?
*If I run this in visual studio 2008 or 2010, is there any
difference?
A: You can download the Microsoft Device Emulator 3.0 -- Standalone Release here. In fact, it is the same emulator that MS starts from within Visual Studio and attaches a debugger to the emulator, so there should not be any different behavior.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Django - Passing image objects to a second view for processing and db saving Here's the use case:
My main page has an image upload form. When the form is submitted, a page loads with a 4x4 grid of the uploaded image with different photo filters applied. Clicking on an option saves the image with the chosen processing to the database.
My question is, how would I go about doing this without saving to the database until the processing has been chosen?
I'm not opposed to using this problem to learn ajax.
A: Do it in a single view; There are three possibilities it has to take into consideration:
*
*The user has just arrived on the page - server them an empty form (InitialImageForm)
*The user has submitted an image - don't save it, instead create 4 new images and pass them back with a new form (ProcessedImageForm) allowing them to choose one of the generated images
*The user has now submitted the final form along with the original image, and the chosen processed image - save it all
This code is a bit messy but it gives you the idea. You would need to write two Forms yourself, along with probably a Model to represent the image and the processed/chosen image
from PIL import Image
def view(self, request):
if request.method=='POST':
# We check whether the user has just submitted the initial image, or is
# on the next step i.e. chosen a processed image.
# 'is_processing_form' is a hidden field we place in the form to differentiate it
if request.POST.get('is_processing_form', False):
form = ProcessedImageForm(request.POST)
if form.is_valid():
# If you use a model form, simply save the model. Alternatively you would have to get the data from the form and save the images yourself.
form.save()
return HttpResponseRedirect('/confirmation/')
elif form.POST.get('is_initial_form', False) and form.is_valid():
form = InitialImageForm(request.POST)
if form.is_valid():
# Get the image (it's not saved yet)
image = Image.open(form.cleaned_data.get('image').url)
processed_list = []
# Create your 4 new images and save them in list
...
# You can show a template here that displays the 4 choices
return direct_to_template(request,template = 'pick_processing.html',extra_context = { 'image' : image, 'processed_list':processed_list })
else:
# When the user arrives at the page, we give them a form to fill out
form = ImageSubmitForm()
return direct_to_template(request,template = 'upload_image.html',extra_context = { 'form' : form })
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Git Config excludesfile for just a branch I wanted to exclude a file called config/dbconfig.js in my public branch which I use to push to github but still be able to push from master to my noester.com git repo to push to production. I changed the config file to this:
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
excludesfile = +info/exclude
[remote "nodester"]
url = *** My Git Repo ***
fetch = +refs/heads/*:refs/remotes/nodester/*
[branch "public"]
excludesfile = +info/exclude_public
I made sure to remove the .gitignore file and I am using the .git/info/exclude file for the the general excludes and was hoping to use the .git/info/exclude_public to exclude that one file so when I merge to public that file doesn't merge as well as not push to github.
If I do the following it will still add the file to git even in the public branch. So I am thinking ether I have the syntax wrong or it's not possible.
$ git checkout public
$ git add .
$ git status
# On branch public
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# new file: config/dbconfig.json
#
If this isn't possible is there a better way to deal with database configs you do not want to get out on a open Github project without running two git repositories and manually merge between them?
A: For config files, it is best to deals with content filter drivers than trying to ignore a file for certain branches.
You would:
*
*store a config file template
*store public values
*let a content filter 'smudge' script build the target config file out of the template and public values,
... except when that script detects it is on the deployment environment, in which case it would use values from another source on that server (and not public values stored in the repo)
See for illustration:
*
*"Different databases for specific branches of git project" or
*"When a commit to revision control requires a developer to change their own config"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630638",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Core Data syncronization procedure with Web service I'm developing an application that needs to be syncronized with remote database. The database is connected to the a web-based application that user able to modify some records on the web page.(add/remove/modify) User also able to modify the same records in mobile application. So each side (server - client) must be keep the SAME latest records when an user press the sync button in mobile app. Communication between server and client is provided by Web Serives.(SOAP) and i am not able to change it because of it is strict requirements. (i know this is the worst way that can be used). And another requirement is the clients are not able to delete the server records.
I already be familiar with communicating web service (NSURLConnection), receiving data (NSData) and parsing it. But i could not figure out how the syncronization procedure should be. I have already read this answer which about how i can modify server and client sides with some extra attributes (last_updated_date and is_sync)
Then i could imagine to solve the issue like:
As a first step, client keeps try to modify the server records with sending unsyncronized ones. New recoords are directly added into DB but modified records shoud be compared depending on last_updated_date. At the end of this step, server has the latest data.
But the problem is how can manage to modify the records in mobile app. I thought it in a two way:
*
*is the dummiest way that create a new MOC, download all records into this and change with existing one.
*is the getting all modified records which are not in client side, import them into a new MOC and combine these two. But in this point i have some concerns like
There could be two items which are replicated (old version - updated version)
Deleted items could be still located in the main MOCs.
I have to connect multiple relationships among the MOCs. (the new record could have more than 4 relationships with old records)
So i guess you guys can help me to have another ideas which is the best ??
A: Syncing data is a non-trivial task.
There are several levels of synchronization. Based on your question I am guessing you just need to push changes back to a server. In that case I would suggest catching it during the -save: of the NSManagedObjectContext. Just before the -save: you can query the NSManagedObjectContext and ask it for what objects have been created, updated and deleted. From there you can build a query to post back to your web service.
Dealing with merges, however, is far more complicated and I suggest you deal with them on the server.
As for your relationship question; I suggest you open a second question for that so that there is no confusion.
Update
Once the server has finished the merge it pushes the new "truth" to the client. The client should take these updated records and merge them into its own changes. This merge is fairly simple:
*
*Look for an existing record using a uniqueID.
*If the record exists then update it.
*If the record does not exist then create it.
Ignoring performance for the moment, this is fairly straight forward:
*
*Set up a loop over the new data coming in.
*Set up a NSPredicate to identify the record to be updated/created.
*Run your fetch request.
*If the record exists update it.
*If it doesn't then create it.
Once you get this working with a full round trip then you can start looking at performance, etc. Step one is to get it to work :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I have it so images don't flicker when ajax is called? On this page: http://friendsconnect.org/chat/ you can see a very simple chat. How can I have it so the image doesn't flicker each time ajax is called?
Javascript:
function execute_check(){
$.ajax({
type:'GET',
url: 'chat.php',
success: function(data){
$("#container").html(data);
}
});
setTimeout(execute_check, 2000);
}
A: dont send the image and update only content.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630648",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Backbone.js view instance variables? I'm learning Backbone.js and am trying to figure out whether it's possible to have instance variables in Backbone views.
My goal is to load a view's templates from an external file when a view is being instantiated. Currently I'm storing them in a global variable in the Backbone app's global namespace, but it would be cleaner to store the templates in a view's instance variables. Currently I have it set up like this:
var templates = {};
MessageView = Backbone.View.extend({
initialize: function() {
$.get('js/Test2Templates.tpl', function(doc) {
var tmpls = $(doc).filter('template');
templates['MessageView'] = [];
tmpls.each(function() {
templates.MessageView[this.id] = $.jqotec($.unescapeHTML(this.innerHTML));
});
});
},
render: function() {
var tpldata = {name: 'Ville', thing: 'Finland'};
$('#display').jqoteapp(templates.MessageView.greeting_template, tpldata);
},
events: {
"click input[type=button]": "additionalTransactions"
},
additionalTransactions: function() {
this.render();
}
});
But instead of using "templates" being defined as a global var, I'd like to create 'templates' in a view's initialize function, along these lines (but this doesn't work):
MessageView = Backbone.View.extend({
view_templates: {},
initialize: function() {
$.get('js/Test2Templates.tpl', function(doc) {
var tmpls = $(doc).filter('template');
tmpls.each(function() {
this.view_templates[this.id] = $.jqotec($.unescapeHTML(this.innerHTML));
});
});
},
render: function() {
var tpldata = {name: 'Ville', thing: 'Suomi'};
$('#display').jqoteapp(this.view_templates.greeting_template, tpldata);
},
events: {
"click input[type=button]": "additionalTransactions"
},
additionalTransactions: function() {
this.render();
}
});
This is probably (?) pretty straightforward and/or obvious, but me being somewhere on the Backbone.js learning curve, I'd much appreciate any help with this!! Thanks!
A: Your view_templates instance variable is fine (and a good idea as well). You just have to be sure that you're using the right this inside your $.get() callback and inside your tmpls.each() call. I think you want your initialize to look more like this:
initialize: function() {
this.view_templates = { };
var _this = this;
$.get('js/Test2Templates.tpl', function(doc) {
var tmpls = $(doc).filter('template');
tmpls.each(function() {
_this.view_templates[this.id] = $.jqotec($.unescapeHTML(this.innerHTML));
});
});
},
I'm not sure which this.id you want inside the tmpls.each() but I'm guessing that you want the DOM id attribute from the current template so I left it as this.id.
The this.view_templates assignment in your constructor (initialize) is needed because you presumably want each instance of the view to have its own copy of the array. Creating a new view instance doesn't do a deep copy of the the view so if you just have:
MessageView = Backbone.View.extend({
view_templates: {},
// ...
then all the instances will end up sharing the same view_templates object and view_templates will behave more like a class variable than an instance variable.
You can specify your instance variables in the view definition (i.e. the Backbone.View.extend() call) as a form of documentation but you will want to initialize any of them that should behave as an instance variable in your initialize method; read-only or "class variables" like events can be left as part of the view's definition.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: C# reading from text file (which has different data types) to get sum of numerical values So I have a .txt file that reads as the following:
-9
5.23
b
99
Magic
1.333
aa
how would I then loop through it to get the sum of all numerical values, and leave the non-numerical values untouched?
A: Read text file using System.IO.StreamReader and use Double.TryParse method to parse the numeric data.
A: using System;
using System.IO;
using System.Linq;
class Sample {
static void Main(){
string[] data = File.ReadAllLines("data.txt");
double sum = data.Select( x => {double v ;Double.TryParse(x, out v);return v;}).Sum();
Console.WriteLine("sum:{0}", sum);
}
}
A: In your loop you can either:
*
*Use int.TryParse
*Use Regular Expresssion to match only integers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pagination, floating numbers I wan't to do something like:
If user is at first, second or third page then pagination numbers is: 1, 2, 3 (default, and I got this atm.).
I wan't it now, so I user is switching the page to the third page, then pagination number should look like this: 2, 3, 4 ... if user is at fourth page: 3, 4, 5 ... etc.
How can I do that in PHP?
A: If you know the current page, subtract 1 from it to get the previous and add 1 to it to get the next page. Some if statements to determine if the page is <= 0 as well as > the max pages (to prevent those). If those statements are true, just add 1 to the last displayed page or subtract one from the the first displayed page.
Hope that makes senses.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Any good example projects for the Kiwi testing library (offering more complexity than 2+2) I'm looking for a good example project/tutorial that show the Kiwi testing framework in action. I don't need any more examples of testing classes with the only purpose of adding 2 numbers together or something mundane like that. There are plenty of those examples already.
I'm particularly interested in strategies for testing UIViewController subclasses and classes that are in charge of data fetching.
What are the strategies that exist for testing against a web service. Is it to stub out the return methods from the fetch calls?
A: There is a website related to the book "Test Driven iOS Development with Kiwi"
You could find out code samples and in-depth tutorial over here.
http://editorscut.com/Books/001kiwi/001kiwi-details.html
I tried it out myself and it is great, especially if you are getting started with Kiwi on iOS.
The website also has a link to the github with code samples.
https://github.com/editorscut/ec001-iOS-Testing-With-Kiwi
A: Thi is good link to see, how to use Kiwi for testing:
https://github.com/IgorFedorchuk/use-bdd
A: mneorr on Github seems to test most of his projects with Kiwi these days. I also think he is a collaborator on the Kiwi project itself. The following projects use Kiwi for unit tests with varying degrees of coverage:
*
*Objective-Record
*ObjectiveSugar
*Alcatraz
I've used Kiwi to test this project. I don't profess to be a unit testing/TDD/BDD/Kiwi master but maybe it will help someone.
A: Just throwing my two cents, the actual wiki for the Kiwi git's project has some nice examples:
*
*https://github.com/allending/Kiwi/wiki/Specs
*https://github.com/allending/Kiwi/wiki/Mocks-and-Stubs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: How do I find the language from a regular expression? How would I find the language for the following regular expressions over the alphabet {a, b}?
aUb*
(ab*Uc)
ab*Ubc*
a*bc*Uac
EDIT: Before i get downvoted like crazy, i'd appreciate it if someone could show me the steps towards solving these problems, not just the solution. Maybe even walking me through one so I can do the rest on my own.
Thanks!
A: Edit: short answer, * means "zero or more repetitions" in almost all regex/grammar syntaxes include perl5 and RFC 5234. * typically binds more tightly than concatenation and alternation.
You say you want a language over the alphabet (a, b), but include c and U in your expressions. I'm going to assume that you want a language grammar over the alphabet (a, b, c) in a form like BNF given a regular expression where U is a low-precedence union operator, similar to | in perl re.
In that case,
a|b*
is equivalent to the BNF:
L := a
| <M>
M := epsilon
| b <M>
The * operator means zero or more, so the first clause in M is the base case, and the second clause is a recursive use of M that includes a terminal b.
L is just either a single terminal a or the nonterminal M.
(ab*|c)
L ::= a <M>
| c
M ::= epsilon
| b <M>
M is derived the same way as above, and the rest is self explanatory.
ab*|bc*
L ::= a <M>
| b <N>
M ::= epsilon
| b <M>
N ::= epsilon
| c <N>
N is derived in the same way as M above.
a*bc*|ac
The * in most regular expression languages binds more tightly than concatenation, so this is the same as
(a*b(c*))|(ac)
which boils down to
L ::= <M> b <N>
| a c
M ::= epsilon
| a <M>
N ::= epsilon
| c <N>
In general to convert a regex to BNF, you simply use adjacency in a regex to mean adjaceny in BNF, and U or | in a regex means | in BNF.
If you define a nonterminal <X> ::= x then you can handle x* thus:
L ::= epsilon
| <X> <L>
With the same nonterminal <X> ::= x then you can handle x+ thus:
L ::= <X>
| <L> <X>
That gets you the repetition operators * and + which leaves ?. x? is simply
L ::= epsilon
| <X>
A: Although Mike gave grammars generating the languages denoted by the regular expressions, your assignment requests the languages themselves. Because you're dealing with regular expressions, your answers must be regular sets.
Recall the definition of regular sets over an alphabet:
Let Σ be an alphabet. The class of regular sets over Σ is the smallest class
containing ∅, {λ}, and {a}, for all a ∈ Σ, and closed under union, concatenation,
and Kleene star.
Now recall the definition of regular expressions over an alphabet:
Let Σ be an alphabet. The class of regular expressions over Σ is the smallest
class containing ∅, λ, and a, for all a ∈ Σ, and closed under union, concat-
enation, and Kleene star.
The translation, therefore, should be straightforward. In fact, it consists of inserting curly brackets around each letter! For example:
a ∪ b* denotes {a} ∪ {b}*
ab* ∪ c denotes {a}{b}* ∪ {c}
...
If you want to express the language of each regular expression in set-builder notation, you can revert to the definitions of the operations over regular sets. Recall:
Let A and B be regular sets. Then
1 A ∪ B = {x : x ∈ A ∨ x ∈ B}
2. AB = {xy : x ∈ A ∧ y ∈ B}
3. A* = ∪[i = 0 -> ∞]A^i
The regular sets can be translated into set builder notation by substitution of the definitions of the regular set operations. To avoid introducing nested set-builder notation, I've used equality in conjunction with the definition of concatenation to express the concatenation of regular sets.
{a} ∪ {b}* = {w : w ∈ {a} ∨ w ∈ ∪[i = 0 -> ∞]{b}^i}
{a}{b}* ∪ {c} = {w : (w = xy ∧ (x ∈ {a} ∧ y ∈ ∪[i = 0 -> ∞]{b}^i)) ∨ w ∈ {c}}
...
You should now be able to find the languages denoted by the remaining expressions without difficulty.
A: If you know what star, union and concatenation mean, these should be easy. The first is a union b star. According to order of operations, this means a union (b star). Union means anything in the language on the left or anything in the language on the right. a means the language consisting of the length-one string a; b star means the language consisting of any string which consists of zero or more b symbols and nothing else. So this language is {empty, a, b, bb, bbb, bbbb, ...}. In the second one, ab* means all strings consisting of an a followed by zero or more b symbols. Do star first, then concatenation, then union, obeying the given explicit parentheses.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Paramiko hangs while executing a large wget command Hi I am having problems executing a command that performs a wget of a 100mb file over a Ubuntu 10 server. Shorter commands work fine except for this. The below class contains how I use paramiko and my different tries of overcoming this problem (see the different run or exec methods). In the case of exec_cmd the execution hangs on this line:
out = self.in_buffer.read(nbytes, self.timeout)
from the recv method of the channel.py module from paramiko.
The same wget command works perfectly in a shell using the normal ssh utility from Mac.
"""
Management of SSH connections
"""
import logging
import os
import paramiko
import socket
import time
import StringIO
class SSHClient():
def __init__(self):
self._ssh_client = paramiko.SSHClient()
self._ssh_client.load_system_host_keys()
self._ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.time_out = 300
self.wait = 5
def connect(self, hostname, user, pkey):
retry = self.time_out
self.hostname = hostname
logging.info("connecting to:%s user:%s key:%s" % (hostname, user, pkey))
while retry > 0:
try:
self._ssh_client.connect(hostname,
username=user,
key_filename=os.path.expanduser(pkey),
timeout=self.time_out)
return
except socket.error, (value,message):
if value == 61 or value == 111:
logging.warning('SSH Connection refused, will retry in 5 seconds')
time.sleep(self.wait)
retry -= self.wait
else:
raise
except paramiko.BadHostKeyException:
logging.warning("%s has an entry in ~/.ssh/known_hosts and it doesn't match" % self.server.hostname)
logging.warning('Edit that file to remove the entry and then try again')
retry = 0
except EOFError:
logging.warning('Unexpected Error from SSH Connection, retry in 5 seconds')
time.sleep(self.wait)
retry -= self.wait
logging.error('Could not establish SSH connection')
def exists(self, path):
status = self.run('[ -a %s ] || echo "FALSE"' % path)
if status[1].startswith('FALSE'):
return 0
return 1
def shell(self):
"""
Start an interactive shell session on the remote host.
"""
channel = self._ssh_client.invoke_shell()
interactive_shell(channel)
def run(self, command):
"""
Execute a command on the remote host. Return a tuple containing
an integer status and a string containing all output from the command.
"""
logging.info('running:%s on %s' % (command, self.hostname))
log_fp = StringIO.StringIO()
status = 0
try:
t = self._ssh_client.exec_command(command)
except paramiko.SSHException:
logging.error("Error executing command: " + command)
status = 1
log_fp.write(t[1].read())
log_fp.write(t[2].read())
t[0].close()
t[1].close()
t[2].close()
logging.info('output: %s' % log_fp.getvalue())
return (status, log_fp.getvalue())
def run_pty(self, command):
"""
Execute a command on the remote host with a pseudo-terminal.
Returns a string containing the output of the command.
"""
logging.info('running:%s on %s' % (command, self.hostname))
channel = self._ssh_client.get_transport().open_session()
channel.get_pty()
status = 0
try:
channel.exec_command(command)
except:
logging.error("Error executing command: " + command)
status = 1
return status, channel.recv(1024)
def close(self):
transport = self._ssh_client.get_transport()
transport.close()
def run_remote(self, cmd, check_exit_status=True, verbose=True, use_sudo=False):
logging.info('running:%s on %s' % (cmd, self.hostname))
ssh = self._ssh_client
chan = ssh.get_transport().open_session()
stdin = chan.makefile('wb')
stdout = chan.makefile('rb')
stderr = chan.makefile_stderr('rb')
processed_cmd = cmd
if use_sudo:
processed_cmd = 'sudo -S bash -c "%s"' % cmd.replace('"', '\\"')
chan.exec_command(processed_cmd)
result = {
'stdout': [],
'stderr': [],
}
exit_status = chan.recv_exit_status()
result['exit_status'] = exit_status
def print_output():
for line in stdout:
result['stdout'].append(line)
logging.info(line)
for line in stderr:
result['stderr'].append(line)
logging.info(line)
if verbose:
print processed_cmd
print_output()
return exit_status,result
def exec_cmd(self, cmd):
import select
ssh = self._ssh_client
channel = ssh.get_transport().open_session()
END = "CMD_EPILOGqwkjidksjk58754dskhjdksjKDSL"
cmd += ";echo " + END
logging.info('running:%s on %s' % (cmd, self.hostname))
channel.exec_command(cmd)
out = ""
buf = ""
while END not in buf:
rl, wl, xl = select.select([channel],[],[],0.0)
if len(rl) > 0:
# Must be stdout
buf = channel.recv(1024)
logging.info(buf)
out += buf
return 0, out
A: I had the same problem, my python script hung when the shell script I was running on a remote ssh client, did a wget command on a 400Mb file.
I found that adding a time-out to the wget command fixed the problem.
Originally I had:
wget http://blah:8888/file.zip
now with this:
wget -q -T90 http://blah:8888/file.zip
it works like a charm!
Hope it helps.
A: *
*In this case, I would go with list appending and then concatenation. Why? Well, strings are immutable in Python. That means that every time you use += you are basically creating two new strings and reading a third. If you create a list and append it, on the other hand, you halve the number of strings created.
*Do you really need to call select multiple times? My understanding is that you don't really care if the process is thread-blocking. Since select is more or less a wrapper around the C method of the same name:
select() and pselect() allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is con‐
sidered ready if it is possible to perform the corresponding I/O operation (e.g., read(2)) without blocking.
*You are not listening for a socket.timeout Exception in your code.
*Writing to stdout/the file system can be expensive, yet you are logging every single line which is returned by recv. Can you move the log line?
*Have you considered handling reading the channel manually? The only code you technically need is:
try:
out = self.in_buffer.read(nbytes, self.timeout)
except PipeTimeout, e:
# do something with error
It isn't guaranteed, but it will cut out extra processing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: When using unix pipes (in C) does the OS balance every write() with a read() or does it balance the total number of bytes? for example, i want to get an array of 4 ints from child to parent. parent calls
read(apipe, buf, sizeof(int)*4);
child calls
for(int i=0; i<4;i++)
write(bpipe, &array[i], sizeof(int));
does this do what I intend (getting 4 ints to the parent) or does the parent simply get the first integer?
I tried searching for this answer elsewhere, but either I don't know how to search or this is too subtle (or on the other hand too seemingly obvious) for literature to dwell on it much.
EDIT: To clarify further, I was trying to write a 4-part message and read all 4 parts in one read(). See comments on accepted answer.
A: read and write work with bytes, not messages. For details of how they behave with pipes, see the documentation in POSIX:
*
*http://pubs.opengroup.org/onlinepubs/9699919799/functions/read.html
*http://pubs.opengroup.org/onlinepubs/9699919799/functions/write.html
In your code, I think the read should always get 4 ints, due to:
Upon successful completion, where nbyte is greater than 0, read() shall mark for update the last data access timestamp of the file, and shall return the number of bytes read. This number shall never be greater than nbyte. The value returned may be less than nbyte if the number of bytes left in the file is less than nbyte, if the read() request was interrupted by a signal, or if the file is a pipe or FIFO or special file and has fewer than nbyte bytes immediately available for reading. For example, a read() from a file associated with a terminal may return one typed line of data.
There will always be 4 ints available for reading, because 4*sizeof(int) < PIPE_BUF and thus writes of this size are atomic.
It's possible that the allowance for read to return a short read when interrupted by a signal could come into play, but that should not be able to happen (in the real world, at least) when sufficiently many bytes are available immediately.
A: The Definitions section of POSIX says that a pipe is identical to a FIFO except it has no entry in the file system.
From the POSIX definition for write():
Write requests to a pipe or FIFO shall be handled in the same way as a regular file with the following exceptions:
*
*There is no file offset associated with a pipe, hence each write request shall append to the end of the pipe.
*Write requests of {PIPE_BUF} bytes or less shall not be interleaved with data from other processes doing writes on the same pipe. Writes of greater than {PIPE_BUF} bytes may have data interleaved, on arbitrary boundaries, with writes by other processes, whether or not the O_NONBLOCK flag of the file status flags is set.
From the POSIX definition for read():
The value returned may be less than nbyte if the number of bytes left in the file is less than nbyte, if the read() request was interrupted by a signal, or if the file is a pipe or FIFO or special file and has fewer than nbyte bytes immediately available for reading.
Later, in the informative (non-normative) section of read() entry, it says:
The standard developers considered adding atomicity requirements to a pipe or FIFO, but recognized that due to the nature of pipes and FIFOs there could be no guarantee of atomicity of reads of {PIPE_BUF} or any other size that would be an aid to applications portability.
So, the standard implies that if all 4*sizeof(int) bytes are available when the read() is issued, then all 4*sizeof(int) bytes will be returned, but if only 1, 2 or 3 of the write() calls have completed, then the read() will not wait for the fourth to finish; it will return with a short read.
Consequently, your reading code must allow for 'short reads' which are non-erroneous; they simply mean that not all the required data was present.
A: It should read all four. If it doesn't, the error from read should indicate why. The number of writes and reads doesn't need to match.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630675",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: TempData Not Being Cleared I'm working on an ASP.NET MVC 3 web application, where i use TempData to store a model object, in the scenario where the user is not logged in.
Here's the flow:
*
*Use submits form.
*Code (special action filter) adds model to TempData , redirects to logon page.
*User redirected back to GET action, which reads TempData and calls POST action directly
After step 3, i would have thought TempData would be cleared?
Here's the code:
[HttpGet]
public ActionResult Foo()
{
var prefilled = TempData["xxxx"] as MyModel;
if (prefilled != null)
{
return Foo(prefilled);
}
}
[HttpPost]
[StatefulAuthorize] // handles the tempdata storage and redirect to logon page
public ActionResult Foo(MyModel model)
{
// saves to db.. etc
}
I found this article which states:
*
*Items are only removed from TempData at the end of a request if they have been tagged for removal.
*Items are only tagged for removal when they are read.
*Items may be untagged by calling TempData.Keep(key).
*RedirectResult and RedirectToRouteResult always calls TempData.Keep().
Well by reading it with TempData["xxx"] isn't that a "read" and therefore they should be tagged for removal?
And the last one concerns me a bit - since i'm doing a Redirect after the POST (P-R-G). But this can't be avoided.
Is there a way i can say "ditch this item". TempData.Remove ? Or am i doing this wrong?
A: There are 2 GET HTTP requests involved here:
*
*The first request is sent by the client and is the one which stores something into TempData
*At the end of the first request the client sends a second HTTP request to fetch the logon page.
There is no POST request involved in your scenario. The fact that from your GET Foo action you are invoking the POST Foo action doesn't mean that there is a separate request being performed (you are still in the context of the initial GET request). It is only a C# method call, not a separate request.
You store something into TempData during the first request and this TempData will be available for the second one. So it will be available in the controller action rendering the logon page.
So you must read from TempData in action rendering the logon page if you want TempData to be removed.
A: Below are some of the key points to note when using Temp data.
1) A read access to temp data doesn't remove items from the dictionary immediately, but only marks for deletion.
2) Temp data will not always remove the item that has been accessed. It only removes the item when an action results in an Http 200 status code (ViewResult/JsonResult/ContentResult etc).
3) In case of actions that result in an Http 302 (such as any redirect actions), the data is retained in storage even when it is accessed.
A: Fixed by adding TempData.Remove right after i read it.
Not really happy about this. I thought the whole point of TempData was that i didn't have to do this.
May as well be using Session directly.
A: That's not the way to clear it off. You could have pretty much used Session instead of TempData. Only advantage with TempData is that it manages the data by itself.
As I had answered earlier, Value is only cleared when the Action results in a 200 (Such as ViewResult/ContentResult/JsonResult) in all other scenarios, precisely any actions resulting Http Status code of 302(such as RedirectAction )will retain the data in TempData.
Read through the following for more details
ASP.NET TempData isn't cleared even after reading it
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Backbone events not firing I know other posts have been made regarding this, but so far the answers I've seen have not been helpful, and slightly different from my situation.
window.BotView = Backbone.View.extend
initialize: ->
_.bindAll @, 'alert', 'render'
@el # by calling this here, it initializes the jQuery object
el: $("#submit")
model: Chatbot
events:
"click #submit" : "alert"
alert: ->
console.log("alert called")
alert("event observed")
render: ->
alert("Rendered")
jQuery ->
window.App = new BotView
console.log App.el
All I want is when I click on the submit button with the id of submit for it to fire the alert function. However, I can't even get this to work.
What is going on with the events that my simple click handler on #submit isn't working?
I have double checked that my el is properly initialized, but even so, it should not matter because the click handler is not using el
Could anyone shed some light on why this simple event is not firing?
Thanks in advance
A: In your events you are saying, in the #submit element, look for an element that gets clicked with the ID of #submit. Change it to
'click' : 'alert'
and it should work fine.
The jQuery equivalent of what you have above is this:
$('#submit').find('#submit').click(alert);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to do integration testing in Rails 3? I tried using the code in the RailsGuides and some other code I found on Google, but nothing is working.
How do you do a simple integration test in Rails 3 using Test::Unit? How do you make the session persist across http requests?
The following code fails because Expected response to be a <:success>, but was <302>. I think it is because the session is lost after the post request.
class UserFlowsTest < ActionDispatch::IntegrationTest
fixtures :all
test "client can get client dashboard" do
post '/login', :login=> users(:client).login, :password => 'thepassword'
get '/dash'
assert_response :success
end
end
Working in Rails 3.07.
Thanks.
A: It turns out the above code is correct.
I had changed part of the user validation code, causing a redirect to the login form when I did not intend. That's why the response was 302 (redirect).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How does Mongo handle a tie when sorting? I have a number of documents where the timestamp happens to be the same, as a result of less than stellar process of creating test data.
When sorting by the timestamp (desc), what other factor does Mongo take into account to sort?
A: I do not think Mongo internally tries to solve a tie on a sort.
That said, to be on the safe side, you can pass a 2nd sort argument to the sort() function, for example, if I have comments sorted by created date (desc) and further by the text of the comment as comment.
db.comments.find().sort({created:-1,comment:1})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: In C can I declare a constant character array? I am working on a character string to signify a change in sign. I have had success with the character string that's commented out below, but would prefer a simple if-else statement using constant character arrays UP = "up/0/0" and DOWN = "down".
Does anyone know a simple way to declare such constant values?
char direction[5]; // declares char array to signify sign change
if (value - price1 > - 0.005) { // adjusts for noise near 0
direction = UP;
}
else direction = DOWN;
// update price-change direction string
// if (value - price1 > - 0.005) { // adjusts for noise near 0
// direction[0] = 'u';
// direction[1] = 'p';
// direction[2] = 00; // set character to null value
// direction[3] = 00;
// }
//
// int[4] var_name
// else {
// direction[0] = 'd';
// direction[1] = 'o';
// direction[2] = 'w';
// direction[3] = 'n';
// }
A: If you're not modifying the string later, you could do it like this:
const char *direction:
if (value - price1 > - 0.005) { // adjusts for noise near 0
direction = UP;
}
else
direction = DOWN;
A: You can't assign like that, but you can do:
strcpy(direction, UP);
strcpy(direction, DOWN);
Obviously, be careful not to overflow your buffer. If those are the only possible sources, you're fine.
A: Consider using:
const char up_string[] = "UP";
const char down_string[] = "DOWN";
char *direction;
direction = (value - price1 > - 0.005) ? up_string : down_string;
You could then have direction simply be a pointer to either of those locations (as opposed to using strcpy).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630684",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JavaScript OnClick returning error Object is not a function I have a function where when an element is clicked, it makes that element the selected element in a an Object. Let me show you.
var elem = new Object();
elem = {
title:'',//string
num:null,//number
selected:null
}
function selected(elem){
elem.title = elem.getAttribute("title") || this['title'];
alert(elem.title);
for(x=0;x<classIds.length;x++){
if(elem.title==classIds[x].name){
elem.num=x;
elem.selected=classIds[x];
alert(elem.selected.properties);
}
}
}
So when an element is clicked, the selected function runs from an onlick attr on the element. Which is cool. It works fine. But, if you click on it again, the browser gives the error Object is not a function. This only happens when you click on the same element consecutively. If you click on another element, it doesn't happen. Which is weird because the function should be running a seperate time and overwriting the Object elem (which is defined outside the function as a global variable/object). I have the alert for reasons of debugging. Also, the array classIds is defined out of the function as well. Any insight would be great. Also, I know my coding is a little odd, I am really just starting with Objects and Methods in JavaScript.
Edit
Onclick is called like this below
<li title="+classIds[x].name+" onclick='selected(this)'>"+classIds[x].name+"</li>
So...
onclick='selected(this)'
Is the the call
A: There's one really obvious problem in your code: you're declaring a global variable (outside your function) called elem, and then your function has a parameter also called elem. So every reference to elem within the function will be to the parameter not to the global. Given how you're calling the function the parameter refers to your <li> element so that means the function is currently overwriting and/or creating properties on that element.
If you change the name of the parameter, to say clickedElem then within the function you can use elem when you mean the global variable and clickedElem when you mean the parameter.
Beyond that I'm not quite sure what you're trying to achieve so I don't know what else to advise.
(And as an aside, as I said in a comment above, there's no point initialising elem = new Object() because on the next line you immediately assign it equal to something else. But that isn't going to cause you a problem, it's just pointless.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Scroll bar defaulted in the middle of a dialog box with long text Hello I use Jquery UI dialog box to put in some long text.
Once I open the dialog box, it shows like this in default (It should show the upper part of the dialog box):
I try to change the $('.ui-dialog').css("top", "0px");to push the scroll bar to the top, but it is not working. Is there anyway I can fix this?
Thanks!
A: Try this
$('.ui-dialog').scrollTop(0);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: msgrcv: Invalid argument Error I am getting an error that says:
msgrcv: Invalid argument
what could be causing this error? Here is my code
Bassically I'm passing a message from a parent to a child then I want to pass a message from the child to the parent and even though I'm using basically the same code for both, it isn't working for the second receive.
struct msg {
long int mtype; /* message type */
char mtext[1024]; /* message text */
} msg;
int len, msgflg = 0, msqid, *pint;
pid_t pid;
size_t msgsz = 40;
long int msgtyp;
msqid = msgget(IPC_PRIVATE,S_IRWXU);
char* charpid[250];
msg.mtype = 1;
if (msqid < 0) {
perror("msgget");
exit(1);
}
switch(pid=fork()) //fork child process
{
case 0: //Child process
//receive message from parent
if(msgrcv(msqid,&msg,sizeof msg.mtext, 1,IPC_NOWAIT)>=0){
printf("Serving for client pid #%s",msg.mtext);
asprintf(&charpid[0], "%ld\n", pid);
strncpy(msg.mtext,charpid[0], 1024);
if(msgsnd(msqid,&msg,strlen(msg.mtext),msgflg)<0){
perror("msgsnd");
}
}
else
perror("msgrcv");
msgctl(msqid, IPC_RMID, NULL);
exit(0);
case -1:
printf("fork failed");
exit(2);
break;
default:
//convert pid to string.
asprintf(&charpid[0], "%ld\n", pid);
//set mtext
strncpy(msg.mtext,charpid[0], 1024);
//send message
if(msgsnd(msqid,&msg,strlen(msg.mtext),msgflg)<0){
//report error
perror("msgsnd");
}
//wait for child process to die
wait(NULL);
//receive message from child
if(msgrcv(msqid,&msg,sizeof msg.mtext, msg.mtype,IPC_NOWAIT)>=0){
//print pid
printf("Received reply from pid #%s",msg.mtext);
}
else
//report error
perror("msgrcv");
exit(0);
}
A: The "Invalid argument" error is from your original process (not the forked child), and occurs when it tries to receive the reply from the child. The error occurs because the child has already removed the queue by then. Since your original process created the queue and waits for the child to exit anyway, it would make more sense to remove the queue there (after receiving the reply).
Even if you fix that, you may still find that when the child does its msgrcv it might not get anything, since your original process may not have sent it yet (and you specify IPC_NOWAIT). To get your code to work, with both receives, I had to move the msgctl call as noted above, and also add a sleep call before the msgrcv in the child.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Git warning of file overwriting due to (supposedly) untracked files Attempting to pull from git repo, but getting the following output. I think these files are tracked (As they should be), but its indicating that they are not. They are not in .gitignore. I am about 5-10 commits behind the branch.
git pull --rebase origin master
From github.com:user/Project
* branch master -> FETCH_HEAD
First, rewinding head to replay your work on top of it...
error: The following untracked working tree files would be overwritten by checkout:
mountdoom/protected/models/UserHelper.php
mountdoom/protected/models/UserRegistrationForm.php
mountdoom/protected/runtime/state.bin
mountdoom/protected/views/site/register.php
Please move or remove them before you can switch branches.
Aborting
could not detach HEAD
Any ideas how to resolve this?
A: They're tracked in the version you're checking out, but not in the version you had checked out previously. If you don't care about the untracked versions, just remove them.
If you do care about them, commit them before doing the rebase. You may then have to merge as part of the rebase process.
A: You can add the untracked files to the index (git add), git stash them, then do your git pull --rebase and then git stash pop and resolve conflicts if any.
A: If you simply want to delete the files like I do, you can run
rm `git merge 2>&1 | sed "s/^[^\t].*/ /g" `
(you might want to run it first with echo instead of rm to verify the results)
A: So it seems a scenario for this problem is when a file has been deleted and you still have a copy of it. For some reason, git fails to understand it.
None of these suggestions worked for me.
Finally I could fix it by git rm filename, git commit -m "temporary commit", then git pull --rebase.
At this point, git complained again and then I had to add the file to be tracked by git add filename, git commit -m "temporary commit2", then git pull --rebase.
Then everything went well. And I do not see my temporary commits as they cancel out each other.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630693",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Access chrome extension from a web app I wonder if anybody can lay out the general logic of what I should do to achieve the following:
I have an extension for Chrome, that gets a list of user's bookmarks.
When user visits web page, the information that was retrieved by extension is accessed and displayed on web page.
I already have an extension, I wonder how do I access it from a web page?
A: To communicate with a web page you need a content script that will load on that page. Then you can then use events to communicate. The content script can receive messages from your background page and forward them to the web page if necessary.
Make sure that you take the security considerations section to heart. You make user's bookmarks available to a web page, you should be very certain that this web page should have access to them.
A: So, if the author of the extension wrote the extension, and sandboxed his code (this means that he/she did something to keep his vars out of the global namespace), then there isn't much that you are going to be able to do. So... check to see if the author left his variables accessible at the global namespace level. To do this in Chrome, go to the page, open the Dev Tools, go to the console and type
console.log(window);
This will show you the global namespace, and should show you what you are looking for. If you see anything that doesn't look like a traditional variable or object or function, then that is something you should investigate. I wish I could give you clearer steps here, but you are essentially trying to hijack the code from the extension, and that kind of stuff takes a lot of testing/investigating.
If there isn't anything abnormal in the global namespace, then that means that the code is sandboxed, and you are in a tough spot. It will be tough for you to get any of the vars/values/objects from the extension code.
Good luck.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630696",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Getting a 3D object's orientation and aligning it parallel to a Vector3D in WPF I have a WPF project in which I have imported code that represents a 3D scene created in 3D Max Studio and then converted using a tool to XAML code that I can use in WPF.
So, I have a Viewport3D and inside it a GeometryModel3D object that represents a rectangular prism. I have two 3D points (X, Y, Z) that represent the beginning and the end of my vector.
What I would like to do is just align the prism parallel to my Vector3D along the prism's longest side. I know a few things about transformations and translations of 3D objects in code and I have some knowledge in math, my biggest problem is getting the orientation of a 3D object.
I would like somehow to be able to determine the up vector of the object because I think that it could help me, and what I would also like is to somehow be able to determine the coordinates of the base and the top of the prism, so I could calculate the prism's "direction" vector.
I've been on the web for a few days trying to figure this out but I'm really stuck, please, any help would be very much appreciated.
Thanks!
A: I do not know the code about the WPF actually. But I think it is a math problem.
You can construct the local matrix for a vector. That is, using the vector you want to align as Z vector, and find another vector(which is usually a vector parallel to your prism's bottom side) as X, after that do a cross product of Z,X, then you get the Y.
Finally the matrix is M=[X,Y,Z]. If you want affine matrix, get the position vector of prism, set it as T, then the matrix will be M=[X,Y,Z,T]
using this matrix, transform your prism's vertices: v=Mv
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery Routes Url JQuery Routes Plugin. http://routesjs.com/
sample url : ../support/overview
No problem
$.routes({
"/support/overview": function(){}
});
** In this way, the url does not work **
/support/overview/?id=1&cid=1
$.routes({
"/support/overview": function(){}
});
What am I doing wrong?
A: You're supposed to be submitting this url
/support/overview/?id=1&cid=1
like so:
/support/overview/1/1
and to write your route
"/support/overview": function(){}
like so:
"/support/overview/:id/:cid": function(){}
That should fix your problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: model-view-controller architecture best practices from scratch I need to understand the best practices of MVC architecture implementation. I'm a Java and C# programmer. I know the basic of MVC. But i'm sorta confused on how to implement it. I know how to make a simple MVC based calculator. But here's the thing.
I wanted to make a simple database editor application using MVC. Should I construct a model and controller for every rows (objects) of the table? If so, how about the view of every objects? How do i handle them being deleted, updated, and inserted. And should I make the model and controller for the editor which is also a view?
A: If you don't want to use the Java Persistence API, consider using a Class Literals as Runtime-Type Token in your TableModel.
A: At first, if you are comfortable with Java try the Spring MVC. There are a lot of tutorial regarding this. If you are much more confident in C# try ASP .NET MVC 3. I will prefer the later one as in this case you have to deal with less configuration.
Now I will answer your question one by one.
At first create a model for every table in your database. Actually these models (which are nothing but classes) when instantiated are nothing but an individual row of the respective table. Your ORM (object relational mapping) tool (For java you can use hibernate, for c#.net you can use entity framework) will provide you specific methods (save(object), add(object), delete(object)) for updating the database
Now each controller should work with a specific model (Here I am ignoring the complexities of using multiple models.). But it may generate numerous views. By clicking a link in your view page you actually invoke the related method in the controller. The controller than binds the Data (if any) with the specific view realted to that link and then the view is rendered. So for deleting a row there should be a method named delete() (you may name it anything you want, so dont be confused) in your controller. When you want to delete a row invoke that method and inside the method remove that row by using something like delete(object) (these methods will be provided by your ORM) and then return another view. The same thing is applied for adding and updating data. But each method may generate different views. Its upto you that which view you return in each of these methods.
I hope the answer helps you. Cheers !!!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Disable the toolbar from aquamacs in my init file I want to permanently disable the GUI toolbar (the little buttons for "New" "Open", etc.) from aquamacs in my .emacs file. I have seen suggestions that you disable it in the gui and the go to Options >> Appearance >> Adopt Face and Frame as Default and then set that to permanent, but that is not working for me. I was hoping for something I could add to my .emacs that will disable it.
A: Try putting the following in your ~/.emacs file:
(tool-bar-mode 0)
A: I am using Mavericks and creating ~/.emacs and put (tool-bar-mode 0) did not work. Instead, I just added the line in the ~/Library/Preference/Aquamacs Emacs/Preferences.el file, then it worked fine.
A: building on thomas' answer add
(set-tool-mode 0)
to ~/.emacs.d/init.el, creating the file as needed
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Regular expression replace but keep part of the string So, if I want to replace b[anything here] in a string with f[same thing here] how would I do that? Example:
What is a regular expression that would make foobarfoo to foofarfoo, and foobanfoo to foofanfoo?
A: The basic principle here is a "capture group":
String output = input.replaceAll("foob(..)foo", "foof$1foo");
Put the portion of interest inside parentheses in the regular expression. It can then be referenced by its group number in replacement text, or via the Matcher.group() method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Construct a Turing-Machine to decide ww^Rw w^R is the reverse of w and w is {0, 1}* . So the TM needs to decide a word followed by the reverse of this word followed by the word.
I don't want the answer, I just want a lead to start and to get on the right track.
A: Since some time has passed and the answer probably isn't needed anymore, I guess I'll propose a solution for the benefit of future students looking for an example of how one language can be recognized by a Turing machine.
Here's the idea. We'll take as the tape alphabet {0, 1, a, b, c, d} and make a single-tape singly-infinite tape Turing machine that recognizes w w^R w. The machine will work in five phases:
*
*Replace 0s and 1s in the prefix w w^R with a's and b's.
*See whether w w^R is a palindrome.
*Restore the tape to its pristine state.
*Replace 0s and 1s in the suffix w^R w with c's and d's.
*See whether w^R is a palindrome.
Note that this is simply one easy (for me to understand, that is) way to show that there exists a Turing machine to recognize this language. Naturally, showing that there exists an algorithm to solve this in any Turing-equivalent system of computation is just as good (it proves there exists a TM)... still, this outlines the construction of one such TM. Also note that there may be a simpler, more efficient or more intuitive TM to solve this problem... again, this is only one approach.
Step 1 will work as follows:
*
*Precondition: The tape begins with a blank, contains any string in (0+1)*, and is followed by an infinite string of blank squares.
*Postcondition: Halts if tape is empty or if length is not a multiple of 3; else, the tape begins with a blank, is followed by (a+b)^2n (c+d)^n, followed by an infinite string of blanks.
*
*Move to the right.
*If empty, halt accept. Otherwise, Scan to the right until you find an empty tape square, then move left.
*Change the tape to c if 0 or d if 1.
*Scan left until you find an empty tape square. Move right.
*If the tape is 0 or 1, change to a or b then move right. If the tape is c or d, halt reject.
*If the tape is 0 or 1, change to a or b then move right. If the tape is c or d, halt reject.
*If tape is c or d, scan to the beginning of the tape and go to Step 2. Otherwise, scan right until c or d, then move left.
*Change the tape to c if 0 or d if 1.
*Scan left until you find either a or b. Move right.
*Repeat starting at 4.
Step 2 will work as follows:
*
*Precondition: The tape begins with a blank, is followed by (a+b)^2n (c+d)^n, followed by an infinite string of blanks.
*Postcondition: Halts if the prefix (a+b)^2n isn't a palindrome; otherwise, leaves the tape in a state like D (c+d)^3n D*
*
*Move right.
*If tape is a (or b), move right. If tape is c or d, go to the beginning of the tape, then go to Step 3.
*If the tape is c, d or blank, halt reject. Otherwise, scan right until you find a c, d or blank. Move left.
*If the tape is a b (or a), halt reject. Otherwise, change this to a c (or d) and scan back to the left until you see a blank, a c or a d. Move right. Change a (or b) to c (or d). Move right.
*Repeat starting at step 2.
Step 3 will work as follows
*
*Precondition: Tape is D (c+d)^3n D*
*Postcondition: Tape is D (0+1)^3n D*
*
*Move right.
*If tape is c, write 0 and move right. If tape is d, write 1 and move right. If tape is blank, move to first blank space at the end of tape and go to step 4.
*Repeat step 2.
Step 4 and 5 work just like steps 1 and 2, except you work backwards (the tape now looks like D (c+d)^n (a+b)^2n D*, and you must check to see whether the (a+b)^2n part is a palindrome.
Any string passing both these tests must be of the form w w^R w where w is in (0+1)*.
A: As a hint, note that wwRw must have length 3n for some n (since each character appears exactly three times). You might therefore build a Turing machine that works by somehow counting the length of the string, using this to determine where the boundaries of the three strings are, and then checking that the three pieces all have the appropriate composition. If you can't count up a multiple of 3 characters, you could immediately reject.
Depending on what sort of TM is allowed, this might be easiest with a multitrack or multitape Turing machine so that you can mark up the letters with some extra information.
Hope this helps!
A: Here's how I did it with 2 tapes and O(n) complexity:
*
*make sure the length divides by 3 by scanning tape 1 while moving right on tape 2 every 3 steps in tape 1
*If you reached the end of tape 1 while the next step for tape 2 is to move right you the sufficient number of letters (divisible by 3)
*Mark the letter you reached on tape 2 (this is the end of the first thirds)
*Roll back to the beginning of both tapes
*Get to the second third by going over tape 2 till the mark and back
*confirm WWR: move both tapes till the end of tape 2 and then move tape 1 forward and tape 2 backwards. If they match you got WWR
*Check W at the beginning and the end: simply continue the scan on tape 1 while comparing to tape 2 from its beginning
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: linq expression error:cant display column name I am using LinqPad 4(nutshell database) and I am trying to display the (Customer) Name which is a column in the Customer table.
How can i display the Name in this query because now I am getting an error: does not contain a definition for 'Name'?
from p in Purchases
join c in Customers on p.CustomerID equals c.ID
group p by p.Date.Year into SalesPerYear
select new {
customername= SalesPerYear.First().Name,
customerid= SalesPerYear.First().CustomerID,
totalsales= SalesPerYear.Sum(x=>x.Price)
}
A: You've already grouped by CustomerID, therefore it is the grouping key. i.e. in your query, you should say: customerid = SalesByYear.Key. Not sure where the year comes from in your query.
A: Try this...
I assume you have a Purchase table with (Price, CustomerID and Date) columns..
from p in Purchases
group p by p.Date.Year into SalesByYear
select new {
customerid = SalesByYear.First().CustomerID,
year=SalesByYear.Key,
TotalVal = SalesByYear.Sum(g => g.Price)
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the difference between a primed cache and empty cache? What is the difference between a primed cache and empty cache?
For example the statistics result of YSlow provides a graphical data of an empty cached vs. primed cache. What are the difference between them?
A: This was asked 3 years before, but I bumped into this question my self since I had it to. So I did a small research on the internet and I found that :
Statistics is the third tab and provides a graphical representation of the number of HTTP requests made to the server and the total weight of the page in kilobytes for both Empty Cache and Primed Cache scenarios.
The Empty Cache scenario is when the browser makes the first request to the page and the Primed Cache scenario is when the browser has a cached version of the page. In a Primed Cache scenario, the components are already in the cache, so this will reduce the number of HTTP requests and thereby the weight of the page.
Keyword here is "scenarios". This does not mean that the graphs will change if you already have cached the page. I run the test two times even though I cached it and it always displays both graphs since it shows the "scenarios". So if I cached the page I am looking at the Primed Cache scenario but for my new visitors the Empty Cache.
So in the above example, when I request the page and it is cached, my browser will still make 3 requests with total weight of 86.6K
This page explains what actually yslow displays. http://www.devcurry.com/2010/07/understanding-yslow-firebug-extension.html
A: Simply, a primed cache means the browser has it cached. It has been there before, or (though I don't think YSlow means it this way) it has been somewhere that uses some of the same resources (images, CSS, JavaScript)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: issue with iframe height I know this topic has been asked about and answered multiple times but please believe that I have spend many hours searching for help and answers that work and/or I can actually understand.
It's the same ol' issue:
I have figured out how to add a custom tab and even a custom icon for it (and I am really happy to have been able to do even that!).
But, as per many other requests for help, it has the dreaded scroll bars.
I, like the others, want it to flow down past it's limited 800px size.
I have several different fixes for this, some I have tried unsuccessfully and some just go right over my head and I do not understand what is being written at all, where it goes and what needs to be edited in it.
I would really appreciate someone taking the time to walk me through the process and explaining the what's and how to's please.
View page here: http://www.bronts.com/bronts_facebook/index.html
View page within facebook here: http://www.facebook.com/pages/brontscom/191839754181703
A: You will need to use javascript sdk to autosize the iframe in a pagetab app. You will need to have an application id for this. Refer to https://developers.facebook.com/docs/reference/javascript/
the FB.Canvas.setAutoResize(); sets the height of the canvas.
here is working example on my app. http://www.facebook.com/apps/application.php?id=135669679827333&sk=app_135669679827333
NOTE: setAutoResize(); will be changing to setAutoGrow();
ALSO: you may need to reduce the width of your image, not sure until auto size is in place.
---------- i use this and add just below the < body > tags of my documents.
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'Your-App-Id-Here',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
//channelUrl : 'http://WWW.MYDOMAIN.COM/channel.html', // channel.html file
oauth : true // enable OAuth 2.0
});
/* sets auto size to app canvas and page tab app. */
FB.Canvas.setAutoResize();
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
A: Add overflow: hidden; to your body and use jQuery.ScrollTo to navigate inside iframe.
A: <script src="https://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript" charset="utf-8">
window.fbAsyncInit = function()
{
FB.init({ appId: '1375268019431848',
status: true,
cookie: true,
xfbml: true,
oauth: true});
FB.Canvas.setAutoGrow();
FB.Canvas.setAutoResize();
}
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: PHP: Export DB Table to CSV FILE I've got a custom table in WordPress and I'd like to be able to export the data in that table as a FILE in CSV (semi-colon seperated) format.
I've got the data coming out properly, but how do I then save it as an attachment?
Keep in mind that when using WordPress, headers have already been set... and I really don't know how to get around that.
A: I'm not sure exactly HOW you're doing what you're TRYING to do ...
... but this link gives you a simple, straightforward way to write the data as a .csv file you can do a "save as" from your browser:
http://wordpress.org/support/topic/export-wordpress-db-table-to-excel
A: For these plugins, they use database to store row & column details. You have to extract the data in MySQL database tables ( those table names are usually named after the plugin's name ) .
If you are still not sure how to do, you can just copy the table being displayed in page in browser, then paste in Excel. Last, save as CSV or XLS if you like.
A: you can use this code. just copy and past and you have it :)
https://gist.github.com/umairidrees/8952054#file-php-save-db-table-as-csv
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Facebook php Oauth is not working I'm new to facebook apps and php in general, and I have a bit of a problem. I cannot get OAuth to work correctly with my application. When you go the application itself, it does not redirect to the oAuth dialog. It merely displays a blank page that does nothing. If anyone can help me with this, I really need it haha. Thanks!
So far, my code is as follows:
<?php
include_once ('santatree/facebook.php');
$app_id = '276853929000834';
$application_secret = 'e3a12b11221f3fef1e06952e15fdc8e4';
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $application_secret,
'cookie' => true, // enable optional cookie support
));
?><?
if ($facebook->getSession())
{
$user = $facebook->getUser();
}
else
{
$loginUrl = "https://www.facebook.com/dialog/oauth? type=user_agent&display=page&client_id=276853929000834
&redirect_uri=http://apps.facebook.com/digitalsanta/&scope=user_photos";
header("Location: https://www.facebook.com/dialog/oauth? type=user_agent&display=page&client_id=276853929000834 &redirect_uri=http://apps.facebook.com/digitalsanta/ &scope=user_photos");
echo '';
}
A: I do my redirects based on the session token.
This assumes that you will be using the most recent php-sdk 3.1.1 and have Oauth2 enabled in your app settings.
SAMPLE HERE: login / out url is in footer of plugin. http://apps.facebook.com/anotherfeed/TimeLineFeed.php?ref=facebook-stackoverflow
<?php
require './src/facebook.php';
$facebook = new Facebook(array(
'appId' => '',
'secret' => '',
));
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);
$user = null;
}
}
if ($user) {
$logoutUrl = $facebook->getLogoutUrl();
} else {
$loginUrl = $facebook->getLoginUrl();
}
$access_token = $_SESSION['fb_135669679827333_access_token'];
if (!$access_token) {
echo '<script>';
echo 'top.location.href = "'.loginUrl.'";';
echo '</script>';
} else {
echo '<a href="'.logoutUrl.'">Logout</a>';
}
?>
https://developers.facebook.com/apps to edit your app.
*
*If you do not have an app you will need to create one.
*You will also need to set up the canvas and secure canvas urls to avoid errors.
A: You only defined the variable $loginUrl, but you haven't redirect user to go to the URL. Consider using
header("Location: $loginUrl");
to forward your user if you haven't sent your header yet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How would I get an error to display with this controller/model setup? I have a create method that calls a method in a model that pings some third-party APIs.
What I need to do is if the API sends back a certain message, then I'd display an error.
Below is my current controller and model setup, so how would I get the error back in to the controller (and ultimately the view)?
Here is the method in my controller:
def create
@number = Number.where(:tracking => params[:number][:tracking], :user_id => current_user.id).first
if @number.blank?
@number = Number.new
@number.tracking = params[:number][:tracking]
@number.user_id = current_user.id
@number.notes = params[:number][:notes]
@number.track
end
respond_with(@number) do |format|
format.html { redirect_to root_path }
end
end
Here are the methods in my model:
def track
create_events
end
def create_events(&block)
tracker = fedex.track(:tracking_number => number)
if tracker.valid?
self.assign_tracker(tracker)
tracker.events.each do |e|
self.create_event(e) unless (block_given? && !block.call(e))
end
save
else
# NEED TO THROW THE ERROR HERE
end
end
A: You should typically offload the the API calls to a background job and you could either use notifiers (or Rack middleware) to raise self-defined errors and handle them accordingly.
A: How about if rather than throwing errors, you just use validation? Something like the following (Just to get your started. This would need work.):
# if you don't cache the tracker in an attribute already, do this so
# you can add errors as if it were a column.
attr_accessor :tracker
def create_events(&block)
tracker = fedex.track(:tracking_number => number)
if tracker.valid?
# ...
else
# add the error with i18n
errors.add(:tracker, :error_type_if_you_know_it)
# or add it from a returned message
errors.add(:tracker, nil, :message => fedex.get_error())
end
end
Then in your controller:
@number.track
respond_with(@number) do |format|
if @number.errors.any?
format.html { redirect_to root_path }
else
format.html { render :some_template_with_errors }
end
end
Alternatively you could do this as part of validation (so calling valid? would work as expected and not destroy your custom "track" errors)
# do your tracking on creation, if number was given
validate :on => :create do
if number.present?
tracker = fedex.track(:tracking_number => number)
unless tracker.valid?
errors.add :tracker, nil, :message => tracker.get_error()
end
end
end
# then do your actual creation of tracking events sometime after validation
before_save :handle_tracker_assignment
def handle_tracker_assignment
self.assign_tracker(tracker)
# note the block method you're using would need to be reworked
# ...
end
Note in the latter case you'd have to change your logic a bit, and simply pass the tracking number and attempt to save a new record, which would trigger the tracking attempt.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I programmatically set the time zone in Java? I know I can feed VM arguments as follows
-Duser.timezone="Australia/Sydney"
Is there a programmatic way to do the equivalent? I would like the setting to be applied across the entire virtual machine.
A: java.util.TimeZone.setDefault() can be used to set a default time zone to be returned by getDefault().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: JOGL Texture problems I'm in the process of trying to learn JOGL bindings. The tutorials seem to be outdated, so I'm always trying to piece together what is valid from each one.
I'm having problems trying to apply a simple texture to a square plane.
I have an image that is 204 X 204 called box.png.
In my init() I do the following to get the texture loaded:
try {
InputStream stream = getClass().getResourceAsStream("box.png");
TextureData data = TextureIO.newTextureData(gl.getGLProfile(),
stream, 100, 200, false, "png");
boxTexture = TextureIO.newTexture(data);
} catch (IOException exc) {
exc.printStackTrace();
System.exit(1);
}
Then I try to apply my texture doing the following in my display():
gl.glEnable(GL.GL_TEXTURE_2D);
boxTexture.enable(gl);
boxTexture.bind(gl);
gl.glBegin(GL2.GL_QUADS);
// Front Face
gl.glTexCoord2f(0.0f, 0.0f);
gl.glVertex3f(-1.0f, -1.0f, 1.0f); // Bottom Left Of The Texture and Quad
gl.glTexCoord2f(1.0f, 0.0f);
gl.glVertex3f(1.0f, -1.0f, 1.0f); // Bottom Right Of The Texture and Quad
gl.glTexCoord2f(1.0f, 1.0f);
gl.glVertex3f(1.0f, 1.0f, 1.0f); // Top Right Of The Texture and Quad
gl.glTexCoord2f(0.0f, 1.0f);
gl.glVertex3f(-1.0f, 1.0f, 1.0f);
gl.glEnd();
Are there any blaring problems that would explain why I'm failing?
A: Only thing I can think of is that the texture isn't a power of 2. Change the size of the texture to 256x256 and see if it works then. Depending on your graphics card, it will or won't be supported (it should be if the card isn't ancient).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7630754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits