text
stringlengths 8
267k
| meta
dict |
---|---|
Q: JS: Splitting a long string into strings with char limit while avoiding splitting words I am trying to take a large block of text and split it into multiple strings that are 148 characters each, while avoiding cutting off words.
I have this now, which is splitting words:
var length = shortData.new.length;
if (length < 160){
outputString[0] = shortData.new;
document.write(outputString[0]);
}
if (length > 160 && length < 308){
outputString[0] = shortData.new.substring(0,148);
outputString[1] = shortData.new.substring(148,length);
document.write(outputString[0]+"(txt4more..)");
document.write(outputString[1]);
}
if (length > 308 && length < 468){
outputString[0] = shortData.new.substring(0,148);
outputString[1] = shortData.new.substring(148,308);
outputString[2] = shortData.new.substring(308,length);
document.write(outputString[0]+"(txt4more..)");
document.write(outputString[1]+"(txt4more..)");
document.write(outputString[2]);
}
if (length > 468 && length < 641){
outputString[0] = shortData.new.substring(0,148);
outputString[1] = shortData.new.substring(148,308);
outputString[2] = shortData.new.substring(308,468);
outputString[3] = shortData.new.substring(468,length);
document.write(outputString[0]+"(txt4more..)");
document.write(outputString[1]+"(txt4more..)");
document.write(outputString[2]+"(txt4more..)");
document.write(outputString[3]);
}
A: You are going to have to pad some of your strings, to make them have the number of characters you require.
var lines= s.match(/(.{1,147}\s)\s*/g);
A: You can use this function, just pass in your string and the length and it will return the array, like:
var outputString = splitter(shortData['new'], 148);
The function:
function splitter(str, l){
var strs = [];
while(str.length > l){
var pos = str.substring(0, l).lastIndexOf(' ');
pos = pos <= 0 ? l : pos;
strs.push(str.substring(0, pos));
var i = str.indexOf(' ', pos)+1;
if(i < pos || i > pos+l)
i = pos;
str = str.substring(i);
}
strs.push(str);
return strs;
}
Example usage:
splitter("This is a string with several characters.\
120 to be precise I want to split it into substrings of length twenty or less.", 20);
Outputs:
["This is a string","with several","characters. 120 to",
"be precise I want","to split it into","substrings of",
"length twenty or","less."]
A: You could use lastIndexOf() on a substr() of length 148 to find where to break the original string, remove that and loop while the length is > 148, like this:
var myText = "ad aenean adipiscing elit eget eleifend phasellus aenean lobortis vero venenatis ultricies eget iaculis ac neque nibh dignissim eleifend erat et in in justo sollicitudin mattis maecenas purus quis mi sed molestie integer magna non hendrerit nulla id neque augue suspendisse in in eget consectetuer et cubilia eu ullamcorper morbi elementum sed sed pharetra quam velit ante pellentesque eros nullam lobortis lorem fringilla libero elit nonummy purus sodales mauris sagittis praesent aenean in ut nullam ultricies quam aliquam arcu quisque semper lacinia lacinia sodales imperdiet ante venenatis suspendisse amet ante tellus nec nibh lorem in viverra magna cursus elit erat lobortis mattis purus pellentesque velit pellentesque dolor quam id mauris nibh pellentesque augue vel posuere aptent varius vivamus parturient hac ligula libero a varius sollicitudin sed dictumst morbi eros vestibulum donec purus turpis urna vel nisl quisque vulputate tristique non sed risus viverra varius tincidunt hendrerit ac dui mollis quam nunc suspendisse mattis volutpat vulputate integer ipsum cursus erat justo eu vestibulum sed blandit ac mi ligula montes sollicitudin vitae vel lacus imperdiet orci tincidunt sed imperdiet nunc vehicula pellentesque orci gravida diam non ut wisi sit et massa congue id scelerisque et mauris arcu nunc litora dignissim urna ea nullam magna felis duis pellentesque ultricies tincidunt vel pede fusce nunc sed interdum cursus wisi qui pulvinar wisi consectetuer fames sed hendrerit vitae velit viverra malesuada eu magna vehicula vivamus augue sagittis curabitur rutrum fringilla vivamus nisl enim eros elit vestibulum duis et duis erat sit auctor ac ipsum in et lacinia eu magna accumsan in nulla a sed massa maecenas ultricies duis dignissim sem augue id posuere lacus felis nisl quam ultricies urna dui curabitur morbi ante ut est eget tellus pulvinar mollis elementum tellus malesuada sollicitudin ligula fusce eget libero metus cras ligula felis nunc porttitor sit at";
var MAX_LENGTH = 148;
while (myText.length > MAX_LENGTH) {
var s = myText.substr(0, MAX_LENGTH);
var i = s.lastIndexOf(" ");
alert(myText.substr(0, i));
myText = myText.substr(i + 1, myText.length);
}
alert(myText);
A: Without thinking to much about it, I would do something like this, just not in pseudo code
if string length > 148
for i=148;i<string length;i+148
if character at i = space
add substring(i-148 to i) to output[]
else
add substring(i-148 to lastindoxof space) to output[]
set i to lastindoxof space + 1)
if i-148 != string length
add substring (i-148 to string length -1) to output[]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: C++ : how do I use type_traits to determine if a class is trivial? In C++0x, I would like to determine if a class is trivial/has standard layout so I can use memcpy(), memset(), etc...
How should I implement the code below, using type_traits, so I can confirm that a type is trivial?
template< typename T >
bool isTrivialType()
{
bool isTrivial = ???
return isTrivial;
}
NOTE: is_pod() is too restrictive: I would like my class to have trivial constructors, etc... ...for convenience.
Added: I think std::is_standard_layout<> may give me what I'm looking for.
1. If I add constructors, it still returns true
2. If I add a virtual method, it returns false
This is what I need to determine if I can use memcpy(), memset()
Edit: From Luc Danton's explanation and link below (clarification):
struct N { // neither trivial nor standard-layout
int i;
int j;
virtual ~N();
};
struct T { // trivial but not standard-layout
int i;
private:
int j;
};
struct SL { // standard-layout but not trivial
int i;
int j;
~SL();
};
struct POD { // both trivial and standard-layout
int i;
int j;
};
For memcpy() to be happy:
// N -> false
// T -> true
// SL -> ??? (if there are pointer members in destructor, we are in trouble)
// POD -> true
So it does look like is_trivial_class<> is correct: is_standard_layout<> is not necessarily right...
A: For std::memcpy it is sufficient that the type be trivially copyable. From n3290, 3.9 Types [basic.types] paragraph 2:
For any object (other than a base-class subobject) of trivially copyable type T, whether or not the object holds a valid value of type T, the underlying bytes (1.7) making up the object can be copied into an array of char or unsigned char.
Following paragraphs also describe other useful properties of trivially copyables types (i.e. not just copying to a char array).
std::is_trivially_copyable is the trait to detect just that. However as of my writing it's not implemented by e.g. GCC, so you may want to use std::is_trivial as a fallback (since in turn it requires a trivial copy constructor).
I really do not recommend using is_standard_layout, unless you really know what you're doing (e.g. language interoperability on one particular platform) it's not what you want. More information on what triviality and standard layout is about to perhaps help you specify the exact requirements you want.
A: The definition of POD in C++11 is:
A POD struct is a non-union class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types).
So unless you are violating the rules of standard layout or something of that nature, is_pod should be sufficient. And if you're breaking the rules of standard layout, then you can't use memcpy and memset and so forth.
So I don't know why you need this unless you trying to test triviality specifically.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Shrink-wrap / Shrink-to-fit a div to reflowed floated divs in css http://jsfiddle.net/zEcn3/12/
I'm trying to get a div content that resizes to the number of divs that fit in a line. So the example works fine when the window is bigger than all the item divs combined so they're all in a row, but when the window is resized smaller so one of the items is reflowed to the next row, the content div's width is 100% instead of shrink wrapped.
The reason I want this is so I can have centered content with a menu bar above the content that shrinks to the size of the combined reflowed content.
HTML:
<div class="wrapper">
<div class="content">
<div class="item">Hello.</div>
<div class="item">Hello.</div>
<div class="item">Hello.</div>
<div class="item">Hello.</div>
<div class="item">Hello.</div>
</div>
</div>
CSS:
.item {
float: left;
width: 70px;
border: 1px solid black;
}
.content {
display: inline-block;
border: 1px solid black;
}
.content:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
A: A friend figured it out for me, the answer is to use media queries.
@media (max-width: 1080px) {
#main {
max-width: 640px;
}
}
So I set at the intervals of the width of each item div, so when the viewing window is smaller than a certain number, it sets the width of the container to the next level down.
A: I'm not quite sure if you were trying to remove the 100% width on the container, or just have the container shrink along with the content, depending on the size of the screen.
The problem, as I see it, is that when I shrink the screen, the last "Hello" on the right side gets pushed down to the next row.
So what I did is set 100% width to the wrapper. I then just removed the fixed width from the items and changed it to % widths. In this case I took the number of boxes and divided them into 100%, which was 20% each (but with 1px border I reduced to 19% each). Also, I added display:block; margin-left:auto; margin-right:auto; to the id="content".
Here's the link to JS Fiddle: http://jsfiddle.net/rm2773/Lq7H7/
A: I found the answer here:
http://haslayout.net/css-tuts/CSS-Shrink-Wrap
It basically amounts to using display: inline-block; on the block element you want to shrink to fit its contents.
A: Try to use margin:auto to the container <div> and set a fixed position.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624718",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: What's the best way to create "vertical rules" in CSS, and where can I read more about it? I have a main content region in the center of my page which is 660px wide. I want to separate it into two 330px-wide divs. What's the best way to go about this? Should I be using px? Do you have any place that I can read more about a good approach or two?
A: put two divs inside of your center div, float one to the left and one to the right. Clear your floats (http://www.quirksmode.org/css/clearing.html) by adding 'overflow:hidden' to the container.
This will effectively split your column into two. You can specific the dimensions of the interior divs in px, or %, whichever you prefer.
Here is a working example: http://tinkerbin.com/MGjJBDS4
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: colorWithPatternImage creates black grids in iphone 4 I have
UIView *topPart = [[UIView alloc] initWithFrame:CGRectMake(9, 0, 302, 318)];
topPart.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"pattern.png"]];
[someScroller addSubview:topPart];
[topPart release];
and I can see the pattern fine when I use a 3gs or the iphone simulator, but when I tested on an actual iPhone 4, I see the pattern images but there are black lines separating each pattern so it looks like a grid. I checked the pattern image and there is no black border or anything .
There was someone with a different problem but it may be the same solution
colorWithPatternImage with iPhone 4 Retina Display ([email protected])
but they suggested using the -(void)drawRect: method, only problem is i have no idea how to do that.
Thanks
A: I was experiencing the same issue and found it was due to my png being greyscale (not RGB)
To check if this is the case, just select the image in Xcode, show the Utilities sidebar (the one that appears from the right) and look at the Color Space.
To fix this you can use your favourite image editor, but for photoshop do this:
Open the greyscale image
Select all and copy
Create a new document (but this time make sure the colour space is RGB)
Paste
Hope it helps :)
A: I figured it out by combining the answers from these 2 posts
https://devforums.apple.com/message/259150#259150
How can I use CGContextDrawTiledImage to tile an image?
UIImage *thePattern= [self GetFineTiles:[UIImage imageNamed:@"Feedbackpattern.png"]];
theView.backgroundColor = [UIColor colorWithPatternImage:thePattern];
-(UIImage*)GetFineTiles:(UIImage*)badImage{
UIGraphicsBeginImageContext(badImage.size);
CGContextRef imageContext = UIGraphicsGetCurrentContext();
CGContextDrawTiledImage(imageContext, (CGRect){CGPointZero,badImage.size}, badImage.CGImage);
UIImage *goodPattern = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return goodPattern;
}
Hope this helps others
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using AWS Elastic Beanstalk with a Java/BlazeDS/Spring application Is it possible to deploy my Spring/BlazeDS/Java application to elastic beanstalk? I'm using MyEclipse and built a Java Web Project with the required jar files etc. Do you need to specifically create an AWS Java Web Project - reason I ask is the options to include the BlazeDS files aren't there - so I'm wondering if Spring / BlazeDS is even supported? By default the turnkey blazeds runs through Port 8400 - so I imagine there are some additional tasks required to configure the endpoints to work through port 80?
Gracias!
A: Take a look at this example. Will be trying something similar over the next few weeks.
http://www.riaspace.com/tag/aws/
A: BlazeDS is not a standalone application, it consists from a bunch of jar files which should be added to your web application. You will also need to declare a servlet in the web.xml file. I wrote an article a couple of years ago how to add the blazeds jar files to a java web application (and what to configure), you can take a look here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I create an image filter in Symfony2 AvalancheImagineBundle? I'm using Symfony 2 and I just installed the AvalancheImagineBundle successfully. I created my own thumbnail filter as described in the README, and I created a 2nd filter called "profile" which (for the moment just to make sure it works) does the same thing as the thumbnail.
// app/config/config.yml
# Avalanche Imagine Configuration
avalanche_imagine:
web_root: %kernel.root_dir%/../web
cache_prefix: images/cache
driver: gd
filters:
my_thumb:
type: thumbnail
options: { size: [100, 100], mode: outbound }
profile:
type: thumbnail <-- HOW DO I DEFINE OTHER TYPES?
options: { size: [200, 200], mode: outbound }
However, I don't want profile to be a thumbnail. My Question: How do I define new "types" of filters?
Edit: I've seen the example that the README gives, but I can't understand how to write my own filter. I want to write a simple filter that takes a "width" parameter and scales the image down to have that width.
Update: I've been fiddling with these image filters for a while now, and I am still just as lost as before.... Could someone provide me with a hint in the right direction? I'm working on an open source project if it encourages anyone :)
A: It's funny to reply to your question here as I'm the creator and maintainer of Imagine :)
Basically, to add a filter to a bundle is a several step process
*
*Create filter loader - a class that implements Avalanche\Bundle\ImagineBundle\Imagine\Filter\Loader\LoaderInterface
*Register it in the Symfony DIC as a service and properly tag it
Here is how the default thumbnail filter loader is tagged
You can find it in the source of the bundle here - https://github.com/avalanche123/AvalancheImagineBundle/blob/master/Resources/config/imagine.xml#L100
*Finally, specify your filter in the yaml, use whatever value you specified in the "filter" attribute of your loader tag:
avalanche_imagine:
filters:
my_thumb:
type: <your filter name>
options: { #your options# }
Let me know if you run into any issues, additionally, feel free to create issues in the github repository of the bundle.
Cheers!
A: Did you read the "Load your Custom Filters" chapter in the README? It tells you how to configure your filter.
For an example implementation look at the ThumbnailFilterLoader class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Mongoid document persistence after find I having trouble persisting my documents in mongoid. I have the following code fragment in my controller:
params[:user][:residence_attributes][:locations_attributes].each do |num,location_attributes|
zipcode = Location.find(location_attributes[:id])
if !zipcode.update_attributes(location_attributes)
puts "fail"
fail = true
end
puts "zipcode again #{zipcode}"
puts "zipcode number #{zipcode.number}"
puts "zipcodes = #{Zipcode.count}"
zipcode = Zipcode.find(@user.residence.locations[0].id)
puts "zipcode again #{zipcode}"
puts "zipcode number #{zipcode.number}"
puts "zipcodes = #{Zipcode.count}"
zipcode = Zipcode.find(@user.residence.locations[0].id)
puts "zipcode again #{zipcode}"
puts "zipcode number #{zipcode.number}"
puts "zipcodes = #{Zipcode.count}"
end
And it yields the following output:
zipcode again #<Zipcode:0x000000063826a0>
zipcode number 11210
zipcodes = 1
zipcode again #<Zipcode:0x00000006348860>
zipcode number
zipcodes = 1
zipcode again #<Zipcode:0x00000006340ef8>
zipcode number
zipcodes = 1
So the question is why does the zipcode id change when I find the document the second and third time?
This is a problem because the document does not persist.
I have the following models:
class Zipcode < Location
include Mongoid::Document
attr_accessible :number
attr_accessor :number
validates_presence_of :number
validate :check_zipcode
end
class Location
include Mongoid::Document
attr_accessible :latitude, :longitude
belongs_to :locatable, polymorphic: true
end
class UserResidence
include Mongoid::Document
has_many :locations, as: :locatable
embedded_in :user, :inverse_of => :residence
attr_accessible :locations_attributes
accepts_nested_attributes_for :locations, autosave: true
#validates_presence_of :locations
#validates :locations, :length => {:minimum => 1}
end
Thanks
A: are you saving the document?
try to set autosave to true
see:
http://mongoid.org/docs/upgrading.html
(search on the page for autosave)
A: As per http://mongoid.org/docs/relations/nested_attributes.html you need to set autosave: true on has_many :locations.
has_many :locations, as: :locatable, autosave: true
accepts_nested_attributes_for :locations
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Unable to determine randomness vs code issue I'm unable to tell if there is something wrong with Random number generator in this case.
Random x = new Random();
do
{
a = x.Next(1, 200);
aa = x.Next(1, 200);
b = x.Next(a + 1, 200);
bb = x.Next(aa + 1, 200);
Console.WriteLine(a + " " + aa + " " + b + " " + bb);
} while (a != aa || b != bb);
I'm comparing when two pairs of random numbers are the same, when they are I want to know what those numbers are. For some reason they always end up being in range of 150 - 200. Which doesn't seem random enough to me.
Basically I'm trying simulate how long it would take until 2 number lottery is won.
Is this because Random class is not random enough or is there problem with the code?
A: There is nothing wrong with the randomness of the Random class, at least nothing that would affect your code.
Your way of picking lottery numbers is incorrect. The first number that you pick gets a correct distribution in itself, but then you pick another number to be higher than the first, which will favour higher numbers in the range.
Also, when the first number is high, it's more likely to guess the second number as there is a smaller variation. In your guesses you will see considerably more hits in the higher numbers.
Other than that it looks all right. Determining how often you could guess a number doesn't have any linear distribution. You would very seldom get a right guess very early, and you would very seldom go for very long without ever getting it right. It's normal that you see a concentration around a specific number of guesses.
A: Your code isn't doing what you think it's doing. First, neither a nor b will ever be 56, because the upper limit is exclusive. Second if a is 54, b will always be 55. So there's a 1 in 56 chance that a and b are 54 and 55 respectively, but there should only be a 1 in 3,136 chance of that.
Update: This answer applies to a previous version of the question. Once things stabilize, I'll update it with the answer to whatever the final question works out to be.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624738",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Heroku database backup strategy? I'm just setting up my backup strategy for Heroku and i'm after more information on what i need to protect against.
Obviously I need to ensure I back up to protect data loss through my own mistakes or malicious attacks etc but do I also need to protect against Heroku screwing up and losing/corrupting my data?
I.E. Can i rely on heroku to have sufficient redundancy for hardware failure etc or do i need to protect against this.
A: Heroku now provides an add-on to backup your database. It is called PG Backups.
From the add-on page:
Heroku's database backup solution. Captures and restores backups from the shared and/or dedicated PostgreSQL databases for an application. Imports data from an existing database backup, and exports backups for off-site storage.
You can keep manually 2 or 7 backups. You can also have daily automatic backups, with re-cycling, to keep for example the last 7 daily backups and the last 5 weekly backups.
A: There's never any harm in having more than one backup - I use a strategy similar to http://trevorturk.com/2010/04/14/automated-heroku-backups/ - to get a backup file to outside of Heroku (should I ever need it) but I have 100% confidence in Heroku to be honest but it's for my own sanity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: port only a single method of class to C? I have a class with few methods and I'm happy with the performance of all of them except one method. We want to port that to C++. However we don't want to spend too much time porting the whole class to C++, just that single method. Is this possible? How should I do it? Should it be in a blank class? Not in a class?
What I want is to try to use the C version and if failed (other OS, missing pyd), load the Python version.
Thank you.
A: Depending on the complexity of your code, you could look into using Weave, which is part of SciPy. It allows you to embed C/C++ code in your python module. There's a tutorial here.
Another option you could look at is Boost::Python, which may be a bit more complex to use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624740",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to set the logged in user ID on a session (CodeIgniter)? I am having trouble, getting the logged in user ID from the database...
This is my controller code :
function validation(){
$this->load->model('users_model');
$query = $this->users_model->validate();
if ($query){
$this->users_model->get_userID($this->input->post('email'));
$data = array(
'email' => $this->input->post('email'),
'is_logged_in' => true,
'user_id' => $user_id
);
$this->session->set_userdata($data);
redirect('home');
}
else {
$this->index();
}
}
This is my model function where I return the user id from the database:
function get_userID($email){
$this->db->where('email',$email);
$query = $this->db->get('users');
foreach ($query->result() as $row)
{
$user_id = $row->id;
}
return $user_id;
}
Everything works perfect, except that $user_id returns empty... What am I doing wrong?
A: Try:
$user_id= $this->users_model->get_userID($this->input->post('email'));
A: try modifying the model function to this -
function get_userID($email){
$this->db->where('email',$email);
$query = $this->db->get('users')->row_array(); // retrieves only first-row.
return $query['id'];
}
In controller the function needs just a bit of modification as follows -
function validation(){
$this->load->model('users_model');
$query = $this->users_model->validate();
if($query){
//$user_id was not assigned before :)
$user_id = $this->users_model->get_userID($this->input->post('email'));
$data = array(
'email' => $this->input->post('email'),
'is_logged_in' => true,
'user_id' => $user_id
);
$this->session->set_userdata($data);
redirect('home');
}
else {
$this->index();
}
}
hope it helps,
faisal ahmed
blog / site
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why are objects still created when I omit importing classes in actionscript? I'm working through a tutorial to create an mp3 player in actionscript. When I delete my first 4 lines of code, the .swf still works great! I thought you needed to declare what classes you're importing for every object you create later on.
import flash.events.MouseEvent;
import flash.media.Sound;
import flash.net.URLRequest;
import flash.media.SoundChannel;
//Objects and Variables
var myMusic:Sound= new Sound();
var soundFile:URLRequest = new URLRequest ("bobDylan.mp3");
var channel:SoundChannel = new SoundChannel();
//Listeners
btnPlay.addEventListener(MouseEvent.CLICK, playMusic);
btnStop.addEventListener(MouseEvent.CLICK, stopMusic);
function stopMusic(evt:MouseEvent):void{
channel.stop();
}
function playMusic(evt:MouseEvent):void
{
myMusic.load(soundFile);
channel = myMusic.play();
}
*
*Why are objects still created when I omit importing classes in
actionscript?
*Also... What other than "classes" can you "import". Or can
you only import classes?
A: It looks like you're working in the Flash IDE. If that is the case, then you can expect that it will be a good deal more forgiving than you would expect (or would like). Flash is probably importing the classes for you (check your publish settings and make sure they are on strict mode to force this issue). If it is, the objects being created are still the same objects you expect them to be, but don't trust it, fix the code.
The three things I've every imported are classes, functions (setTimeout, for example), and namespaces (mx_internal is used a lot in Flex).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624752",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Accessing the current position of UIView during animation I am trying to find the current position of an iPhone ImageView that is animating across the screen.
I create and animate the imageView like so
-(IBAction)button:(UIButton *)sender{
UIImageView *myImageView =[[UIImageView alloc] initWithImage:
[UIImage imageNamed:@"ball.png"]];
myImageView.frame = CGRectMake(0, self.view.frame.size.height/2, 40, 40);
[self.view addSubview:myImageView];
[myArray addObject:myImageView];
[UIView animateWithDuration:.5
delay:0
options:(UIViewAnimationOptionAllowUserInteraction) // | something here?)
animations:^{
myImageView.frame = CGRectOffset(myImageView.frame, 500, 0);
}
completion:^(BOOL finished){
[myArray removeObject:myImageView];
[myImageView removeFromSuperview];
[myImageView release];
}
];
}
then to detect the current CGPoint of the imageView I call this method every 60th of a second
-(void)findPoint{
for (UIImageView *projectile in bullets) {
label.text = [NSString stringWithFormat:@"%f", projectile.center.x];
label2.text = [NSString stringWithFormat:@"%f", projectile.center.y];
}
}
However this only gives me the point where the animation ends, I want to get the current CGPoint of the image that is animating across the screen. Is there an option that I need to apply other than UIViewAnimationOptionAllowUserInteraction to do this? If not, how do I get the current position of an animating imageView?
A: You can use the presentationLayer - a property of the CALayer that "provides a close approximation to the version of the layer that is currently being displayed". Just use it like this:
CGRect projectileFrame = [[projectile.layer presentationLayer] frame];
A: Swift 5:
Get temporary position and size (CGRect) during the animation with:
let currentFrame = projectileFrame.layer.presentation()!.frame
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624755",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: Dynamic Reports using SSRS Let me declare... I am a newbie at this filling in the spot temporarily at the moment.
Problem: Develop a application summary report using SSRS 2008( the completed product should be a RDL file, which can be deployed to the SSRS Server) for the online application completed by the applicant.
A little bit of background: The applicant fills in an online application using our web application, where he completes required and optional fields. The app summary report, is provided to the applicant filling out the application as a summary of his app and should display only the fields completed by the applicant.
Example:
Lest us say John Smith lives at
Add Line 1: 123 Any Street
Add Line 2: Null
City: Some City
State: Some State
And his spouse Jane Smith lives at
Add Line 1: 321 Any other Street
Add Line 2: Apt A
City: Some City
State: Some State
So in the report, the null field (Add Line 2) should not be displayed for john but displayed for Jane. When I say not displayed, meaning, the field label should be hidden the and report should adjust the spacing to not show a skipped blank line in the report.
We have about 1000 such fields that can or cannot be answered by the applicant. So the report should be generic and use as much of inbuilt functionality as possible.
If needed, an Xml containing key value pairs of fields and responses. this Xml can be made so that it can contain all fields and unanswered responses as null or only answered responses. i am not sure how this would help but putting it out there if needed.
I have done simple reports, but i have no idea on how to approach this situation. Any help will be great help.
Thanks.
A: I have had a similar situation and ended up using this approach within a textbox. Taking your example above, you would have this setup for your fields within the textbox, with the [ ] being fields from the dataset:
Name: [first_name] [m_name] [last_name]
Add Line 1: [address_1]
[expression]City: [city_name]
State: [state_name]
Zip: [zip_code]
Note that the expression and the City have no space between them. What happens is the city will be on its current line when [address_2] is null and move to the next line when there is an address line 2, using this expression:
=IIF(IsNothing(Fields!address_2.Value), "",
“Add Line 2: “ & Fields!address_2.Value & VbCrLF)
When the IFF is true and [address_2] is null the expression will write “” (Nothing) and [city_name] will remain on the same line. When the IFF is false and there is an [address_2] the label “Add Line 2” will be written along with the value of [address_2] and the [city_name] will be moved to the next line by “VbCrLf”. A more robust method that handles if [address-2] has a string of length 0 or a few spaces is this expression:
=IIF(IsNothing(Fields!address_2.Value) OR Len(Trim(Fields!address_2.Value)) < 1, "",
“Add Line 2: “ & Fields!address_2.Value & VbCrLF)
This stops the strange double space when a field is empty but not null; something similar woks great for middle names. Hopefully this is helpful to you or someone else reading this post.
A: This was really simple...
Lets say we have a report which is in a tabular format using rectangles and textboxes,
--------------------
|FIRST NAME : AAAA |
|LAST NAME : BBBB |
|PHONE: XXX-XXX-XXXX|
--------------------
Use the following expression to control visibility of the controls that you want to hide
=IsNothing(First(Fields!WorkPhoneNumber.Value, "DataSet1"))
Make sure all the controls are of the same height and width. I created a row with just 2 controls (the label text box and the value text box) and set their visibility using the value of the value text box as described in the expression above.
Since the row had just two controls the hiding the would auto adjust the layout as i desired.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I need to figure out multiple UIActionsSheets? I am trying to create multiple UIActions sheets with my view. I have read a few questions on here and browsed the internet, but nothing seems to get me a valid answer.
I have tried the "switch and case" method that looks like this....
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
switch (actionSheet.tag) {
case 10:
if(buttonIndex == 0)
{
and I have tried this method too...
UIActionSheet *actionSheet1;
UIActionSheet *actionSheet2;
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex: (NSInteger)buttonIndex{
if(actionSheet==actionSheet1)
{
The action sheet options work as individuals, so I know that the links and code is right, but I can't seem to get them both to work at the same time.
Let me know if I need to post more code.
Cheers Jeff
More Info:
-(IBAction)Action01:(id)sender {
UIActionSheet *actionSheet1 = [[UIActionSheet alloc] initWithTitle:@"Please Choose a Website:" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Facebook",@"Twitter",@"Google Maps",nil];
actionSheet1.tag = 10;
[actionSheet1 showInView:self.view];
}
and the second one is set up with tag = 11.O have also linked the buttons in Interface Builder with the same tag number.
In my heads file, I have defined my properties and IB Actions as well. Everything is done properly as it works if i use only one or the other of the action sheets and comment the rest out.
Here are the links to the files if it makes them easier:
Header file
Implementation file
Cheers Jeff
A: You mention in your updated post that you have set the tags in Interface Builder and in code. This is likely causing a conflict. You don't want those IB buttons to have the same tags as the action sheet, or strange thing will happen.
Change the tags in Interface Builder and that should solve your problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Disable Browser Input Field Effects? Okay, I'm trying to get rid of all these little things browsers do to input fields (like focus borders and what not).
input[type="text"] {
font:bold 10px/12px verdana,arial,serif;
padding: 20px;
border-radius: 15px;
}
input[type="text"]:focus {
outline: none!important;
}
The code above does not work. I also tried editing the input via the 2.1 way (
input.text { /*stuffhere*/};
input.text:focus{ outline: none; }
). It didn't work. Anybody have any ideas?
A: I'm at a loss; you seem to be doing it correctly. Border for the normally-visible border, and outline for the focusy thing.
Have a look at this fiddle and see if it's working as expected. If it does (as it does for me), it could be conflicting CSS in your case. !important is a dangerous and powerful tool, but it's still no guarantee.
http://jsfiddle.net/LQppm/1/
input[type="text"] {border: none}
input[type="text"]:focus {outline: none}
A: maybe outline: 0!important; will work?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Converting an OpenCV Image to Black and White How do you convert a grayscale OpenCV image to black and white? I see a similar question has already been asked, but I'm using OpenCV 2.3, and the proposed solution no longer seems to work.
I'm trying to convert a greyscale image to black and white, so that anything not absolutely black is white, and use this as a mask for surf.detect(), in order to ignore keypoints found on the edge of the black mask area.
The following Python gets me almost there, but the threshold value sent to Threshold() doesn't appear to have any effect. If I set it to 0 or 16 or 128 or 255, the result is the same, with all pixels with a value > 128 becoming white, and everything else becoming black.
What am I doing wrong?
import cv, cv2
fn = 'myfile.jpg'
im_gray = cv2.imread(fn, cv.CV_LOAD_IMAGE_GRAYSCALE)
im_gray_mat = cv.fromarray(im_gray)
im_bw = cv.CreateImage(cv.GetSize(im_gray_mat), cv.IPL_DEPTH_8U, 1);
im_bw_mat = cv.GetMat(im_bw)
threshold = 0 # 128#255# HAS NO EFFECT!?!?
cv.Threshold(im_gray_mat, im_bw_mat, threshold, 255, cv.CV_THRESH_BINARY | cv.CV_THRESH_OTSU);
cv2.imshow('', np.asarray(im_bw_mat))
cv2.waitKey()
A: Approach 1
While converting a gray scale image to a binary image, we usually use cv2.threshold() and set a threshold value manually. Sometimes to get a decent result we opt for Otsu's binarization.
I have a small hack I came across while reading some blog posts.
*
*Convert your color (RGB) image to gray scale.
*Obtain the median of the gray scale image.
*Choose a threshold value either 33% above the median
Why 33%?
This is because 33% works for most of the images/data-set.
You can also work out the same approach by replacing median with the mean.
Approach 2
Another approach would be to take an x number of standard deviations (std) from the mean, either on the positive or negative side; and set a threshold. So it could be one of the following:
*
*th1 = mean - (x * std)
*th2 = mean + (x * std)
Note: Before applying threshold it is advisable to enhance the contrast of the gray scale image locally (See CLAHE).
A: Simply you can write the following code snippet to convert an OpenCV image into a grey scale image
import cv2
image = cv2.imread('image.jpg',0)
cv2.imshow('grey scale image',image)
Observe that the image.jpg and the code must be saved in same folder.
Note that:
*
*('image.jpg') gives a RGB image
*('image.jpg',0) gives Grey Scale Image.
A: Step-by-step answer similar to the one you refer to, using the new cv2 Python bindings:
1. Read a grayscale image
import cv2
im_gray = cv2.imread('grayscale_image.png', cv2.IMREAD_GRAYSCALE)
2. Convert grayscale image to binary
(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
which determines the threshold automatically from the image using Otsu's method, or if you already know the threshold you can use:
thresh = 127
im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]
3. Save to disk
cv2.imwrite('bw_image.png', im_bw)
A: Specifying CV_THRESH_OTSU causes the threshold value to be ignored. From the documentation:
Also, the special value THRESH_OTSU may be combined with one of the above values. In this case, the function determines the optimal threshold value using the Otsu’s algorithm and uses it instead of the specified thresh . The function returns the computed threshold value. Currently, the Otsu’s method is implemented only for 8-bit images.
This code reads frames from the camera and performs the binary threshold at the value 20.
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
using namespace cv;
int main(int argc, const char * argv[]) {
VideoCapture cap;
if(argc > 1)
cap.open(string(argv[1]));
else
cap.open(0);
Mat frame;
namedWindow("video", 1);
for(;;) {
cap >> frame;
if(!frame.data)
break;
cvtColor(frame, frame, CV_BGR2GRAY);
threshold(frame, frame, 20, 255, THRESH_BINARY);
imshow("video", frame);
if(waitKey(30) >= 0)
break;
}
return 0;
}
A: For those doing video I cobbled the following based on @tsh :
import cv2 as cv
import numpy as np
def nothing(x):pass
cap = cv.VideoCapture(0)
cv.namedWindow('videoUI', cv.WINDOW_NORMAL)
cv.createTrackbar('T','videoUI',0,255,nothing)
while(True):
ret, frame = cap.read()
vid_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
thresh = cv.getTrackbarPos('T','videoUI');
vid_bw = cv.threshold(vid_gray, thresh, 255, cv.THRESH_BINARY)[1]
cv.imshow('videoUI',cv.flip(vid_bw,1))
if cv.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv.destroyAllWindows()
Results in:
A: Pay attention, if you use cv.CV_THRESH_BINARY means every pixel greater than threshold becomes the maxValue (in your case 255), otherwise the value is 0. Obviously if your threshold is 0 everything becomes white (maxValue = 255) and if the value is 255 everything becomes black (i.e. 0).
If you don't want to work out a threshold, you can use the Otsu's method. But this algorithm only works with 8bit images in the implementation of OpenCV. If your image is 8bit use the algorithm like this:
cv.Threshold(im_gray_mat, im_bw_mat, threshold, 255, cv.CV_THRESH_BINARY | cv.CV_THRESH_OTSU);
No matter the value of threshold if you have a 8bit image.
A: Here's a two line code I found online that might be helpful for a beginner
# Absolute value of the 32/64
abs_image_in32_64 = np.absolute(image_in32_64)
image_8U = np.uint8(abs_image_in32_64)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "80"
} |
Q: Represent drop down menu of QPushButton with Qt Style Sheet? I'm wondering which is a proper way for representing the menu dropped down from a QPushButton ?
QPushButton::drop-down { blabla }
doesn't work
A: In QT Style Sheets, you can style widgets that are members of other widgets like so:
QPushButton QMenu
{
/* blahblah */
}
Where QPushButton is the parent widget, and QMenu is the child. It also works for other stylable items and pseudo-states, for example
QPushButton QMenu::separator
{
height: 1px;
border-bottom: 1px solid lightGray;
background: #5A5A5A;
margin-left: 2px;
margin-right: 0px;
margin-top: 2px;
margin-bottom: 2px;
}
A: When you set the menu for a QPushButton using setMenu(), the menu continues to exist as its own entity so you would target the QMenu object itself with an appropriate selector. A QMenu supports the box model. Some example styling can be found here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Getting n smallest numbers in a sequence What would be the most efficient way to take n smallest numbers from a sequence,
[ [1 2 3] [9 2 1] [2 3 4] [5 6 7] ]
I would like to take 2 smallest from the sequence based on the first item,
[1 2 3] [2 3 4]
currently I am sorting the whole list then taking first n items but that probably is not the most efficient way to go, it is a big list and I need to do this frequently.
A: As referenced, you can use the median-of-medians algorithm to select the kth smallest element in linear time, and then partition in linear time. This will provide you with the k smallest elements in O(n). The elements will however be unsorted, so if you want the k smallest elements sorted it will cost you another O(klogk).
A few important notes:
*
*Firstly, although the complexity is O(n) small constants are not guaranteed and you might find minimal improvement, especially if your n is reasonably small. There are random linear selection algorithms that run in better actual times (usually the expected running time is O(n) with worse worst-cases but they have smaller constants than the deterministic ones).
*Why can't you maintain the array in a sorted fashion? That would probably be much more performant. You would simply need to insert each element in the correct place which costs O(logn), but finding the k smallest would then be O(1) (or O(k) if you have to build the array afresh).
*If you decide against the above note, then an alternative is to keep the array sorted after every such procedure, provide insert in O(1) to the end of the array and then execute a "merge sort" every time you need to find the k smallest elements. I.e. you sort only the new ones and then merge them in in linear time. So that would cost O(mlogm + n) where m is the number of elements added since last sort.
A: The Joy of Clojure, Chapter 6.4 describes a lazy sorting algorithm.The beauty of lazy sorting is that it will only do as much work as necessary to find the first x values. So if x << n this algorithm is O(n). Here is a modified version of that algorithm.
(defn sort-parts
[work f]
(lazy-seq
(loop [[part & parts] work]
(if-let [[pivot & xs] (seq part)]
(let [psmaller? (partial f pivot)]
(recur (list* (filter psmaller? xs)
pivot
(remove psmaller? xs)
parts)))
(when-let [[x & parts] parts]
(cons x
(sort-parts parts f)))))))
(defn qsort [xs f] (sort-parts (list xs) f))
(defn cmp [[a _ _] [b _ _]] (> a b))
(def a [[1 2 3] [9 2 1] [2 3 4] [5 6 7]])
(take 2 (qsort a cmp))
A: If n is small, you can create a second list of size n that you keep sorted, so you always have quick access to the largest in that list;
iterate through the big list checking if each is less than the largest in the small list;
if so, insert it into the small list... the small list is full, pop off the prior oldest.
If n is less than 3 or 4, you can just brute force it. If n can be larger, you'll want to do a binary search to find the insertion point for each. If n can be very large, then a different mechanism may be in order.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: 2 Dimentional array dereferencing ,how to evaluate through pointers a[2][3] = {{-3,14,5},{1,-10,8}}
*(a[j]+k)
*(a[j+k-2])
(*(a+j))[k])
(*(a+k-1))[j]
*((*(a+j))+k))
(**(a+j)+k)
*(&a[0][0]+j+k)
when i printf these i get
Output:
8
1
8
-10
8
3
1
respectively
Please if anyone can explain in detail how the values are coming ,i am a new starter please pardon me for bad formatting here and also bothering you for with so much work :)
A: I assume j == 1 and k == 2:
*(a[j]+k) == *(a[1]+2) :
a[1] = {1, -10, 8};
So a[1]+2 is a pointer to 8, and *(a[1]+2) == 8
*(a[j+k-2]) == *(a[1+2-2]) == *(a[1]):
a[1] = {1, -10, 8}
Since *a[1] is the value of the first element in a[1], the expression evaluates to 1
(*(a+j))[k] == (*(a+1))[2]:
a+1 is a pointer to the second element in a, so *(a+1) == a[1] = {1, -10, 8}
a[1][2] == 8
(*(a+k-1))[j] == (*(a+2-1))[1] == (*(a+1))[1]:
*(a+1) == a[1] (see the last answer)
a[1][1] == -10
*((*(a+j))+k) == *((*(a+1))+2):
*(a+1) == a[1], so the expressions is equivalent to *(a[1]+2)
*(a[1]+2) is equivalent to a[1][2] for the same reasoning as above, which is 8
(**(a+j)+k) == (**(a+1)+2):
*(a+1) = a[1]
**(a+1) = a[1][0] == 1
Adding 2 to that gives 3
*(&a[0][0]+j+k) == *(&a[0][0]+1+2) == *(&a[0][0]+3):
&a[0][0] == a[0]
*(a[0]+3) == a[0][3];
This last one is returning 1, because it is extending in memory past the end of a[0] into a[1], and you're getting a[1][0]. I think this behavior is actually undefined though. It depends on whether the C standard guarantees that an initialized 2D array will be allocated sequentially in memory or not, and could result in a Segmentation fault or worse.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624773",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Haskell Map for Trees My tree is defined by
data Tree a = Leaf a | Node (Tree a) (Tree a)
deriving (Show)
I also declare a testing tree.
myTree = Node (Node (Leaf 1) (Leaf 2)) (Leaf 3)
What I want to do is create a function maptree f which will act on Leaf. To be more specifically, f x = x +1,
then maptree f myTree will return
Node (Node (Leaf 2) (Leaf 3)) (Leaf 4)
My solution is
maptree f (Leaf a)= Leaf (f a)
maptree f (Node xl xr ) = Node (maptree xl) (maptree xr)
but it will return the following error
Couldn't match expected type `Tree a'
against inferred type `Tree t -> Tree t'
Probable cause: `maptree' is applied to too few arguments
In the first argument of `Node', namely `(maptree xl)'
In the expression: Node (maptree xl) (maptree xr)
Failed, modules loaded: none.
However, if I do
maptree (Leaf a)= Leaf ( a + 1)
maptree (Node xl xr ) = Node (maptree xl) (maptree xr)
it does work out.
I can not see the difference between the first function and the second one. How do I get error? Thanks.
A: The error message basically tells you what's wrong: you are not passing maptree enough arguments. The definition maptree f (Node xl xr) says that maptree takes two arguments, a function and a tree. But when you call it like maptree xl, you're only giving it one argument (a tree).
In your second version, you've defined maptree to only take one argument (a tree), which is why it doesn't produce that error.
You can fix your problem by, for example, calling maptree f xl instead of maptree xl.
A: One dumb way to not forget to pass along the function as you recurse deeper (for this sort of higher-order function) is to use a helper:
maptree f (Leaf a) = Leaf (f a)
maptree f (Node xl xr) = Node (go xl) (go xr)
where go = maptree f
Or, alternatively (and perhaps more commonly):
maptree f tree = go tree -- or eta reduce: maptree f = go
where go (Leaf a) = Leaf (f a)
go (Node xl xr) = Node (go xl) (go xr)
In the first example, I use go sort of as a macro for maptree f. In the second example, I take advantage of the fact that maptree's input f is in scope inside the go function because go is declared in a where clause of maptree.
A: You are missing the function on the recursive maptree calls:
maptree f (Leaf a)= Leaf (f a)
maptree f (Node xl xr ) = Node (maptree xl) (maptree xr)
should be
maptree f (Leaf a)= Leaf (f a)
maptree f (Node xl xr ) = Node (maptree f xl) (maptree f xr)
A: Note that this is the obvious fmap of a Functor instance for your Tree type. You can therefore use the DeriveFunctor extension to have GHC generate it for you.
{-# LANGUAGE DeriveFunctor #-}
data Tree a = Leaf a | Node (Tree a) (Tree a)
deriving (Functor, Show)
Let's try it.
*Main> fmap (+1) (Node (Node (Leaf 1) (Leaf 2)) (Leaf 3))
Node (Node (Leaf 2) (Leaf 3)) (Leaf 4)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: how can I limit input to 5 lines in a UITextView on iPad? I have a UITextView in which the user enters lines of text. After the entry of the text I take a screen capture. Problem is, if you enter more than visible lines in textView, you can't screen capture all the text. I tried disabling scrolling, but that makes it worse because text entry from keyboard makes the textview scroll into non-visible area and there's no way for the user to scroll text down again. Thanks in advance for your help.
A: UITextView is also a ScrollView, so you can use it's contentSize property to only allow text input if the text fits the textView like this:
-(BOOL) textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
// Only allow text input if the size of the content is smaller than the size of the textView
return (textView.contentSize.height < textView.bounds.size.height);
}
You will also need to disable the scrolling like you did, to make the UI look good.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Returning multiple data items from a function in C or C++ I am confused on a couple homework questions I have...
Can you return multiple data items from a function by using return()? Can a function only return one value, unless it is a pointer to an array?
I believe that the answer is that a function can return multiple data items by returning a structure. Then, returning a pointer to an array is not the only way - if that is a way?
But there seems to be a lot of discussion on this topic and so I want to make sure I have at least the basic idea correct: You can return multiple data items using a structure but using pointer (I don't understand this) will use memory more efficiently. Is this correct?
A: With C++0x/C++11 you can use this:
#include <string>
#include <iostream>
#include <tuple>
using namespace std;
tuple<int, unsigned, string, int> getValues()
{
return tuple<int, unsigned, string, int>(1, 2, "3", 4);
}
int main()
{
int a;
unsigned b;
string c;
int d;
tie(a, b, c, d) = getValues();
cout << a << ", " << b << ", " << c << ", " << d << endl;
return 0;
}
Compile it with
g++ tuple_test.cpp -std=c++0x -o tuple_test
And and if you run the programm it will output this:
1, 2, 3, 4
But it's better to use references like this (i would say):
void getValues(int& a, unsigned& b, string& c, int& d)
{
a = 1;
b = 2;
c = "3";
d = 4;
}
int main()
{
...
getValues(a, b, c, d)
...
}
Uch thats what I get for not reading the question carefully...
Can a function only return one value, unless it is a pointer to an array?
Yeah you only can return 1 single value, but this single value can include multiply values (struct, class, array).
You can return multiple data items using a structure but using pointer (I don't understand this) will use memory more efficiently. Is this correct?
True. But when you use pointers it depends on how you use it.
When you dynamic allocate it each function call it wont be very efficient and you would need to deallocate the memory manually after usage. When you use a global-array/struct it will be efficient. But can give you problems when you call the function multiply times.
A: In addition to what is already said in this thread, in C++11 you can return structures initialized using uniform initialization:
struct XYZ {
int x;
int y;
int z;
};
XYZ foo() {
return {1, 2, 3};
}
Personally I prefer returning structures with named members rather than tuples because the latter doesn't provide names for its members.
A: That is correct.
You can however "return" multiple items, by adding parameters that are passed by reference, then writing the multiple results to them.
A: A function can indeed only return one 'thing' with its return statement. That thing can, however, be a pointer (C & C++ arrays are simply pointers in disguise), a reference (a pointer which can't be reseated or array-indexed) or an object, which may encapsulate multiple things.
If you return a structure, you're passing back the entire structure. If you return a pointer or reference, you are returning only the address of the structure - so you had better not return a reference or pointer to a structure that goes out of scope when the function returns! Doing so invokes undefined behavior, which most likely (but not always) is a segmentation fault.
A: If you want a bigger picture about this read about passing parameters by value and passing by reference it also applies for returning parameters.
As you mentioned:
You can return multiple data items using a structure but using pointer (I don't understand this) will use memory more efficiently. Is this correct?
Lets say you have some structure:
struct BigStructure{
int array[1000];
double otherData[1000];
//... etc
};
and some method:
BigStructure workWhenCopying(BigStructure bigStruct){
// some work with a structure
return bigStruct;
}
This method illustrates the case when you pass parameters to the method and return it by value, which means that each time you call this method you are copying the method's argument into another place in memory. This copying takes time and when you have bigger structures it slows down your program run time thus it is more efficient to pass big structures by reference.
void workWithReference(BigStructure & bigStruct){
// do some work
}
In this case you are not copying whole data structure, just passing the address of the memory where this structure resides. You also don't need a return statement since changes to that structure object will be visible outside this method. But if you will reassign bigStruct to a new memory location it will be visible only within local method: workWithReference
I hope it's more clearer now;)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Node.js Whiteboard App for Team / Educational Collaboration I'm looking to build/adapt a shared whiteboard app for team and educational collaboration. Draw on a board, write some text, save picture, clear board, etc. We've already got a simple chat system setup with node.js and socket.io so probably want to stay on that route.
*
*What open source apps exist that might be pluggable / adaptable for this use?
*What node.js / javascript / html5 technologies might be useful for this task?
A: As far as node.js technologies you would need the following
*
*express to handle your http server
*socket.io to handle communication
As far as rendering on the client I would recommend
*
*rapheal as an SVG rendering
Apart from that you need some kind of database, Redis, mongoDB & CouchDB are popular.
Apart from that just write it. Any other libraries you think you might need along the way can be found on the npm registry
However I can offer some package.json examples for my chat and my blog to give some inspiration as to what libraries are useful
A: Another open source whiteboard in Node.js is here
https://github.com/Imaginea/matisse
website: http://www.thematisse.org
A: Open Source Whiteboard in NodeJs
https://github.com/opinsys/walma
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Replacing list of li in a div with another list of li in the same div How do I replace a list of li in a div with another list of li in the same div? I tried this:
$("#divList").empty();
$('#divList').append('<li>' + textValue + '</li>');
I want to clear out all data that was originally in the div and replace data using the same div at the same margin-left and margin-top as first list of li.
In my code, the div is emptied, but the li is not appended.
A: Grab the new lists html and then replace it : http://jsfiddle.net/bikerabhinav/V6g8d/
//Assuming the new li items fall under ul#list-new
var list_new = $('#list_new').html();
//Now replace the old one
$('#list-old').empty().append(list_new);
A: $('#divList').html('').append('<li>'+textValue+'</li>');
Guestimate. Also, you do realise that this will just append 1 li, right?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: What is the git equivalent of of hg outgoing (hg out) or hg incoming (hg in)?
Possible Duplicate:
How can I see incoming commits in git?
What is the git equivalent of of "hg outgoing" or "hg incoming"?
In Mercurial, hg outgoing lists the changesets that are newer than what's on the server and will be sent if I were to do hg push. Same in reverse for hg incoming and hg pull.
A: If you want to list commits that are on branch B but not on branch A, do git log A..B.
If you want to list commits that are on your local branch dev, but not the the remote branch origin/dev, do:
git fetch origin # Update origin/dev if needed
git log origin/dev..dev
If you want to list commits that are on the remote branch, but not on the local branch, simply do the converse:
git fetch origin # Update origin/dev if needed
git log dev..origin/dev
Note: you might find it easier to compare branches graphically using gitk origin origin/dev
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624790",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "97"
} |
Q: MySQL Update only certain fields in a table I have some insurance information in a website, and I'd like to only edit certain fields the user wants to change like for example:
user, id, phone, address, city
and the user wants to change his city and phone...do i have to make a query for each specific case or is there a code that can help me retrieve the key(phone) and value (9397171602)??
to then send it in a query
A: Basic update would take the form of:
UPDATE table_name SET column_1 = value_1, column_2 = value_2 WHERE column_3 = value_3
Where col1, col2 would be your city and phone, and col3 would be the user id. Check out the MySQL website http://dev.mysql.com/doc/refman/5.0/en/update.html for more info
A: Just add some sql to it:
$sql = "UPDATE example SET col_1 = val_1, col_9 = val_9 WHERE col_7 = val_7";
mysql_query($sql);
Then replace the columns and values with you stuff. For further info: PHP MySql Update
A: There are number of ways to update a record safely. Conside the following pseudo code + php program.
class Example
{
function UpdateRecord($editedRecord)
{
//Fetch existing record from the database
$originalRecord=DB::fetchExample($editedRecord->getId())
//validate each edited field and it is valid then assign its value
//to the originalRecord's field
if(IsValid($editedRecord->getName())
{
$originalRecord->setName($editedRecord->getName());
}
.....
//update the record.
$originalRecord->Update();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Does having Rails logging enabled on a production environment a performance hit? I hope this question isn't too vague, but does logging in a production environment cause a hit in performance? In addition to the traditional production.log logging, we have a couple of additional things we record in begin/rescue type events to help us for debugging issues.
In our production.rb file, our settings are:
config.log_level = :info
config.active_support.deprecation = :log
And we also have some:
TRACKER_LOG.warn xml_response_hash
These files can become quite large (1 or 2 GB each) and our website receives a couple million page views a month. Chould minimizing our use of logs on production help with performance?
A: Logging does impact on performance, but it can still be useful in production if it allows the people running the service to diagnose problems without taking the service down.
That said, a couple of million hits a month is less than 100k per day (on average) and that shouldn't be too much of a worry. Similarly, a few GB of log files should not be a worry provided the service is deployed sanely — and provided you're using a log rotation strategy of course — since disk space is pretty cheap. Thus at current levels, I'd suggest you should be OK. Keep an eye on it though; if traffic suddenly spikes (e.g., to 1M hits in a normal day) you could have problems. Document this! You don't want the production people to be surprised by these sorts of things.
Consider making the extra logging conditional on a flag that you can disable or enable at runtime so that you only collect anything large if you're looking for it; with usual volumes of logging data there's a good chance that you'll only look for problems occasionally anyway.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624814",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adding Outlook Object Library to Excel 2011 for Mac I am trying to move a VBA macro code from Excel 2003 to Excel 2011.
The macro requires sending an Email from Outlook. However, when I went to Tool > References to add the Outlook Object Library, it does not show up in the List box.
How do I go about adding the reference in so i can access Outlook?
A: As of my knowledge Office Automation in the MAC world is somehow limited. Please see this discussion. Also this one in a Microsoft Forum..
A: You can add reference by using Browse option.
You just need to add reference to the file "MSOUTL.OLB"
In my system I have it in "C:\Program Files\Microsoft Office\Office12\MSOUTL.OLB" , In your system it could be in different folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: route index for a resource What is the equivalent index path for resources :topics if I were to write it out manually?
When I run rake routes with the resources line in the routes.rb file it shows.
GET /topics(.:format) {:action=>"index", :controller=>"topics"}
I have tried a few things with no success, for example:
get 'topics/index' #=> 'topics#index'
A: as the route says:
get "/topics" => "topics#index", :as => :topics
you can now use topics_path or topics_url
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624823",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails Formtastic: adding "data-" field to option tag I have:
form.input :duration, as: select, collection: {}
I need:
<option value="" data-price="XXX"></option>
Rails does not support HTML5 data attributes for the option tag. Formtastic suggests to create a helper method for this.
Formtastic readme describes how to extend input tags. However, in select_input.rb I can't find any method which would affect the option tag. So, how do I do this?
Also, I found enhanced_select gem which does exactly what I need, but I am not able to make it work with formtastic.
A: Assuming you have a model called Items, you can actually do this in formtastic like so:
form.select :duration,
collection: Items.map{|item| [item.name, item.id, {"data-price" => item.price}]}
Essentially what you are doing is passing an array of arrays where the final value in each array is a hash.
E.g.
[
['Item 1', 1, {"data-price" => '$100'}],
['Item 2', 2, {"data-price" => '$200'}]
]
Rails 3+ (perhaps 2.x - I didn't confirm) will use the hash in such as array and simply add it to the html of the option tag. Giving you the following:
<option data-price="$100" value="1">Item 1</option>
<option data-price="$200" value="2">Item 2</option>
A: Actually rails does support adding any kind of html tag to options. Usually you would have:
options_for_select( [['First', 1], ['Second', 2]] )
which would give you
<option value="1">First</option>
<option value="2">Second</option>
If you add a hash into the arrays for each option the hash keys/values will be added as HTML attribute to the option, e.g.
options_for_select( [['First', 1, {:'data-price' => 20}],
['Second', 2, {:'data-price' => 30}]] )
will produce the required tags:
<option value="1" data-price="20">First</option>
<option value="2" data-price="30">Second</option>
A: options_for_select([
['Item 1', 1, data:{price: 121, delivery: 11}],
['Item 2', 2, data:{price: 122, delivery: 22}]
])
Produces
<option data-delivery="11" data-price="121" value="1">Item 1</option>
<option data-delivery="22" data-price="122" value="2">Item 2</option>
Advantage
Using data:{...} is more concise and if using multiple data tags can save code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Deploying Android Hello world on DELL XCD35 i have created a successfully hello world program with an image in it. and here is how it looks on windows 7
I have now connected to my DELL XCD to the computer, ensured that "USB Debugging" is ticked and also made sure that "Settings > Applications and enable Unknown sources" is ticked
I have followed all the steps given here - in android documentation
But the following steps fail:
You can verify that your device is connected by executing adb devices
from your SDK platform-tools/ directory. If connected, you'll see the
device name listed as a "device."
Here no device is displayed in command prompt.
If using Eclipse, run or debug your application as usual. You will be
presented with a Device Chooser dialog that lists the available
emulator(s) and connected device(s). Select the device upon which you
want to install and run the application.
And this doesn't happen
I have the following packages installed currently
So how to deploy my simple hello world program on my phone now?
A:
After exhaustive search i found out that the USB driver required for
my DELL XCD35 was available in the form of a .exe file on my mobile's
original Micro SD memory card. The shocker was that there was no
direct download available from DELL's website for the same. So if you
loose this file, or have exchanged the Micro SD card for a better
version then you are in trouble as you wont get it from DELL also.
So folks, i have uploaded the same file for those who want it. - Dell Phone Android USB Connector Device Driver
PS: I spent so much time on this silly matter that i had to let others know of this and wrote an article for the same, so that others don't make the same mistake lol.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iOS App Portrait and Landscape Views I'm trying to make and iOS app with both portrait and landscape views, but if I open it and change the orientation to Landscape, some buttons got offscreen, after going to IB and reordering the buttons, in Portrait they go off screen.
After googling, I dont have ANY ideia how to 'change' views according to orientation.
Could you guys give me some help?
Ah, also, Apple Support Documents seems pretty useless to me :P
Thanks!
A: There a method - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{}
which is useful in such cases.
A: You should change autosizing properties in IB (they're in the same place where frame size is) or change autoresizingMask properties of your inner views and controls programmatically. This controls what happens to the elements of your screen after it gets resized (for example when the screen is rotating). You can glue your components to left or right or both, top or bottom or both and similar. Play with it, it's pretty powerful and you don't need any code for that if what they can do is enough.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Resizing images according to the Screen Size on Android I am making a graphic intensive application for Android.
The problem i am facing is that on my home screen there are 6 images that are placed on a FrameLayout. Since i own a HTC Desire, I placed the images such that they look great on 3.7in but when i test it on a 5 or a 7in display, the UI goes crazy and there are huge gaps amongst the tiny images which were nice on 3.7in.
How do I fix my app for all screen sizes?
How do I scale the images such that there are no gaps?
please help ....
A: Look out this Supporting Multiple Screens in Android Developers from where you will get the exact answer. You have to create different images and put them in the respected folder's according to the densities.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: "call 0x80482f0 "? Just need clarification of one line of code in a 'hello world' program in x86 assembly "call 0x80482f0 <puts@plt>"? Just need help with one line of code in a 'hello world' program in x86 assembly.
NOTE: i'm running ubuntu linux while programming/debugging this, using gcc as the compiler and gdb for the debugger.
I am reading Hacking: The art of Exploitation V2 and I compiled this C program:
1 #include <stdio.h>
2
3 int main()
4 {
5 int i;
6 for(i=0; i<10; i++)
7 {
8 printf("Hello, world\n");
9 }
10 return 0;
into this program in assembly:
0x080483b4 <+0>: push ebp
0x080483b5 <+1>: mov ebp,esp
0x080483b7 <+3>: and esp,0xfffffff0
0x080483ba <+6>: sub esp,0x20
0x080483bd <+9>: mov DWORD PTR [esp+0x1c],0x0
0x080483c5 <+17>: jmp 0x80483d8 <main+36>
0x080483c7 <+19>: mov DWORD PTR [esp],0x80484b0
0x080483ce <+26>: call 0x80482f0 <puts@plt>
=> 0x080483d3 <+31>: add DWORD PTR [esp+0x1c],0x1
0x080483d8 <+36>: cmp DWORD PTR [esp+0x1c],0x9
0x080483dd <+41>: jle 0x80483c7 <main+19>
0x080483df <+43>: mov eax,0x0
0x080483e4 <+48>: leave
0x080483e5 <+49>: ret
now.. i understand every portion of this program, until it gets to:
0x080483ce <+26>: call 0x80482f0 <puts@plt>
what i do not understand is.. if "Hello, world\n" is stored at 0x80484b0, and that address is then stored into the address at ESP, why does the:
0x080483ce <+26>: call 0x80482f0 <puts@plt>
refer to 0x80482f0, instead of [esp] or just "0x80484b0" to print "Hello, world\n" to the screen? i used gdb and i cannot figure out what exactly is being referenced with 0x80482f0.. any help would be great
thanks (and remember, im just starting out with this stuff, so im a noob)
also.. i copy and pasted the disassembled main function from gdb for convenience, if you need any more info, just ask. and if you would like to explain that one command for me, that would be great as well because i've only used "int 80h"'s for printing stuff to the screen before
A: 0x80482f0 is the address of the puts function. To be more precise, it points to the entry for puts() in the program linker table (PLT) - basically just a bunch of JMP <some routine in a so-library>s (it's a little more complex than that, but that's not important for this discussion). The puts function looks for its argument on the stack - ie, at [esp].
You may be wondering where that puts() call came from - the compiler here was smart enough to see that you didn't actually use any format string parameters in your call to printf(), and replaced that call with a call to the (somewhat faster) puts(). If you'll look closely, you'll see that it also removed the newline from your string, because puts() appends a newline after printing the string it is given.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624836",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: WP7 - How can I display a menu when holding down my finger on a ListBoxItem Almost everywhere in Windows Phone (for instance in the People hub), when you hold down your finger anywhere, a context-menu-ish menu pops up that says "Refresh".
How can I recreate this menu in my own application? I don't even know what to call it.
A: You can achieve this by using the toolkit's (August 2011) ContextMenu.
xmlns:toolkit="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone.Controls.Toolkit"
<ListBoxItem>
<toolkit:ContextMenuService.ContextMenu>
<toolkit:ContextMenu>
<toolkit:MenuItem Header="something" Command="{Binding SomeCommand}" />
<toolkit:MenuItem Header="something else" Command="{Binding SomeOtherCommand}" />
</toolkit:ContextMenu>
</toolkit:ContextMenuService.ContextMenu>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: python: is it possible to require that arguments to the functions are all keyword? To avoid the obvious bugs, I'd like to prevent the use of positional arguments with some functions. Is there any way to achieve that?
A: You could define a decorator that, using introspection, causes an error if the function that it decorates uses any positional arguments. This allows you to prevent the use of positional arguments with some functions, while allowing you to define those functions as you wish.
As an example:
def kwargs_only(f):
def new_f(**kwargs):
return f(**kwargs)
return new_f
To use it:
@kwargs_only
def abc(a, b, c): return a + b + c
You cannot use it thus (type error):
abc(1,2,3)
You can use it thus:
abc(a=1,b=2,c=3)
A more robust solution would use the decorator module.
Disclaimer: late night answers are not guaranteed!
A: Only Python 3 can do it properly (and you used the python3 tag, so it's fine):
def function(*, x, y, z):
print(x,y,z)
using **kwargs will let the user input any argument unless you check later. Also, it will hide the real arguments names from introspection.
**kwargs is not the answer for this problem.
Testing the program:
>>> function(1,2,3)
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
function(1,2,3)
TypeError: function() takes exactly 0 positional arguments (3 given)
>>> function(x=1, y=2, z=3)
1 2 3
A: Yes, just use the **kwargs construct and only read your parameters from there.
def my_function(**kwargs):
for key, value in kwargs.iteritems():
print ("%s = %s" % (key, value))
my_function(a="test", b="string")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: How to clear all data in MIMEBase (email module) so i have this code:
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
import os
def sendMail(to, subject, text, files=[],server="smtp.gmail.com:587"):
assert type(to)==list
assert type(files)==list
fro = "[email protected]>"
msg = MIMEMultipart()
msg['From'] = fro
msg['To'] = COMMASPACE.join(to)
msg['Date'] = formatdate(localtime=True)
msg['Subject'] = subject
msg.attach( MIMEText(text) )
a=0
username = '[email protected]'
password = 'pass'
# The actual mail send
smtp = smtplib.SMTP(server)
smtp.starttls()
smtp.login(username,password)
for file in files:
a+=1
print a
part = MIMEBase('application', "octet-stream")
part.set_payload( open(file,"rb").read() )
Encoders.encode_base64(part)
part.add_header('Content-Disposition', 'attachment; filename="%s"'
% os.path.basename(file))
msg.attach(part)
if a==21:
smtp.sendmail(fro, to, msg.as_string() )
a=0
print 'sent'
smtp.quit()
sendMail(
["[email protected]"],
"hello","cheers",
["Thousands of one megabyte files"]
in this code it sends 21 files at a time to avoid going over the limit of gmail messages. But the probleme is that the data in MIMEBase stays... my question is is there a way to delete all data in the MIMEBase? Im sorry that the indentation is wrong
A: It looks like your problem is that you:
*
*Create a msg.
*Append 21 files to msg.
*Send it.
*Append 21 more files, so that it has 42 files now attached.
*Send it again; this second message is twice as large as the first.
*Append 21 more files, bringing the total to 63.
*Send it again; it's getting pretty huge now.
*And so forth.
When a==21 you should start over with a fresh msg object instead of continuing to append more and more files to the old one.
Alternately, you could try removing the 21 attachments already there before attaching the new ones; but just starting over might be simpler, since you already have the code in place to start a new message with the right headers — it just needs refactoring into a little “start a new message” function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: quicksort implementation Following code for quicksort does not work and I can't understand what is reason.
#include <iostream>
using namespace std;
void exch(int a[],int i,int j){
int s=a[i];
a[i]=a[j];
a[j]=s;
}
int partition(int a[],int l,int h);
void quick(int a[],int l,int h){
if (h<=l) return ;
int j=partition(a,l,h);
quick(a,l,j-1);
quick(a,j+1,h);
}
int partition(int a[],int l,int h){
int i=l-1;
int j=h;
int v=a[l];
while(true){
while( a[++i]<v);
while(a[--j]>v) if (j==i) break;
if (i>=j) break;
exch(a,i,j);
}
exch(a,i,h);
return i;
}
int main(){
int a[]={12,43,13,5,8,10,11,9,20,17};
int n=sizeof(a)/sizeof(int);
quick(a,0,n-1);
for (int i=0;i<n;i++){
cout<<a[i]<<" ";
}
return 0;
}
It outputs
5 8 9 11 10 17 12 20 13 43
A: In your partition method, that should be
int v = a[h];
and not
int v = a[l];
[Update: I've just tested the code with that change, and it works correctly, outputting:
5 8 9 10 11 12 13 17 20 43
A: Here is a clearer implementation of the partition step:
def quicksort(arr, low, high):
if low > high or low == high:
return
pivot = randint(low, high)
updated_pivot = partition(pivot,arr, low, high)
quicksort(arr, low, updated_pivot-1)
quicksort(arr, updated_pivot+1, high)
def partition(pivot, arr, low, high):
arr[low], arr[pivot] = arr[pivot], arr[low] #now pivot is at 'low' index of current subarray
start_of_ = 1
curr = 1
while curr <= high:
if arr[curr] <= arr[low]:
arr[start], arr[curr] = arr[curr], arr[start] #making sure all values between index low and index start (exclusive) are less than or equal to the pivot.
start+=1
curr += 1
new_pivot_location = start - 1 #the value at index start is the first value greater than the pivot (the range considered in the while loop is exclusive)
arr[new_pivot_location], arr[low] =arr[low], arr[new_pivot_location]
return new_pivot_location
EXAMPLE RUN:
Input:
[5,1,3,8, 0,2]
|
pivot
Partition algorithm:
[3,1,5,8,0,2] --> after switching pivot's position
|
pivot
start
|
[3,1,5,8,0,2] --> initializing start and curr
|
curr
start
|
[3,1,5,8,0,2] --> 1 < 3, so we swap 1 & 1, and start++, curr++
|
curr
start
|
[3,1,5,8,0,2] --> 5 > 3, so we don't swap. Don't move start, curr++
|
curr
start
|
[3,1,5,8,0,2] --> 8 > 3, so we don't swap. Don't move start, curr++
|
curr
start
|
[3,1,0,8,5,2] --> 0 < 3, so we swap 5 and 0. start++, curr++
|
curr
start
|
[3,1,0,2,5,8] --> 2 < 3, so we swap 8 and 2. start++, curr++
|
curr
[2,1,0,3,5,8] --> swap 2 and 3, and reset pivot index.
Output:
[2,1,0,3,5,8]
|
pivot
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Why is my Linq statement being executed twice? I am working on an internal message system. I have the mvc mini profiler hooked up, and it is showing me some statements are executed twice, and I can't figure out why,
My controller is as simple as you can get:
var db = MessagingDataContext.Get();
return db.Posts.OrderByDescending(p => p.DatePosted).Skip(pagenumber * pagesize).Take(pagesize);
and my view is just as simple (my _Layout page has the rest of the markup):
@foreach (var post in Model)
{
<div class="post">
<p>
@Html.ActionLink(post.Title, "View", "Posts", new { postid = post.Id}) by @post.User.Name
</p>
</div>
}
So why would get_User be executed twice?
A: My guess is because the @post.User.Name part is executing for each record. Did the original query return 2 results?
Best way to fix this is in the original query do a select to get all the info you want (Title, ID and Username).
A: The query is fetching the username for each user. The parameter @p0 is the user ID. If you check the value of it, you will most likely find that it is different for each query.
A: The Linq statement is not being executed twice. The first query is from the Linq statement, and I am guessing the 2nd and 3rd queries are from your @foreach loop.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: PHP parse error on database search result return I'm trying to get data out of a mysql db and I have the login info saved in another file. The username is getting sent from my form to the page with the code and i'm getting a
Parse error: syntax error, unexpected '[', expecting ',' or ';' in C:\xampp\htdocs\waladmin\ipfinder.php on line 31.
I don't understand why its saying that though, everything looks fine.
Here's my PHP:
<?php
testinclude('db_login.php');
$con = mysql_connect($db_host,$db_username,$db_password);
//$con = mysql_connect('10.241.10.40','waladmin','waladmin');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
$db_select=mysql_select_db($db_database);
if(!db_select)
{
die("Could not select the database. <br />".mysql_error());
}
$select = ' Select ';
$column = ' IP_Address,Workstation,Username ';
$from = ' FROM ';
$tables = ' admintable ';
$where = ' where Username = " & ControlChars.Quote & Username & Username & ControlChars.Quote & "ORDER BY admintable.Time_Stamp DESC';
$query = $select.$column.$from.$tables.$where;
$result = mysql_query($query);
if(!result)
{
die("Could not query the database: <br />".mysql_error());
}
while($result_row = mysql_fetch_row(($result))){
echo 'Username: ' . result_row[2] . ' <br /> ';
echo 'Workstation: ' . result_row[2] . ' <br /> ';
echo 'IP Address: ' . result_row[1] . ' <br /> ';
}
echo $con;
mysql_close($con)
echo $con;
?>
A: change all the result_row[1/2] to $result_row[1/2]
A: You are missing the $ in front of several references to $result_row. Since PHP sees constants, the [ is unexpected.
A: You have problem in last while loop...you missed $ sign and you also missed semicolumn too...
replace this code with respectives..
while($result_row = mysql_fetch_row(($result))){
echo 'Username: ' . $result_row[2] . ' <br /> ';
echo 'Workstation: ' . $result_row[2] . ' <br /> ';
echo 'IP Address: ' . $result_row[1] . ' <br /> ';
}
echo $con;
mysql_close($con);
echo $con;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: javascript innerHTML is not overridden document.form1.field1.innerHTML="hi1"; works in onload() function.
but the same doesnt work if it is placed in some onclick() function/ some other function. If placed in onclick function, document.form1.field1.innerHTML="hi1"; is not overridden.
what we suppose to do in order to work?
A: *
*in plain JS please use .value instead of .innerHTML for form fields
*if you use an onclick handler of a link or a submit button you need to return false
Assuming
a) a form named form1
b) inline event handlers for sake of clarity (Purist can close their eyes for a second, ok?), this would work
<a href="#" onclick="document.form1.field1.value='value from link'; return false">Set value from link</a>
and so would this:
<input type="button" onclick="document.form1.field1.value='value from button'" value="Set value from button" />
<input type="checkbox" id="chk1"
onclick="document.form1.field1.value=this.checked?this.value:''" value="value from button" /><label for="chk1">Set value from checkbox</label>
No need for return false on a button or check/radiobox
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Binding Derived DataTable to SQL-made DataTable to Fill Datagrid I am at a loss and have searched everywhere to figure out how to do this in a way I understand but still no luck. I am trying to show the time the client has free and what is scheduled on a day-to-day basis. Their schedule is kept on a server and displays their busy time. I pulled that data using a sql query and dropped that into a datatable called dtSched. I then created another datatable called dtTime to list the time from 6:00 AM - 10:00 PM by 15 minute increments. What I am now trying to do is combine both datatables to display all the time listed in dtTime and display where the client has time scheduled so I can show empty rows to allow appointments to be added and display scheduled time so appointments are not added in that time slot.
Here is my code to create the dtTime table (all time):
Dim strStartDate As DateTime
Dim strEndDate As DateTime
strStartDate = DateValue(Now()) & " 6:00 AM"
strEndDate = DateValue(Now()) & " 10:00 PM"
While strStartDate <= strEndDate
strStartDate = strStartDate.AddMinutes(15)
Dim dr As System.Data.DataRow = dt.NewRow()
dr("Time") = strStartDate
dt.Rows.Add(dr)
End While
Here is my sql-derived datatable dtSched (scheduled time):
Dim conn = New SqlConnection("Connection")
Dim strSQL As String
strSQL = "SELECT * FROM MYTABLE WHERE SCHED DATE = 'Date'"
Me.dataAdapter = New SqlDataAdapter(strSQL, conn)
Dim commandBuilder As New SqlCommandBuilder(Me.dataAdapter)
Dim dtSched As New DataTable()
dtSched.Locale = System.Globalization.CultureInfo.InvariantCulture
Me.dataAdapter.Fill(dtSched)
I was trying to use a GetData execution to tie the two datatables but it did not work:
Me.dataGrid.DataSource = Me.BindingSource1
GetData("SELECT dt.Time, dtSched.Date, dtSched.ID, dtSched.Client, dtSched.StartTime, dtSched.Reason FROM dt LEFT JOIN dtSched ON dt.Time = dtSched.StartTime")
I am trying to connect both datatables by dt.Time and dtSched.StartTime. Then fill the datagrid. Any assistance anyone can provide would be downright awesome!
Thanks!
A: Never mind, I figured it out! Yea!
In case anyone has the same problem, I took my two datatables and did a merge using the following code:
Dim pk1(0) As DataColumn
Dim pk2(0) As DataColumn
pk1(0) = dtTime.Columns("Time")
dtTime.PrimaryKey = pk1
pk2(0) = dtSched.Columns("Time")
dtSched.PrimaryKey = pk2
dtTime.Merge(tblSched, False, MissingSchemaAction.Ignore)
Me.BindingSource1.DataSource = dtTime
I added the column names to my dtTime table that were in the dtSched table before merging and then boud dtTime to my datagrid and it was a wrap! I also added a third data table to the mix and it worked like a glove. What a relief!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624851",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to let child widget process QKeyEvent? I'm using a QTabWidget as centralWidget in a QMainWindow , however , keyPressEvent() won't trigger in any child widget of QTabWidget , if i try the following in that QMainWindow::keyPressEvent() , it will crash.
void Window::keyPressEvent(QKeyEvent *e) {
QApplication::sendEvent( centralWidget->currentWidget() , e );
}
Window is an instance of QMainWindow.
What's the correct way to let child handle those events , instead of parent widgets ?
A: If the child widget is designed to receive and handle key press events, then it will receive them if it has keyboard focus. If it is a custom or subclassed widget then you will need to do a few other things besides just overriding the child widget's keyPressEvent() as described here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Accessing Parameters from the Main Data Source from A Secondary Dataset I've got a chart that uses a secondary dataset. It allows for the use of the fields and parameters of the second dataset, however I'm not able to use the parameters set in the main report dataset. Does anyone have any clue how to access the values of the parameters?
For example
I have the following parameters in the main dataset:
valueOne
valueTwo
And a secondary data set:
fieldOne, fieldTwo
From the chart that is set to use the second dataset, how would I request parameter: "valueOne"?
A: Add a parameter to your subDataset that has the exact same name as the parameter in the main dataset. Leave the default value expression blank and do not prompt for a value. When you reference the parameter in the subdataset, the value from the main dataset will be returned.
So in your case monksy, you should add an empty parameter named "valueOne" to your second dataset.
I've never seen this behaviour documented anywhere; I found it out by accident when working on a report.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624864",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: regex special char? Is there a character that does the same thing as the asterix mark in unix (*).. that is, ignore everything after that letter ? (Including special characters)
For example, i want to match the following with just one regex expression
http://example.com/blah
http://example.com/blah/blah
http://example.com/blah?blah/blah
Sorry, couldn't find this somewhere but i have a feeling it must be something elementary.
A: You can use .* (a dot followed by a star). Dot means "match (almost) any character". Star means "zero or more times". It does not ignore anything, it matches anything. You could try this regular expression:
^http://abc\.com/blah.*$
Or perhaps just this (depending on how you are using it):
^http://abc\.com/blah
Note that it will also match http://abc.com/blahblah and will fail to match http://abc.com/./blah. If this is a problem, you might want to consider using a URL parsing library instead.
A: Yep, that would be ".*" -- the dot matches anything, and the asterisk means as many as you want.
So, in your example:
http://abc[.]com/blah.*
You need the [.] in brackets so that it will match just the actual literal "dot".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why Grails war file gets corrupted sometimes We are using grails 1.3.4, we have 2 physical servers running separate load balanced tomcats. At times when I deploy war file on these tomcats one of the server starts giving strange errors, to fix I have to clean the ROOT context where war is exploded and restart tomcat again it works or starts giving some other error.
Currently I was getting this error and clearing context and restarting again fixed the issue
groovy.lang.MissingMethodException: No signature of method: static com.coollabs.cooldeals.Address.save() is applicable for argument types: () values: []
Any clue whats wrong ?
A: Are you hot deploying the war? If so, it may be related to this: Tomcat Hot Deploy not working
i.e., edit your context.xml and add either antiJARLocking=true or antiResourceLocking=true. The Tomcat Docs suggest against setting both to true:
antiJARLocking is a subset of antiResourceLocking and therefore, to prevent duplicate work and possible issues, only one of these attributes should be set to true at any one time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Issue with refinerycms I18n Translation Default Frontend Locale Im working with RefineryCMS to upload a blog. Every works fine, but when i change the "I18n Translation Default Frontend Locale (Refinery) - en" to "es" (spanish) only somethings changes in the blog engine, but others desapear.
I want to know where and how i can make the changes to translate the rest of the options and this dont desapear.
A: https://github.com/resolve/refinerycms-blog/blob/master/config/locales/es.yml is the locale file which should be updated to match english version ( https://github.com/resolve/refinerycms-blog/blob/master/config/locales/en.yml ). You can add missing translations in your config/locales/es.yml file preserving the structure from files above.
If you could send us a pull request with your changes it would awesome. Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ACTION_BATTERY_CHANGED firing like crazy Okay, so I'm working on an AppWidget that checks the battery level and displays it on a TextView. My code looks like this:
public class BattWidget extends AppWidgetProvider {
private RemoteViews views = new RemoteViews("com.nickavv.cleanwidgets", R.layout.battlayout);
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int appWidgetIds[]) {
final int N = appWidgetIds.length;
context.getApplicationContext().registerReceiver(this,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
appWidgetManager.updateAppWidget(appWidgetId, views);
}
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Log.d("onReceive", "Received intent " + intent);
if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {
Integer level = intent.getIntExtra("level", -1);
views.setTextViewText(R.id.batteryText, level+"%");
AppWidgetManager myAWM = AppWidgetManager.getInstance(context);
ComponentName cn = new ComponentName(context, AirWidget.class);
onUpdate(context, myAWM, myAWM.getAppWidgetIds(cn));
}
}
}
And I'm getting concerned because as soon as I drop the widget onto my homescreen it begins firing off about 100 of those Log calls a second, saying it's receiving ACTION_BATTERY_CHANGED. Isn't this only supposed to be broadcast for each percent decrease? It actually caused my entire launcher to lag, I had to uninstall it. That can't be right.
A:
My code looks like this:
You cannot register a BroadcastReceiver from another BroadcastReceiver and get reliable results. Android will terminate your process, because it doesn't think anything is running. The only way to listen for ACTION_BATTERY_CHANGED will be to register that receiver from an activity or a service.
Isn't this only supposed to be broadcast for each percent decrease?
Where do you see that documented? AFAIK, ACTION_BATTERY_CHANGED will be broadcast whenever the hardware feels like it. Also, bear in mind that other data changes within that Intent, such as temperature.
If you want to implement this app widget, do not register for ACTION_BATTERY_CHANGED the way you are. Instead:
*
*Allow the user to choose a polling period via a SharedPreference (e.g., once a minute, once every 15 mintues)
*Use AlarmManager to give you control on that polling period via a getBroadcast() PendingIntent
*In that BroadcastReceiver, call registerReceiver() for ACTION_BATTERY_CHANGED but with a null BroadcastReceiver, as this will return to you the last Intent that was broadcast for that action (note: you will still need to use getApplicationContext() for this)
*Use AppWidgetManager to update your app widget instances with the battery level pulled out of the Intent you retrieved in the preceding step (note: if you are setting them all to be the same, you do not need to iterate over the IDs -- use the updateAppWidget() that takes a ComponentName as a parameter)
This has several advantages:
*
*You do not care how often ACTION_BATTERY_CHANGED is broadcast
*The user gets to control how much battery you consume by doing these checks (should be negligible if you keep the polling period to a minute or more)
*Your process can be safely terminated in between polls, thereby making it less likely that users will attack you with task killers and semi-permanently mess up your app
A: Well, your onUpdate is registering its own class as receiver for the batteryinfo intent. This intent is then immediately triggered for the first info.
Your onReceive is calling your onUpdate again. We call this a loop. Hence the 100 logs a second ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: B4ABridge not working for most of files I am trying several examples from the forum, most of the samples are not in my phone but are unable to be installed via the B4ABridge even it says it is connected. How can this be fixed?
this is what it says:
Installing file to device. 0.20
Installing with B4A-Bridge.
Installation will fail if the signing key is different than the previous used key.
In that case you will need to manually uninstall the existing application.
Completed successfully.
regards
A: First check if other features work. For example, can you see the logs?
Make sure that you allowed installation of non-market applications.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why am I getting these errors? // Inventory.java part 1
// this program is to calculate the value of the inventory of the Electronics Department's cameras
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class Inventory
{
public void main(String[] args)
{
// create Scanner to obtain input from the command window
Scanner input = new Scanner (System.in);
int itemNumber; // first number to multiply
int itemStock; // second number to multiply
double itemPrice; //
double totalValue; // product of number1 and number2
while(true){ // infinite loop
// make new Camera object
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice, totalValue);
System.out.print("Enter Department name: "); //prompt
String itemDept = input.nextLine(); // read name from user
if(itemDept.equals("stop")) // exit the loop
break;
while(true){
System.out.print("Enter item name: "); // prompt
String name = input.nextLine(); // read first number from user
input.nextLine();
if(name != ("camera"))
System.out.print("Enter valid item name:"); // prompt
name = input.nextLine(); // read first number from user
input.nextLine();
break;
}
System.out.print("Enter number of items on hand: "); // prompt
itemStock = input.nextInt(); // read first number from user
input.nextLine();
while( itemStock <= -1){
System.out.print("Enter positive number of items on hand:"); // prompt
itemStock = input.nextInt(); // read first number from user
input.nextLine();
} /* while statement with the condition that negative numbers are entered
user is prompted to enter a positive number */
System.out.print("Enter item Price: "); // prompt
itemPrice = input.nextDouble(); // read second number from user
input.nextLine();
while( itemPrice <= -1){
System.out.print("Enter positive number for item price:"); // prompt
itemPrice = input.nextDouble(); // read first number from user
input.nextLine();
} /* while statement with the condition that negative numbers are entered
user is prompted to enter a positive number */
totalValue = itemStock * itemPrice; // multiply numbers
System.out.println("Department name:" + itemDept); // display Department name
System.out.println("Item number: " + camera.getItemNumber()); //display Item number
System.out.println("Product name:" + camera.getName()); // display the item
System.out.println("Quantity: " + camera.getItemStock());
System.out.println("Price per unit" + camera.getItemPrice());
System.out.printf("Total value is: $%.2f\n", camera.getTotalValue()); // display product
} // end while method
} // end method main
}/* end class Inventory */
class Cam{
private String name;
private int itemNumber;
private int itemStock;
private double itemPrice;
private String deptName;
private Cam(String name, int itemNumber, int itemStock, double itemPrice, double totalValue) {
this.name = name;
this.itemNumber = itemNumber;
this.itemStock = itemStock;
this.itemPrice = itemPrice;
this.totalValue = totalValue;
}
public String getName(){
return name;
}
public double getTotalValue(){
return itemStock * itemPrice;
}
public int getItemNumber(){
return itemNumber;
}
public int getItemStock(){
return itemStock;
}
public double getItemPrice(){
return itemPrice;
}
}
This is the output when I try to compile this code:
C:\Java>javac Inventory.java
Inventory.java:25: error: cannot find symbol
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice, totalValue);
^
symbol: variable name
location: class Inventory
Inventory.java:98: error: cannot find symbol
this.totalValue = totalValue;
^
symbol: variable totalValue
2 errors
I don't understand why I keep getting these errors. I feel like I am close to finishing the problem, but find that I need help getting over this bit of the problem.
Okay, I have made a few changes, but now I get these errors:
C:\Java>javac Inventory.java
Inventory.java:68: error: variable itemNumber might not have been initialized
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice, totalValue);
^
Inventory.java:68: error: variable totalValue might not have been initialized
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice, totalValue);
^
2 errors
A: You have declared a variable totalValue inside the main function of the Inventory class. It is not available for class Cam as an instance (this) variable.
A: Your missing declaration for the variable name in main.
// create Scanner to obtain input from the command window
Scanner input = new Scanner (System.in);
String name; //missing declaration
int itemNumber; // first number to multiply
int itemStock; // second number to multiply
double itemPrice; //
double totalValue; // product of number1 and number2
Also:
class Cam{
private String name;
private int itemNumber;
private int itemStock;
private double itemPrice;
private String deptName;
private double totalValue; //missing field
private Cam(String name, int itemNumber, int itemStock, double itemPrice, double totalValue) {
The constructor is private.
Your are also missing static in your main method.
A: The two errors are pretty simple:
First:
Inventory.java:25: error: cannot find symbol
Cam camera = new Cam(name, itemNumber, itemStock, itemPrice, totalValue);
^
symbol: variable name
location: class Inventory
This sais it cannot find the variable called name, which is true. There is no name variable in the scope when you try to construct the Cam. We know you have a name variable a bit further, but that does not work, because the variable isn't in the scope of the newstatement.
Second:
Inventory.java:98: error: cannot find symbol
this.totalValue = totalValue;
^
symbol: variable totalValue
It sais it can't find a value called totalValue in the Cam class, which is true as well. Check out the member list of Cam and you will see that there is no totalValue. I guess you want to remove it from the constructor, because you are calculating total value depending on itemStock and itemPrice.
Notes:
If you solved this, (and probably more compilation errors) you will notice that your application will compile, but not run. This is because of you forget to declare your main-method static.
If you have solved this you will notice that all the Cam objects you constructed, will contain the data you entered for the previous Cam. This is because of you are constructing the Cam before prompting the data. You started good: Declare fields for the data you want to prompt. When the user entered all the data of one Camera, construct the Camera.
A: There are two classes in your file
*
*Inventory
*Cam
You need to define
*
*variable name in Class Inventory
*variable totalValue in Class Cam
Also your in Inventory.java the call to Cam constructor seems to be at a wrong place, you might want to make it the last line of While loop
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to use log4j with multiple classes? I'm currently writing a big project in java, with numerous classes, some classes are quiet small, that simply represent objects with only few methods.
I have a logger set in my main class, and it works fine.
I want to be able to use only one logger (with one console appender) with all the classes.
I tried to pass a reference to the logger to the different classes, but it doesn't look right.
besides, sometimes I'm running tests on the classes without running main, and thus the logger is not initialized for the other classes.
What's the best approach to accomplish that, I mean, how to log from different classes to one log, with no hard dependency between the classes and with the ability to use the log independently with each class ?
A: Your logger instances should typically be private, static and final. By doing so, each class will have it's own logger instance (that is created once the class is loaded), so that you could identify the class where the log record was created, and also you no longer need to pass logger instances across classes.
A: The best way to do it is to have each class have it's own logger (named after the class), then set up your configuration so that they all append to the same appender.
For example:
class A {
private static final Logger log = Logger.getLogger(A.class);
}
class B {
private static final Logger log = Logger.getLogger(B.class);
}
Then your log4j.properties can look like the example in the log4j documentation:
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
Both A and B will log to the root logger and hence to the same appender (in this case the console).
This will give you what you want: each class is independent but they all write to the same log. You also get the bonus feature that you can change the logging level for each class in the log4j configuration.
As an aside, you might want to consider moving to slf4j if the project is still in early development. slf4j has some enhancements over log4j that make it a little easier to work with.
A: If I understand correctly, what you have at the minute is:
public class Main {
public static final Logger LOGGER = Logger.getLogger(Main.class);
}
public class AnotherClass {
public void doSomething() {
Main.LOGGER.debug("value=" + value);
}
}
or, you pass references to a logger into the constructors of the class.
Firstly, you can use one global logger by simply using the same value passed to Logger.getLogger, like:
public class Main {
private static final Logger LOGGER = Logger.getLogger("GLOBAL");
}
public class AnotherClass {
private final Logger LOGGER = Logger.getLogger("GLOBAL");
public void doSomething() {
LOGGER.debug("value=" + value);
}
}
This uses exactly the same logger, Logger.getLogger returns the same object in both calls. You no longer have a dependency between the classes, and this will work.
The other thing I gather from your comments is that you are configuring by hand (using BasicConfigurator.configure. Most of the time this isn't necessary, and you should be doing your configuration by simply adding a log4j.properties or log4j.xml to your classpath. In Eclipse this is done by adding it to src/ (or src/main/resources if you're using maven). If you're using junit, then add it to the test/ source directory (or src/test/resources with maven). This is a much better long term way of configuring log4j, because you don't have to pass information between classes.
Also, the recommended way to use loggers is to pass the class to the Logger.getLogger(). In this way you can filter your output based upon the class name, which is usually much more useful than just having one global logger:
public class Main {
private static final Logger LOGGER = Logger.getLogger(Main.class);
public static final main(String[] args) {
LOGGER.debug("started");
}
}
public class AnotherClass {
private final Logger LOGGER = Logger.getLogger(this.getClass());
public void doSomething() {
LOGGER.debug("value=" + value);
}
}
Then in the log4j.properties, you can configure a single appender to one file.
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
Finally, it is not necessary to declare all of your loggers as static. This only makes a noticeable difference if you are doing lots[*] of object creation. Declaring your loggers as non-static fields allows you to use Logger.getLogger(this.getClass()); in which case adding a logger to a class becomes a cut and paste of a single line. This slf4j page contains a good explanation of the pros and cons. So use non-static fields unless you have a very good reason not to.
Cameron is right when he say that you should try and use slf4j if possible, it has one killer feature, you can use multiple logging frameworks with it.
[*] and I mean lots.
A: I recently found out this solution.
Use @Log4j annotation with all the classes in which you wish using logger.
Benefits:
*
*Easy to maintain, easy to track down.
*Only one object of the logger is created which will be used through out.
How to do this?
Pre-req: Install Lombok Plugin in your editor, add lombok dependency in your project.
Now for the definition part:
@Log4j2
public class TestClass {
TestClass() {
log.info("Default Constructor");
//With the help of lombok plugin, you'll be able to see the suggestions
}
<Data members and data methods>
}
UPDATE:
Did some research on this, you can use other Log classes via this method, once you build the code and the Jar has been generated, all the classes using the annotations will share a singleton Logger.
*
*Make sure you are keeping the same standard throughout the project, if someone else starts using the general definition of classes like the traditional way, you might end up having multiple instances.
*Make sure that you are using the same logger classes throughout the project, if you have chosen to use @Slf4j, keep it consistent throughout, you might end up with some errors at some places and yes definitely inconsistencies.
A: The reason you have multiple logger instances is because you want them to behave different when logging (usually by printing out the class name they are configured with). If you do not care about that, you can just create a single static logger instance in a class and use that all over the place.
To create single logger, you can simply create a static utility logging class to be single point logger, so if we need to change the logger package, you will only update this class.
final public class Logger {
private static final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("Log");
enum Level {Error, Warn, Fatal, Info, Debug}
private Logger() {/* do nothing */};
public static void logError(Class clazz, String msg) {
log(Level.Error, clazz, msg, null);
}
public static void logWarn(Class clazz, String msg) {
log(Level.Warn, clazz, msg, null);
}
public static void logFatal(Class clazz, String msg) {
log(Level.Fatal, clazz, msg, null);
}
public static void logInfo(Class clazz, String msg) {
log(Level.Info, clazz, msg, null);
}
public static void logDebug(Class clazz, String msg) {
log(Level.Debug, clazz, msg, null);
}
public static void logError(Class clazz, String msg, Throwable throwable) {
log(Level.Error, clazz, msg, throwable);
}
public static void logWarn(Class clazz, String msg, Throwable throwable) {
log(Level.Warn, clazz, msg, throwable);
}
public static void logFatal(Class clazz, String msg, Throwable throwable) {
log(Level.Fatal, clazz, msg, throwable);
}
public static void logInfo(Class clazz, String msg, Throwable throwable) {
log(Level.Info, clazz, msg, throwable);
}
public static void logDebug(Class clazz, String msg, Throwable throwable) {
log(Level.Debug, clazz, msg, throwable);
}
private static void log(Level level, Class clazz, String msg, Throwable throwable) {
String message = String.format("[%s] : %s", clazz, msg);
switch (level) {
case Info:
logger.info(message, throwable);
break;
case Warn:
logger.warn(message, throwable);
break;
case Error:
logger.error(message, throwable);
break;
case Fatal:
logger.fatal(message, throwable);
break;
default:
case Debug:
logger.debug(message, throwable);
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: Margin-top/Padding-top having no effect? I'm building a jQuery form-field validator, and at the moment I'm working on building in the pop-up notifications in CSS.
The problem is, I can't get .notification-point to align to the center of .notification-body, regardless of the application of margin-top/padding-top properties.
Here's a link to my JsFiddle: http://jsfiddle.net/Z6Jtd/8/
Any help/edits would be greatly appreciated!
A: Solution: http://jsfiddle.net/vonkly/Z6Jtd/9/
There you go.
Note: I changed your javascript a little. I removed .fadeOut; I would highly recommend creating a function for .focusout() - or better yet, detect changes to the value and when it matches the required rule, hide the message.
For future readers:
The solution to this issue was to wrap both the marker ("point") and the body ("message") in a container with position: relative; on it.
Then, I positioned the marker using position: absolute; and top: 8px.
Next, I added margin-left: 12px to the message in order to not overlap the marker.
CSS
input[type="text"], input[type="password"] {
display: inline-block;
font: bold 13px Arial;
color: #555;
width: 300px;
padding: 8px 10px;
border: 0;
}
.notify-wrap {
position: relative;
display: none;
}
.notify-point {
position: absolute;
top: 8px;
display: inline-block;
border-style: solid;
border-color: transparent rgba(0, 0, 0, 0.75) transparent transparent;
border-width: 6px;
}
.notify-body {
margin-left: 12px; /* push the body out to make room for point */
padding: 8px 10px;
font: bold 11px Arial, Helvetica;
color: #fff !important;
background-color: rgba(0, 0, 0, 0.75);
}
note: above code is modified to not take up loads of room with border-radius, etc
HTML
<div id="email">
<input name="1" type="text" value="Enter your email address"/>
<div class="notify-wrap x1">
<div class="notify-point"></div>
<div class="notify-body">
You've entered an invalid email address.
</div>
</div>
</div>
note: on notify-wrap, i added the class x1 to define a specific error message to keep in line with the OP's original formatting for javascript.
Javascript (jQuery)
$('input').focus( function() {
var num = $(this).attr('name');
$('div.notify-wrap.x' + num).css('display','inline-block');
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can I use boto to stream a file out of Amazon S3 to Rackspace Cloudfiles? I'm copying a file from S3 to Cloudfiles, and I would like to avoid writing the file to disk. The Python-Cloudfiles library has an object.stream() call that looks to be what I need, but I can't find an equivalent call in boto. I'm hoping that I would be able to do something like:
shutil.copyfileobj(s3Object.stream(),rsObject.stream())
Is this possible with boto (or I suppose any other s3 library)?
A: Other answers in this thread are related to boto, but S3.Object is not iterable anymore in boto3. So, the following DOES NOT WORK, it produces an TypeError: 's3.Object' object is not iterable error message:
s3 = boto3.session.Session(profile_name=my_profile).resource('s3')
s3_obj = s3.Object(bucket_name=my_bucket, key=my_key)
with io.FileIO('sample.txt', 'w') as file:
for i in s3_obj:
file.write(i)
In boto3, the contents of the object is available at S3.Object.get()['Body'] which is an iterable since version 1.9.68 but previously wasn't. Thus the following will work for the latest versions of boto3 but not earlier ones:
body = s3_obj.get()['Body']
with io.FileIO('sample.txt', 'w') as file:
for i in body:
file.write(i)
So, an alternative for older boto3 versions is to use the read method, but this loads the WHOLE S3 object in memory which when dealing with large files is not always a possibility:
body = s3_obj.get()['Body']
with io.FileIO('sample.txt', 'w') as file:
for i in body.read():
file.write(i)
But the read method allows to pass in the amt parameter specifying the number of bytes we want to read from the underlying stream. This method can be repeatedly called until the whole stream has been read:
body = s3_obj.get()['Body']
with io.FileIO('sample.txt', 'w') as file:
while file.write(body.read(amt=512)):
pass
Digging into botocore.response.StreamingBody code one realizes that the underlying stream is also available, so we could iterate as follows:
body = s3_obj.get()['Body']
with io.FileIO('sample.txt', 'w') as file:
for b in body._raw_stream:
file.write(b)
While googling I've also seen some links that could be use, but I haven't tried:
*
*WrappedStreamingBody
*Another related thread
*An issue in boto3 github to request StreamingBody is a proper stream - which has been closed!!!
A: This is my solution of wrapping streaming body:
import io
class S3ObjectInterator(io.RawIOBase):
def __init__(self, bucket, key):
"""Initialize with S3 bucket and key names"""
self.s3c = boto3.client('s3')
self.obj_stream = self.s3c.get_object(Bucket=bucket, Key=key)['Body']
def read(self, n=-1):
"""Read from the stream"""
return self.obj_stream.read() if n == -1 else self.obj_stream.read(n)
Example usage:
obj_stream = S3ObjectInterator(bucket, key)
for line in obj_stream:
print line
A: The Key object in boto, which represents on object in S3, can be used like an iterator so you should be able to do something like this:
>>> import boto
>>> c = boto.connect_s3()
>>> bucket = c.lookup('garnaat_pub')
>>> key = bucket.lookup('Scan1.jpg')
>>> for bytes in key:
... write bytes to output stream
Or, as in the case of your example, you could do:
>>> shutil.copyfileobj(key, rsObject.stream())
A: I figure at least some of the people seeing this question will be like me, and will want a way to stream a file from boto line by line (or comma by comma, or any other delimiter). Here's a simple way to do that:
def getS3ResultsAsIterator(self, aws_access_info, key, prefix):
s3_conn = S3Connection(**aws_access)
bucket_obj = s3_conn.get_bucket(key)
# go through the list of files in the key
for f in bucket_obj.list(prefix=prefix):
unfinished_line = ''
for byte in f:
byte = unfinished_line + byte
#split on whatever, or use a regex with re.split()
lines = byte.split('\n')
unfinished_line = lines.pop()
for line in lines:
yield line
@garnaat's answer above is still great and 100% true. Hopefully mine still helps someone out.
A: Botocore's StreamingBody has an iter_lines() method:
https://botocore.amazonaws.com/v1/documentation/api/latest/reference/response.html#botocore.response.StreamingBody.iter_lines
So:
import boto3
s3r = boto3.resource('s3')
iterator = s3r.Object(bucket, key).get()['Body'].iter_lines()
for line in iterator:
print(line)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "49"
} |
Q: StringIndexOutOfBoundsException when switching page When I load a gridview (with adapter weekAdapter) from inside a fragment (weekFragment) for a viewpager, the first page loads fine. However, once I want to switch page, it gives a StringIndexOutOfBoundsException. I can't figure out what is wrong. In the LogCat nothing is reported, and the error only shows native methods, that I don't have modified. Please tell me how I can solve this.
weekFragment.java:
package nl.siebeh.schoolmate;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
public class weekFragment extends Fragment {
dbLayer db;
String[] array = new String[60];
public String title;
View v;
/*@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
GridView gridview = (GridView) v.findViewById(R.id.gridview);
gridview.setAdapter(new weekAdapter(getActivity(), mContent));
}*/
public weekFragment newInstance(String title) {
weekFragment fragment = new weekFragment();
fragment.title = title;
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (container == null) {
return null;
}
db = new dbLayer(getActivity());
for(int i = 0; i < 60; i++){
this.array[i] = String.valueOf(i);
}
ArrayList<ArrayList<Object>> result = new ArrayList<ArrayList<Object>>();
if(title == "leraren"){
result = db.getAllRowsAsArrays("weekTeacher", null);
}else if(title == "locatie"){
result = db.getAllRowsAsArrays("weekLocation", null);
}else if(title == "vakken"){
result = db.getAllRowsAsArrays("weekSubjects", null);
}
Log.i("SchoolMate", "Size of result: "+String.valueOf(result.size()));
for(int position = 0; position < result.size(); position++){
ArrayList<Object> row = result.get(position);
int hour = Integer.valueOf(row.get(1).toString()).intValue();
int day = Integer.valueOf(row.get(0).toString()).intValue();
int pos = 6 * hour + day;
this.array[pos] = row.get(position).toString();
}
this.array[2] = getResources().getStringArray(R.array.days)[0];
this.array[3] = getResources().getStringArray(R.array.days)[1];
this.array[4] = getResources().getStringArray(R.array.days)[2];
this.array[5] = getResources().getStringArray(R.array.days)[3];
this.array[6] = getResources().getStringArray(R.array.days)[4];
for(int i = 1; i < 10; i++){
this.array[i] = Integer.toString(i);
}
v = inflater.inflate(R.layout.week_fragment, container, false);
GridView gridview = (GridView) v.findViewById(R.id.gridview);
if(getActivity() == null){
Log.i("SchoolMate", "getActivty() returns null");
}
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 60; i++){
sb.append("array["+i+"] = \""+array[i]+"\" \n");
}
Log.i("SchoolMate", sb.toString());
gridview.setAdapter(new weekAdapter(getActivity(), array));
return gridview;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
return super.onContextItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
}
}
weekAdapter.java:
package nl.siebeh.schoolmate;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
public class weekAdapter extends BaseAdapter {
public String[] strings;
Context mContext;
public weekAdapter(Context c, String[] s){
strings = s.clone();
mContext = c;
Log.i("SchoolMate", "weekAdapter called");
}
@Override
public int getCount() {
return 60;
}
@Override
public Object getItem(int arg0) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv;
//if (convertView == null) { // if it's not recycled, initialize some attributes
tv = new TextView(mContext);
try{
tv.setText(strings[position]);
}catch(ArrayIndexOutOfBoundsException e){
Log.i("SchoolMate", "Out of bounds; position = "+String.valueOf(position));
}
tv.setBackgroundColor(Color.BLACK);
tv.setTextColor(Color.WHITE);
/*} else {
tv = (TextView) convertView;
}*/
return tv;
}
}
The error:
ViewRoot.draw(boolean) line: 1546
ViewRoot.performTraversals() line: 1258
ViewRoot.handleMessage(Message) line: 1859
ViewRoot(Handler).dispatchMessage(Message) line: 99
Looper.loop() line: 123
ActivityThread.main(String[]) line: 3683
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 507
ZygoteInit$MethodAndArgsCaller.run() line: 839
ZygoteInit.main(String[]) line: 597
NativeStart.main(String[]) line: not available [native method]
EDIT:
I determined that the else if(title == "vakken") is the cause. If it is commented out, it just works. The order doesn't matter, it is this clause that causes the error. Later today I will try to make just seperate ifs.
A: Ok, I found out my problem. Here:
}else if(title == "vakken"){
result = db.getAllRowsAsArrays("weekSubjects", null);
}
weekSubjects should be weekSubject (without the s at the end)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624901",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Access Two Controllers in same bean - Dispatcher Servlet I am new to spring framework and hibernate. I want to Access Two Controllers in same view. Here is my Dispatcher Servlet code.
<bean name="/EditTask.htm"
class="HumanResource.FindTaskController"
p:HResourceService-ref="hresourceService" />
<bean name="/EditTask.htm"
class="HumanResource.UpdateTaskController"
p:HResourceService-ref="hresourceService" />
I have EditTask.jsp view. I want to access FindTaskController when user hits first submit and access UpdateTaskController when user hits second submit button in the same jsp.
I can't map Dispatcher Servlet as above because it genarates an exception Bean name '/EditTask.htm' is already used in this file.
Please help me.
A: You need two <form>s in your jsp - one with action="/findTask" and the other with action="/updateTask. (assuming you map your two controllers / controller methods to these urls).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to force generation of assets with Rails Asset Pipeline? Is there a way to force regeneration of assets every request when using the Rails 3.1 Asset Pipeline?
I am having problems getting the system to pick up changes to files when using Less (less-rails) with a series of partials and mixin files. If I could just force the system to generation on each request I would be much more productive.
A: To force a complete regeneration of all assets use:
rake assets:clobber assets:precompile
Very handy when asset_sync isn't playing fair with you...
I know this may not help you, but hopefully it will make it easier for someone else to find the answer.
A: You have to run your server in the development environment. I think you can also use something like config.cache_classes = false in your current environment's config file.
A: I worked it out.
The master.less file (as in the main less file that coordinates the other include files) needed to have the pipeline directives added to it.
So in my case, application.css contains:
/*
*= require html5reset-1.6.1
*= require master
*/
And master.css.less contains:
/*
*= depend_on mixins
*/
@import "mixins";
A: You can reset the assets cache with
rake tmp:cache:clear
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: Check if a user-defined type already exists in PostgreSQL Say I have created some user-defined types in the DB,
i.e. CREATE TYPE abc ...
Is it then possible to determine if the user-defined type exists or not? Perhaps, using any of the postgres information tables?
The main reason for this is since PostgreSQL does not seem to support CREATE OR REPLACE TYPE ..., and if a certain type gets created more than once, I want to be able to drop the existing one first, then re-load the new one.
A: -- All of this to create a type if it does not exist
CREATE OR REPLACE FUNCTION create_abc_type() RETURNS integer AS $$
DECLARE v_exists INTEGER;
BEGIN
SELECT into v_exists (SELECT 1 FROM pg_type WHERE typname = 'abc');
IF v_exists IS NULL THEN
CREATE TYPE abc AS ENUM ('height', 'weight', 'distance');
END IF;
RETURN v_exists;
END;
$$ LANGUAGE plpgsql;
-- Call the function you just created
SELECT create_abc_type();
-- Remove the function you just created
DROP function create_abc_type();
-----------------------------------
A: Indeed, Postgres does not have CREATE OR REPLACE functionality for types. So the best approach is to drop it:
DROP TYPE IF EXISTS YOUR_TYPE;
CREATE TYPE YOUR_TYPE AS (
id integer,
field varchar
);
Simple solution is always the best one.
A: You can look in the pg_type table:
select exists (select 1 from pg_type where typname = 'abc');
If that is true then abc exists.
A: Inspired by @Cromax's answer, here's an alternative solution using the system catalog information function to_regtype that avoids the extra overhead of an exception clause but still checks the correct schema for the type's existence:
DO $$ BEGIN
IF to_regtype('my_schema.abc') IS NULL THEN
CREATE TYPE my_schema.abc ... ;
END IF;
END $$;
In the case of the default public schema being used, it would look like:
DO $$ BEGIN
IF to_regtype('abc') IS NULL THEN
CREATE TYPE abc ... ;
END IF;
END $$;
A: To solve @rog's dilemma to @bluish's answer it could be more appropriate to make use of regtype data type. Consider this:
DO $$ BEGIN
PERFORM 'my_schema.my_type'::regtype;
EXCEPTION
WHEN undefined_object THEN
CREATE TYPE my_schema.my_type AS (/* fields go here */);
END $$;
PERFORM clause is like SELECT, but it discards results, so basically we're checking if it is possible to cast 'my_schema.my_type' (or just 'my_type' if you don't care to be schema specific) to actual registered type. If the type does exist, then nothing "wrong" will happen and whole block will end—no changes, since the type my_type is already there. But if the cast is not possible, then there will be thrown an error of code 42704 which has label of undefined_object. So in the next lines we try to catch that error and if that happens, we simply create our new data type.
A: I add here the complete solution for creating types in a simple script, without the need of creating a function just for this purpose.
--create types
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'my_type') THEN
CREATE TYPE my_type AS
(
--my fields here...
);
END IF;
--more types here...
END$$;
A: The simplest solution I've found so far that copes with schemas, inspired by @Cromax's answer, is this:
DO $$ BEGIN
CREATE TYPE my_type AS (/* fields go here */);
EXCEPTION
WHEN duplicate_object THEN null;
END $$;
Just what you might expect really - we just wrap the CREATE TYPE statement in an exception handler so it doesn't abort the current transaction.
A: I'm trying to do the same thing, ensure a type exists.
I started psql with the --echo-hidden (-E) option and entered \dT:
$ psql -E
psql (9.1.9)
testdb=> \dT
********* QUERY **********
SELECT n.nspname as "Schema",
pg_catalog.format_type(t.oid, NULL) AS "Name",
pg_catalog.obj_description(t.oid, 'pg_type') as "Description"
FROM pg_catalog.pg_type t
LEFT JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace
WHERE (t.typrelid = 0 OR (SELECT c.relkind = 'c' FROM pg_catalog.pg_class c WHERE c.oid = t.typrelid))
AND NOT EXISTS(SELECT 1 FROM pg_catalog.pg_type el WHERE el.oid = t.typelem AND el.typarray = t.oid)
AND n.nspname <> 'pg_catalog'
AND n.nspname <> 'information_schema'
AND pg_catalog.pg_type_is_visible(t.oid)
ORDER BY 1, 2;
**************************
List of data types
Schema | Name | Description
--------+------------------+-------------
public | errmsg_agg_state |
(1 row)
If you are using schemas and search_path (I am) then you'll probably need to keep the pg_catalog.pg_type_is_visible(t.oid) check. I don't know what all the conditions in the WHERE are doing, but they didn't seem relevant to my case. Currently using:
SELECT 1 FROM pg_catalog.pg_type as t
WHERE typname = 'mytype' AND pg_catalog.pg_type_is_visible(t.oid);
A: A more generic solution
CREATE OR REPLACE FUNCTION create_type(name text, _type text) RETURNS
integer AS $$
DECLARE v_exists INTEGER;
BEGIN
SELECT into v_exists (SELECT 1 FROM pg_type WHERE typname = name);
IF v_exists IS NULL THEN
EXECUTE format('CREATE TYPE %I AS %s', name, _type);
END IF;
RETURN v_exists;
END;
$$ LANGUAGE plpgsql;
and then you can call it like this:
select create_type('lwm2m_instancetype', 'enum (''single'',''multiple'')');
A: This plays well with schemas, and avoids exception handling:
DO $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM pg_type t
LEFT JOIN pg_namespace p ON t.typnamespace=p.oid
WHERE t.typname='my_type' AND p.nspname='my_schema'
) THEN
CREATE TYPE my_schema.my_type AS (/* fields go here */);
END IF;
END
$$;
A: Another alternative
WITH namespace AS(
SELECT oid
FROM pg_namespace
WHERE nspname = 'my_schema'
),
type_name AS (
SELECT 1 type_exist
FROM pg_type
WHERE typname = 'my_type' AND typnamespace = (SELECT * FROM namespace)
)
SELECT EXISTS (SELECT * FROM type_name);
A: You should try this:
SELECT * from pg_enum WHERE enumlabel='WHAT YOU WANT';
A: Continue with bluish code, we also need to check if DB has such a type in current schema. Because current code will not create type if db has same type in any of db schemas. So full universal code will look like this:
$$
BEGIN
IF NOT EXISTS(select
from pg_type
WHERE typname = 'YOUR_ENUM_NAME'
AND typnamespace in
(SELECT oid FROM pg_catalog.pg_namespace where nspname = "current_schema"())) THEN
CREATE TYPE YOUR_ENUM_NAME AS ENUM (....list of values ....);
END IF;
END
$$;```
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624919",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "118"
} |
Q: Number.sign() in javascript Wonder if there are any nontrivial ways of finding number's sign (signum function)?
May be shorter / faster / more elegant solutions than the obvious one
var sign = number > 0 ? 1 : number < 0 ? -1 : 0;
Short answer!
Use this and you'll be safe and fast (source: moz)
if (!Math.sign) Math.sign = function(x) { return ((x > 0) - (x < 0)) || +x; };
You may want to look at performance and type-coercing comparison fiddle
Long time has passed. Further is mainly for historical reasons.
Results
For now we have these solutions:
1. Obvious and fast
function sign(x) { return x > 0 ? 1 : x < 0 ? -1 : 0; }
1.1. Modification from kbec - one type cast less, more performant, shorter [fastest]
function sign(x) { return x ? x < 0 ? -1 : 1 : 0; }
caution: sign("0") -> 1
2. Elegant, short, not so fast [slowest]
function sign(x) { return x && x / Math.abs(x); }
caution: sign(+-Infinity) -> NaN, sign("0") -> NaN
As of Infinity is a legal number in JS this solution doesn't seem fully correct.
3. The art... but very slow [slowest]
function sign(x) { return (x > 0) - (x < 0); }
4. Using bit-shift
fast, but sign(-Infinity) -> 0
function sign(x) { return (x >> 31) + (x > 0 ? 1 : 0); }
5. Type-safe [megafast]
! Seems like browsers (especially chrome's v8) make some magic optimizations and this solution turns out to be much more performant than others, even than (1.1) despite it contains 2 extra operations and logically never can't be faster.
function sign(x) {
return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? 0 : NaN : NaN;
}
Tools
*
*jsperf preformance tests;
*fiddle - type-cast tests;
Improvements are welcome!
[Offtopic] Accepted answer
*
*Andrey Tarantsov - +100 for the art, but sadly it is about 5 times slower than the obvious approach
*Frédéric Hamidi - somehow the most upvoted answer (for the time writing) and it's kinda cool, but it's definitely not how things should be done, imho. Also it doesn't correctly handle Infinity numbers, which are also numbers, you know.
*kbec - is an improvement of the obvious solution. Not that revolutionary, but taking all together I consider this approach the best. Vote for him :)
A: More elegant version of fast solution:
var sign = number?number<0?-1:1:0
A: var sign = number >> 31 | -number >>> 31;
Superfast if you do not need Infinity and know that the number is an integer, found in openjdk-7 source: java.lang.Integer.signum()
A: Dividing the number by its absolute value also gives its sign. Using the short-circuiting logical AND operator allows us to special-case 0 so we don't end up dividing by it:
var sign = number && number / Math.abs(number);
A: The function you're looking for is called signum, and the best way to implement it is:
function sgn(x) {
return (x > 0) - (x < 0);
}
A: Should this not support JavaScript’s (ECMAScript’s) signed zeroes? It seems to work when returning x rather than 0 in the “megafast” function:
function sign(x) {
return typeof x === 'number' ? x ? x < 0 ? -1 : 1 : x === x ? x : NaN : NaN;
}
This makes it compatible with a draft of ECMAScript’s Math.sign (MDN):
Returns the sign of the x, indicating whether x is positive, negative or zero.
*
*If x is NaN, the result is NaN.
*If x is −0, the result is −0.
*If x is +0, the result is +0.
*If x is negative and not −0, the result is −1.
*If x is positive and not +0, the result is +1.
A: For people who are interested what is going on with latest browsers, in ES6 version there is a native Math.sign method. You can check the support here.
Basically it returns -1, 1, 0 or NaN
Math.sign(3); // 1
Math.sign(-3); // -1
Math.sign('-3'); // -1
Math.sign(0); // 0
Math.sign(-0); // -0
Math.sign(NaN); // NaN
Math.sign('foo'); // NaN
Math.sign(); // NaN
A: I thought I'd add this just for fun:
function sgn(x){
return 2*(x>0)-1;
}
0 and NaN will return -1works fine on +/-Infinity
A: A solution that works on all numbers, as well as 0 and -0, as well as Infinity and -Infinity, is:
function sign( number ) {
return 1 / number > 0 ? 1 : -1;
}
See the question "Are +0 and -0 the same?" for more information.
Warning: None of these answers, including the now standard Math.sign will work on the case 0 vs -0. This may not be an issue for you, but in certain physics implementations it may matter.
A: You could bit shift the number and check the Most Significant Bit (MSB). If the MSB is a 1 then the number is negative. If it is 0 then the number is positive (or 0).
A: I just was about to ask the same question, but came to a solution before i was finished writing, saw this Question already existed, but didn't saw this solution.
(n >> 31) + (n > 0)
it seems to be faster by adding a ternary though (n >> 31) + (n>0?1:0)
A: Very similar to Martijn's answer is
function sgn(x) {
isNaN(x) ? NaN : (x === 0 ? x : (x < 0 ? -1 : 1));
}
I find it more readable. Also (or, depending on your point of view, however), it also groks things that can be interpreted as a number; e.g., it returns -1 when presented with '-5'.
A: I don't see any practical sence of returning -0 and 0 from Math.sign so my version is:
function sign(x) {
x = Number(x);
if (isNaN(x)) {
return NaN;
}
if (x === -Infinity || 1 / x < 0) {
return -1;
}
return 1;
};
sign(100); // 1
sign(-100); // -1
sign(0); // 1
sign(-0); // -1
A: The methods I know of are as follows:
Math.sign(n)
var s = Math.sign(n)
This is the native function, but is slowest of all because of the overhead of a function call. It does however handle 'NaN' where the others below may just assume 0 (i.e. Math.sign('abc') is NaN).
((n>0) - (n<0))
var s = ((n>0) - (n<0));
In this case only the left or right side can be a 1 based on the sign. This results in either 1-0 (1), 0-1 (-1), or 0-0 (0).
The speed of this one seems neck and neck with the next one below in Chrome.
(n>>31)|(!!n)
var s = (n>>31)|(!!n);
Uses the "Sign-propagating right shift". Basically shifting by 31 drops all bits except the sign. If the sign was set, this results in -1, otherwise it is 0. Right of | it tests for positive by converting the value to boolean (0 or 1 [BTW: non-numeric strings, like !!'abc', become 0 in this case, and not NaN]) then uses a bitwise OR operation to combine the bits.
This seems the best average performance across the browsers (best in Chrome and Firefox at least), but not the fastest in ALL of them. For some reason, the ternary operator is faster in IE.
n?n<0?-1:1:0
var s = n?n<0?-1:1:0;
Fastest in IE for some reason.
jsPerf
Tests performed: https://jsperf.com/get-sign-from-value
A: My two cents, with a function that returns the same results as Math.sign would do, ie sign(-0) --> -0, sign(-Infinity) --> -Infinity, sign(null) --> 0, sign(undefined) --> NaN, etc.
function sign(x) {
return +(x > -x) || (x && -1) || +x;
}
Jsperf won't let me create a test or revision, sorry for not being able to provide you with tests (i've given jsbench.github.io a try, but results seem much closer to one another than with Jsperf...)
If someone could please add it to a Jsperf revision, I would be curious to see how it compares to all the previously given solutions...
Thank you!
Jim.
EDIT:
I should have written:
function sign(x) {
return +(x > -x) || (+x && -1) || +x;
}
((+x && -1) instead of (x && -1)) in order to handle sign('abc') properly (--> NaN)
A: Math.sign is not supported on IE 11. I am combining the best answer with Math.sign answer :
Math.sign = Math.sign || function(number){
var sign = number ? ( (number <0) ? -1 : 1) : 0;
return sign;
};
Now, one can use Math.sign directly.
A: Here is a compact version:
let sign=x=>2*(x>=0)-1
//Tests
console.log(sign(0)); //1
console.log(sign(6)); //1
console.log(sign(Infinity)); //1
console.log(sign(-6)); //-1
console.log(sign(-Infinity)); //-1
console.log(sign("foo")); //-1
If you want to deal with NaN and other edge cases, use this (it is longer though):
let sign=x=>isNaN(x)?NaN:2*(x>=0)-1
//Tests
console.log(sign(0)); //1
console.log(sign(6)); //1
console.log(sign(Infinity)); //1
console.log(sign(-6)); //-1
console.log(sign(-Infinity)); //-1
console.log(sign("foo")); //NaN
If you want sign(0) to return 0 as well:
let sign=x=>isNaN(x)?NaN:(x?2*(x>=0)-1:0)
//Tests
console.log(sign(0)); //0
console.log(sign(6)); //1
console.log(sign(Infinity)); //1
console.log(sign(-6)); //-1
console.log(sign(-Infinity)); //-1
console.log(sign("foo")); //NaN
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "107"
} |
Q: WCF Services for both Web Application and Ipad development I am in a situation where i have wcf services and which can be consumed by both web application and ipad application. So my question is, my client needs to be authenticated with user name and password, so what is the authentication method i have to follow. whether i have to use any sessionid or some thing in url to authenticate each request or is there any other method where initially pass user name and password and from then on,the wcf take the credentials automatically once the user is authenticated.
A: Actually, your question is probably already answered in WCF sessions or pass username/password per call?. If that does not do the job for you, please take a look at the Custom User Name and Password Validator.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How can I search a specific variable in vector in c++? I'm new to vector in C++, and I'm using pointer in it.
I'd like to search a variable if it already exists in the vector but I'm not sure how to do it.
B.cpp
vector<Animal*> vec_Animal;
vector<Animal*>::iterator ite_Animal;
What I'm trying to compare is Animal->getID();
And I have one more question.
Is there any way to make a limit when a user inputs value?
What I mean by is that if there's a value year then, I want it to be typed 1000~2011 only. If user puts 999, it'd be wrong.
Is it possible?
Cheers
A: You can use the std::find_if algorithm.
Probably, You are using std::vector::push_back or such methods to fill up the vector, These methods do not provide any checks, but one way to do achieve this is, by writing a small wrapper function inside which you check for the valid data conditions, and if the data is good then you add that in the vector or else you just return some error or throw std::out_of_range exception from your wrapper function.
Online Demo
Here is a minimilastic code sample, ofcourse you will need t tweak it further to suit your need:
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class Animal
{
public:
int id;
};
class Ispresent
{
public:
int m_i;
Ispresent(int i):m_i(i){}
bool operator()(Animal *ptr)
{
cout<<"\n\nInside IsPresent:"<<ptr->id;
return (ptr->id == m_i);
}
};
int main()
{
vector<Animal*> vec_Animal;
Animal *ptr = new Animal();
ptr->id = 10;
vec_Animal.push_back(ptr);
Animal *ptr1 = new Animal();
ptr1->id = 20;
vec_Animal.push_back(ptr1);
Animal *ptr2 = new Animal();
ptr2->id = 30;
vec_Animal.push_back(ptr2);
vector<Animal*>::iterator ite_Animal = vec_Animal.begin();
for(ite_Animal; ite_Animal != vec_Animal.end(); ++ite_Animal)
cout<<"\nVector contains:"<< (*ite_Animal)->id;
vector<Animal*>::iterator ite_search;
/*Find a value*/
ite_search = std::find_if( vec_Animal.begin(), vec_Animal.end(), Ispresent(20));
if(ite_search != vec_Animal.end())
cout<<"\n\nElement Found:"<<(*ite_search)->id;
else
cout<<"\n\nElement Not Found";
return 0;
}
Note that the sample is just an example of how to get find_if working, it does not follow the best practices.
A: You could just move through the vector by index, accessing each element's ID property and comparing against your own. There's a few different methods of doing it over at http://setoreaustralia.com/ZpdHMFATCphM4Xz.php that are designed to find an element based on a series of properties
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to display status updates from followed users? (MVC) What would be a good approach to display on a dashboard, status updates from users that are being followed (e.g. twitter) on a MVC framework such as codeigniter.
I have a Table, just for the status update, where I record the ID,user_id & message.
Should I create a DB table where I record who is following who, by recording the Users ID when a user choose to follow someone?
If so how would I make a query to the database to request for status update only for followed users?
A: This is a typical Many-To-Many relationship, so you'll need a table to store this relation. The table would simply contain two user id's one for the follower and one for the one being followed. For example:
Followed_Id (BIGINT) | Follower_Id (BIGINT)
These columns would then both have a foreign key, referencing the ID column of your user table.
There are a few ORM tools for CI, like swatkins notes in his comment.
For the querying of the status updates, you basically have two options:
*
*Polling, where your client would periodically poll the backend for new updates
*Pushing, where your backend will notify your client of new updates
The second option is considered a better approach for problems like these because:
*
*It can be implemented asynchronously
*It avoids unnecessary calls to the backend in case there's no new data
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SSL Certificate signature calculation
What I have understood is that a signature of a certificate would be hash of the certificate encrypted with private key of CA and then encrypted with the private key of server (which is the owner of certificate.)
SSL connection initiation/negotiation also allows for sending the public key in ServerKeyExchange message and sending the public key separately. This would probably be done in scenarios where signing algorithms support only authentication and not encryption, or due to strict encryption policies. In such a case:
*
*Would the certificate (body) contain the public key
*Would the calculation of certificate signature involve using the private key of server
*If the answer to 1. and 2. is no, then it means that the client relies on the ServerKeyExchange message for getting the public key of the server. Is it possible that a man-in-the-middle intercepts and changes the public key in ServerKeyMessage ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: COCOS2D best way to change level when score has been reached I have some difficulties making the level change only once when the player has reach a certain score during the game. It keeps changing every time the players gets a new score which is very annoying.
//Change the level
if(score >= 600){
level = level+1;
[levellabel setString:[NSString stringWithFormat:@"%d",level]];
id ScaleUp = [CCScaleTo actionWithDuration:0.3 scale:14.0 ];
id ScaleDown = [CCScaleTo actionWithDuration:0.3 scale:1.0 ];
[levellabel runAction:[CCSequence actions:ScaleUp, ScaleDown, nil] ];
}
I also tried with setting the if statement to if(score >= 600 && score<1000) and then use a new if statement telling it to change the level once again when the score >=2000 but if I do that nothing seems to happen.
What am I doing wrong?
A: The following if you have a control over the levels and a max cap on the levels..
-(void)addLevel
{
level = level+1;
[levellabel setString:[NSString stringWithFormat:@"%d",level]];
id ScaleUp = [CCScaleTo actionWithDuration:0.3 scale:14.0 ];
id ScaleDown = [CCScaleTo actionWithDuration:0.3 scale:1.0 ];
[levellabel runAction:[CCSequence actions:ScaleUp, ScaleDown, nil] ];
}
-(void)newScore
{
int target = 0;
switch(level):
{
case 1:
target = 600;
break;
case 2:
target = 1000;
break;
case 3:
target = 2000;
break;
}
if(score>=target)
[self addLevel];
}
if its infinite and follows a standard formula, in this example, increase level for every 1000 score, it should be:
-(void)addScore
{
int nxtLvl = level +1;
if(score>=1000*nxtLvl)
[self addLevel];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creation date of a file How do I return a date of a file?
Something like this does not work and it is ugly too.
ls -l tz1.sql | awk '{print $7$6 $8}'
7Jun10:00
A: You can use stat to get the modification time, access time, or metadata change time of a file. Creation time is not recorded.
$ stat -c '%y' t.txt
2011-09-30 11:18:07.909118203 -0400
A: use commas to separate the fields:
ls -l tz1.sql | awk '{print $7, $6, $8}'
When awk reads an input line, this line is split on the field separator FS.
Thus you have to put those field separators back in, when you print the line.
"," stands for those FSs.
EDIT:
If you want to use the variant with Ignacio Vazquez, try:
stat -c "%y" s.awk | cut -d. -f1
Output:
2011-09-30 22:44:46
HTH Chris
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQueryUI Dialog not working in JS File I have JQuery code which makes Ajax call, In order to reuse same code, I have put my code in .JS File.
Here is the scenario.
1) I have hyperlink control and div control in my aspx page. div control is for displaying JQueryUI dialog message.
2) I have JS file which receives reference of hyperlink object and div object
3) In JS file i am insert record through JQuery Ajax, it is working good, but problem is it is not displaying JQuery UI Dialog
Code for that
In Aspx File
<asp:HyperLink ID="hlInsertRecord" runat="server" Text="Insert Record" Font-Bold="true" />
<div id="pnlInsertRecordMsg" title="Insert Record"></div>
In Aspx.cs File (Binding reference of javascript function)
string strInsertRecord = "InsertRecord(" + hlInsertRecord.ClientID + ",pnlInsertRecordMsg);return false;";
hlInsertRecord.Attributes.Add("onclick", strInsertRecord);
Please note: autoOpen:true and i have check my code with uncommenting open dialog
In .JS File
function InsertRecord(hlInsertRecord, pnlInsertRecordMsg) {
$(document).ready(function () {
//--------Message Box Start-------------------
// increase the default animation speed to exaggerate the effect
$.fx.speeds._default = 900;
$(function () {
$(pnlInsertRecordMsg.id).dialog({
autoOpen: true,
resizable: false,
show: "highlight",
hide: "fade"
});
// $(hlInsertRecord.id).click(function () {
// $(pnlInsertRecordMsg.id).dialog("open");
// return false;
// });
});
//--------Message Box End-------------------
pnlInsertRecordMsg.innerHTML = "Please wait, we are sending your request...";
$.ajax({
type: "POST",
url: hlInsertRecord.href,
success: OnInsertRecordSuccess,
error: OnInsertRecordFail
});
//});
function OnInsertRecordSuccess(response) {
hlInsertRecord.innerHTML = "Record Inserted";
pnlInsertRecordMsg.innerHTML = response;
setTimeout(function () { $(pnlInsertRecordMsg.id).dialog("close"); }, 2000);
}
function OnInsertRecordFail(response) {
pnlInsertRecordMsg.innerHTML = "Oops we are unable to send your request. Please try again!!!";
setTimeout(function () { $(pnlInsertRecordMsg.id).dialog("close"); }, 10000);
}
});
}
A: I am not getting why you use this $(pnlInsertRecordMsg.id)
I think here should $('#pnlInsertRecordMsg').dialog
If i am wrong then correct me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using mysql triggers on 2 unrelated tables I need to create a user activity log which I then insert into the database. And for this, I'm thinking of using mysql triggers instead of placing a query that would do this on every successful query.
The 2 tables have no relationship at all.
Here's an example:
table_fruits
*
*fruit name
*flavor
table_log
*
*user id
*name of table
*time stamp
table_users
*
*user id
Now every time I insert on table fruits, the trigger that would insert the values into table_log would also executes. My problem here is getting the user id which is stored in another table. How do I determine which user id to insert. As far as I know triggers doesn't require parameters, so I can't probably use that to supply the id from my script.
Any ideas? Should I just use stored procedures for this?
A: There are 3 approaches to this:
*
*As you mentioned, use a stored proc to insert into both main table and a log table
*Store the user ID (supplied by the app) as a column in main (fruit) table as "inserted_by" column; then have the trigger populate the log table and read the user from the main table.
*Have the trigger automatically figure out the userid. This has two flavors:
*
*User IDs exist on applications side, but NOT on database side (e.g. a user logs in to a web page, but the CGI backend code always connects to a database as special "http" database user).
*User ID from the app actually connects to DB as identically named database user.
In this case, you should use USER() (but NOT current_user() which instead returns whoever created the trigger, or more precisely, which ID was used for trigger permission check)
A: When you insert into the fruits table, you also know the user_id value.
I would suggest create an blackhole table like so:
CREATE TABLE bh_fruit (
user_id integer not null,
fruit_name varchar(255),
flavor varchar(255)
) ENGINE = BLACKHOLE;
Put a trigger on the blackhole table.
DELIMITER $$
CREATE TRIGGER ai_bh_fruit_each AFTER INSERT ON bh_fruit FOR EACH ROW
BEGIN
INSERT INTO fruit (fruit_name, flavor) VALUES (NEW.fruit_name, NEW.flavor);
INSERT INTO log (user_id, tablename) VALUES (NEW.user_id, 'fruit');
END $$
DELIMITER ;
Now your php code becomes:
$user_id = mysql_real_escape_string($user_id);
$fruit = mysql_real_escape_string($fruit);
$flavor = mysql_real_escape_string($flavor);
$sql = "INSERT INTO bh_fruit (user_id, fruit_name, flavor)
VALUES ('$user_id','$fruit','$flavor')";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Mysql Datasource is absent in datasource in data connections I installed MySQL server in my desktop, but MySQL is absent from the datasource list in dataconnections.
This is what I have:
This is what I need
A: You need to install MySql Connector API.
EDIT:
How to connect to a MySQL Data Source in Visual Studio
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to do processing for a range of dates which are within the upper and lower limit set by 2 date variables I have with me 2 dates in different date variables in a java desktop application. Now I want to create a loop that does some processing for each date within these 2 dates. (Excluding scenario where date= Upper bound value of date but including scenario where date=lower bound value of date).
I do understand basic usage of dates in java, I just want to know, is there any easy way of looping through all dates between these 2 dates, and then do some processing for each date?
Another question related to dates- how do I obtain only the current system date in java, as well as the year portion of a date variable (For getting year portion of a date do I have to put the entire value of date variable into a string variable and then extract relevant portion that represents year?)
A: Here is a sample: http://helpdesk.objects.com.au/java/how-can-i-iterate-through-all-dates-in-a-range
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
public class DateIterator
implements Iterator<Date>, Iterable<Date>
{
private Calendar end = Calendar.getInstance();
private Calendar current = Calendar.getInstance();
public DateIterator(Date start, Date end)
{
this.end.setTime(end);
this.end.add(Calendar.DATE, -1);
this.current.setTime(start);
this.current.add(Calendar.DATE, -1);
}
public boolean hasNext()
{
return !current.after(end);
}
public Date next()
{
current.add(Calendar.DATE, 1);
return current.getTime();
}
public void remove()
{
throw new UnsupportedOperationException(
"Cannot remove");
}
public Iterator<Date> iterator()
{
return this;
}
public static void main(String[] args)
{
Date d1 = new Date();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 22);
Date d2 = cal.getTime();
Iterator<Date> i = new DateIterator(d1, d2);
while(i.hasNext())
{
Date date = i.next();
System.out.println(date);
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Updated Value in SQL Server specially in SQL server 2005 How can detect an updated value in a Trigger specially in SQL Server 2005?
A: IF UPDATE (mycol1)
e.g.
CREATE TRIGGER reminder
ON Person.Address
AFTER UPDATE
AS
IF ( UPDATE (StateProvinceID) OR UPDATE (PostalCode) )
BEGIN
RAISERROR (50009, 16, 10)
END;
GO
Ref.
If you are refering to the actual values, these are held in the inserted and deleted tables. See Using the inserted and deleted Tables
A: Note that you shouldn't try to get the value because triggers should be coded to deal with multiple row changes
That said, you can use the special DELETED and INSERTED tables
CREATE TRIGGER TRG_SomeTable_U ON dbo.SomeTable AFTER UPDATE
AS
-- DECLARE @ TABLE ...
-- INSERT HistoryTable
-- whatever
SELECT
...
FROM
INSERTED I
JOIN
UPDATED U ON I.PK 0 U.PK
WHERE
I.SomeColumn <> U.SomeColumn -- does not handle NULLs
GO
A: I found this answer true !!
An UPDATE trigger is used to perform an action after an update is made on a table.
CREATE TRIGGER tr_Orders_UPDATE
ON Orders
AFTER UPDATE
AS
--Make sure Priority was changed
IF NOT UPDATE(Ord_Priority)
RETURN
--Determine if Priority was changed to high
IF EXISTS (SELECT *
FROM INSERTED a
JOIN DELETED b ON a.Ord_ID=b.Ord_ID
WHERE b.Ord_Priority <> 'High' AND
a.Ord_Priority = 'High')
BEGIN
DECLARE @Count tinyint
SET @Count = (SELECT COUNT(*)
FROM INSERTED a
JOIN DELETED b ON a.Ord_ID=b.Ord_ID
WHERE b.Ord_Priority <> 'High' AND
a.Ord_Priority = 'High')
PRINT CAST(@Count as varchar(3))+' row(s) where changed to a priority of High'
END
go
In Part I the INSERT trigger watched for orders with a priority of 'High.' The UPDATE trigger watches for orders whose priority are changed from something else to High.
The IF statement checks to see if the Ord_Priority value was changed. If not we can save some time by exiting the trigger immediately.
The deleted table holds the pre-UPDATE values and inserted table holds the new values. When the tables are joined it is easy to tell when the priority changes from something else to High.
Reference
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: fork and execlp When I use fork to create a new child process and then call execlp syscall to run a new program in the child. The process ids that I get in the child process after execlp and I get from waitpid syscall after the child terminates are different.
For example, getpid() returns 7103 in the child and waitpid returns 7101 in the parent.
I guess something happens after execlp runs. Can anyone explain this. Thanks.
BTW, I run my code on Fedora.
Here is the code:
/* program parent */
if ((pid = fork()) < 0){
perror("fork failed");
exit(2);
}
if (pid == 0){
// child
execlp("xterm", "xterm", "-e", "./echo_cli", "127.0.0.1", (char *)0);
exit(0);
}
/* ... */
// sig_chld handles SIGCHLD singal
void sig_chld(int signo){
pid_t pid;
int stat;
while ((pid = waitpid(-1, &stat, WNOHANG)) > 0){
printf("Child %d terminated\n", pid);
}
return ;
}
/* program echo_cli */
pid = getpid();
A: You're executing xterm, not echo_cli. Your child's child will of course report a different PID.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Disabling MongoDB logging on Heroku/MongoHQ After getting the "logging negatively" warning, I guess ther's a way to disable on Heroku/MongoHQ too :
2011-10-02T05:35:38+00:00 heroku[web.1]: Starting process with command `thin -p 54227 -e production -R /home/heroku_rack/heroku.ru start`
2011-10-02T05:35:44+00:00 app[web.1]: MongoDB logging. Please note that logging negatively impacts performance and should be disabled for high-performance production apps.
Does enybody know how to disable MongoDB logging on Heroku/MongoHQ ?
Thanks
Luca
A: I guess from the error message that you are using Mongoid. You can disable the logger by setting it to nil.
Mongoid.logger = nil
I believe there's also a way to set it to nil in the configuration block.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Audio switching in background mode AVFoundation - objective-c I have an array of Audio objects called LocalAudio. For playing audio I use AVAudioPlayer. I've implemented delegate method: audioPlayerDidFinishPlaying:,where i put code to switch next sound in my LocalAudio array.
-(void) audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
[self switchTrack:nextAudioIndex];
}
Audio plays in background but sound doesn't switch. So how to switch audio in background mode?
For debugging i use iPad 2.
A: I use the same logic and it is working, so something else have to be incorrect.
EDIT:
Example
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
if (flag == NO)
NSLog(@"Playback finished unsuccessfully");
[player setCurrentTime:0.0];
[backgroundMusicPlayer release];
backgroundMusicPlayer = nil;
if (![music isEqualToString:@"10"]) {
[self playMusicWithKey:[NSString stringWithFormat:@"%i", ([music intValue] + 1)] timesToRepeat:0];
}
}
where
- (void) playMusicWithKey:(NSString*)theMusicKey timesToRepeat:(NSUInteger)theTimesToRepeat {
NSError *error;
NSString *path = [musicLibrary objectForKey:theMusicKey];
// Initialize the AVAudioPlayer
if (backgroundMusicPlayer == nil) {
backgroundMusicPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];
[backgroundMusicPlayer setDelegate: self];
[backgroundMusicPlayer setVolume:backgroundMusicVolume];
musicLenght = backgroundMusicPlayer.duration;
}
// If the backgroundMusicPlayer object is nil then there was an error
if(!backgroundMusicPlayer) {
NSLog(@"ERROR SoundManager: Could not play music for key '%@'", theMusicKey);
return;
}
// Set the number of times this music should repeat. -1 means never stop until its asked to stop
[backgroundMusicPlayer setNumberOfLoops:theTimesToRepeat];
// Play the music
[backgroundMusicPlayer prepareToPlay];
[backgroundMusicPlayer play];
}
A: Thanks Vanya. I've also found good solution for people who using AVPlayer. Works perfect:
http://www.crocodella.com.br/2011/01/using-avplayer-to-play-background-music-from-library/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the difference between Uri.ToString() and Uri.AbsoluteUri? As a comment to an Azure question just now, @smarx noted
I think it's generally better to do blob.Uri.AbsoluteUri than
blob.Uri.ToString().
Is there a reason for this? The documentation for Uri.AbsoluteUri notes that it "Gets the absolute URI", Uri.ToString() "Gets a canonical string representation for the specified instance."
A: Why not check and use the correct one?
string GetUrl(Uri uri) => uri?.IsAbsoluteUri == true ? uri?.AbsoluteUri : uri?.ToString();
A: Since everybody seems to think that uri.AbsoluteUri is better, but because it fails with relative paths, then probably the universal way would be:
Uri uri = new Uri("fuu/bar.xyz", UriKind.Relative);
string notCorruptUri = Uri.EscapeUriString(uri.ToString());
A: Additionally: If your Uri is a relative Uri AbsoluteUri will fail, ToString() not.
Uri uri = new Uri("fuu/bar.xyz", UriKind.Relative);
string str1 = uri.ToString(); // "fuu/bar.xyz"
string str2 = uri.AbsoluteUri; // InvalidOperationException
A: Given for example:
UriBuilder builder = new UriBuilder("http://somehost/somepath");
builder.Query = "somekey=" + HttpUtility.UrlEncode("some+value");
Uri someUri = builder.Uri;
In this case,
Uri.ToString() will return a human-readable URL: http://somehost/somepath?somekey=some+value
Uri.AbsoluteUri on the other hand will return the encoded form as HttpUtility.UrlEncode returned it: http://somehost/somepath?somekey=some%2bvalue
A: The following example writes the complete contents of the Uri instance to the console. In the example shown,
http://www.cartechnewz.com/catalog/shownew.htm?date=today
is written to the console.
Uri baseUri = new Uri("http://www.cartechnewz.com");
Uri myUri = new Uri(baseUri, "catalog/shownew.htm?date=today");
Console.WriteLine(myUri.AbsoluteUri);
The AbsoluteUri property includes the entire URI stored in the Uri instance, including all fragments and query strings.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "112"
} |
Q: unique constraint in couchrest-model What is the best practice in Couchrest for implementing something like a unique constraint. I could do this with the _id , but what if I want to implemnet it on multiple fields, not necesarily as a composite, but even separately. Say for e.g. I want email ID and the username both to be unique, just to point out an example.
Is there a best practice around doing this without using the _id field.
A: The only way to enforce uniqueness in CouchDB is with _id field.
I believe the best practice for other things which need uniqueness is to allow the client to store it, and then check for uniqueness as an external program (or thread, or cron job, etc.) and then react to that. For example, a map/reduce view can easily produce a count of identical field values, thus searching for fields with count > 1 is easy. Next, correct any duplicates you find.
You can even treat this as a simple workflow with request/reject or request/approve steps. Store the initial document, but it is not official until e.g. it has "confirmed":true. It only receives a confirmation after your offline checker has performed the above checks.
I think in real-world applications, people developing with CouchDB postpone uniqueness constraints, for the same reason people try not to prematurely optimize. You will probably notice that 99% of users always input a unique email address anyway, so trying to enforce uniqueness all the time is just creating a problem for yourself that you don't need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624996",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: django modelform showing an existing instance I have the following model:
ynChoice = ((None, 'Acknowledgement not required'),
(True, 'Acknowledgement and consent required'),
(False, 'Acknowledgement required but consent not required'))
class AbstractForm(models.Model):
"""base class for the below 2 classes"""
#require users to say yes and no other than acknowledging #null = not required
yes_no_required = models.NullBooleanField(choices=ynChoice, blank=False)
and I map it to my modelform:
class LiveConsentForm(forms.ModelForm):
ynChoice = (
('', '---------------'),
(None, 'Acknowledgement not required'),
(True, 'Acknowledgement and consent required'),
(False, 'Acknowledgement required but consent not required'),
)
yes_no_required = forms.TypedChoiceField(choices=ynChoice,empty_value='')
class Meta:
model = ConsentFormTemplate
Here, ConsentFormTemplate is a subclass of AbstractForm. I wrote yes_no_required in the form because the empty value for the nullbooleanfield's formfield will return a None, which I do not want.
Now, when I want instantiate my form to show an existing record, LiveConsentForm(instance=templateInstance), I run into a problem.
My templateInstance.yes_no_required's value is None, but when the html is rendered, ------ is selected. (I do not have such trouble when yes_no_required is either True or False)
Need some help here.
A: ok i've looked at the forms.fields and
turns out that when rendering to html, turns out that None is just treated as '', and empty_value is not taken into consideration here. I'm not sure why @Ignacio Vazquez-Abrams dude took away his answer, so if you can please put it back up again, i'll accept it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7624997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: write chars into DB with correct character-set I met a problem writing Chinese characters into an Oracle database. Here's some information for your reference.
*
*Environment: Oracle 8
select userenv('language') form dual;
returns
American.America.UTF8
*Developing:
.NET2/C#
*Client characterset:
gb2312
I simply test write value into the table manually, the result is correct and should be as the following:
VALUE: 朋友 //chinese word means 'friend'
DUMP: 197,243,211,209 //caculated by Oracle dump() function
Using code to write, code snap as following:
Encoding def = Encoding.Default;
Encoding utf8 = Encoding.UTF8;
byte[] bytes = def.GetBytes("朋友");
//For debug
//string debug = "";
//foreach(byte b in bytes)
// debug += b.ToString() + " ";
//Debug.WriteLine(debug); //That will display 197,243,211,209 as the same as the Dump value mentioned
string value = utf8.GetString(bytes);
//I also try, string value = utf8.GetString(Encoding.Convert(def,utf8,bytes))
string sql = String.Format("UPDATE T SET C='{0}' WHERE...",value);
//execute the sql...
After that, the value stored in the DBMS is not right, both value and it's dump result.
A: Decimal Hexadecimal Binary
197 c5 1100 0101
243 f3 1111 0011
211 d3 1101 0011
209 d1 1101 0001
Looking at Wikipedia We see that 197 is the first byte of a two byte sequence, 243 is the first byte of a four byte sequence, 211 is the first byte of a two byte sequence, 208 is the first byte of a two byte sequence. That is not valid UTF-8. Could you tell us what the unicode code points for the two characters 朋友 are?
EDIT Ah, GB2313, c5f3 is Unicode code point u+670b. And d3d1 is u+53cb. (Found using converter at http://demo.icu-project.org/icu-bin/convexp?conv=ibm-1383_P110-1999&ShowLocales&s=ALL#ShowLocales)
Double check the client character set that the Oracle client is using. What I have seen (on Oracle 10gR2) is that if the Oracle's client has the same character encoding as the database server, then the characters will not be translated (because they are the same character set) but they will not be validated. It appears that they were the same at the time of the manual insert and the GB2313 values were inserted for the characters you wanted, which is invalid inside the DB, since it is utf8.
Note, Oracle's "utf8" character set is not full modern UTF-8, but instead CESU-8. Not an issue in this case, since these characters sit on the Basic Multilingual Plane, and have the same encoding in UTF-8 and CESU-8. The earliest reference I could find was for Oracle 8i: http://download.oracle.com/docs/cd/A87860_01/doc/server.817/a76966/appa.htm#971460.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: setcookie and redirect loads page from cache I have a page that sets a cookie and then redirects the user to the same page:
setcookie('name', $value, time() + $time, '/', '.domain.com');
header("Refresh: 0; url={$to}");
The problem is that after refresh the page gets loaded from cache and I can't use the cookie. I have to manually refresh (cmd+r) the page to actually be able to use the cookie.
I've also tried using
header("Location: {$to}");
for the refresh but with no success.
One method that works is appending a timestamp to the end of the page, like
$to .= '?' . time();
butthis is not something I want the user to see in his address bar.
I couldn't find any way to force the browser to reload the page rather than load it from its cache.
Thanks!
A: try to do this headers
header("Cache-Control: no-cache");
header("Pragma: no-cache");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Django models.Model superclass I would like to create a models.Model class that doesn't became part of the database but just an interface to other models (I want to avoid repeating code).
Something like that:
class Interface(models.Model):
a = models.IntegerField()
b = models.TextField()
class Foo(Interface):
c = models.IntegerField()
class Bar(Interface):
d = models.CharField(max_length='255')
So my database should have only Foo (with a,b,c collumns) and Bar (with a,b,d) but not the table Interface.
A: "Abstract base classes"
Abstract base classes are useful when you want to put some common information into a number of other models. You write your base class and put abstract=True in the Meta class. This model will then not be used to create any database table. Instead, when it is used as a base class for other models, its fields will be added to those of the child class.
A: You can define your classes like this:
from django.db import models
class CommonInfo(models.Model):
name = models.CharField(max_length=100)
age = models.PositiveIntegerField()
class Meta:
abstract = True
class Student(CommonInfo):
home_group = models.CharField(max_length=5)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Fetching cursor location and highlighted text in textarea using JQuery Having a textarea in a form I am trying to do several things:
*
*fetch the current location of the cursor within the text area
*fetch the current selection within the textarea
*insert some text at the current cursor location
*replace the current selection by some other text
As I am already using JQuery, I'd prefer a solution that works smoothly with that.
Any pointers how to achieve the above would be appreciated.
A: There are many jQuery plugins for this. Here's a good one I've used before:
http://plugins.jquery.com/project/a-tools
To fetch the current location of the cursor within the text area:
$("textarea").getSelection().start;
To fetch the current selection within the textarea:
$("textarea").getSelection();
this returns an object like this:
{
start: 1, // where the selection starts
end: 4, // where the selection ends
length: 3, // the length of the selection
text: 'The selected text'
}
To insert some text at the current cursor location:
$("#textarea").insertAtCaretPos("The text to insert");
To replace the current selection by some other text:
$("#textarea").replaceSelection('This text will replace the selection');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: iOS:How to open camera with animation effect? I want to open camera with animation effect, so that it should appear that camera is opening in the parent screen only.
I am using camera overlay screen and on click event of button in parent screen,camera overlay screen is opening,in camera overlay screen there is a cancel button to close the camera,so while closing the camera again I need to show the animation effect that it should appear that now camera is closed in the same parent scree.
I have tried kCATransitionMoveIn but not fully satisfied,if any once has better solution please help me.
CATransition * contentAnimation = [CATransition animation];
contentAnimation.type = kCATransitionMoveIn;
contentAnimation.subtype = kCATransitionFromBottom;
contentAnimation.duration = 1.0;
contentAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseOut];
[[self.view layer] addAnimation:contentAnimation forKey:kCATransition];
//self.view.hidden = YES;
[CATransaction commit];
// Show the scanner overlay
[self presentModalViewController:overlayController.parentPicker animated:TRUE];
A: This could be somewhat tidious but try out downloading ZBar SDK which is .dmg file. and double click it. You will find Examples Folder. In that you will find 4 apps. Try out that app in Device only. You will find amazing CAMERA open with animation effect.
A: I have resolved the issue and I have taken the ZBar SDK example as a reference and this link1 and link2 also helped me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Using getLoginStatus to fire a Js redirect I'm trying to use Fb.getLoginStatus to implement a Js redirect to another page IF the user is logged in to Facebook upon coming to my website AND connected to my Fb app. It's not working and I don't know why! Is this possible? Any advice would be gratefully received.
Here's my code - I'm using a PHP include to insert it into my page, and it appears the Fb Javascript SDK init function is working fine:
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init({
appId : 'my-app-id',
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true, // parse XFBML
channelUrl : 'http://www.jamesherlihy.com/sandbox/fb-channel.html', // Custom Channel URL
oauth : true //enables OAuth 2.0
});
};
(function() {
var e = document.createElement('script');
e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
FB.getLoginStatus(function(response) {
/* if user is logged in to Fb and connected to Soulmap, redirect them to logged-in homepage */
if (response.authResponse){
window.location = "http://www.jamesherlihy.com/fb-03-logged-in.php";
}
/* if user is NOT logged in to Fb and/or connected to Soulmap, do not execute any script */
});
</script>
A: You need to make sure you have a <div id="fb-root"></div> somewhere in your page because the script references it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Distorted canvas shape when using dynamic dimensions I'm trying to create a guillotine-blade shaped trapezium using the canvas element, based on the current viewport dimensions full width, half height), but every time I do this the coordinates seem to be out of proportion (and sometimes the shape that I draw seems magnified - the edges are pixelated as though I've zoomed in x10)
My code currently looks like this (I'm using jquery 1.5.x) - it's on jsfiddle
//Get the page dimensions:
var page = {
width:$(window).width(),
height:$(window).height()
};
var halfHeight = page.height/2;
var canvas = $('<canvas />', {width:page.width, height:page.height});
var blade1 = canvas[0].getContext('2d');
blade1.fillStyle = "#000";
blade1.beginPath();
blade1.moveTo(0,0); // topleft
blade1.lineTo(page.width, 0); //topright
blade1.lineTo(page.width,halfHeight/2); //right, quarterway down
blade1.lineTo(0,(halfHeight)); //left, halfway down
blade1.closePath();
blade1.fill();
$(canvas[0]).css({backgroundColor:'#fc0'});
$(canvas[0]).prependTo('body');
I think my calculations make sense as it's a simple shape, but it's not fitting inside the canvas at all.
Can anyone help me make this shape work inside a dynamically generated canvas element? THe reason I'm doing it all in JS is that I only want to do this if the referrer is outside the current domain.
A: Edit: It looks like you have to set display: block; on the canvas element in jsfiddle to eliminate the additional spacing that's causing the scrollbars. Here's the corrected version: http://jsfiddle.net/LAuUh/3/
You will probably want to hook into the window resize event so that you can re-draw the guillotine and resize the canvas. Otherwise, if the user resizes their browser the background won't fit anymore.
I'm not quite sure where the extra few pixels of spacing are coming from in the jsfiddle example, but tested on a standalone page this code seems to achieve what you're looking for:
var vpW = $(window).width();
var vpH = $(window).height();
var halfHeight = vpH/2;
var canvas = document.createElement("canvas");
canvas.width = vpW; canvas.height = vpH;
var blade1 = canvas.getContext('2d');
blade1.fillStyle = "#000";
blade1.beginPath();
blade1.moveTo(0,0); // top left
blade1.lineTo(vpW, 0); // top right
blade1.lineTo(vpW,halfHeight / 2.0); // right, quarterway down
blade1.lineTo(0,halfHeight + halfHeight / 2.0); // left, threequarters down
blade1.closePath();
blade1.fill();
$(canvas).css('backgroundColor','#fc0');
$(canvas).prependTo('body');
With this CSS:
html, body {
width: 100%;
height: 100%;
margin: 0px;
padding: 0px;
}
The main issue that I fixed was the coordinates you were using for your guillotine shape. In addition, using this syntax:
var canvas = $('<canvas />', {width:page.width, height:page.height});
when you create your canvas element is not good as it applies the width and height as style attributes. With canvas elements, the CSS width and height controls magnification while the DOM-level object width and height attributes control the actual dimensions of the canvas.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adding an Access 2003 System DSN in Windows 7
Possible Duplicate:
Is there a Windows 7 ODBC driver for Access?
I'm migrating an Access 2003 app from Windows XP to Windows 7. In the ODBC Data Source Administrator - User or System DSN, when I click on "Add", the only selection is SQL Server. Where/how do I install the ODBC for Access so it's available
A: Apparently using odbcad32.exe under %WINDIR%\SYSWOW64, you will find all the 32bit drivers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Which is the fastest way to search a value within a set of many "range" objects in Python I have a list of many Python objects like this:
class RangeClass(object):
def __init__(self,address,size):
self.address=address
self.size=size
#other attributes and methods...
Then, I have a list (rangelist) of RangeClass objects.
I need to find within which range a given value is.
I can use some code like this:
for r in ragelist:
if(value>=r.address and value<(r.address+r.size)):
return r
return None
But I think there is a faster way. Ranges have arbitrary size, but we can assume that they don't overlap.
Thank you.
A: If you have many values to test, then you could use the bisect module to find which range the values are in more quickly.
If
*
*m = the number of values to test, and
*n = len(rangelist)
then looping through the values and rangelist as you suggest would take O(m*n) time.
If you use bisection, then you must first sort the starting addresses O(nlogn) and find each value's place in rangelist O(m*logn).
So if
O(nlogn + m*logn) < O(m*n)
then bisection wins. For large n, O(m*logn) is miniscule compared to O(m*n).
So the inequality above would be true if
O(nlogn) < O(m*n)
or equivalently, when
C log(n) < m
for some constant C.
Thus, when n is large and C log(n) < m, you might try something like
import bisect
class RangeClass(object):
def __init__(self,address,size):
self.address=address
self.size=size
def __str__(self):
return '[{0},{1})'.format(self.address,self.address+self.size)
def __lt__(self,other):
return self.address<other.address
rangelist=sorted([RangeClass(i,1) for i in (1,3,4,5,7.5)])
starts=[r.address for r in rangelist]
def find_range(value):
start_idx=bisect.bisect(starts,value)-1
try:
r=rangelist[start_idx]
except IndexError:
return None
start=r.address
end=r.address+r.size
if start<=value<end:
return rangelist[start_idx]
return None
print(','.join(str(r) for r in rangelist))
for value in (0,1,1.5,2,3,4,5,6,7,8,9,10):
r=find_range(value)
if r:
print('{v} in {r}'.format(v=value,r=str(r)))
else:
print('{v} not in any range'.format(v=value))
A: Not really. All you can do is take advantage of Python's relational operator chaining.
if r.address <= value < (r.address + r.size):
You could also define __contains__ on RangeClass to allow you to use in to find it instead.
class RangeClass(object):
...
def __contains__(self, val):
return self.address <= val < (self.address + self.size)
...
if value in r:
A: Implement the comparison operator in Range, have the range list sorted, and use bisect to search for the range a value belongs in:
import bisect
def find_range(value):
index = bisect.bisect(rangelist, value)
if index not in (0, len(rangelist)):
index -= 1
return rangelist[index]
A: Thank you to everyone,
I am actually using the method proposed by unutbu.
Moreover, I add another optimization:
if(value <= first_range_value or value >= last_range_value):
return None
Where first_range_value and last_range_value have been computed before, and they are the smallest r.address value and the largest r.address+r.size value .
This is worthing in my application, but it really depends on the distribution of ranges and values.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I properly go about building an Android App? Specifically, what kind of conventions in terms of Activities does one follow? If I'm building a program with many screens, do I create an Activity for each screen?
If I want to properly navigate between Activities, do I stick intents in every activity? I want to make this code as clean and efficient as possible
A: In short: yes.
Although you can work around this by dynamically altering your UI inside a single Activity, android recommends that each application 'activity' should be coded in a separate Activity class.
See this quite good article on the android recommended way.
This Intent/Activity design pattern has many advantages, one of it being that you can override
and extend other application activities with your own with matching intent filters.
I see that you are concerned about efficiency. Be assured that the Activity switching overhead is highly optimized in android (for example, a Dalvik instance is always preallocated, ready to handle a new activity without the context switching overhead).
A: The short answer: It really depends on how you want to lay out your app.
For example, if you want to have tabs, you can use a tabhost, which will easily switch between Activities for you.
If you want to launch Activities yourself, you can launch Activities with intents (as you mentioned in your question). An example is launching intents from a Button or ListView. For a ListView (with an OnItemClickListener) you might have something like:
(your ListView).setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int index,
long arg3) {
Intent intent = new Intent(TheActivityYou'reLaunchingFrom.this, OtherActivityYouWishToLaunch.class);
startActivity(intent);
}
}
The links I've provided have really good examples. When you wish to end the activity you launched from another activity, you can call finish(), which should be called from a different event (like clicking on a Button).
Also keep in mind that you can launch Activities with hopes of receiving data from the launched activity via startActivityForResult, which uses Bundles.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Which connectionstring to use in EF Code-first with an existing database The existing database was created in the project itself and resides on App_Data as prompted by visual studio while adding a new sql database item to the project.
So, should i use this string :
data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Database.mdf;User Instance=true"
Or this one
Data Source=.\SQLEXPRESS;Database=Database22;Integrated Security=SSPI;
A: I am not following why you should use those connection strings with EF. Take a look at this:
How to: Build an EntityConnection Connection String
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Web application architecture with web services I want to build a web application + web service just to learn some new technologies, and I was thinking about the architecture of the projects in the application. I made an architectural diagram (never made one before), but I was wondering if this is a good one, if it's reusable, and if I should stick with it.
Here is the diagram, waiting for your opinions. Thanks.
A: Your architecture diagram is in line with a common 3-tier architecture. Some other images providing the same idea.
The seperation between the UI / logic and database is needed as deployment pre-requisite, being able to scale-up and scale-out your application. The seperation between the DAL and the data source is for sake of DB technology abstraction, so you can privide compatibility with diffent DB technologies without your UI and business logic knowing this.
A bit more detailed picutre showing the different components and their placement in the layer pattern. But in principle, all follow the same high-level concept you have drawn.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there any way to extend an object? In scala, we cannot extend object:
object X
object Y extends X
gives an error error: not found: type X
In my case someone has defined some functionality in an object and I need to extend it (basically add another method). What would be the easiest way to extend this object?
A: As so often the correct answer depends on the actual business requirement. Extending from an object would in some sense defy the purpose of that object since it wouldn't be a singleton any longer.
What might be a solution is to extract the behavior into an abstract trait. And create objects extending that trait like so:
trait T{
// some behavior goes here
}
object X extends T
object Y extends T {
// additional stuff here
}
A: The only way to share code between two objects is by having one or more common superclass/trait.
A: Note that starting in Scala 3, you can alternatively use composition (instead of inheritance) via export clauses which allow defining aliases for selected members of an object:
object X { def f = 5 }
object Y {
export X._
def g = 42
def h = f * g
}
Y.f // 5
Y.g // 42
Y.h // 210
Note that you can also restrict which members you want to export:
object X { def f = 5; def g = 6 }
object Y { export X.f }
Y.f // 5
Y.g
^^^
value g is not a member of Y
A: If you want use methods and values from another object you can use import.
object X{
def x = 5
}
object Y{
import X._
val y = x
}
A: You can convert parent into class + companion object, and then have child extend class E.g.
in Parent.scala
class Parent {}
object Parent extends Parent {}
And then in Child.scala
object Child extends Parent {}
Yes, it's more a hack than a solution.
A: You can't actually extend an object, because that would create two of it, and an object by definition exists only once (edit: well, that's not quite true, because the object definition can be in a class or method).
For your purposes, try this:
object X {
}
object Y {
def a = 5
}
implicit def xToY(x: X.type) = Y
println(X.a)
It doesn't actually extend, but it does allow you to call new methods on it than were originally defined.
A: This is a Scala 3 of Owen's answer: You can extend a companion object using extensions.
object X:
def a = 5
end X
// Somewhere else, another file where X is visible
extension (x: X.type)
def b = 42
end extension
// Somewhere else, another file where
// both X and the extension are visible
@main def main =
println(X.a)
println(X.b)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "63"
} |
Q: Update and delete data in database mysql I use codeigniter. i have following values as json_encode in database row, i want delete value 3 in row 1 and values 14 & 5 in database table.
DELETE -> value 3 on row 1 & values 14, 5 on rows 2
UPDATE -> value 2 to 8 on row 1 & value 3 to 17 on rows 2.
How is query it for values json?
Row 1:
id=1
[{
"hotel_id": ["3"]
}, {
"hotel_id": ["2"]
}, {
"hotel_id": ["1"]
}]
Row 2:
id=2
[{
"hotel_id": ["14"]
}, {
"hotel_id": ["5"]
}, {
"hotel_id": ["4"]
}, {
"hotel_id": ["3"]
}, {
"hotel_id": ["2"]
}, {
"hotel_id": ["1"]
}]
A: What most of the commenters are trying to say is that your problem is a very common one when storing serialized data in the DB (like JSON strings) - That is exactly why this is considered bad practice.
All the wonderful tools of relational databases, like indexing, sorting, grouping and querying according to any column are gone once the data is stored as a big pile of characters the DB can't parse.
The solution is to save the actual DATA in the DB, and format it as JSON only on the application side, for use when needed.
In your case, you can create a table like hotels_to_users (I am doing some guesswork here about the meaning of your data, hoping you get it even if it's not exactly what you need). This table will look like:
user_id (?) | hotel_id
1 | 1
1 | 2
2 | 14
This will make it very easy to query, update, insert and delete any specific hotel to any user.
Hope this makes sense and that you are able to make that change, otherwise your problem can be solved with either some MySQL string functions like REPLACE and SUBSTR, or by doing all the work in the application code and saving a new JSON when done. Either way, maintaining it will be hard and require more effort in the long term.
A: Storing data as json_encode is really a bad choice since you can't do anything trough sql with them.
You have to take your data, read it (json_decode), do stuff with php and then replace the new data with a new json_encode. Really bad.
Think changing the way you store that values. Maybe a support table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: what is your suggestion for a simple javascript editor with code completion? could you please let me know about good IDEs available for javascript programming?
I am looking for a no-frills, simple editor focussing primarily on the below functionalities -
a) syntax highlighting
b) auto-suggest for code completion
Note - I use windows 7, and have tried Aptana Studio. I do not want editors as powerful as aptana..something like simple looking notepad++, with a feature rich code-completion algorithm would do.
If this question is off topic, I apologize.
Thanks.
A: Sublime Text 2 is definitely the way to go.
I've used Notepad++ in the past since I didn't want to use a full fledged IDE, but was never really happy with it. I've since switched to Sublime Text, and never looked back.
A: Well I guess after a lot of googling, I've found the best solution to my own question :)
Here's what I think is the best Javascript IDE: CODELOBSTER IDE
http://www.codelobster.com/js_editing.html
Why?
1. Code-autocomplete
2. Syntax Highlighting
3. Not just JS, the above two features are functional for PHP, xHTML, CSS..!!
4. Did I mention its FREEEEEEEEEEEEE....?
Guys, let me know how you find this software.
A: How about eclipse and a full blown javascript, jsp environment eclipse.org.... Granted the learning curve can be huge, its powerful!
A: PsPad or Notepad++ are simple but powerfull editors for many languages.
You also have the big Eclipse IDE for JavaScript.
Other JavaScript only editor :
FreeJavaScript editor
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to Solve this "missing ) argument after list"? This looks like a trivial question, but I am not sure how to deal with it. I have a DIV tag generated from javascript that goes like this:
$('#results')
.append('<DIV id='
+ A.pid
+ ' onmouseover=function(){google.maps.event.trigger(marker, 'mouseover');};><H3>'
+ A.name
+ '</H3></DIV>');
Firebug is giving me an error "missing ) argument after list" as it does not recognise the ) immediately after 'mouseover'. How do I resolve this?
UPDATE:
I understand this is about escaping quote, just that doing \'mouseover\' produces a syntax error upon mouseover of the DIV and doing "mouseover" produces a blank document.
The syntax error reads: function(){google.maps.event.trigger(marker,
A: You need to escape quote if it's inside another quote:
*
*var x = "I don't like you!";
*var y = 'I don\'t like you!';
*var z = 'echo "this text?";';
To implement it on your case, it would be like this:
'<DIV id='
+ A.pid
+ ' onmouseover=function(){google.maps.event.trigger(marker, \'mouseover\');};><H3>'
+ A.name
+ '</H3></DIV>'
A: You issue is in the use of the ' character to delimit both the function and the arguments in your call.
Either switch one set of ' out for " or use \' around the values of the argument
$('#results')
.append('<DIV id='
+ A.pid
+ ' onmouseover=function(){google.maps.event.trigger(marker, "mouseover");};><H3>'
+ A.name
+ '</H3></DIV>');
//OR
$('#results')
.append('<DIV id='
+ A.pid
+ ' onmouseover=function(){google.maps.event.trigger(marker, \'mouseover\');};><H3>'
+ A.name
+ '</H3></DIV>');
A: You need to put " around the values of your html attributes. Otherwise the browser thinks the attribute ends at the next whitespace and that is exactly right after the (marker, part.
$('#results')
.append('<DIV id="'
+ A.pid + '"'
+ ' onmouseover="function(){google.maps.event.trigger(marker, \'mouseover\');};"><H3>'
+ A.name
+ '</H3></DIV>');
A: Try to generate the following string
'<DIV id=' +
A.pid +
' onmouseover=\"google.maps.event.trigger(marker, \'mouseover\');\"> <H3>' +
A.name + '</H3></DIV>'
A: Several things
*
*Stop putting HTML in all caps. This is the 21st century not the 20th century.
*You don't need an anonymous function for the onmouseover event.
*Wrap attribute values in either single or double quotes (I use double below).
*Read about JavaScript strings and quotes. Here is a tutorial.
Try this
$('#results').append('<div id="' +
A.pid +
'" onmouseover="google.maps.event.trigger(marker, \'mouseover\');"><h3>' +
A.name +
'</h3></div>');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to set textarea height with jQuery There is a table and many textareas in some cells.
The cells with textarea span multiple row (2, 3, 4, or more rows).
I want to make textareas occupy the whole cell areas.
I can do this with jQuery but it takes too long and the browser gives a warning.
$("textarea").each(function() {
$(this).height($(this).parent().height());
});
Is there a better way?
Thanks.
Sam
A: I turned up this test:
http://jsperf.com/jquery-each-vs-for-loop/4
Which (after running the tests) shows that .each() is eclipsed by other iterators in terms of performance. If you can devise a way to use one of the high-performing iterators shown on that page, you will obviously see better results.
edit: this WORKS, but whether or not there's a performance benefit I can't say:
http://jsfiddle.net/T7wzT/1/
var $textarea = $('textarea');
numTextareas = $textarea.length;
for (var i = 0, len = numTextareas; i < len; i++) {
$textarea.eq(i).height($textarea.parent().height());
}
A: Am I missing something or why can't you just use css style height:100% on the textareas?
See this jsFiddle: http://jsfiddle.net/J2njk/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting exported part instance from MEF container How I can the existing instance of an exported part in MEF container . If I have class A which was composed in the container , I need in some places in my code to get the instance , if I call GetExortedValue() , then if class A signed with CreationPolicy.NonShared , then it'll be instantiated again and I need the current one .
Thanks in advance ...
A: Obviously calling GetExportedValue<T> on your container could result on the generation of a new instance of T (depending on the CreationPolicy used for the part), but there is an option to call GetExport<T> which will return you a Lazy<T> instance. This is the singular part that is generated and only generated the once:
var part = container.GetExport<IMyInterface>();
In the above example, part would be an instance of Lazy<IMyInterface>, so when you first access part.Value, the delegate bound in the Lazy<IMyInterface> calls back to the container to create and compose the IMyInterface instance and is returned. Subsequent calls to part.Value will always return this same instance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Need to call three webflow states in parallel We are facing serious performance issues in our application. We need to send three different requests to our backend, when we are using webflow and we are sending them one by one and this is leading to considerable screen loading time.
Can we call three states of webflow in parallel so that we are able to send three requests to our backend in parallel? Or is there any way to load our screen and call one or two methods later?
we need to navigate from retrieveAccInsList view state to accSummary view state but in between i need to send three different Request to backenf as AccSumary screen contain 3 screen merged,so i need data from three different places.but is the required solution
<view-state id="retrieveAccInsList">
<transition on="openAccount" to="detailForAccountAction">
<set name="conversationScope.selectedAccount" value="reqSearchHandler.selectedAccIns" />
<set name="reqSearchHandler.objectToRetrieveCd" value="'RequestSearch'" />
</transition>
</view-state>
<action-state id="detailForAccountAction">
<evaluate expression="accountDetail.getDetailsForAccount(ClientDetailRq)"
result="flowScope.response">
<attribute name="name" value="detailAccountResponse" />
</evaluate>
<transition on="detailAccountResponse.success" to="searchNoteAction" />
<transition on="detailAccountResponse.error" to="retrieveAccInsList" />
</action-state>
<action-state id="searchNoteAction">
<evaluate expression="certNotesHandler.searchForNotes()"
result="flowScope.response">
<attribute name="name" value="noteResponse" />
</evaluate>
<transition on="noteResponse.success" to="searchActivityAction" />
<transition on="noteResponse.error" to="retrieveAccInsList" />
</action-state>
<action-state id="searchActivityAction">
<set name="reqSearchHandler.requestStatus" value="'O'" />
<set name="reqSearchHandler.objectToRetrieveCd" value="'RequestSearch'" />
<evaluate expression="reqSearchHandler.setparam()" />
<evaluate expression="reqSearchHandler.searchForRequest(ReqInquireRq)"
result="flowScope.response">
<attribute name="name" value="activtiyResponse" />
</evaluate>
<transition on="activtiyResponse.success" to="accSummary" />
<transition on="activtiyResponse.error" to="retrieveAccInsList" />
</action-state
A: Sure; use Ajax. But without further details it's tough to say--why would you need to call three webflow states "in parallel"? It's called "flow" because they're linear (at least within a single conversation; I know you can have multiple flows active at once).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Any solution to use non-guessable links in a program? I've been looking for a file hosting site to host my files and my friend offered me a premium account on Box.net.
The problem in this host site (and on many others) is that the links arent guessable, they cant be predicted. That means: If you upload 2 images called "1.jpg" and "2.jpg", the links aren't like
"www.host.com/omar/1.jpg , www.host.com/omar/2.jpg" ,
instead, they are like
"www.host.com/qweqwasd , www.host.com/123lqqwje" ..
So I cant use them on my application since I upload a lot of small site and I cant copy each link manually, it will take days.
Is there a way to override this problem in a program? maybe run a script to get all the links on the site?
A: When you upload a file, presumably the page shown afterwards gives the link - so just parse that page and extract the link from it.
Just think about how you'd get the link if you were a human, and do the same thing in code. (I assume you're already performing the upload in code.)
Alternatively, use a different file hosting site, which lets you specify the filename.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What interval should I use between each WiFi scan on Android? I need to perform Wifi scans at regular intervals. I am encountering a problem when the time interval is set to 1-2 seconds. It seems like I am not getting any ScanResult. Is there a minimum amount of time to set so that the WifiManager is able to perform a successful WiFi scan?
Here is the code. I am using a Service to do the Wifi scan:
public class WifiScanning extends Service{
private static final String TAG = "WifiScanning";
private Timer timer;
public int refreshRate, numberOfWifiScan, wifiScanGranularity;
WifiReceiver receiverWifi = new WifiReceiver();
WifiManager wifi;
StringBuilder sb;
List<ScanResult> wifiList;
List<APData> apdataList;
List<List<APData>>surveyData;
private TimerTask updateTask = new TimerTask() {
@Override
public void run() {
Log.i(TAG, "Timer task doing work");
wifi.startScan();
}
};
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG, "Service creating");
//retrieve the mapRefreshRate from config.xml
XMLOperations test = new XMLOperations();
Configuration config = new Configuration();
config = test.saxXmlParsing(this, 1);
if(config==null)
config = test.saxXmlParsing(this, 2);
refreshRate = Integer.parseInt(config.getMapRefreshRate());
numberOfWifiScan = Integer.parseInt(config.getNumberOfWifiScan_Positioning());
wifiScanGranularity = Integer.parseInt(config.getWifiScanGranularity_Positioning());
timer = new Timer();
Log.i(TAG, "Refresh Rate: "+ String.valueOf(refreshRate));
timer.schedule(updateTask, 0, refreshRate);
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
registerReceiver(receiverWifi, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
}
@Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "Service destroying");
unregisterReceiver(receiverWifi);
if (timer != null){
timer.cancel();
timer.purge();
timer = null;
}
}
class WifiReceiver extends BroadcastReceiver {
public void onReceive(Context c, Intent intent) {
sb = new StringBuilder();
wifiList = wifi.getScanResults();
String ap_ssid;
String ap_mac;
Double ap_rssi;
for(int i = 0; i < wifiList.size(); i++){
ap_ssid = wifiList.get(i).SSID;
ap_mac = wifiList.get(i).BSSID;
ap_rssi = Double.valueOf(wifiList.get(i).level);
APData ap = new APData(ap_ssid,ap_mac,ap_rssi);
apdataList.add(ap);
sb.append(" " + (wifiList.get(i).SSID).toString());
sb.append(" " + (wifiList.get(i).BSSID).toString());
sb.append((" " + String.valueOf(wifiList.get(i).level)));
sb.append("\n");
}
Log.d(TAG, sb.toString());
for(int i=1; i<=numberOfWifiScan; i++){
surveyData.add(apdataList);
}
}
}
}
However, I seem to get Nullpointer at this line: apdataList.add(ap);. So I wonder whether the interval is too short, which causes ScanResult to be empty?
A: EDIT after you posted your code:
apdataList does not seem to be initialized in onCreate()
add this to onCreate():
apdataList = new List<APData>();
Minimum scanning delay
I think that there is no absolute minimum scanning delay. It depends too much on the hardware performances.
My advice is that you add a 'As Fast As Possible' option to your preferences then use an asynchronous loop that relaunch a scan as soon as new results are found (see the code snippet below, it was updated to suit your needs). This way, it will only be limited by hardware performances.
Also you can poll the ScanResults using WifiManager.getScanResults() The recommended way is to launch WifiManager.startScan() and set up a BroadcastReceiver for WifiManager.SCAN_RESULTS_AVAILABLE_ACTION to be notified as soon as the scan results are ready.
Here's a sample code (borrowed from here and adapted to your needs):
IntentFilter i = new IntentFilter();
i.addAction (WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(new BroadcastReceiver(){
public void onReceive(Context c, Intent i){
// Code to execute when SCAN_RESULTS_AVAILABLE_ACTION event occurs
WifiManager w = (WifiManager) c.getApplicationContext().getSystemService(Context.WIFI_SERVICE); //Use getApplicationContext to prevent memory leak
myScanResultHandler(w.getScanResults()); // your method to handle Scan results
if (ScanAsFastAsPossible) w.startScan(); // relaunch scan immediately
else { /* Schedule the scan to be run later here */}
}
}, i );
// Launch wifiscanner the first time here (it will call the broadcast receiver above)
WifiManager wm = (WifiManager)getApplicationContext.getSystemService(Context.WIFI_SERVICE);
boolean a = wm.startScan();
A: From Android 8 and higher, the limit is 4 times in 2 minutes.
So you could scan 4 times with 1 second of delay in between. But you would not get any further scan results for the next 126 seconds.
So the fastest interval where every scan is successful would be every 30 seconds.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: PHP APC 5.3.8 Hangs Page Request I had difficulty finding the newest version of php_apc.dll so I went ahead and compiled it myself. I had no issue getting it compiled using NTS v5.3.8. I had two separate files set up to test, one with a simple phpinfo() call on it and the other being the standard apc.php file that comes with the apc source files.
Strangely, when I would load the phpinfo() file it would work totally fine, but when I tried to access apc.php the webserver would hang until a timeout. I restarted the webserver, accessed apc.php and it worked just fine, but trying to go back to phpinfo() would cause the server to hang until timeout. It is probably worth noting that phpmyadmin and my own codeigniter application do not work period, even after a restart.
I have tried previous versions of apc with no luck; 5.3.5 with apc.stat = 0 works but I am in need of that feature as this is a development server, but I'm testing out some production type caching.
Noteworthy stuff:
Server is powered by Nginx 1.0.8 running PHP 5.3.8 (using fast-cgi). Everything works as intended with the exception of when apc is loaded.
A: You can download the php_apc.dll from http://downloads.php.net/pierre/
You can find there different versions of it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Download CSV directly into Python CSV parser I'm trying to download CSV content from morningstar and then parse its contents. If I inject the HTTP content directly into Python's CSV parser, the result is not formatted correctly. Yet, if I save the HTTP content to a file (/tmp/tmp.csv), and then import the file in the python's csv parser the result is correct. In other words, why does:
def finDownload(code,report):
h = httplib2.Http('.cache')
url = 'http://financials.morningstar.com/ajax/ReportProcess4CSV.html?t=' + code + '®ion=AUS&culture=en_us&reportType='+ report + '&period=12&dataType=A&order=asc&columnYear=5&rounding=1&view=raw&productCode=usa&denominatorView=raw&number=1'
headers, data = h.request(url)
return data
balancesheet = csv.reader(finDownload('FGE','is'))
for row in balancesheet:
print row
return:
['F']
['o']
['r']
['g']
['e']
[' ']
['G']
['r']
['o']
['u']
(etc...)
instead of:
[Forge Group Limited (FGE) Income Statement']
?
A: The problem results from the fact that iteration over a file is done line-by-line whereas iteration over a string is done character-by-character.
You want StringIO/cStringIO (Python 2) or io.StringIO (Python 3, thanks to John Machin for pointing me to it) so a string can be treated as a file-like object:
Python 2:
mystring = 'a,"b\nb",c\n1,2,3'
import cStringIO
csvio = cStringIO.StringIO(mystring)
mycsv = csv.reader(csvio)
Python 3:
mystring = 'a,"b\nb",c\n1,2,3'
import io
csvio = io.StringIO(mystring, newline="")
mycsv = csv.reader(csvio)
Both will correctly preserve newlines inside quoted fields:
>>> for row in mycsv: print(row)
...
['a', 'b\nb', 'c']
['1', '2', '3']
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7625079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.