text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Uncaught Throw generated by JLink or UseFrontEnd This example routine generates two Throw::nocatch warning messages in the kernel window. Can they be handled somehow?
The example consists of this code in a file "test.m" created in C:\Temp:
Needs["JLink`"];
$FrontEndLaunchCommand = "Mathematica.exe";
UseFrontEnd[NotebookWrite[CreateDocument[], "Testing"]];
Then these commands pasted and run at the Windows Command Prompt:
PATH = C:\Program Files\Wolfram Research\Mathematica\8.0\;%PATH%
start MathKernel -noprompt -initfile "C:\Temp\test.m"
Addendum
The reason for using UseFrontEnd as opposed to UsingFrontEnd is that an interactive front end may be required to preserve output and messages from notebooks that are usually run interactively. For example, with C:\Temp\test.m modified like so:
Needs["JLink`"];
$FrontEndLaunchCommand="Mathematica.exe";
UseFrontEnd[
nb = NotebookOpen["C:\\Temp\\run.nb"];
SelectionMove[nb, Next, Cell];
SelectionEvaluate[nb];
];
Pause[10];
CloseFrontEnd[];
and a notebook C:\Temp\run.nb created with a single cell containing:
x1 = 0; While[x1 < 1000000,
If[Mod[x1, 100000] == 0,
Print["x1=" <> ToString[x1]]]; x1++];
NotebookSave[EvaluationNotebook[]];
NotebookClose[EvaluationNotebook[]];
this code, launched from a Windows Command Prompt, will run interactively and save its output. This is not possible to achieve using UsingFrontEnd or MathKernel -script "C:\Temp\test.m".
A: During the initialization, the kernel code is in a mode which prevents aborts.
Throw/Catch are implemented with Abort, therefore they do not work during initialization.
A simple example that shows the problem is to put this in your test.m file:
Catch[Throw[test]];
Similarly, functions like TimeConstrained, MemoryConstrained, Break, the Trace family, Abort and those that depend upon it (like certain data paclets) will have problems like this during initialization.
A possible solution to your problem might be to consider the -script option:
math.exe -script test.m
Also, note that in version 8 there is a documented function called UsingFrontEnd, which does what UseFrontEnd did, but is auto-configured, so this:
Needs["JLink`"];
UsingFrontEnd[NotebookWrite[CreateDocument[], "Testing"]];
should be all you need in your test.m file.
See also: Mathematica Scripts
Addendum
One possible solution to use the -script and UsingFrontEnd is to use the 'run.m script
included below. This does require setting up a 'Test' kernel in the kernel configuration options (basically a clone of the 'Local' kernel settings).
The script includes two utility functions, NotebookEvaluatingQ and NotebookPauseForEvaluation, which help the script to wait for the client notebook to finish evaluating before saving it. The upside of this approach is that all the evaluation control code is in the 'run.m' script, so the client notebook does not need to have a NotebookSave[EvaluationNotebook[]] statement at the end.
NotebookPauseForEvaluation[nb_] := Module[{},While[NotebookEvaluatingQ[nb],Pause[.25]]]
NotebookEvaluatingQ[nb_]:=Module[{},
SelectionMove[nb,All,Notebook];
Or@@Map["Evaluating"/.#&,Developer`CellInformation[nb]]
]
UsingFrontEnd[
nb = NotebookOpen["c:\\users\\arnoudb\\run.nb"];
SetOptions[nb,Evaluator->"Test"];
SelectionMove[nb,All,Notebook];
SelectionEvaluate[nb];
NotebookPauseForEvaluation[nb];
NotebookSave[nb];
]
I hope this is useful in some way to you. It could use a few more improvements like resetting the notebook's kernel to its original and closing the notebook after saving it,
but this code should work for this particular purpose.
On a side note, I tried one other approach, using this:
UsingFrontEnd[ NotebookEvaluate[ "c:\\users\\arnoudb\\run.nb", InsertResults->True ] ]
But this is kicking the kernel terminal session into a dialog mode, which seems like a bug
to me (I'll check into this and get this reported if this is a valid issue).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Why are my tunneling event arguments object and bubbling event arguments object not equal? I'm working through the 70-511 book, and am looking at the section on Routed Events.
I noticed it mentions that bubbling-tunneling event pairs share the same EventArgs instance, so if you handle the tunneling event (eg PreviewMouseDown), it halts the paired bubbling event (eg MouseDown); I've tried this and it works... But, if I test for equality each time the event handler fires (for test purposes I'm using 1 event handler for both events) it seems as though the EventArgs are NOT the same instance (ie they have different hashvalues and Object.Equals returns false)...
It would greatly improve my understanding of how routed events work if I could figure out why this is!
Any .NET gurus our there care to explain?
I've checked out the Pro WPF book (excellent book) and this also just states:
"To make life more interesting, if you mark the tunneling event as handled, the bubbling event won’t occur. That’s because the two events share the same instance of the RoutedEventArgs class."
If the two events share the SAME INSTANCE of a class, shouldn't the eventargs have the same hashvalues and return 'True' for Object.Equals???
private RoutedEventArgs args;
private void MouseDownHandler(object sender, MouseButtonEventArgs e)
{
listEvents.Items.Add(string.Format("{0} - {1} - {2} - {3}",
sender.GetType().Name, e.RoutedEvent.ToString(), e.Source.GetType().Name,
e.OriginalSource.GetType().Name));
listEvents.Items.Add(e.GetHashCode().ToString());
if (args != null) listEvents.Items.Add(e.Equals(args).ToString());
args = e;
}
The XAML:
<Window x:Class="Chapter_2___WPF_RoutedEvents.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="428" Width="658"
PreviewMouseDown="MouseDownHandler" MouseDown="MouseDownHandler">
<Grid Name="grid"
MouseDown="MouseDownHandler" PreviewMouseDown="MouseDownHandler">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ListBox Name="listEvents" Grid.Column="1"/>
<Button Content="Click Me!" Width="150" Height="50" Margin="10" Grid.Column="0"
MouseDown="MouseDownHandler" PreviewMouseDown="MouseDownHandler"/>
</Grid>
</Window>
A: When I run your code and click the button, it does return the same hash code and 'True' for e.Equals(args). If I click again, e.Equals(args) returns 'False' because it is a new instance of RoutedEventArgs for each click, but the next one returns True because the tunneling event is the same as the bubbling event.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Providing EntityManager by an @ConversationScoped method I tried to run the simple JEE6 application generated by maven archetype groupId: org.fluttercode.knappsack , artifactID: jee6-sandbox-archetype in JBoss7.
(went through this turial, sorry, in German)
However, when calling the welcome JSF, I get the following error message:
org.jboss.weld.exceptions.IllegalProductException: WELD-000053 Producers
cannot declare passivating scope and return a non-serializable class:
[method] @Produces @DataRepository @ConversationScoped
public org.rap.jee6project.bean.DataRepositoryProducer.getEntityManager()
org.jboss.weld.bean.AbstractProducerBean.checkReturnValue(AbstractProducerBean.java:264)
org.jboss.weld.bean.AbstractProducerBean.create(AbstractProducerBean.java:362)
org.jboss.weld.context.AbstractContext.get(AbstractContext.java:122)
Indeed, the DataRepositoyProducer class which is supposed to return an EntityManager instance, is defined an annotated as follws:
@Stateless
public class DataRepositoryProducer {
private EntityManager entityManager;
@Produces @DataRepository @ConversationScoped
public EntityManager getEntityManager() {
return entityManager;
}
@PersistenceContext
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
}
}
If I use @RequestScoped, the application runs as promised. I wonder why other people who went through this tutorial didn't experience this problem? And how to fix it properly (using @RequestScoped means that the bean is recreated for each user request, right?, which I expect to be not very efficient)
The official JEE6 Tutorial says: "Beans that use session, application, or conversation scope must be serializable, but beans that use request scope do not have to be serializable" . However, that does not seem to be the problem here, since the server is not comlaining about the bean not serializable but the product of the producer bean.
A: It should be..
@Stateful
@ConversationScoped
public class ProducerCreator implements Serializable{
@PersistenceConText
private EntityManager entityManager;
....
}
and if you want to use the same entity context in of each conversation it should be
@PersistenceContex(type = PersistenceContextType.EXTENDED)
finally, If you want to have service layer, should create stateful and inject to conversation bean
A: I had same problem running the demo on a jboss7.
Just remove @ConversationScoped at getEntityManager() did the trick to me to let it deploy.
Even though there are some flaws:
javax.servlet.ServletException: javax.faces.component.StateHolderSaver cannot be cast to [Ljava.lang.Object;
javax.faces.webapp.FacesServlet.service(FacesServlet.java:606)
org.jboss.weld.servlet.ConversationPropagationFilter.doFilter(ConversationPropagationFilter.java:62)
I don't know exactly, if it is related, but I guess so.
A: Remember: EntityManager is not serializable, so it cannot be stored in ConversationScope
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In xcode does anyone know how to check that a string is this kind of phone number (123) 456-7890? I've tried this and it's not working:
range1 = NSMakeRange(0,[string length]);
NSRegularExpression *regex;
regex = [NSRegularExpression
regularExpressionWithPattern:@"([0-9]{3}) [0-9]{3}-[0-9]{4}"
options:0 error:NULL];
range2 = [regex rangeOfFirstMatchInString:string options:0 range:range1];
if (NSEqualRanges(range1, range2)) {
return YES;
}
// range2 always equals the "not found" range.
// Thx
A: I think it should be '\\' (double slashes) and not '\' (single slash)..
- (BOOL) validatePhone: (NSString *) candidate {
NSString *phoneRegex = @"\\(?([0-9]{3})\\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})";
NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", phoneRegex];
return [phoneTest evaluateWithObject:candidate];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Uploading a photo to Facebook album from Windows server doesn't work I've an app with which users can add pictures to their albums using curl.
I've coded it on my linux server and everything worked perfect. So I've uploaded the app into my clients server (which is windows) and photo upload doesn't work, I cant figure out why.
My code is
$file = $img_path;
$args = array(
'message' => APP_TITLE,
);
$args[basename($file)] = '@' . $file;
$ch = curl_init();
$url = 'https://graph.facebook.com/' . $album_id . '/photos?access_token=' . $access_token;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
$data = curl_exec($ch);
//returns the photo id
$res = json_decode($data,true);
The only difference I can see between windows and linux is how you define image paths
The image path on windows is:
C:\Projects\appname\www\gallery\folder\picture.jpg
and on linux: /var/www/appname/gallery/folder/picture.jpg
Should I do something extra for windows?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Actionscrpipt 3 OOP I am developing player which has several my own custom developed buttons which has their own classes. Also the player has its own class which is the main class and instansiate all the buttons I have.
So this is a simple example of "has a" relationship i.e composition.
I used to past a reference of the player trought every buttons constructor in order buttons to be able to access properties and methods from the players class. This method is working good, but the problem is it has a lot of duplicate code than needs to be added to every button class.
So I tried to workit out by using inheritance, i.e buttons extend the playes main class.
But this way although i declare all properties protected I get the final swf blank white. So there must a problem.
Am I doing the structure wrong or what? Any idea?
Here is a sample code
public class Player extends MovieClip{
protected var prop1:Number;
protected var prop2:String;
protected var playButton:PlayButton;
....
public function Player(){
// with composition
playButton=new PlayBUtton(this);
// with inhgeritance
playButton=new PlayButton();
addChild(playBUtton);
}
}
//first implementation with composition
public class PlayButton extends MovieCLip{
public function PlayButton(player:Player){
//access Player trough player parameter
}
}
//second implementation with inheritance
public class PlayButton extends Player{
public function PlayButton(){
//access Player trough inheritance
}
}
A: You could use the state design pattern like in the following example I made:
package
{
import flash.display.Sprite;
import flash.events.Event;
public class Main extends Sprite
{
public function Main():void
{
if (stage) init();
else addEventListener(Event.ADDED_TO_STAGE, init);
}// end function
private function init(e:Event = null):void
{
removeEventListener(Event.ADDED_TO_STAGE, init);
var player:Player = new Player();
addChild(player);
}// end function
}// end class
}// end package
import flash.display.Sprite;
import flash.events.MouseEvent;
import flash.text.TextField;
internal class TextButton extends Sprite
{
public function TextButton(text:String)
{
graphics.beginFill(0xFF0000);
graphics.drawRect(0, 0, 100, 25);
graphics.endFill();
var textField:TextField = new TextField();
textField.text = text;
textField.mouseEnabled = false;
textField.x = this.width / 2 - textField.textWidth /2;
textField.y = this.height / 2 - textField.textHeight / 2;
addChild(textField);
}// end function
}// end class
internal interface IState
{
function play():void
function stop():void
}// end interface
internal class Player extends Sprite
{
private var _playState:IState;
private var _stopState:IState;
private var _state:IState;
private var _playButton:TextButton;
private var _stopButton:TextButton;
public function get playState():IState { return _playState }
public function get stopState():IState { return _stopState }
public function get state():IState { return _state }
public function set state(state:IState):void { _state = state }
public function Player()
{
_playState = new PlayState(this);
_stopState = new StopState(this);
_state = stopState;
_playButton = new TextButton("PLAY");
_playButton.addEventListener(MouseEvent.CLICK, onClick);
addChild(_playButton);
_stopButton = new TextButton("STOP");
_stopButton.addEventListener(MouseEvent.CLICK, onClick);
_stopButton.x = 110;
addChild(_stopButton);
}// end function
private function onClick(e:MouseEvent):void
{
var textButton:TextButton = e.target as TextButton;
switch(textButton)
{
case _playButton : _state.play(); break;
case _stopButton : _state.stop(); break;
}// end function
}// end function
}// end class
internal class PlayState implements IState
{
private var _player:Player;
public function PlayState(player:Player)
{
_player = player;
}// end function
public function play():void
{
trace("player already playing");
}// end class
public function stop():void
{
_player.state = _player.stopState;
trace("stopping player");
}// end function
}// end class
internal class StopState implements IState
{
private var _player:Player;
public function StopState(player:Player)
{
_player = player;
}// end function
public function play():void
{
_player.state = _player.playState;
trace("playing player");
}// end function
public function stop():void
{
trace("player already stopped");
}// end function
}// end class
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How is the map function in Perl implemented? Is map function in Perl written in Perl? I just can not figure out how to implement it. Here is my attempt:
use Data::Dumper;
sub Map {
my ($function, $sequence) = @_;
my @result;
foreach my $item (@$sequence) {
my $_ = $item;
push @result, $function->($item);
}
return @result
}
my @sample = qw(1 2 3 4 5);
print Dumper Map(sub { $_ * $_ }, \@sample);
print Dumper map({ $_ * $_ } @sample);
$_ in $function is undefined as it should be, but how map overcomes this?
A: While the accepted answer implements a map-like function, it does NOT do it in the way perl would. An important part of for, foreach, map, and grep is that the $_ they provide to you is always an alias to the values in the argument list. This means that calling something like s/a/b/ in any of those constructs will modify the elements they were called with. This allows you to write things like:
my ($x, $y) = qw(foo bar);
$_ .= '!' for $x, $y;
say "$x $y"; # foo! bar!
map {s/$/!!!/} $x, $y;
say "$x $y"; # foo!!!! bar!!!!
Since in your question, you have asked for Map to use array references rather than arrays, here is a version that works on array refs that is as close to the builtin map as you can get in pure Perl.
use 5.010;
use warnings;
use strict;
sub Map (&\@) {
my ($code, $array) = splice @_;
my @return;
push @return, &$code for @$array;
@return
}
my @sample = qw(1 2 3 4 5);
say join ', ' => Map { $_ * $_ } @sample; # 1, 4, 9, 16, 25
say join ', ' => map { $_ * $_ } @sample; # 1, 4, 9, 16, 25
In Map, the (&\@) prototype tells perl that the Map bareword will be parsed with different rules than a usual subroutine. The & indicates that the first argument will either be a bare block Map {...} NEXT or it will be a literal code reference Map \&somesub, NEXT. Note the comma between the arguments in the latter version. The \@ prototype indicates that the next argument will start with @ and will be passed in as an array reference.
Finally, the splice @_ line empties @_ rather than just copying the values out. This is so that the &$code line will see an empty @_ rather than the args Map received. The reason for &$code is that it is the fastest way to call a subroutine, and is as close to the multicall calling style that map uses as you can get without using C. This calling style is perfectly suited for this usage, since the argument to the block is in $_, which does not require any stack manipulation.
In the code above, I cheat a little bit and let for do the work of localizing $_. This is good for performance, but to see how it works, here is that line rewritten:
for my $i (0 .. $#$array) { # for each index
local *_ = \$$array[$i]; # install alias into $_
push @return, &$code;
}
A: map has some special syntax, so you can't entirely implement it in pure-perl, but this would come pretty close to it (as long as you're using the block form of map):
sub Map(&@) {
my ($function, @sequence) = @_;
my @result;
foreach my $item (@sequence) {
local $_ = $item;
push @result, $function->($item);
}
return @result
}
use Data::Dumper;
my @sample = qw(1 2 3 4 5);
print Dumper Map { $_ * $_ } @sample;
print Dumper map { $_ * $_ } @sample;
$_ being undefined is overcome by using local $_ instead of my $_. Actually you almost never want to use my $_ (even though you do want to use it on almost all other variables).
Adding the (&@) prototype allows you not to specify sub in front of the block. Again, you almost never want to use prototypes but this is a valid use of them.
A: My Object::Iterate module is an example of what you are trying to do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626516",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: how to add two variables to URL in JSP? I want to add two variables to URL in JSP
<a href="buyOrSell.do?symbol=<%=trade.getSymbol()%>&mktPrice="<%=trade.getCurrentMktPrice()%>>Buy</a>
ex - http://loclhost:8080/myProj/buyOrSell.do?symbol=anySymbol&mktPrice=price
but I am not able to get second variable.
A: Seems like you had a quote mark placed wrong in your code. Test the line below instead
<a href="buyOrSell.do?symbol=<%=trade.getSymbol()%>&mktPrice=<%=trade.getCurrentMktPrice()%>">Buy</a>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Copy resources with frank and cucumber I have a iPhone project where i use frank and cucumber for acceptance testing.
My application has a feature to collect files from the documents directory and index them in the applications database.
I want to test this feature with cucumber. But this means i have to copy files to the applications documents directory.
My questions are:
*
*How do i dynamically make step definitions to copy files?
*Where do place the resources before they get copied? In what folder structure?
*How do i reach these files from my step definitions?
Thanks.
A: We created a helper function to do something like this for injecting images into the simulator gallery..
def init_simulator_images(num_images)
(1..num_images.to_i).each do |n|
target_file = "IMG_000#{n}.JPG"
begin
File.stat("#{ENV['simulator_media_path']}/#{target_file}")
rescue Errno::ENOENT
app_exec 'FEX_loadPhotoLibraryImage:', "test/#{target_file}"
end
end
end
and then on the native code side, we have a helper class called FEX_Helper to aid in anything where we need to modify the app at runtime (RubyMotion code but v. similar to objective-c except for the syntax):
def FEX_loadPhotoLibraryImage(imageStr)
img = UIImage.imageNamed(imageStr)
UIImageWriteToSavedPhotosAlbum(img, nil, nil, nil)
end
Lastly the simulator media path is defined thusly:
def simulator_media_path
"#{self.simulator_version_path}/Media/DCIM/100APPLE"
end
def simulator_path
"/Users/#{self.user}/Library/Application\ Support/iPhone\ Simulator"
end
def simulator_version_path
"#{self.simulator_path}/#{self.simulator_version}"
end
Hope that helps someone trying to inject files into the simulator for testing.
Mark
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Load shared library by path at runtime I am building a Java application that uses a shared library written in C++ and compiled for different operating systems. The problem is, that this shared library itself depends on an additional library it normally finds under the appropriate environment variable (PATH, LIBRARY_PATH or LD_LIBRARY_PATH).
I can - but don't want to - set these environment variables. I'd rather load the needed shared libraries from a given path at runtime - just like a plugin. And no - I don't want any starter application that starts a new process with a new environment. Does anybody know how to achieve this?
I know that this must be possible, as one of the libraries I use is capable of loading its plugins from a given path. Of course I'd prefer platform independent code, but if this ain't possible, seperate solutions for Windows, Linux and MacOS would also do it.
EDIT
I should have mentioned that the shared library I'd wish to use is object oriented, which means that a binding of single functions won't do it.
A: I concur with the other posters about the use of dlopen and LoadLibrary. The libltdl gives you a platform-independent interface to these functions.
A: Un UNIX/Linux systems you can use dlopen. The issue then is you have to fetch all symbols you need via dlsym
Simple example:
typedef int (*some_func)(char *param);
void *myso = dlopen("/path/to/my.so", RTLD_NOW);
some_func *func = dlsym(myso, "function_name_to_fetch");
func("foo");
dlclose(myso);
Will load the .so and execute function_name_to_fetch() from in there. See the man page dlopen(1) for more.
A: On Windows, you can use LoadLibrary, and on Linux, dlopen. The APIs are extremely similar and can load a so/dll directly by providing the full path. That works if it is a run-time dependency (after loading, you "link" by calling GetProcAddress/dlsym.)
A: I do not think you can do it for it.
Most Dlls have some sort of init() function that must be called after it have been loaded, and sometime that init() function needs some parameters and returns some handle to be used to call the dll's functions. Do you know the definition of the additional library?
Then, the first library can not simply look if the DLL X is in RAM only by using its name. The one it needs can be in a different directory or a different build/version. The OS will recognize the library if the full path is the same than another one already loaded and it will share it instead of loading it a second time.
The other library can load its plugins from another path because it written to not depend on PATH and they are his own plugins.
Have you try to update the process's environment variables from the code before loading the Dll? That will not depends on a starter process.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: produces an HTML file from XML I have a XML file with Rectangle elements that contains sub-elements - RGBcolor,ID, height and width.
Now i need to draw the rectangles into a HTML web page with the mentioned sizes, color and name into several DIVs. how do i do it? I'm new in the business so please try to detail as much as you can.
here's my xml:
<?xml version="1.0"?>
<ArrayOfRectangle xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Rectangle>
<Id>First one</Id>
<TopLeft>
<X>0.06</X>
<Y>0.4</Y>
</TopLeft>
<BottomRight>
<X>0.12</X>
<Y>0.13</Y>
</BottomRight>
<Color>
<Red>205</Red>
<Green>60</Green>
<Blue>5</Blue>
</Color>
</Rectangle>
<Rectangle>
<Id>Second One</Id>
The XML is fine and i even deserialized it back, but i dont know how to do the parsing into HTML..
Thank you all
A: The short answer is that you can't. HTML is a text markup language, not a graphics language.
You could convert all your rules to CSS and apply them to divs (generic block elements), although that would be a hack.
SVG is a graphics language which is going to be better supported than your made up one, but still has limitations. If you convert your rules into JavaScript then Raphaël can generate SVG or VML as required by different browsers. This would give wider support at a cost of depending on JS.
For widest support, you could convert the XML document into a PNG image on the server.
The specifics of how you convert from your format to another are open to several options. You'll need an XML parser. Then you need to read the document and output whatever format you like. You could use DOM for this, and XSLT is a popular option (especially for XML to other XML translations).
A: It's not clear to me whether your problem is designing the HTML (and/or SVG) that you want to generate, or in deciding what technology to use for the transformation. For simple rectangles, it's certainly possible to us HTML DIV elements with appropriate CSS properties, but SVG gives you more flexibility. Either way, I would use XSLT for the transformation; but allow some time to read up about the language and become familiar with it, because it's probably unlike anything you have used before.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: facebook shows "not found." when clicking the received app requests sent by graph api just as the title.
I sent a app request to my facebook account by this way.
http://developers.facebook.com/docs/reference/dialogs/requests/
and then, I received a notification on facebook.
says like that: *Johanna Bassam Bassam Haro sent you a request in APP_NAME. 9:55am*
when I click*APP_NAME* ( a link). I got this http://www.facebook.com/4oh4.php
I guess there should be a configuration on our app. anyone know what's it? or what I forgot to set? thank you very much
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unparseable date Exception Well, i'm trying to catch date from rss, and i get this execption in logcat:
E/AndroidNews( 870): Caused by: java.text.ParseException: Unparseable date: "Su
n, 02 Oct 2011 14:00:00 +0100"
E/AndroidNews( 870): at java.text.DateFormat.parse(DateFormat.java:626)
E/AndroidNews( 870): at com.warriorpoint.androidxmlsimple.Message.setDate(Mes
sage.java:57)
My formatter is
static SimpleDateFormat FORMATTER =
new SimpleDateFormat("yyyy-MM-dd HH:mm");´
My method setDate();
public void setDate(String date) {
this.date=null;
// pad the date if necessary
while (!date.endsWith("00")){
date += "0";
}
try {
this.date = FORMATTER.parse(date.trim());
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
A: You're using the wrong format, for "Sun, 02 Oct 2011 14:00:00 +0100" try this instead:
new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.US)
This also forces the locale to (American) English, so the day and month names aren't affected by the device's locale, e.g. expecting "Dom" for "Sun" and "Oct" for "Out" in a Portuguese locale (I peeked at your profile).
The format you have in your question would only be able to parse dates like "2011-10-02 14:00".
Also, don't pad the date, let your formatter do the parsing.
If you want to output/display a java.util.Date in a certain way, just create a new SimpleDateFormat (let's call it displayFmt) with the desired formatting string and call format() on it:
String formattedDate = new SimpleDateFormat("dd MM yyyy H").format(date);
This will give you something like "02 10 2011 17" for today, formatted in the user's/device's preferred locale.
Please note that in your comment, you said dd mm yyyy h (lower case m and h) which would give you "dayOfMonth minutes year hours12" -- I think that's not what you want, so I changed it to an upper case M and upper case H to give you "dayOfMonth month year hours24".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Are SQL strings null terminated? I was learning how to use len() function. When I found out the length of a cell having 12 characters, it gave me result 12. Now I was thinking that arent the SQL strings null terminated(As if they would have been then len() should have returned 13 not 12)?
Please help me out.
Thanks
A: In SQL Server, LEN will ignore trailing spaces (http://msdn.microsoft.com/en-us/library/ms187403.aspx) - here's a modified example from that link:
PRINT 'Testing with ANSI_PADDING ON'
SET ANSI_PADDING ON ;
GO
CREATE TABLE t1
(
charcol CHAR(16) NULL
,varcharcol VARCHAR(16) NULL
,varbinarycol VARBINARY(8)
) ;
GO
INSERT INTO t1
VALUES ('No blanks', 'No blanks', 0x00ee) ;
INSERT INTO t1
VALUES ('Trailing blank ', 'Trailing blank ', 0x00ee00) ;
SELECT 'CHAR' = '>' + charcol + '<'
,'VARCHAR' = '>' + varcharcol + '<'
,varbinarycol
,LEN(charcol)
,LEN(varcharcol)
,DATALENGTH(charcol)
,DATALENGTH(varcharcol)
FROM t1 ;
GO
PRINT 'Testing with ANSI_PADDING OFF' ;
SET ANSI_PADDING OFF ;
GO
CREATE TABLE t2
(
charcol CHAR(16) NULL
,varcharcol VARCHAR(16) NULL
,varbinarycol VARBINARY(8)
) ;
GO
INSERT INTO t2
VALUES ('No blanks', 'No blanks', 0x00ee) ;
INSERT INTO t2
VALUES ('Trailing blank ', 'Trailing blank ', 0x00ee00) ;
SELECT 'CHAR' = '>' + charcol + '<'
,'VARCHAR' = '>' + varcharcol + '<'
,varbinarycol
,LEN(charcol)
,LEN(varcharcol)
,DATALENGTH(charcol)
,DATALENGTH(varcharcol)
FROM t2 ;
GO
DROP TABLE t1
DROP TABLE t2
A: If we're talking pure SQL, there's no NUL terminator for you to worry about. If we're talking interfacing to SQL from other languages (e.g. C), then the answer depends on the language in question.
There are a couple of relevant points worth remembering:
*
*There are two character types in SQL: CHAR(N) and VARCHAR(N). The former is always the same length (N) and padded with spaces; the latter is variable-length (up to N chars).
*In Transact-SQL, LEN returns the length on the string excluding trailing spaces.
A: In some SQL strings are zero- terminated.
On some SQL they have a leading length byte/ word.
This of course does not matter for the len() function.
But it does matter if you want to insert a \0 into the string.
Usually varchar has a leading length byte.
But char is \0 terminated.
A: Well, first - the len function does not depend on null termination, programming languages not using null termination ALSO have a len function an it works.
Thus, a len function in SQL will give you the length of the string AS THE SERVER STORES IT - what do you care how that works?
Actually it will likely not be null terminated as this would make it hard to split a string over multiple database pages. And even if - this would be seriously implementation dependent (and you don't say which product you mean - the SQL language says nothing about how the server internally stores strings).
So, at the end your question is totally irrelevant. All that is relevant is that the len function implementation is compatible with the internal storage.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Visual Studio Find and Replace with Regex I want to replace C# attributes with VB.NET, which means, [Serializable] should become <Serializable>.
The pattern (\[)(.+)(\]) does find the results but I don't know how to replace the first and the last groups with the appropriate parenthesis.
I read this page, but I didn't understand how to use the curly braces for F&R, I tried to wrap the groups with it but it didn't work.
A: If you are using the Productivity Power Tools extension from Microsoft that support normal .NET regexes, what you would put in the textbox for the replacement given your regular expression above is:
<$2>
where $2 refers to the second capture group in your regex, i.e. the text between the brackets.
Note that this only works with the Quick Find from Productivity Power Tools though. The normal find/replace in Visual Studio use another syntax altogether.
A: Find what: \[{Serializable}\]
Replace with: <\1>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Converting Rails 2 routes to Rails 3 Like in my first question from yesterday, I'm still doing that tutorial.
I've encountered another issue with the Rails 2 / Rails 3 routing differences.
So my question is: How do you "translate" this:
<%= form_remote_tag(:controller => "posts", :action => "create") do %>
to Rails 3 routing?
Edit: This is the error code I get :
Showing C:/Users/Lunasea/Web-Site/Standart/app/views/posts/_message_form.html.erb where line #5 raised:
C:/Users/Lunasea/Web-Site/Standart/app/views/posts/_message_form.html.erb:5: syntax error, unexpected tASSOC, expecting '}'
...pend= form_tag {:controller => "posts", :action => "create"...
C:/Users/Lunasea/Web-Site/Standart/app/views/posts/_message_form.html.erb:5: syntax error, unexpected ',', expecting '}'
...rm_tag {:controller => "posts", :action => "create"}, :remot...
C:/Users/Lunasea/Web-Site/Standart/app/views/posts/_message_form.html.erb:5: syntax error, unexpected tASSOC, expecting keyword_end
...action => "create"}, :remote => true do @output_buffer.safe_...
C:/Users/Lunasea/Web-Site/Standart/app/views/posts/_message_form.html.erb:12: syntax error, unexpected keyword_ensure, expecting keyword_end
C:/Users/Lunasea/Web-Site/Standart/app/views/posts/_message_form.html.erb:14: syntax error, unexpected $end, expecting keyword_end
The content of _message_form.html.erb:
<% if logged_in? %>
<!--<% form_for product, :url => {:action => 'add_to_cart', :id => product.id}, :remote => true do %>-->
<!--<%= form_remote_tag(:controller => "posts", :action => "create") do %>-->
<%= form_for{:controller => "posts", :action => "create"}, :remote => true do %>
<%= label_tag(:message, "What are you doing?") %><br />
<%= text_area_tag(:message, nil, :size => "60x2") %><br />
<%= submit_tag("Update") %>
<% end %>
<% end %>
A: You'd use a form_tag and pass :remote => true to it…
form_tag :url => {:controller => 'posts', :action => 'create'}, :remote => true
(Make sure you've included jQuery UJS or equivalent Prototype library, because Rails no longer includes the javascript inline like it used to.)
A: I cite here from the book Fernandez: The Rails 3 Way section 11.13
PrototypeHelper
PrototypeHelper has been heavily modified ... The following helper methods were removed and made available in an official Prototype Legacy Helper
*
*...
*form_remote_for
*form_remote_tag
That is the reason for your error. You have to translate that to the new syntax with the option :remote => true to indicate a remote call (AJAX).
So the following should work:
<%= form_tag({:controller => "posts", :action => "create"}, {:remote => true}) do %>
...
<% end %>
See the API for Rails and search there for form_tag for additional information.
A: The error is saying there is a syntax problem in the message form template. My guess is that you are missing a <% end %> to close the do in your form_remote_tag call.
A: form_remote_tag is not there in the Rails 3
Use
form_tag :url => {...}, :remote => true
instead
What this means is that all previous remote_ helpers have been
removed from Rails core and put into the Prototype Legacy Helper. To
get UJS hooks into your HTML, you now pass :remote => true instead.
For example:
form_for @post, :remote => true
http://edgeguides.rubyonrails.org/3_0_release_notes.html
A: Your problem is that you use <!-- and --> to hide old code. Rails will still execute that code. Use the following format instead:
<% if logged_in? %>
<%-# form_for product, :url => {:action => 'add_to_cart', :id => product.id}, :remote => true do %>
<%-#= form_remote_tag(:controller => "posts", :action => "create") do %>
<%= form_for{:controller => "posts", :action => "create"}, :remote => true do %>
<%= label_tag(:message, "What are you doing?") %><br />
<%= text_area_tag(:message, nil, :size => "60x2") %><br />
<%= submit_tag("Update") %>
<% end %>
<% end %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: TouchXML (Sudzc) and using this data properly I am using Sudzc (it uses TouchXML) for parsing my web services WSDL, now I am using multiple web services with almost the same WSDL definitions. I edited my code to use this, this is what happens:
CXMLNode* element = [[Soap getNode: [doc rootElement] withName: @"Body"] childAtIndex:0];
output = [Soap deserialize:element];
And the soap deserialize is as following:
// Deserialize an object as a generic object
+ (id) deserialize: (CXMLNode*) element{
return [element stringValue];
}
I get data back ilke this when I log it:
{
RetrieveSetResult = {
Entities = {
RequestData = {
AccountCode = {
IsDirty = false;
IsNothing = true;
NoRights = false;
Value = "<null>";
};
AccountContactEmail = {
IsDirty = false;
IsNothing = true;
NoRights = false;
Value = "<null>";
};
};
};
SessionID = 40;
};
}
How can I use this data in a user friendly way, so i want to be able to say which field I want to select and read.
A: try access them like a dictionary
NSDictionary *dic = [myXMLparsedObject valueForKey:@"RetrieveSetResult"];
int sesID = [[dic valueForKey:@"SessionID"] intValue];
NSDictionary *entis = [dic valueForKey:@"Entities"];
// … and so on
looping through all elements:
// for iOS prior 4.0
NSArray *dicKeys = [xmlDic allKeys];
for (NSString *key in dicKeys) {
id obj = [xmlDic valueForKey:key];
}
// way simpler in > 4.0
[xmlDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
}];
in both cases you can access each key and obj value ;)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Packages for Beginners When a classfile that belongs to a package,
then
package PackageName;
is included in the source code of that file.
So when jvm is invoked by writing
java PackageName.classfilename
it gets executed.
Is it that "package PackageName" guarantees the jvm that this classfile belongs to this very package?
Because if we omit the "package PackageName" statement, then jvm still finds out the class file but gives
Exception in thread "main" java.lang.NoClassDefFoundError: Classfilename
wrongname PackageName/ClassfileName
It means jvm finds out the file but there is some reason for which it considers that this classfile has a wrong name.
A: The package declarations on your classes must match the folder structure that you have for your code.
Packages are used by the JVM for several "tasks", from the visibility of methods, to the resolution of situations where two classes could have the same name.
A NoClassDefFoundError actually means the JVM cannot find the class with the package you gave it. If you ommit the package definition on the class, and run the program like:
java ClassFileName
The JVM will find the class, as long as you're running the java command from the folder where your class is.
Also... package names should be all lowercase and Class names should start with an Uppercase. :) Conventions are really helpful when someone else is reading your code!
Hope the comment helped.
A: The class file needs to exist on the file system in the same hierarchy as is defined in the package name. If you remove the package name, I believe you must have the file in the root folder of your jar to work in the "unnamed" package. Likely you removed the package line from the source file but still left the class definition inside of the PackageName folder.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android draw border in ImageView I want to draw a border around an image. But I can't align the border at the ImageView itself (like it is done mostly) because I translate and scale the image inside of the ImageView with the ImageMatrix (the ImageView itself is fill_parent / fills the whole screen). I had the idea to add a second image (which looks like a border) and translate & scale it in the same way as the image which should have a border, but it isn't very handy to do it this way.
Has anybody a better idea to reach that goal?
A: There are two ways to achieve this:
1) add padding to the imageView and set a background color to it.
final ImageView imageView = new ImageView(context);
imageView.setPadding(2*border,2*border,0,0);
final ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(width,height);
params.leftMargin = marginYouWouldSet + border;
params.topMargin = marginYouWouldSet + border;
imageView.setBackgroundDrawable(drawable);
imageView.setBackgroundColor(borderColor);
addView(imageView, params);
2) another option is to override the draw method of your view and there draw the border:
@Override
protected void dispatchDraw(Canvas canvas)
{
borderDrawable.draw(canvas);
super.dispatchDraw(canvas);
}
...
public class BorderDrawable extends Drawable{
private Rect mBounds;
private Paint mBorderPaint;
public BorderDrawable(Rect bounds, int thickness, int color) {
mBounds = bounds;
mBorderPaint = new Paint();
mBorderPaint.setStrokeWidth(thickness);
mBorderPaint.setColor(color);
}
@Override
public void draw(Canvas canvas) {
//left border
canvas.drawLine(
mBounds.left - thickness/2,
mBounds.top,
mBounds.left - thickness/2,
mBounds.bottom,
mBorderPaint);
//top border
canvas.drawLine(
mBounds.left,
mBounds.top - thickness/2,
mBounds.right,
mBounds.top - thickness/2,
mBorderPaint);
//right border
canvas.drawLine(
mBounds.right + thickness/2,
mBounds.top,
mBounds.right + thickness/2,
mBounds.bottom,
mBorderPaint);
//bottom border
canvas.drawLine(
mBounds.left,
mBounds.bottom + thickness/2,
mBounds.right,
mBounds.bottom + thickness/2,
mBorderPaint);
}
}
Note that you are to give the middle of the line you want to draw(!) And also I haven't run, nor compiled this, so I'm not 100% sure it's correct, but these are the ways :) Rect bounds should be the bounding rect of your view - (0,0,width,height).
A: Alternatively, put the imageView in a layout of some sort and just set padding:
static class BorderView extends FrameLayout
{
public ImageView imageView;
public BorderView(Context context)
{
super(context);
setLayoutParams(//wrap content)
imageView = new ImageView(context);//set image and so forth
addView(imageView);
}
public void addSelectionBorder()
{
int border = 8;
setPadding(border,border,border,border);
setBackgroundColor(Color.BLUE);
}
public void removeSelectionBorder()
{
int border = 0;
setPadding(border,border,border,border);
setBackgroundColor(Color.BLACK);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Android USB reverse tethering: How to fool the apps USB reverse tethering = Cellphone gets network connection from PC via USB.
I know how to do USB reverse tethering except for one problem: Many Android apps will check network connection using the code below before doing any useful work:
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = connectivityManager.getActiveNetworkInfo();
The problem is that, when using USB reverse tethering, the above code will report no network connection. However, there IS a network connection (which is the USB reverse tethering itself), and ping, wget and all programs not doing this stupid check work well.
So the question is: How can I hack the system to let this network connection check return success (so that I can fool these apps)?
BTW. I use Cyanogenmod 7. And any solution specific to this MOD is also welcome.
A: If you are doing this much hacking I am assuming that you will probably have your device rooted. If so program a shell interface to send commands to the device shell with JNI and receive STDOUT. Use this interface to run a netcfg command that can be parsed into an array - this will give you all the details the API hides. It also allows you to override Androids device settings using the ipconfig command.
As far as using this to send and receive from your device - in my experience - you will have to probably compile a device specif module that can be loaded into the kernel at run time. Or just download the kernel from the manufacturer and compile the module into the kernel and then flash the phone with the new custom kernel.
Hope this helps.
A: To do this , you have to download ReverseTethering_3.19.zip file (Google it to find the link.)
Extract to your desired location.
Prerequisite: -
*
*only rooted phones work.
*USB debugging should be enabled.
Now connect your rooted android mobile to PC through USB cable.Wait for PC to recognize your mobile. Now open the extracted zip file and open AndroidTool.exe with admin rights.
Now click connect in the android tool.
Now it tries to connect and installs USB tunneling apk on your device.It also asks for super user rights . Grant it.
Finally after successfully establishing the connection, you will see.
https://drive.google.com/file/d/0B11p07T8VxhNNUdIM3gtTFR4N3M/view?usp=sharing
(Sorry, I cant upload image.)
Now you get the internet on your mobile and usb tunneling app is installed.But you can access only HTTP connections(i.e;) works only in chrome. Play store apps may not work.
So you have to fool apps and make it believe that either is mobile is connected to WiFi or mobile data . Only then apps work.
So you have to go to Tools menu in Android tool.
https://drive.google.com/file/d/0B11p07T8VxhNRXR3aTVUZUl1dVk/view?usp=sharing
Now install hack(optional).It installs Xposed framework and installs hack connectivity apk. Just follow the instructions , it is easy.
Hack connectivity makes the apps believe that mobile is connected to WiFi or mobile data depending on which type of hack u did after installing Hack connectivity. Finally after hacking ,it asks for reboot. After reboot , you can enjoy internet using USB reverse tethering on all apps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "45"
} |
Q: Is there a way to pre-cache a web page for viewing with an Android WebView? I've read about the HTML5 cache manifest, and I've seen Android does support caching websites using the cache manifest. I want to use the cache manifest to download all the required resources for my website to preload it, and then open a WebView and display the remote website using the pre-cached resources. I want to pre-cache my remote page somehow, preferably without using a WebView for the caching process.
The problem with using a WebView for the pre-caching process is that loading the webpage using a WebView renders and executes the page instead of just downloading it.
I've read this: http://alex.tapmania.org/2010/11/html5-cache-android-webview.html, but having a WebView support caching is not what I want. I want the loading process to be instantaneous (assuming the cache manifest / etags of the remote website are the same as the cached version) right after I finish pre-caching the resources, instead of waiting for the WebView to load up and cache everything on the first access.
What is the correct way of pre-caching web pages for viewing later?
Thanks!
A: What you want to do requires implementing a mechanism for app cache, linked resources, cookies, and local database store for HTML5 apps that use database API, and that's an important part of what browsers do in these days. I don't recommend doing the caching by yourself, not only because it's so much work, but also because I can't recall any method in WebView and it's friends (WebViewClient, etc.) that accepts an outside cache.
But your problem has a very simpler solution: you can put a WebView in your view and set its visibility to gone. Then make it visible when it has finished loading the page. WebView also automatically keeps the cache for your app so that the next time it runs it loads the page more quickly.
For hiding your WebView and then automatically showing it you just have to override onPageFinished in WebViewClient.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: designing a REST api that supports multiple screensizes Until now all my thumbnails have been 150x150. I would like to support different thumbnail sizes, in order to deal with different Android/iPhone models.
I have been considering this way of supporting multiple sizes. Always working with square thumbnails to makes things simpler.
Obtaining a 75x75 thumbnail
GET http://example.com/gallery?resolution=75
...
{
"id": 1001,
"thumbnail": "http://lh5.ggpht.com/EEIl3_hedJSAT4RscoceShtWy3DE4WGKXXNp4rusI-kpzWfDIbzrWx1KVywf9YqGI-elD_k4xg8bUemeRTtLgtAPOlVc0kpw=s75"
}
Obtaining a 150x150 thumbnail
GET http://example.com/gallery?resolution=150
...
{
"id": 1001,
"thumbnail": "http://lh5.ggpht.com/EEIl3_hedJSAT4RscoceShtWy3DE4WGKXXNp4rusI-kpzWfDIbzrWx1KVywf9YqGI-elD_k4xg8bUemeRTtLgtAPOlVc0kpw=s150"
}
I have seen seen a lot of api's that doesn't support custom sizes, e.g. the flickr api support small, medium, large and original size.
Can this api be improved somehow?
A: Well you could have fixed values like the Flickr API (Small, Medium, Large and Original). What you could do is pre-render and store them which means you can directly grab them off the disk or cache rather than rendering them on the fly. Your Request URL can then look something like:
GET http://example.com/gallery?resolution=small
However if you want to provide the most flexibility, you should continue with the way you are doing the API now and allow the API User to specify the square size. You should have a fixed maximum built in to stop abuse. An example of this would be the Gravatar API which has a fixed maximum of 512px and size can be specified with the s= parameter in the URL.
At the end it depends on your cost/benefit ratio. Would it be substantially more difficult to maintain a flexible size API rather than a pre-rendered fixed size(s) API and does rendering on the fly need more investment in Servers/RAM/Bandwidth etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why document.ready waits? I know that Document.ready - DONt wait for images to download.
So why it does here ?
http://jsbin.com/ehuke4/27/edit#source
(after each test - change the v=xxx in the img SRC)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert('0');
});
</script>
</head>
<body >
<img src='http://musically.com/blog/wp-content/uploads/2011/04/Google-Logo.jpg?v=42333' />
</body>
</html>
A: I think, the problem comes out from JSBin.com
Because, when you try this example on JSFiddle.net, it works properly
http://jsfiddle.net/vqte9/
A: It has to do with the fact that you're using "alert()", I think, though I'm not 100% sure why. If you change your code like this:
<body>
<div id='x'></div>
<img ...>
</body>
<script>
$(function() { $('#x').text("hello there"); });
</script>
you'll see that the text is filled in before the image loads.
edit — I don't know why this would make a difference, but I notice quite different behavior when I set up the ready handler with:
$(function() { whatever; });
and:
$(document).ready(function() { whatever; });
Now that's not supposed to be the case; the two forms are supposed to do exactly the same thing, as far as I know. However, they don't seem to. Here is a jsbin example that sets up the ready handler with the first form, and here is one that uses the second one. They behave very differently for me. I'll have to check the jQuery source to figure out how that can be true.
Here is the jQuery documentation explaining the equivalence of $(handler) and $(document).ready(handler).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Problems with changing the Orthogonal Projection Matrix I was experimenting with opengles, and made some simple squares moving around the screen:
//inside my renderScreen() method, called from onDrawFrame()
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_MODELVIEW);
if (gameObjects != null) {
// iterate and draw objects
for (GameObject obj : gameObjects) {
if (obj != null) {
gl.glLoadIdentity();
gl.glTranslatef(obj.posX, obj.posY, 0.0f);
obj.doDraw(gl);
}
Just simple, draws objects to the screen (still working). Now I wanted to like drag around the screen by translating the projection matrix based on touch input. I added this code above my previous code (before drawing the objects)
//change projection matrix
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glTranslatef(-cameraX, -cameraY, 0.0f); //cameraX and cameraY set in updateGame()
updateGame is just gets those from MyPanel.getDiffX() where DiffX is just how much your finger moved:
// Inside MyPanel Class
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
startingX = event.getX();
startingY = event.getY();
MyRenderer.addObject(new GameSquare(event.getX(), v
.getHeight() - event.getY())); // Y is inverted!
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
diffX = (event.getX() - startingX) / 100;
//diffY = (event.getX() - startingY) / 1000;
Log.d("diffX" ,Float.toString(diffX));
}
return true;
}
Now if I use the code to translate the projection Matrix, I don't get to see any objects on my screen anymore (just the glClear color). Does anyone know what's going on ? Am I using the matrices wrong ?
A: What happens when you set cameraX and cameraY to 0? By changing the projection matrix, are you sure you're not overwriting some previously set values?
Aside from that, you should be translating by -cameraX and -cameraY. Think about it, if you want your camera to be at position (10, 10), then anything at (10, 10) should be at the origin after transforming by the camera, the logical translation would be (-10, -10). You're not translating the camera in the world, but you're translating the world around the camera.
EDIT: let me suggest an alternative method of doing this, that doesn't change the projection matrix.
//inside my renderScreen() method, called from onDrawFrame()
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glTranslate(-cameraX, -cameraY, 0); //Apply the camera here
if (gameObjects != null){
// iterate and draw objects
for (GameObject obj : gameObjects) {
if (obj != null) {
gl.glPushMatrix(); //Note this line here, we 'push' a matrix onto the top
gl.glTranslatef(obj.posX, obj.posY, 0.0f);
obj.doDraw(gl);
gl.glPopMatrix(); //Here we remove our modified matrix to get the original one
}
}
A: I always learnt that you should use projection matrix for perspective, not the camera (compare OpenGL FAQ). So I would set the projection (perspective) with GLU once and not change it anymore. In your draw routine you can set the camera (translate) before every draw or use glPushMatrix and glPopMatrix to safe and restore the camera.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626573",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Best way to refill data in ListAdapter (ListView) I do use this code for refill ListView with data after they change
// ListView lv;
// MyListAdapter la;
// DataClass dc;
dc.remove(object_id);
lv.setAdapter(la);
Is this the best way since we can't use notifyDataSetChanged() which is available only in ArrayAdapter ?
Solution
//MyListAdapter.java
private ArrayList<DataSetObserver> observers = new ArrayList<DataSetObserver>();
public void registerDataSetObserver(DataSetObserver arg0) {
observers.add(arg0);
}
public void unregisterDataSetObserver(DataSetObserver arg0) {
observers.remove(arg0);
}
public void notifyDataSetChange() {
for (DataSetObserver d : observers) {
d.onChanged();
}
}
public void remove(int position) {
[DataClass object].remove(position);
notifyDataSetChange();
}
A: For a CursorAdapter I use the following code:
mAdapter.getCursor().requery();
If you are using custom adapter or as you commented: only want ListAdapter as member variable. Instead of using private CustomAdapter mAdapter; (which i would recommended to avoid creating unnecessary objects).
You can use DataSetObserver part and ListAdapter.registerDataSetObserver(DataSetObserver observer). DataSetObserver.onChanged() will be called by the BaseAdapter implementation, so it should work for all adapter.
BaseAdapter.notifyDataSetChanged():
public void notifyDataSetChanged() {
mDataSetObservable.notifyChanged();
}
A: You can use ArrayAdapter, which accepts Lists instead of Arrays. This way you can use notifyDataSetChanged() on it.
A: It seems that you think something wrong as I was did.
As you know, ListAdapter hasn't notifyDataSetChanged.
It seems that Cursor is the best match with a ListView. Doc. says that "Frequently that data comes from a Cursor, but that is not required. The ListView can display any data provided that it is wrapped in a ListAdapter."
If you check both links registerDataSetObserver ([DataSetObserver]2 observer), you can notice something. ListAdapter go well with a cursor. So why don't you try to use other adapters.
I think the best way to refresh adapter is using or extending BaseAdapter(with ListView). And use notifyDataSetChanged after change your dataset. In my case it works well and softly(invalidating list view and items, and scroll position is just there! Not going to first position).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to get plain text response using AJAX using Dojo I created a sample web service that returns a plain/text value (you can access it HERE (it's safe)). I just created something similar to those that I will use in my project. I tried using Dojo's xhrGet method but it didn't work. I had read about The Same Origin Policy, so I tried dojo.io.script, but then it still didn't work. I'm a newbie in Dojo and Ajax so I really don't know what to do next. How will I do this in Dojo (or even in plain javascript)? Please help me. Thanks!
A: To retrieve via javascript get
<script type="text/javascript">
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://jalbautista.xtreemhost.com/givename.php", false );
xmlHttp.send( null );
alert(xmlHttp.responseText);
</script>
To retrieve via dojo (cross domain)
Use dojo.xd.js for cross domain build (or use the one provided by google see below)
If you're going to use JSONP your script should spit out something like
doSomething("AUTO\\x-BautistaJ");
Script should look something like:
<script src="https://ajax.googleapis.com/ajax/libs/dojo/1.6.1/dojo/dojo.xd.js"></script>
<script type="text/javascript">
dojo.require("dojo.io.script");
function doSomething(data){
alert(data);
}
dojo.addOnLoad(function(){
dojo.io.script.get( {url : "http://jalbautista.xtreemhost.com/givename.php",
callbackParamName : 'doSomething',
preventCache :true,
load : function(response, ioArgs) {
console.log("Response", response + ' ' + ioArgs);
return response;
},
error : function(response, ioArgs) {
console.log("Response error : ", response + ' '
+ ioArgs);
return response;
}
}
);
});
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Using a foreach loop to get create variables from $_POST security issues? In the past I have used the following to create variables from a posted form.
foreach($_POST as $k=>$v)
{
$$k = $v;
}
What are the security risks associates with using this method?
im trying some test atm. how about this version where it removes anything that is not a letter or number before making the variable?
foreach($_POST as $k=>$v)
{
$k = preg_replace("/[^[:alnum:]]/","",$k);
$$k=$v;
}
A: An attacker can inject a POST variable called _SESSION and by that write data in your session so you can't trust your session anymore.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Mystery issue with GIF upload? Alright, so whenever I upload this GIF to my board (NGINX+PHP-FPM) I get a slow down until an eventual 504 Gateway Time-out, alright, so I know what you're thinking, "go ahead and fix those nginx.conf and php-fpm settings", well I tweaked them to near perfection last night, my server is running brilliantly now. However, that one particular GIF still screws up, runs php-FPM to almost 100% (I have a great top of the line quad core processor in my server, my server is by no means primitive).
So want to know where it gets weirder? I've uploaded 10MB GIF's with bigger dimensions than the one in case (the one which is causing the issues is about 600KB) and had the server process them ridiculously quickly.
Alright! So let's get into the log, error_log doesn't output anything in regards to this issue. So I went ahlead and set up a slowlog within the php-FPM config.
Here's the issue:
[02-Oct-2011 05:54:17] [pool www] pid 76004
script_filename = /usr/local/www/mydomain/post.php
[0x0000000805afc6d8] imagefill() /usr/local/www/mydomain/inc/post.php:159
[0x0000000805afb908] fastImageCopyResampled() /usr/local/www/mydomain/inc/post.php:107
[0x0000000805af4240] createThumbnail() /usr/local/www/mydomain/classes/upload.php:182
[0x0000000805aeb058] HandleUpload() /usr/local/www/mydomain/post.php:235
Okay, let's look at post.php (line 159 in bold):
if (preg_match("/png/", $system[0]) || preg_match("/gif/", $system[0])) {
$colorcount = imagecolorstotal($src_image);
if ($colorcount <= 256 && $colorcount != 0) {
imagetruecolortopalette($dst_image,true,$colorcount);
imagepalettecopy($dst_image,$src_image);
$transparentcolor = imagecolortransparent($src_image);
**imagefill($dst_image,0,0,$transparentcolor);**
imagecolortransparent($dst_image,$transparentcolor);
}
Line 107:
fastImageCopyResampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y, $system);
upload.php, line 182 (in bold):
**if (!createThumbnail($this->file_location, $this->file_thumb_location, KU_REPLYTHUMBWIDTH, KU_REPLYTHUMBHEIGHT))** { exitWithErrorPage(_gettext('Could not create thumbnail.'));
(note, that error does not show up)
The other post.php (line 235):
$upload_class->HandleUpload();
So what can I do? How can I fix this? I know this is a tough issue, but if you guys could give me any input, it would be greatly appreciated.
Oh and in case anyone is curious, here's the GIF: http://i.imgur.com/rmvau.gif
A: Have you tried setting the client_body_buffer_size directive in your nginx configs?
See more here: http://www.lifelinux.com/how-to-optimize-nginx-for-maximum-performance/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Storing HTML in MySQL: blob or text? I have to store large amount of HTML data in a database .
I have Googled and found something about the blob datatype, I checked it and it is working correctly.
I need to store the HTML pages in the tables and need to show them correctly as web pages on demand.
So, which is better for storing large HTML pages, text or blob?
A: I'd use blob it's a varbinary and does not do any translation. So your html will come out exactly the same way that it went in.
If you want to search and index that html TEXT may be a better choice.
In that case make sure you use the proper charset.
I'd recommend UTF8.
A: Seven years have passed since this question was asked. The database industry is converging on using UTF-8 for all text.
If you use TEXT and make it CHARACTER SET utf8mb4, and you do likewise for all other text fields (except postal_code, country_code, hex, and a few other that are defined to be ascii), then TEXT makes sense.
But, there is another consideration. If your HTML is an entire page, it makes good sense to put that in a file, not a database table. That way, it can be fetched directly by HTTP. Similarly images and BLOB lead to a argument for <img src=...> where ... is the url of a .jpg file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Java Desktop Application - how to obtain list of files with similar file names in a specific folder I have a Java Desktop Application, in which at an intermediate stage, some files with the following file names are generated
file-01-1.xml
file-01-2.xml
file-01-3.xml
and so on.
The number of files with such names is variable, I want to determine the total number of files of above type of name, so that I can then do further processing on these files. (THese files are generated by a DOS command which does not give number of files generated in its output/number of files generated varies depending on input file, hence this problem).
A: You can implement pure java solution using File.list(), File.listFiles() combining them with FileFilter. Both methods return arrays, so you can retrieve the array length to get number of files.
This method might be ineffective if number of files is very big (e.g. thousands). In this case I'd suggest you to implement platform specific solution by executing external command like sh ls file* | wc -l.
A: You can use a custom FilenameFilter when listing file in the output folder.
See: http://download.oracle.com/javase/6/docs/api/java/io/File.html#list%28java.io.FilenameFilter%29
A: Use File.listFiles(FilenameFilter) or similar methods.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to put wait condition in Signal-Slot? I am doing one web related project. Recently I hit on this situation. This is just a stub
Class My_Class
{
public:
My_Class();
void start();
public slots():
void after_Load_Function();
}
My_Class::My_Class()
{
//Some initializations
connect(WebPage,SIGNAL(finished()),this,SLOTS(after_Load_Function()));
}
void My_Class::start()
{
WebPage->load();
}
void My_Class::after_Load_Function()
{
//Do something with the finished WebPage
}
int main(int argc,char * argv[])
{
//Some Qt things
My_Class a;
a.start();
}
"WebPage" emits the signal "finished" when it loaded fully.
Now the problem is before the "webPage" got loaded the "start" is returning. Thereby the control reaches the "main". So, now the control should return from "start" only after "after_Load_Function" finishes it's job. Thereby I want the below sequence,
*
*main creates the My_Class object A.
*main calls "start" from A.
*start calls load from "WebPage" and it waits untill the "WebPage" emits "finished",
and that emit in turn calls the "after_Load_Function", and "after_Load_Function"
finishes it's job.
*now, the "start" returns
*main returns
But, I don't know how to make this kind of wait condition. How can I go about it?
A: You can do this by running a local event loop, letting the components process network income and load the page. When they emit the signal, you execute a slot on the event loop to quit it.
void My_Class::start()
{
QEventLoop qel;
QObject::connect(WebPage, SIGNAL(finished()), &qel, SLOT(quit()));
WebPage->load();
qel.exec();
}
I've been using this before and it works fine. I don't advice to use this too often though, because it will process events, including those that the caller of start might not be expecting to be processed during the call to start, so you need to document this to its callers. You can prevent the processing of some events by passing certain flags to QEventLoop::exec, like preventing to process user interface events.
A: You should never wait in UI code. You need to break your "main" function into pieces so the later part can be executed separately.
A: Use condition variables thats what they are used for. You can make threads wait on a condition variable and proceed when notified.
A: The WebPage->load() method is asynchronous, meaning that it runs immediately, not when the loading is complete. The operation runs in the background while you go to do other things.
This is considered a good thing, as it enables your app to be more responsive and get more done. For example, if your app has a GUI, you could update the GUI with some sort of animation that indicates that the web page is being retrieved.
If you prefer a model in which the application blocks until the page is fully loaded, then consider making this change:
void My_Class::start()
{
WebPage->load();
while (!WebPage->isLoaded())
Sleep(1);
after_Load_Function();
}
Notes:
*
*the Sleep function will work on Windows. If you are on a Unix OS you can use usleep.
*since this function will effectively block until the web page is loaded, there is no reason to use the signal from the web page object, you can just simply call your handler after the wait completes, as this will make your handler run in the same thread.
*doing this is really bad practice. You may get away with it if your program is command line and has no GUI and/or event loop, but you should consider a better design for your app where the loading of web pages does not block the whole app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: C++ variadic function templates The concept of variadic templates is quite confusing to me and I want to make it a bit more complex (well I think...).
Let us consider the following code:
template <typename T>
class base
{
template <typename... E>
virtual void variadic_method_here(E... args) = 0;
};
and an implementing class:
class derive : public base<some_object>
{
void variadic_method_here(concrete_args_here);
};
How do I do that?
A: I think if I were faced with this problem I'd use CRTP and overloads to solve the problem.
e.g.:
#include <iostream>
template <typename Impl>
class base {
public:
template <typename... E>
void foo(E... args) {
Impl::foo_real(args...);
}
};
class derived : public base<derived> {
public:
static void foo_real(double, double) {
std::cout << "Two doubles" << std::endl;
}
static void foo_real(char) {
std::cout << "Char" << std::endl;
}
};
int main() {
derived bar;
bar.foo(1.0,1.0);
bar.foo('h');
}
A: You can't have a templated virtual function.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Java complains I haven't implemented a method I have the following interface:
interface IBasicListNode<T> {
/**
* Returns the current element
*/
public T getElement();
/**
* Gets the next ListNode. Returns null if theres no next element
*/
public IBasicListNode<T> getNext();
/**
* Sets the next ListNode
*/
public void setNext(IBasicListNode<T> node);
}
And a class:
class BasicListNode<T> implements IBasicListNode<T> {
protected T _elem;
protected BasicListNode<T> _next;
public T getElement() {
return this._elem;
}
public BasicListNode<T> getNext() {
return this._next;
}
public void setNext(BasicListNode<T> node) {
this._next = node;
}
/**
* Transverse through ListNodes until getNext() returns null
*/
public BasicListNode<T> getLast() {
BasicListNode<T> tmp = this;
while (tmp != null) {
tmp = tmp.getNext();
}
return tmp;
}
}
And I got the folloeing error:
jiewmeng@JM-PC:/labs/Uni/CS1020/Lab/03/prob 2/LinkedList$ javac BasicListNode.java
BasicListNode.java:1: BasicListNode is not abstract and does not override
abstract method setNext(IBasicListNode<T>) in IBasicListNode
class BasicListNode<T> implements IBasicListNode<T> {
^
Why isn't java detecting that BasicListNode<T> implements IBasicListNode<T>?
A: The problem here is that you need to implement the method:
public void setNext(IBasicListNode<T> node);
Note the type of the parameter node is in fact IBasicListNode<T> and not simply BasicListNode<T>.
Take a look at the way ArrayList is implemented (here). It implements the Collection interface. Yet there is no addAll(ArrayList<T> list) method. Instead it must implement the Collection interface and thus it must implement a addAll(Collection<? extends E> c) method.
In you example you want to change your interface to read as follows:
public void setNext(IBasicListNode<T> node);
Then implement the method in your BasicListNode class as follows:
public void setNext(IBasicListNode<T> node) {
this._next = node;
}
*Note: Your _next variable must now be of type IBasicListNode<T> or you must some how check for and cast to BasicListNode.
EDIT:
To be clear ArrayList could in fact contain a method called addAll(ArrayList<T> list) if it wanted to but that is optional. However, it absolutely must contain a method called addAll(Collection<? extends E> c) in order to fully implement the Collection interface.
The take away of the story is that when implementing an interface your class must contain a method signature that is identical to the interface it is implementing. That is it must have the same return type, the same method name and the parameter list must have the same types and order.
EDIT 2:
To use instanceof with generics you will need to use the wildcard <?> as follows:
if(node instanceof BasicListNode<?>) {
this._next = (BasicListNode<T>)node;
}
This is needed as <T> is not a type that can be checked against at compile time since you don't know what type will be used at runtime. The <?> allows you accept a BasicListNode of any type generic.
As to why the getNext() method works despite having a slightly different return type has to do with the power of generics. There are a lot of special cases when using generics and requires a little more time to understand it all. For more details I would recommend looking up generics and perhaps taking a look at this post here. The accepted answer will only make things a little more confusing so I recommend taking a look at the second answer provided by Cam
A: your setnext() in the interface class should be
public void setNext(BasicListNode<T> node);
Its missing the argument that's implemented in the class. Change the interface to match the class or the class to match the interface and it will stop complaining.
Your interface should be:
public interface IBasicListNode<T> {
/**
* Returns the current element
*/
public T getElement();
/**
* Gets the next ListNode. Returns null if theres no next element
*/
public IBasicListNode<T> getNext();
/**
* Sets the next ListNode
*/
public void setNext(IBasicListNode<T> node);
}
For your next error remember to put
public infront of
public class BasicListNode<t> implements BasicListNodeI<T>
and
public interface IBasicListNode<T>
A: In your interface:
public void setNext();
in your class:
public void setNext(BasicListNode<T> node)
A: It's simply
You haven't reimplemented method public void setNext() without arguments!
If you need it to don't complain, change your interface to declare setNext like this
public void setNext(BasicListNode<T> node);
or implement interface like it is declared ;-)
A: Your interface has the following method:
public void setNext(IBasicListNode<T> node);
But your class has this one:
public void setNext(BasicListNode<T> node) {
The contract is thus not respected: the interface method accepts any implementation of IBasicListNode<T> as argument, whereas the class method only accepts the specific BasicListNode<T> implementation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626601",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Scala final vs val for concurrency visibility In Java, when using an object across multiple threads (and in general), it is good practice to make fields final. For example,
public class ShareMe {
private final MyObject obj;
public ShareMe(MyObject obj) {
this.obj = obj;
}
}
In this case, the visibility of obj will be consistent across multiple threads (let's assume obj has all final fields as well) since it is safely constructed using the final keyword.
In scala, it doesn't appear val compiles down to a final reference, but rather val is semantics in scala that prevents you from reassigning a variable (Scala final variables in constructor). If scala constructor variables are not defined as final, will they suffer from the same problem (when using these objects in actors)?
A: The answer to the other question is misleading. There are two meanings of the term final: a) for Scala fields/methods and Java methods it means "cannot be overridden in a subclass" and b) for Java fields and in JVM bytecode it means "the field must be initialized in the constructor and cannot be reassigned".
Class parameters marked with val (or, equivalently, case class parameters without a modifier) are indeed final in second sense, and hence thread safe.
Here's proof:
scala> class A(val a: Any); class B(final val b: Any); class C(var c: Any)
defined class A
defined class B
defined class C
scala> import java.lang.reflect._
import java.lang.reflect._
scala> def isFinal(cls: Class[_], fieldName: String) = {
| val f = cls.getDeclaredFields.find(_.getName == fieldName).get
| val mods = f.getModifiers
| Modifier.isFinal(mods)
| }
isFinal: (cls: Class[_], fieldName: String)Boolean
scala> isFinal(classOf[A], "a")
res32: Boolean = true
scala> isFinal(classOf[B], "b")
res33: Boolean = true
scala> isFinal(classOf[C], "c")
res34: Boolean = false
Or with javap, which can be conveniently run from the REPL:
scala> class A(val a: Any)
defined class A
scala> :javap -private A
Compiled from "<console>"
public class A extends java.lang.Object implements scala.ScalaObject{
private final java.lang.Object a;
public java.lang.Object a();
public A(java.lang.Object);
}
A: I think I may have misunderstood how var is compiled. I created the sample class
class AVarTest(name:String) {
def printName() {
println(name)
}
}
I ran javap -private and it resulted in
public class AVarTest extends java.lang.Object implements scala.ScalaObject{
private final java.lang.String name;
public void printName();
public AVarTest(java.lang.String);
}
And name is actually compiled to final.
This is also shown in Scala val has to be guarded with synchronized for concurrent access?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: Programmatically add a new layout inside a SwipeView I will try to explain my question in a very clear and understandable way.
I am currently using the SwipeView here: http://jasonfry.co.uk/?id=23
<uk.co.jasonfry.android.tools.ui.SwipeView
android:id="@+id/swipe_view"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<View android:id="@+id/view1" />
<View android:id="@+id/view2" />
<View android:id="@+id/view3" />
</uk.co.jasonfry.android.tools.ui.SwipeView>
That'quite easy and powerful, and of course working fine.
What I would like to achieve now is to add some of my loayouts programmatically inside this SwipeView.
I have now:
SwipeView svmain=(SwipeView) findViewById(R.id.svmain);
//View v= findViewById(R.layout.anylayout);
svmain.addView(v);
That's crashing because the xml I want to add is not in my main layout.
Any idea?
A: Just found the answer:
SwipeView svmain=(SwipeView) findViewById(R.id.svmain);
LayoutInflater inflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.header, null);
svmain.addView(view);
View view2 = inflater.inflate(R.layout.header, null);
svmain.addView(view2);
View view3 = inflater.inflate(R.layout.header, null);
svmain.addView(view3);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pass textures in shader The problem is that I pass two textures in shader, but the picture on 3-d model is the same for both sampler2D variables (It is with image "normal.jpg", the first one.). I'll be very grateful for help. Here is the code:
GLuint _textures[2];
glEnable(GL_TEXTURE_2D);
glGenTextures(2, _textures);
glActiveTexture(GL_TEXTURE0);
bump = [self loadTextureWithName: @"normal.jpg"];
//bump = [self loadTextureWithName: @"specular.jpg"];
glUniform1i(bump, 0);
glActiveTexture(GL_TEXTURE1);
diffuse = [self loadTextureWithName2: @"diffuse.jpg"];
glUniform1i(diffuse, 0);
- (GLuint) loadTextureWithName: (NSString*) filename{
CGImageRef textureImage = [UIImage imageNamed: filename].CGImage;
NSInteger texWidth = CGImageGetWidth(textureImage);
NSInteger texHeight = CGImageGetHeight(textureImage);
GLubyte *textureData = (GLubyte *)malloc(texWidth * texHeight * 4*sizeof(GLubyte));
memset((void*) textureData, 0, texWidth * texHeight * 4*sizeof(GLubyte));
CGContextRef textureContext = CGBitmapContextCreate(textureData,texWidth,texHeight,8, texWidth * 4,CGImageGetColorSpace(textureImage),kCGImageAlphaPremultipliedLast);
CGContextDrawImage(textureContext,CGRectMake(0.0, 0.0, (float)texWidth, (float)texHeight),textureImage);
CGContextRelease(textureContext);
//glActiveTexture(GL_TEXTURE0);
//glShadeModel(GL_FLAT);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
//glGenTextures(1, &TEX);
glBindTexture(GL_TEXTURE_2D, _textures[0]);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData);
free(textureData);
//texId = [NSNumber numberWithInt:TEX];
//[textureImage release];//
//[textureContext release];//
return _textures[0];
}
- (GLuint) loadTextureWithName2: (NSString*) filename{
CGImageRef textureImage = [UIImage imageNamed: filename].CGImage;
NSInteger texWidth = CGImageGetWidth(textureImage);
NSInteger texHeight = CGImageGetHeight(textureImage);
GLubyte *textureData = (GLubyte *)malloc(texWidth * texHeight * 4*sizeof(GLubyte));
memset((void*) textureData, 0, texWidth * texHeight * 4*sizeof(GLubyte));
CGContextRef textureContext = CGBitmapContextCreate(textureData,texWidth,texHeight,8, texWidth * 4, CGImageGetColorSpace(textureImage),kCGImageAlphaPremultipliedLast);
CGContextDrawImage(textureContext,CGRectMake(0.0, 0.0, (float)texWidth, (float)texHeight),textureImage);
CGContextRelease(textureContext);
//glActiveTexture(GL_TEXTURE1);
//glShadeModel(GL_FLAT);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
//glGenTextures(1, &TEX);
glBindTexture(GL_TEXTURE_2D, _textures[1]);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texWidth, texHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureData);
free(textureData);
return _textures[1];
}
A: These two lines:
glUniform1i(bump, 0);
glUniform1i(diffuse, 0);
Appear to point both of your sampler2Ds to the first texture unit. I'd imagine you want:
glUniform1i(diffuse, 1);
To set a sampler2D you pass it the texture unit that it should read from.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery in html injection For example I have 2 input's and one button with attribute, where i wanna use input values, it may be something like this:
<input data-link="test?input1=$('#input1'.val())&input2=$('input2.val()')" />
A: --------------Mind reading mode on---------------------
You have;
<input id='input1' type='text'>
<input id='input2' type='text'>
<input id='input3' type='text'>
<button>Copy data</button>
$(document).ready(function(){
$('button').click(function(){
var string = "test?input1="+$('#input1').val()+"&input2="+$('#input2').val();
$('#input3').data('link', string);
});
});
fiddle here http://jsfiddle.net/bGTQJ/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inline Function Arguments Passing Is there a need performance-wise for inline functions to pass its arguments by const reference like
foo(const T & a, const T &b)
compared to by value
foo(T a, T b)
if I don't change the values of a and b in the function? Does C++11 change recommend anything specific here?
A: Theoretically the ones without reference might be copied in memory as there is the possibility that your inline function might be modifying them (even if it actually doesn't).
In many cases the compiler is smart enough to pick out that kind of thing but it will depend on the compiler and the optimization settings. Also if your function call on any non-const member functions in the class variables then your compiler will have to be smart enough to check if they are modifying anything as well.
By using a const reference you can basically give it a fairly clear indication.
EDIT: I just to a look at the machine code for a simple test program compiled with GCC 4.6 in ddd. The generated code seemed identical so it does seem to be optimized out. It's still good practice though for other compilers and if nothing else give a clear indication of the code's intent. It's also possible there are more complex situations that the compiler can't optimize though.
Also the llvm online dissembler demo shows identical bitcode is generated there too. If you turn off optimization it is slightly longer without the const reference.
* 1964 bytes - No const reference (and no other consts on functions/paramaters)
* 1960 bytes - Just no const reference but other consts.
* 1856 bytes - With consts and const reference.
A: Pass by value can only elide the copy-constructor call if the argument is a temporary.
Passing primitive types by const reference will have no cost when the function is inlined. But passing a complex lvalue by value will impose a potentially expensive copy constructor call. So prefer to pass by const reference (if aliasing is not a problem).
A: Pass by reference is faster than by value depending on data type.
However for inline functions the function body (and thus all references / passed in values) are added to the line of code they are used in anyway so technically there are no variables being passed around, only more lines of code in the same area.
reference http://www.cprogramming.com/tutorial/lesson13.html
There is also a very helpful answer under the question should-i-take-arguments-to-inline-functions-by-reference-or-value
*
*Example may have been misleading, removed -
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Frozen Android emulator due to audio problems? Today I installed the latest version of Eclipse, Android SDK and AVD plugin. But I have a tedious problem. When I want to quit the emulator (with the X button), the emulator freezes and I can't click anything there anymore. Obviously it has something to do with the sound, because when I execute "pulseaudio -k" in console, the emulator quits.
Due to this fact, I tried the following to let the emulator at least run properly:
In Preferences->Android->Launch -> Default Emulator option -> -noaudio
and
Run Configuration -> Android Application -> [Application] -> Target -> Addidtional Emulator Command Line Options -> -noaudio
But nothing helps. Emulator stays frozen. Actually I want audio to run, but switching it off doesn't work either. So what can I do?
A: I replied on the issue, but just if interested:
you may need to disable audio output instead, this is not desirable for me, so just select alsa (or esd/oss) by setting environment variable
QEMU_AUDIO_DRV=alsa
Looks like there is no way to specify audio drivers in hardware.ini so the best solution is going to sdk tools directory, rename emulator in emulator.real and make a shell script named emulator containing:
#!/bin/sh
export QEMU_AUDIO_DRV=alsa
exec $(dirname $0)/emulator.real $*
then chmod 755 emulator
A: It's this problem described here:
http://code.google.com/p/android/issues/detail?id=17294
There is a workaround so that you can quit the emulator:
Set in your virtual devices "Audio Playback Support" and "Audio recording support" to "no".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how can i fetch the whole word on the basis of index no of that string in perl I have one string of line like
comments:[I#1278327] is related to office communicator.i fixed the bug to declare it null at first time.
Here I am searching index of I#then I want the whole word means [I#1278327]. I'm doing it like this:
open(READ1,"<letter.txt");
while(<READ1>)
{
if(index($_,"I#")!=-1)
{
$indexof=index($_,"I#");
print $indexof,"\n";
$string=substr($_,$indexof);##i m cutting that string first from index of I# to end then...
$string=substr($string,0,index($string," "));
$lengthof=length($string);
print $lengthof,"\n";
print $string,"\n";
print $_,"\n";
}
}
Is any API is there in perl to find the word length directly after finding the index of I# in that line.
A: You could do something like:
$indexof=index($_,"I#");
$index2 = index($_,' ',$indexof);
$lengthof = $index2 - $indexof;
However, the bigger issue is you are using Perl as if it were BASIC. A more perlish approach to the task of printing selected lines:
use strict;
use warnings;
open my $read, '<', 'letter.txt'; # safer version of open
LINE:
while (<$read>) {
print "$1 - $_" if (/(I#.*?) /);
}
A: I would use a regex instead, a regex will allow you to match a pattern ("I#") and also capture other data from the string:
$_ =~ m/I#(\d+)/;
The line above will match and set $1 to the number.
See perldoc perlre
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: python tweet parsing I'm trying to parse tweets data.
My data shape is as follows:
59593936 3061025991 null null <d>2009-08-01 00:00:37</d> <s><a href="http://help.twitter.com/index.php?pg=kb.page&id=75" rel="nofollow">txt</a></s> <t>honda just recalled 440k accords...traffic around here is gonna be light...win!!</t> ajc8587 15 24 158 -18000 0 0 <n>adrienne conner</n> <ud>2009-07-23 21:27:10</ud> <t>eastern time (us & canada)</t> <l>ga</l>
22020233 3061032620 null null <d>2009-08-01 00:01:03</d> <s><a href="http://alexking.org/projects/wordpress" rel="nofollow">twitter tools</a></s> <t>new blog post: honda recalls 440k cars over airbag risk http://bit.ly/2wsma</t> madcitywi 294 290 9098 -21600 0 0 <n>madcity</n> <ud>2009-02-26 15:25:04</ud> <t>central time (us & canada)</t> <l>madison, wi</l>
I want to get the total numbers of tweets and the numbers of keyword related tweets. I prepared the keywords in text file. In addition, I wanna get the tweet text contents, total number of tweets which contain mention(@), retweet(RT), and URL (I wanna save every URL in other file).
So, I coded like this.
import time
import os
total_tweet_count = 0
related_tweet_count = 0
rt_count = 0
mention_count = 0
URLs = {}
def get_keywords(filepath):
with open(filepath) as f:
for line in f:
yield line.split()
for line in open('/nas/minsu/2009_06.txt'):
tweet = line.strip()
total_tweet_count += 1
with open('./related_tweets.txt', 'a') as save_file_1:
keywords = get_keywords('./related_keywords.txt', 'r')
if keywords in line:
text = line.split('<t>')[1].split('</t>')[0]
if 'http://' in text:
try:
url = text.split('http://')[1].split()[0]
url = 'http://' + url
if url not in URLs:
URLs[url] = []
URLs[url].append('\t' + text)
save_file_3 = open('./URLs_in_related_tweets.txt', 'a')
print >> save_file_3, URLs
except:
pass
if '@' in text:
mention_count +=1
if 'RT' in text:
rt_count += 1
related_tweet_count += 1
print >> save_file_1, text
save_file_2 = open('./info_related_tweets.txt', 'w')
print >> save_file_2, str(total_tweet_count) + '\t' + srt(related_tweet_count) + '\t' + str(mention_count) + '\t' + str(rt_count)
save_file_1.close()
save_file_2.close()
save_file_3.close()
The keyword set likes
Happy
Hello
Together
I think my code has many problem, but the first error is as follws:
Traceback (most recent call last):
File "health_related_tweets.py", line 21, in <module>
keywords = get_keywords('./public_health_related_words.txt', 'r')
TypeError: get_keywords() takes exactly 1 argument (2 given)
Please help me out!
A: The issue is self explanatory in the error, you have specified two parameters in your call to get_keywords() but your implementation only has one parameter. You should change your get_keywords implementation to something like:
def get_keywords(filepath, mode):
with open(filepath, mode) as f:
for line in f:
yield line.split()
Then you can use the following line without that specific error:
keywords = get_keywords('./related_keywords.txt', 'r')
A: Now you are getting this error:
Traceback (most recent call last): File "health_related_tweets.py", line 23, in if keywords in line: TypeError: 'in ' requires string as left operand, not generator
The reason is that keywords = get_keywords(...) returns a generator. Logically thinking about it, keywords should be a list of all the keywords. And for each keyword in this list, you want to check if it's in the tweet/line or not.
Sample code:
keywords = get_keywords('./related_keywords.txt', 'r')
has_keyword = False
for keyword in keywords:
if keyword in line:
has_keyword = True
break
if has_keyword:
# Your code here (for the case when the line has at least one keyword)
(The above code would be replacing if keywords in line:)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Writing binary data from encrypted file to pointed memory location First of all the code for aes cryptographic function :
void
xorcrypto(u_int8_t *key, u_int32_t keylen,
u_int8_t *data, u_int32_t datalen)
{
/*u_int8_t ....etc are alias for uint8_t...etc so don't bother about them*/
FILE *fp,*fq,*fr;
int i;
fp=fopen("key","wb");
fwrite((char *)key,keylen,1,fp);
fq=fopen("file.txt","wb");
fwrite((char *)data,datalen,1,fq);
fclose(fq);
fclose(fp);
system("sudo openssl enc -aes-256-cbc -salt -in file.txt
-out file.enc -pass file:key");
/* Here is the code section i need*/
}
What i need in the code section i have specified above is that it should be able to
fill/change the data (pointed by u_int8_t*data) with the contents of file file.enc
Don't worry about the data length actually the input it is taking is from a n/w ip
packet so it has provision for data upto 1024 bytes and file contents are never going to
exceed this limit.
Here is my attempt for it (also for debugging purpose i need to mention the contents of file.enc as well as data section to stdout)
fr=fopen("file.enc","rb");
memset(data,0,sizeof(data));
i=0;
while( (ch=fgetc(fr))==EOF) {
data[i]=ch;
i++;
}
data[i]='\0';
i=0;
puts((char *)data);
printf("\n");
fclose(fr);
Here are some output snapshots which may help .....
udit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $ cat key
thisisaeskey
udit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $ cat file.txt
w�uP����abcd
udit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $ cat file.enc
Salted__����a�dR�P��l�C-<��y�O^Z��/a��3����Q
udit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $ hexdump -C file.enc
00000000 53 61 6c 74 65 64 5f 5f b6 f2 b2 d0 61 d9 64 1c |Salted__....a.d.|
00000010 52 e0 50 96 e8 6c 0e c0 43 2d 3c c4 f6 79 1b d2 |R.P..l..C-<..y..|
00000020 4f 5e 5a b1 d6 2f 61 f8 15 f6 33 e1 88 f0 db 51 |O^Z../a...3....Q|
00000030
udit@udit-Dabba ~/Downloads/sendip-2.5-mec-2/mec $
The functon is unable to change the contents of pointed location (u_int8_t *data) and so was unable to write data on stdout puts(data).
Please help me on this ...if any further information needed about this i will add it.
A: Try changing
while( (ch=fgetc(fr))==EOF)
into
while( (ch=fgetc(fr))!=EOF)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Printing all Possible nCr Combinations in Java I'm trying to print out all possibilities of nCr, which are the combinations when order doesn't matter. So 5C1 there are 5 possibilities: 1 , 2, 3, 4, 5. 5C2 there are 10 possibilities: 1 2, 1 3, 1 4, 1 5, 2 3, 2 4, 2 5, 3 4, 3 5, 4 5.
I made functions that print what I want for r = 2, r = 3, and r = 4, and I sort of see the pattern, but I cant seem to make a working method for variable r:
public void printCombinationsChoose2(int n, int k) //for when k = 2
{
for (int a = 1; a < n; a++)
{
for (int b = a + 1; b <= n; b++)
{
System.out.println("" + a + " " + b);
}
}
}
public void printCombinationsChoose3(int n, int k) //for when k = 3
{
for (int a = 1; a < n - 1; a++)
{
for (int b = a + 1; b < n; b++)
{
for (int c = b + 1; c <= n; c++)
{
System.out.println("" + a + " " + b + " " + c);
}
}
}
}
public void printCombinationsChoose4(int n, int k) //for when k = 4
{
for (int a = 1; a < n - 2; a++)
{
for (int b = a + 1; b < n - 1; b++)
{
for (int c = b + 1; c < n; c++)
{
for (int d = c + 1; d <= n; d++)
{
System.out.println("" + a + " " + b + " " + c + " " + d);
}
}
}
}
}
public void printCombinations(int n, int k) //Doesn't work
{
int[] nums = new int[k];
for (int i = 1; i <= nums.length; i++)
nums[i - 1] = i;
int count = 1;
while (count <= k)
{
for (int a = nums[k - count]; a <= n; a++)
{
nums[k - count] = a;
for (int i = 0; i < nums.length; i++)
System.out.print("" + nums[i] + " ");
System.out.println();
}
count++;
}
}
So I think the layout of my last method is right, but I'm just not doing the right things, because when I call printCominbations(5, 2), it prints
1 2
1 3
1 4
1 5
1 5
2 5
3 5
4 5
5 5
when it should be what I said earlier for 5C2.
Edit
The last example was bad. This is a better one to illustrate what it's doing wrong: printCombinations(5, 3) gives this:
1 2 3
1 2 4
1 2 5
1 2 5
1 3 5
1 4 5
1 5 5
1 5 5
2 5 5
3 5 5
4 5 5
5 5 5
How do I get it to be:
1 2 3
1 2 4
1 2 5
1 3 4
1 3 5
1 4 5
2 3 4
2 3 5
2 4 5
3 4 5
A: How about this:
public class Test {
public static void main(final String[] args) {
print_nCr(7, 4);
}
public static final void print_nCr(final int n, final int r) {
int[] res = new int[r];
for (int i = 0; i < res.length; i++) {
res[i] = i + 1;
}
boolean done = false;
while (!done) {
System.out.println(Arrays.toString(res));
done = getNext(res, n, r);
}
}
/////////
public static final boolean getNext(final int[] num, final int n, final int r) {
int target = r - 1;
num[target]++;
if (num[target] > ((n - (r - target)) + 1)) {
// Carry the One
while (num[target] > ((n - (r - target)))) {
target--;
if (target < 0) {
break;
}
}
if (target < 0) {
return true;
}
num[target]++;
for (int i = target + 1; i < num.length; i++) {
num[i] = num[i - 1] + 1;
}
}
return false;
}
}
The key to this solution for me was to look at the problem as a numbering system and you want to increase a number by one and every time you reach an upper bound, you just carry the excess to the left one and ... You just need to implement the increasing algorithm correctly...
A: The first point where your code deviates from the expectation is here:
...
1 2 5
1 2 5 <-- first bad output
1 3 5
...
So ask yourself three things:
*
*What should have happened in that line of code with the given state of the variables?
*Why doesn't do my code exactly that?
*What must be changed to achieve that?
The answer for the first part is like this:
*
*It should have incremented the 2 to 3 and it should have set the following numbers to
4, 5, ... similar to the initialisation of nums.
The second and third part is your part again.
BTW: When you come back because you need more help, please explain in detail what you have deduced so far and clean up and shorten the question quite a bit.
A: OK... What is the solution when we know we need loops, but not the number of them?? RECURSION...
You need to use a recursive implementation. Have this in mind: ANYTIME, you need loops but the number of the nested loops can only be known at runtime, based on the specific parameters of the problem, you should use recursive methods... I'll give you some time to try it yourself, I'll be back to give you the final implementation...
A: I have done it in c++
#include <iostream>
using namespace std;
#define ARR_LIMIT 100
int arr[ARR_LIMIT];
void _ncr(int N,int R, int n,int r , int start )
{
if(r>0)
{
for(int i = start ; i <= start + (n-r); i++)
{
arr[R-r] = i;
_ncr(N,R,N-i, r-1, i+1 );
}
}
else
{
for(int i=0;i<R;i++)
{
cout << arr[i] << " ";
if(i==R-1)
cout<<"\n";
}
}
}
void ncr(int n,int r)
{
//Error checking of parameters
bool error = false;
if( n < 1)
{
error = true;
cout<< "ERROR : n should be greater 0 \n";
}
if( r < 1)
{
error = true;
cout<< "ERROR : r should be greater 0 \n";
}
if(r > n)
{
error = true;
cout<< "ERROR : n should be greater than or equal to r \n";
}
// end of Error checking of parameters
if(error)
return;
else
_ncr(n,r,n,r,1);
}
int main()
{
int n,r;
cout << "Enter n : ";
cin >> n;
cout << "Enter r : ";
cin >> r;
ncr(n,r);
return 0;
}
A: The layout of function printCombination() seems wrong. The while loop will iterate two times, for count = 1 and count = 2.
When count = 1, only values in nums[0][here] will change, since in this case k - count = 1.
Hence,
1,2
1,3
1,4 and
1,5.
And when count = 2, only values in nums[here][1] will change, since here k - count = 0.
Hence
1,5
2,5
3,5
4,5 and
5,5
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: In Windows, how do I find out which process is on the other end of a local network socket? That is to say, if I have a server listening on 127.0.0.1, and a TCP connection comes in, how can I determine the process id of the client?
Also if there isn't an API for this, where would I be able to extract the information from in a more hackish manner?
(The purpose of this is to modify a local HTTP proxy server to accept or deny requests based on the requesting process.)
Edit: palacsint's answer below led me to find this answer to a similar question which is just what's needed
A: netstat -a -o
prints it. I suppose they are on the same machine becase you are listening on 127.0.0.1.
A: The only way to do this is if the connecting process sends some sort of custom headers which contains identifier. This is due to the fact that the networking layer is completely separated from the application layer (hint: OSI MODEL. This way it is possible to write lower layers software without caring what happens above as long as the messages exchanged (read: networking packets) follow a pre-determined format (read: use the same protocol).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Undefined reference to svc_create My problem is the following: I'm trying to implement a C RPC example and I keep running into the following compiler error:
remote_exec.c: In function ‘main’:
remote_exec.c:13:3: warning: implicit declaration of function ‘svc_create’
remote_exec.o: In function `main':
remote_exec.c:(.text+0x31): undefined reference to `svc_create'
collect2: ld returned 1 exit status
My code:
#include <stdio.h>
#include <rpc/rpc.h>
#include "rls.h"
int main(int argc, char* argv[])
{
extern void execute();
const char* nettype = "tcp";
int no_of_handles;
no_of_handles = svc_create(execute, EXECPROG, EXECVERS, nettype);
svc_run();
return 0;
}
I really don't know how to solve this. The man page and all the examples I've studied just say to include rpc/rpc.h, however it doesn't seem to work. I am compiling with
gcc -Wall -c
A: There is no such function as svc_create on linux in libc. See the manpage for rpc. Your guide is using the transport independent(ti) RPC library of Solaris and other unixes. See this question for RPC guides for linux.
The RPC library in linux is based on a slightly different RPC library than the ti-RPC library from Sun, though there is a ti-RPC library here: http://nfsv4.bullopensource.org/doc/tirpc_rpcbind.php , if you use that library, you link with -ltirpc
You probably need svctcp_create or svcudp_create if you're using the standard RPC library included in glibc.
A: You probably have to link against the library when you create your program. If the library is called rpc, for example, this would be done by adding -lrpc to the compiler command line that creates the final executable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a more generic way of iterating,filtering, applying operations on collections in F#? Let's take this code:
open System
open System.IO
let lines = seq {
use sr = new StreamReader(@"d:\a.h")
while not sr.EndOfStream do yield sr.ReadLine()
}
lines |> Seq.iter Console.WriteLine
Console.ReadLine()
Here I am reading all the lines in a seq, and to go over it, I am using Seq.iter. If I have a list I would be using List.iter, and if I have an array I would be using Array.iter. Isn't there a more generic traversal function I could use, instead of having to keep track of what kind of collection I have? For example, in Scala, I would just call a foreach and it would work regardless of the fact that I am using a List, an Array, or a Seq.
Am I doing it wrong?
A: You may or may not need to keep track of what type of collection you deal with, depending on your situation.
In case of simple iterating over items nothing may prevent you from using Seq.iter on lists or arrays in F#: it will work over arrays as well as over lists as both are also sequences, or IEnumerables from .NET standpoint. Using Array.iter over an array, or List.iter over a list would simply offer more effective implementations of traversal based on specific properties of each type of collection. As the signature of Seq.iter Seq.iter : ('T -> unit) -> seq<'T> -> unit shows you do not care about your type 'T after the traversal.
In other situations you may want to consider types of input and output arguments and use specialized functions, if you care about further composition. For example, if you need to filter a list and continue using result, then
List.filter : ('T -> bool) -> 'T list -> 'T list will preserve you the type of underlying collection intact, but Seq.filter : ('T -> bool) -> seq<'T> -> seq<'T> being applied to a list will return you a sequence, not a list anymore:
let alist = [1;2;3;4] |> List.filter (fun x -> x%2 = 0) // alist is still a list
let aseq = [1;2;3;4] |> Seq.filter (fun x -> x%2 = 0) // aseq is not a list anymore
A: Seq.iter works on lists and arrays just as well.
The type seq is actually an alias for the interface IEnumerable<'T>, which list and array both implement. So, as BLUEPIXY indicated, you can use Seq.* functions on arrays or lists.
A less functional-looking way would be the following:
for x in [1..10] do
printfn "%A" x
A: List and Array is treated as Seq.
let printAll seqData =
seqData |> Seq.iter (printfn "%A")
Console.ReadLine() |> ignore
printAll lines
printAll [1..10]
printAll [|1..10|]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why does closing the simulator make my app receive SIGTERM when my app is in the background? When I get this:
- (void)applicationWillResignActive:(UIApplication *)application {
I release all my objects and invalidate all my timers.
When I get this:
- (void)applicationDidBecomeActive:(UIApplication *)application {
I reallocate all my objects and get my timers running again.
It all works fine except that now if I put my program into the background, then I actually terminate the program by closing the IOS Simulator, it gives a SIGTERM signal at line:
int retVal = UIApplicationMain(argc, argv, nil, nil);
On the other hand if I terminate the program by closing the IOS Simulator without putting it into the background first it does not give the SIGTERM signal.
Am I doing something wrong?
For me the leading cause of these kinds of SIGTERMs has been the following. If I release any object that I never owned or already released just prior to terminating the program, then I get that SIGTERM when I terminate the program.
I do not know how to get info from the simulator or debugger about which object I have done this to. But knowing from the SIGTERM that I have done an extraneous release has been enough for me to hunt it down by inspection.
If anyone knows how to look-up which object has been released extraneously in xcode please chime in.
A: You're not doing anything wrong. When you close the iOS Simulator, it kills your app by sending it SIGTERM. Period. That's just the way it works. If you leave your app in the foreground, it'll still be killed, just not by a SIGTERM. Your app is still connected to the simulator when it's in the background; it cannot continue existing without the simulator and it has no way to connect to another instance of the simulator should you start one.
If you don't want your app to receive SIGTERM, don't close the simulator.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Testing of App on Tablet, Android I need to create application for Tablet, Android. I never create app fot Tablet, only mobile with Android. How can I create emulator for tablet testing? And 1 thing - I need to know a width of screen for logotype creating - what screen size Tablet have?
A: For a tablet emulator, just create an AVD using Android 3.0, 3.1 or 3.2 -- this should automatically get you a WXGA (1280x800) screen.
For tablet screen sizes, check out Supporting Multiple Screens: Configuration Examples from the Android documentation:
*
*320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
*480dp: a tweener tablet like the Streak (480x800 mdpi).
*600dp: a 7” tablet (600x1024 mdpi).
*720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).
Most tablets will be in the 7” and 10” range.
A: First, create fluid layout, so your application will fit any screen size
*
*How to create Liquid Layout in android
*http://envyandroid.com/archives/227/stretching-and-spanning-layouts
Second, in android emulator you can change screen size (in settings of ADV)
*
*How do I change screen orientation in the Android emulator?
*How to resize the AVD emulator (in Eclipse)?
*http://developer.android.com/guide/developing/tools/emulator.html
Third, screen size to set you can get in technical details of tablet
*
*GalaxyPad 1280x800 (http://www.samsung.com/global/microsite/galaxytab/10.1/spec.html)
*Motorola XOOM 1280x800 (http://www.motorola.com/Consumers/US-EN/Consumer-Product-and-Services/Tablets/ci.MOTOROLA-XOOM-with-WiFi-US-EN.alt)
*and many more, depends on your choice
A: Sure you can. Just use the android tool to download the SDK for Android 3.0+ (r11 for example) and create an emulator like you would normally.
Note that the 3.0+ emulators like to crash from time to time from my expirience.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MEF vs Unity import into view model When using unity you can import the container in the constructor of a view moder per say.
But how would I do import a MEF container into a view model to resolve instances?
Thanks
A: Generally, it is not a great idea to be passing round the container, as you end up using it as more of a service-location mechanism, but should you wish to do so, you would need to manually export the container, e.g.:
var container = new CompositionContainer(catalog);
container.ComposeExportedValue(container);
This will enable you to import it:
[Import]
public CompositionContainer Container { get; set; }
Or:
[ImportingConstructor]
public MyClass(CompositionContainer container) { }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Django: Query with F() into an object not behaving as expected I am trying to navigate into the Price model to compare prices, but met with an unexpected result.
My model:
class ProfitableBooks(models.Model):
price = models.ForeignKey('Price',primary_key=True)
In my view:
foo = ProfitableBooks.objects.filter(price__buy__gte=F('price__sell'))
Producing this error:
'ProfitableBooks' object has no attribute 'sell'
A: Is this your actual model or a simplification? I think the problem may lie in having a model whose only field is its primary key is a foreign key. If I try to parse that out, it seems to imply that it's essentially a field acting as a proxy for a queryset-- you could never have more profitable books than prices because of the nature of primary keys. It also would seem to mean that your elided books field must have no overlap in prices due to the implied uniqueness constraints.
If I understand correctly, you're trying to compare two values in another model: price.buy vs. price.sell, and you want to know if this unpictured Book model is profitable or not. While I'm not sure exactly how the F() object breaks down here, my intuition is that F() is intended to facilitate a kind of efficient querying and updating where you're comparing or adjusting a model value based on another value in the database. It may not be equipped to deal with a 'shell' model like this which has no fields except a joint primary/foreign key and a comparison of two values both external to the model from which the query is conducted (and also distinct from the Book model which has the identifying info about books, I presume).
The documentation says you can use a join in an F() object as long as you are filtering and not updating, and I assume your price model has a buy and sell field, so it seems to qualify. So I'm not 100% sure where this breaks down behind the scenes. But from a practical perspective, if you want to accomplish exactly the result implied here, you could just do a simple query on your price model, b/c again, there's no distinct data in the ProfitableBooks model (it only returns prices), and you're also implying that each price.buy and price.sell have exactly one corresponding book. So Price.objects.filter(buy__gte=F('sell')) gives the result you've requested in your snipped.
If you want to get results which are book objects, you should do a query like the one you've got here, but start from your Book model instead. You could put that query in a queryset manager called "profitable_books" or something, if you wanted to substantiate it in some way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Are there any cons to putting revision number on app home page? There are obvious pros of having revision number somewhere on the page (like on stackoverflow.com): easy for users to identify and report version, when they have issues; easy way to see that deployment was successful; etc.
Are there any cons to that practice?
A: If you are running an Open Source/Packaged Web Application then it may be inadvisable to display the Revision Number because if any Security Holes are found then it is easy to determine if your site is exploitable.
However if you are deploying an internal tool or something then it could be useful like you say for bug reporting and debugging.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Access a Model property in a javascript file? Is it possible to access a Model property in an external Javascript file?
e.g. In "somescript.js" file
var currency = '@Model.Currency';
alert(currency);
On my View
<script src="../../Scripts/somescript.js" type="text/javascript">
This doesn't appear to work, however if I put the javascript directly into the view inside script tags then it does work? This means having to put the code in the page all the time instead of loading the external script file like this:
@model MyModel;
<script lang=, type=>
var currency = '@Model.Currency';
alert(currency);
</script>
Is there any way around this?
A: There is no way to implement MVC / Razor code in JS files.
You should set variable data in your HTML (in the .cshtml files), and this is conceptually OK and does not violate separation of concerns (Server-generated HTML vs. client script code) because if you think about it, these variable values are a server concern.
Take a look at this (partial but nice) workaround: Using Inline C# inside Javascript File in MVC Framework
A: What you could do is passing the razor tags in as a variable.
In razor File>
var currency = '@Model.Currency';
doAlert(currency);
in JS file >
function doAlert(curr){
alert(curr);
}
A: I tackled this problem using data attributes, along with jQuery. It makes for very readable code, and without the need of partial views or running static javascript through a ViewEngine. The JavaScript file is entirely static and will be cached normally.
Index.cshtml:
@model Namespace.ViewModels.HomeIndexViewModel
<h2>
Index
</h2>
@section scripts
{
<script id="Index.js" src="~/Path/To/Index.js"
data-action-url="@Url.Action("GridData")"
data-relative-url="@Url.Content("~/Content/Images/background.png")"
data-sort-by="@Model.SortBy
data-sort-order="@Model.SortOrder
data-page="@ViewData["Page"]"
data-rows="@ViewData["Rows"]"></script>
}
Index.js:
jQuery(document).ready(function ($) {
// import all the variables from the model
var $vars = $('#Index\\.js').data();
alert($vars.page);
alert($vars.actionUrl); // Note: hyphenated names become camelCased
});
_Layout.cshtml (optional, but good habit):
<body>
<!-- html content here. scripts go to bottom of body -->
@Scripts.Render("~/bundles/js")
@RenderSection("scripts", required: false)
</body>
A: Try JavaScriptModel ( http://jsm.codeplex.com ):
Just add the following code to your controller action:
this.AddJavaScriptVariable("Currency", Currency);
Now you can access the variable "Currency" in JavaScript.
If this variable should be available on the hole site, put it in a filter. An example how to use JavaScriptModel from a filter can be found in the documentation.
A: What i did was create a js object using the Method Invocation pattern, then you can call it from the external js file. As js uses global variables, i encapsulate it to ensure no conflicts from other js libraries.
Example:
In the view
@section scripts{
<script>
var thisPage = {
variableOne: '@Model.One',
someAjaxUrl: function () { return '@Url.Action("ActionName", "ControllerName")'; }
};
</script>
@Scripts.Render("~/Scripts/PathToExternalScriptFile.js")
}
Now inside of the external page you can then get the data with a protected scope to ensure that it does not conflict with other global variables in js.
console.log('VariableOne = ' + thisPage.variableOne);
console.log('Some URL = ' + thisPage.someAjaxUrl());
Also you can wrap it inside of a Module in the external file to even make it more clash proof.
Example:
$(function () {
MyHelperModule.init(thisPage || {});
});
var MyHelperModule = (function () {
var _helperName = 'MyHelperModule';
// default values
var _settings = { debug: false, timeout:10000, intervalRate:60000};
//initialize the module
var _init = function (settings) {
// combine/replace with (thisPage/settings) passed in
_settings = $.extend(_settings, settings);
// will only display if thisPage has a debug var set to true
_write('*** DEBUGGER ENABLED ***');
// do some setup stuff
// Example to set up interval
setInterval(
function () { _someCheck(); }
, _settings.intervalRate
);
return this; // allow for chaining of calls to helper
};
// sends info to console for module
var _write = function (text, always) {
if (always !== undefined && always === true || _settings.debug === true) {
console.log(moment(new Date()).format() + ' ~ ' + _helperName + ': ' + text);
}
};
// makes the request
var _someCheck = function () {
// if needed values are in settings
if (typeof _settings.someAjaxUrl === 'function'
&& _settings.variableOne !== undefined) {
$.ajax({
dataType: 'json'
, url: _settings.someAjaxUrl()
, data: {
varOne: _settings.variableOne
}
, timeout: _settings.timeout
}).done(function (data) {
// do stuff
_write('Done');
}).fail(function (jqxhr, textStatus, error) {
_write('Fail: [' + jqxhr.status + ']', true);
}).always(function () {
_write('Always');
});
} else {// if any of the page settings don't exist
_write('The module settings do not hold all required variables....', true);
}
};
// Public calls
return {
init: _init
};
})();
A: You could always try RazorJs. It's pretty much solves not being able to use a model in your js files RazorJs
A: I had the same problem and I did this:
View.
`var model = @Html.Raw(Json.Encode(Model.myModel));
myFunction(model);`
External js.
`function myFunction(model){
//do stuff
}`
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: Double border size on hover pseudo-class On my nav bar there are two nav links with rounded borders, which when they are hovered, the border size doubles. I can't get it to work without the nav link moving on hover and the hover border doesn't match the area of the original border. I'm sure it has to do with padding but I've tried everything I can think of. See example code - http://jsfiddle.net/mGjs6/3/
A: You need to change
#signup a:hover
to
#signup:hover
and remove the width
#signup:hover {
border: solid 2px #55971e;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
}
Example: http://jsfiddle.net/jasongennaro/mGjs6/6/
Same with #clientarea
The issue with the not matching up was the one element #signup had the border but then you were changing the border of a child element (a) on hover.
EDIT
As per the comment
However when you hover, the text still moves to adjust for the
increased border. The text needs to remain fixed with only the border
changing.
That happens because the border size is increasing. That is what is pushing the text down a pixel (that's the increase in border size)
You can't fix that perfectly. Better to change the color of the border or the background.
Example 2: http://jsfiddle.net/jasongennaro/mGjs6/9/
(Hover over both to see the suggestions)
EDIT 3
I figured it out: decrease the padding by a pixel on the hover and it all works
#signup:hover {
border: solid 2px #55971e;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
padding:3px 4px; //ADD THIS
}
Example 3: http://jsfiddle.net/jasongennaro/mGjs6/10/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626663",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: host a facebook app on multiple locations (variable redirect_uri) I'm currently building a facebook app integration and got stuck on error 191: The specified URL is not owned by the application. (when trying to authenticate a user)
I realize the problem is the Site URL, which was not entered. However, my problem is the fact that Facebook will only redirect users to URI's on this domain - and my app will be hosted on more than one server.
It's a private admin app that will be sold to more than one client, and deployed to their server and domain. Thus, each client will have this app requesting redirect_uri back to their location, one will be installed on mysite1.com and another on mysite2.com
It appears that my only solution now is to create a separate app for each client (?)
Is there a way to request login redirection to an arbitrary URI ?
A: I don't think you can use that kind of a model with facebook apps.
the facebook app allows you to add multiple domain names in the console now but it is not feasible to enter every name of every client to your application setting.
maybe you should think of having one central system and sell subscription service to your clients
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Space after reading in HTML content and echoing it I have an index.php-file, which will echo the string with the returned .html-file prepared by the function which is called in the index.php-file
index.php:
require_once('functions.php');
echo create_page();
functions.php:
function create_page() {
$result = file_get_contents('index.html');
return $result;
}
The problem is that everytime, the html is generated with this functions, I have a gap at the bottom of the page.
If I include several .html-pages into a .html-page with str_replace, a gap is at the top of every replacement.
If I display the .html-file by double-clicking it, it will be displayed without a gap at the bottom.
What am I doing wrong here?
There are no additional echos in the script.
A: Check your php files, I bet they contain some new lines / spaces / tabs / other-white psace characters after php closing tag (?>). The best is to omit this closing tag, then every whitespace from the end of file will be treated as php source (harmless) and will not produce any output.
A: Ok Here ist the soluton:
Don't allow BOM in your texteditor-settings!
The BOM could not be interpreted from the browser, so he added the gap at the bottom of every file which has BOM enabled...
Hope it helps someone else!
Thank you everyone!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626668",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why doesnt work? Its my understanding that by adding the ScaffoldColumn(false) annotation to an property in a class, that property will not added to the view when doing Add View. However even though i have added scaffoldcolumn false to properties i dont want added to a Create form, they are still rendered inthe create view. Is ScaffoldColumn broken? On page 552 in Pro ASP.NET MVC 3 Framework by Freeman and Sanderson, it states
"If we want to exclude a property from the generated HTML, we can use
ScaffoldColumn attribute. When the scaffolding helpers see the
ScaffoldColumn attribute, they skip over the property entirely; no
hidden input elements will be generated and no details of this
property will be included in the generated HTML."
Also the MVC Music Store PDF on p 77 indicates that the attrtibute will do the same -
"Allows hiding fields from editor forms".
They add it to the AlbumId property and then when the app is run AlbumId field is not shown in the browser.
Is this attr broken?
If i change a html helper to DisplayFor it does not appear in the form regardless of whether scaffoldcolumn is present. For example i dont have scaffoldcolumn false on Property PostTitle but if i change @Html.EditorFor(Function(model) model.PostTitle) to displayfor then it does not render regardless of the scaffoldcolumn attr.
Also my Create view is strongly typed to @ModelType RiderDesignMvcBlog.Core.Entities.Post
A: Received this answer in the asp.net forums:
That statement is incorrect. The attribute is recognized by Dynamic
Data, but not by MVC 3 Scaffolding. When I asked about this in March
of this year, I got this response from the team that created the
MvcScafolding Nuget package:
Yes, that particular bit of metadata just isn’t recognized by the
MvcScaffolding T4 templates. There’s a lot of possible metadata, and a
lot of code necessary to recognize and respond to it all, and we have
to trade that off against keeping the T4 templates simple enough that
people can understand and customize them and not be overwhelmed with
all the logic. I don’t think the MVC 3 built-in Add View templates
respond to that one either.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626671",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: List> generics issue I have the following method:
public static List<List<String>> createObject() {
List<List<String>> listOfListOfStrings = new LinkedList<List<String>>();
List<String> listOfStrings = new LinkedList<String>();
//do some populating on the lists here
listOfListOfStrings.add(listOfStrings);
return listOfListOfStrings;
}
Now I want to be able to use an ArrayList/Vector/Stack instead of the LinkedList (and do different combinations if needed. I read some posts on generics regarding this issue and I found out that using a factory pattern for creating those is most suited (since I don't want reflection, and since using the generic <T extends List<K>, K extends List<String>> would not work.). So the solution I came up with is the following:
public class Tester {
public static void main(String[] args){
checkGenericsOfLists();
}
public static void checkGenericsOfLists(){
List<List<String>> listOfListOfStrings = createObject(new LinkedListFactory<List<String>>(), new LinkedListFactory<String>());
print(listOfListOfStrings);
translate(listOfListOfStrings);
print(listOfListOfStrings);
}
public static List<List<String>> createObject(ListFactorable mainListFactory, ListFactorable subListsFactory) {
List<List<String>> listOfListOfStrings = mainListFactory.create();//new LinkedList<List<String>>();
List<String> listOfStrings = subListsFactory.create();//new LinkedList<String>();
listOfStrings.add("A");
listOfListOfStrings.add(listOfStrings);
return listOfListOfStrings;
}
public static void transform(List<List<String>> listOfListOfStrings){
//do some abuse on the lists here.
}}
This solution gives warnings:
ListFactorable is a raw type. References to generic type ListFactorable should be parameterized
This is for the createObject method signature. And:
Type safety: The expression of type List needs unchecked conversion to conform to List of List of String>>
This is for the lines where the factory invokes the create() method.
But if I use this one:
public static List<List<String>> createObject(ListFactorable<List<List<String>>, List<String>> mainListFactory, ListFactorable<List<String>, String> subListsFactory) {
List<List<String>> listOfListOfStrings = mainListFactory.create();//new LinkedList<List<String>>();
List<String> list = subListsFactory.create();//new LinkedList<String>();
list.add("A");
listOfListOfStrings.add(list);
return listOfListOfStrings;
}
I get compiler error:
The method createObject(ListFactorable<List<List<String>>,List<String>>, ListFactorable<List<String>,String>) in the type Tester is not applicable for the arguments (LinkedListFactory<List<String>>, LinkedListFactory<String>)
Is there any way I can make the compiler not throw warning or error and have those lists instantiated without the createObject method being aware of the List implementation used (during compile time)?!
Cheers,
Despot
EDIT:
Excuse me for not posting the rest of the classes (very silly of me:)). Here we go:
public interface ListFactorable<T extends List<K>, K> {
T create();}
public class LinkedListFactory<K> implements ListFactorable<LinkedList<K>, K> {
public LinkedList<K> create(){
return new LinkedList<K>();
}}
EDIT2 (Eugene take on issue):
public interface EugeneListFactorable<T extends List<?>> {T create();}
public class EugeneLinkedListFactory implements EugeneListFactorable<LinkedList<?>> {
public LinkedList<?> create(){
return new LinkedList<List<?>>();
}
}
public static void checkGenericsOfLists2(){
List<List<String>> listOfListOfStrings = createObject(new EugeneLinkedListFactory(), new EugeneLinkedListFactory());
translate(listOfListOfStrings);
}
Compiler error:
- Type mismatch: cannot convert from LinkedList<?> to List<List<String>>
- Bound mismatch: The generic method createObject(EugeneListFactorable<N>, EugeneListFactorable<M>) of type
Tester is not applicable for the arguments (EugeneLinkedListFactory, EugeneLinkedListFactory). The inferred type LinkedList<?>
is not a valid substitute for the bounded parameter <N extends List<List<String>>>
Please do try to compile and run the example I posted and your solution. Its a test class which you can easily run on ur IDE. Thanks!
A: The followin stuff "works on my machine" without warnings or errors. What is beyond my perception is the reason for all the fuss - see the seconds codeblock.
public class Tester {
public static void main(String[] args) {
checkGenericsOfLists();
}
public static void checkGenericsOfLists() {
List<List<String>> listOfListOfStrings = createObject(
new LinkedListFactory<List<String>>(),
new LinkedListFactory<String>());
transform(listOfListOfStrings);
}
public static List<List<String>> createObject(
ListFactorable<List<List<String>>, List<String>> mainListFactory,
ListFactorable<List<String>, String> subListsFactory
)
{
List<List<String>> listOfListOfStrings = mainListFactory.create();
List<String> listOfStrings = subListsFactory.create();
listOfStrings.add("A");
listOfListOfStrings.add(listOfStrings);
return listOfListOfStrings;
}
public static void transform(List<List<String>> listOfListOfStrings) {
// do some abuse on the lists here.
System.out.println(listOfListOfStrings);
}
public interface ListFactorable<T extends List<K>, K> {
T create();
}
static public class LinkedListFactory<K> implements ListFactorable<List<K>, K> {
public LinkedList<K> create() {
return new LinkedList<K>();
}
}
}
This solution is a little bit cleaner leaving out some generics noise.
public class Tester2 {
public static void main(String[] args) {
checkGenericsOfLists();
}
public static void checkGenericsOfLists() {
List<List<String>> listOfListOfStrings = createObject(
new LinkedListFactory<List<String>>(),
new LinkedListFactory<String>());
transform(listOfListOfStrings);
}
public static List<List<String>> createObject(
ListFactory<List<String>> mainListFactory,
ListFactory<String> subListsFactory
)
{
List<List<String>> listOfListOfStrings = mainListFactory.create();
List<String> listOfStrings = subListsFactory.create();
listOfStrings.add("A");
listOfListOfStrings.add(listOfStrings);
return listOfListOfStrings;
}
public static void transform(List<List<String>> listOfListOfStrings) {
// do some abuse on the lists here.
System.out.println(listOfListOfStrings);
}
public interface ListFactory<T> {
List<T> create();
}
static public class LinkedListFactory<T> implements ListFactory<T> {
public List<T> create() {
return new LinkedList<T>();
}
}
}
A: This won't exactly solve your problem, but it will lend itself to finding the solution faster.
When you have anything that looks like this X> consider refactoring into a class. I'll provide an example. You look like you're using transations. Now I don't know exactly what your goals are, because you haven't stated them, but one common way to do it would be:
List<String> english = new LinkedList<String>();
List<String> french = new LinkedList<String>();
List<String> spanish = new LinkedList<String>();
List<List<String>> languages = new LinkedList<List<String>>();
languages.add(english);
languages.add(french);
languages.add(spanish);
for(String word : someWordList) {
for(List<String> language : languages) {
// oh snap! I really have no idea what language I'm working in...
// I could do something silly like make list.get(0) be the language
// name, but that seems lame
}
}
What would be better would be something like this:
class Language {
final String language;
final Map<String,String> english2current;
Language(String language, Set<String> words) {
this.language = language;
english2current = new HashMap<String,String>();
Translator t = TranslatorFactory.getTranslator(language);
for(String word : words) english2current.put(word,t.translate(word));
}
}
Collection<String> wordSet() {
return english2current.values();
}
Now without seeing more of your implementation it's hard to see exactly what you're doing wrong. But WHATEVER you're doing, look at removing any nested generics and instead trying to isolate them into classes. This will allow you to consolidate behavior in an object oriented manner, and better organize your logic so you can focus on what it's supposed to do instead of the semantics of generics.
A: You need to properly ListFactorable class:
public class ListFactorable<T extends List<?>> {
public T create() {
...
}
}
Then createObject method could look something like this:
public static <N extends List<List<String>>,M extends List<String>> N createObject( //
ListFactorable<N> mainListFactory, //
ListFactorable<M> subListsFactory) {
N listOfListOfStrings = mainListFactory.create();//new LinkedList<List<String>>();
M listOfStrings = subListsFactory.create();//new LinkedList<String>();
listOfStrings.add("A");
listOfListOfStrings.add(listOfStrings);
return listOfListOfStrings;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MongoDB GetDate Syntax In SQL Server while trying to insert records you have the option to specify
GETDATE()-1, GETDATE()
I tried below statement for MongoDB
db.TableA.insert({Name:ABC,SaleDate:this.date.getDate-1,SaleValue:2500,City:XYZ})
This does not work. What is the MongoDB equivalent syntax to insert getDate value for a table column?
I am also looking into MongoDB documentation, but I am still figuring it out.
A: Just typing "new Date()" should do it.
http://www.mongodb.org/display/DOCS/Dates
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626676",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: microsoft jscript runtime error object doesn't support this property or method jquery I a using asp.net vs 2008.I am trying jquery. I am getting this error
"microsoft jscript runtime error object doesn't support this property or method jquery"
Any help is appreciated.
This is the code i am using.
<title></title>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
<script type="text/javascript">
$(document).ready(function() {
("button").click(function() {
$("p").hide();
});
}); </script>
</head>
<body>
<form id="form1" runat="server">
<h2>This is a heading</h2>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>Click me</button>
</form>
</body>
A: You are missing a $ i think
$("button").click(function() {
$("p").hide();
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: setup.py install location? I'm running Mac OS X Lion 10.7.1 that has both python 2.6 and 2.7 installed. I've made 2.6 my default version. I am trying to install a package and it installs to 2.7. My setup looks like this:
~:hi› which python
/usr/bin/python
~:hi› python -V
Python 2.6.6
~:hi› python
Python 2.6.6 (r266:84292, Jun 16 2011, 16:59:16)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.prefix
'/System/Library/Frameworks/Python.framework/Versions/2.6'
>>> sys.exec_prefix
'/System/Library/Frameworks/Python.framework/Versions/2.6'
Shouldn't it be installed in 2.6 site-packages? Am I misunderstanding how this ought to work?
Edit
*
*The package in question is virtuanenvwrapper
*I made 2.6 my default version like so:
defaults write com.apple.versioner.python Version 2.6
*I tried installing it like this:
sudo python setup.py install
sudo /usr/bin/python setup.py install
A: When setup.py installs a Python package, it pays no attention to the Apple system settings. The only thing it knows is what version of Python you use to invoke it. If you say:
python2.6 setup.py …
then that version gets used, and the same with
python2.7 setup.py …
If you use the first of these two commands, does the package get installed under 2.6 like you want? My guess is that the shell that sudo runs might have 2.7 as its default, regardless of which Python your normal shell wants to use. What happens if you say:
sudo python -V
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to retrieve content from a website with VS 11 I am trying this in Visual Studio 11 in Windows 8. As I see I can't use WebClient to do this, so I tried using HttpClient:
var client = new HttpClient();
var response = client.Get("http://google.com");
var result = XDocument.Parse(response.Content.ReadAsString());
My problem is that I always get result to be null. In response I get a status code 200 (OK) but I can't see the content.
What am I doing wrong ?
Thanks.
A: Most webpages are not valid XML.
You should use HTML Agility Pack instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ubuntu passing command line arugments to C program I am learning C programming, I wrote the sample code to accept parameters from terminal and print out the arguments.
I invoke the program like this: ./myprogram 1
I expected 1 to be printed out for the argument length instead of 2. why it is so? There was no spacing after the argument "1"
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
printf("%d", argc);
return EXIT_SUCCESS;
}
A: The first argument, argv[0] is the name with which the program was invoked. So there are two arguments and the second, argv[1] is "1".
EDIT
Editing to make clear: argc should always be checked. However uncommon, it is perfectly legal for argc to be 0.
For example on Unix, execvp("./try", (char **){NULL}); is legal.
A: "./myprogram" counts as the first argument.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Windows create dynamic amount of links In my application i'm going to have a list of links I would like the user to be able to click on and will take them to a certain website. The problem is, first, it's possible there is going to be alot of links, second, there is a dynamic amount of links, and the amount changes.
One idea that came to mind was to somehow create a bunch of STATIC windows with SS_NOTIFY, but I would be creating and destroying windows often, and performance is a bit of a concern in this project. And keeping track of how many windows I have, and which one was clicked on wouldn't be easy.
So i'm looking for a easier way, or at least better way, to implement this.
I should also note i'm using C, and the Windows API.
A: You have no need to worry about performance. On any machine from the past 10 years you will have no performance issues with filling a screen with windowed controls.
As for the control to use, I think SysLink sounds like the most appropriate choice.
If you are looking for easier ways to manage dynamic GUIs then you may want to contemplate a higher level framework. Programming the raw Windows API from C is pretty labour intensive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C# Windows Application - Setting Tab Control Transfer between input fields I developed a windows application. The input screen has two date pickers followed by a set of textbox as input fields.
*
*After checking on the Dates
*When I click on Tab Control, Cursor is not transferred for next input, it goes to submit button
What settings should i specify to transfer control sequentially across the input text boxes before finally hitting submit button
Thanks in Advance for the help
A: Set the TabIndex property of each control.
To help with that, you can click the Tab Order button in the WinForms designer toolbar, then click the controls in your desired order to set their TabIndicies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to move a row from a table to another table if a Column's value changes in SQL? I have two tables, Hosts, and UnusedHosts. Hosts has 17 columns, and UnusedHosts has 14 columns, where the first 12 is the same as in Hosts, and the 13th is a UserName, who moved a host to UnusedHosts, and the 14th is a date, when he did it. In Hosts there is a Column Unused which is False. I want do the following. If i change in Hosts this value to True, then it should automatically removed to UnusedHosts.
How can i do this? Could someone provide some example?
P.S.: My SQL knowledge is very small, i can use only very simple selects, updates, inserts, and delete commands.
Thanks!
A: There's two main types of query in SQL Server - the AFTER and the INSTEAD OF. They work, much as they sound - the AFTER performs your original query, and then runs your trigger. The INSTEAD OF runs your trigger in place of the original query. You can use either in this case, though in different ways.
AFTER:
create trigger hosts_unused
on Hosts
after UPDATE
as
insert into UnusedHosts
select h.<<your_columns>>...
from Hosts h
where h.unused = 1 --Or however else you may be denoting True
delete from Hosts
where unused = 0 --Or however else you may be denoting False
GO
INSTEAD OF:
create trigger hosts_unused
on Hosts
instead of UPDATE
as
insert into UnusedHosts
select i.<<your_columns>>...
from inserted i
where i.unused = 1 --Or however else you may be denoting True
delete h
from inserted i inner join
Hosts h on i.host_id = h.host_id
where i.unused = 1 --Or however else you may be denoting True
update h
set hosts_column_1 = i.hosts_column_1,
hosts_column_2 = i.hosts_column_2,
etc
from inserted i inner join
Hosts h on i.host_id = h.host_id
where i.unused = 0 --Or however else you may be denoting False
GO
It's always important to think of performance when applying triggers. If you have a lot of updates on the Hosts table, but only a few of them are setting the unused column, then the AFTER trigger is probably going to give you better performance. The AFTER trigger also has the benefit that you can simply put in , INSERT after the after UPDATE bit, and it'll work for inserts too.
Check out Books Online on the subject.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to parse JSON to a dynamic object on Windows Phone 7? For web applications I can use System.Web and use this trick to convert JSON to a dynamic object.
But for Windows Phone I can't use JavaScriptConverter. What is the workaround to convert JSON in a dynamic object on Windows Phone 7.1?
A: Json.Net ( http://james.newtonking.com/pages/json-net.aspx )
-----EDIT-----
If WP7 supports DynamicObject:
using System;
using System.Dynamic;
using System.Collections;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public class JSonTest
{
public static void Main()
{
string jsonStr = @"
{
'glossary': {
'title': 'example glossary',
'GlossDiv': {
'title': 'S',
'GlossList': {
'GlossEntry': {
'ID': 'SGML',
'SortAs': 'SGML',
'GlossTerm': 'Standard Generalized Markup Language',
'Acronym': 'SGML',
'Abbrev': 'ISO 8879:1986',
'GlossDef': {
'para': 'A meta-markup language, used to create markup languages such as DocBook.',
'GlossSeeAlso': ['GML','XML']
},
'GlossSee': 'markup'
}
}
}
}
}
";
JObject o = (JObject)JsonConvert.DeserializeObject(jsonStr);
dynamic json = new JsonObject(o);
Console.WriteLine(json.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso.Length);
Console.WriteLine(json.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso[1]);
foreach (var x in json.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso)
{
Console.WriteLine(x);
}
Console.ReadLine();
}
}
class JsonObject : DynamicObject,IEnumerable,IEnumerator
{
object _object;
public JsonObject(object jObject)
{
this._object = jObject;
}
public object this[int i]
{
get
{
if (!(_object is JArray)) return null;
object obj = (_object as JArray)[i];
if (obj is JValue)
{
return ((JValue)obj).ToString();
}
return new JsonObject(obj);
}
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
if (_object is JArray && binder.Name == "Length")
{
result = (_object as JArray).Count;
return true;
}
JObject jObject = _object as JObject;
object obj = jObject.SelectToken(binder.Name);
if (obj is JValue)
result = ((JValue)obj).ToString();
else
result = new JsonObject(jObject.SelectToken(binder.Name));
return true;
}
public override string ToString()
{
return _object.ToString();
}
int _index = -1;
public IEnumerator GetEnumerator()
{
_index = -1;
return this;
}
public object Current
{
get
{
if (!(_object is JArray)) return null;
object obj = (_object as JArray)[_index];
if (obj is JValue) return ((JValue)obj).ToString();
return obj;
}
}
public bool MoveNext()
{
if (!(_object is JArray)) return false;
_index++;
return _index <(_object as JArray).Count;
}
public void Reset()
{
throw new NotImplementedException();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Sql Server Delete and Merge performance I've table that contains some buy/sell data, with around 8M records in it:
CREATE TABLE [dbo].[Transactions](
[id] [int] IDENTITY(1,1) NOT NULL,
[itemId] [bigint] NOT NULL,
[dt] [datetime] NOT NULL,
[count] [int] NOT NULL,
[price] [float] NOT NULL,
[platform] [char](1) NOT NULL
) ON [PRIMARY]
Every X mins my program gets new transactions for each itemId and I need to update it. My first solution is two step DELETE+INSERT:
delete from Transactions where platform=@platform and itemid=@itemid
insert into Transactions (platform,itemid,dt,count,price) values (@platform,@itemid,@dt,@count,@price)
[...]
insert into Transactions (platform,itemid,dt,count,price) values (@platform,@itemid,@dt,@count,@price)
The problem is, that this DELETE statement takes average 5 seconds. It's much too long.
The second solution I found is to use MERGE. I've created such Stored Procedure, wchich takes Table-valued parameter:
CREATE PROCEDURE [dbo].[sp_updateTransactions]
@Table dbo.tp_Transactions readonly,
@itemId bigint,
@platform char(1)
AS
BEGIN
MERGE Transactions AS TARGET
USING @Table AS SOURCE
ON (
TARGET.[itemId] = SOURCE.[itemId] AND
TARGET.[platform] = SOURCE.[platform] AND
TARGET.[dt] = SOURCE.[dt] AND
TARGET.[count] = SOURCE.[count] AND
TARGET.[price] = SOURCE.[price] )
WHEN NOT MATCHED BY TARGET THEN
INSERT VALUES (SOURCE.[itemId],
SOURCE.[dt],
SOURCE.[count],
SOURCE.[price],
SOURCE.[platform])
WHEN NOT MATCHED BY SOURCE AND TARGET.[itemId] = @itemId AND TARGET.[platform] = @platform THEN
DELETE;
END
This procedure takes around 7 seconds with table with 70k records. So with 8M it would probably take few minutes. The bottleneck is "When not matched" - when I commented this line, this procedure runs on average 0,01 second.
So the question is: how to improve perfomance of the delete statement?
Delete is needed to make sure, that table doesn't contains transaction that as been removed in application. But it real scenario it happens really rarely, ane the true need of deleting records is less than 1 on 10000 transaction updates.
My theoretical workaround is to create additional column like "transactionDeleted bit" and use UPDATE instead of DELETE, ane then make table cleanup by batch job every X minutes or hours and Execute
delete from transactions where transactionDeleted=1
It should be faster, but I would need to update all SELECT statements in other parts of application, to use only transactionDeleted=0 records and so it also may afect application performance.
Do you know any better solution?
UPDATE: Current indexes:
CREATE NONCLUSTERED INDEX [IX1] ON [dbo].[Transactions]
(
[platform] ASC,
[ItemId] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 50) ON [PRIMARY]
CONSTRAINT [IX2] UNIQUE NONCLUSTERED
(
[ItemId] DESC,
[count] ASC,
[dt] DESC,
[platform] ASC,
[price] ASC
) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
A: Using a BIT field for IsDeleted (or IsActive as many people do) is valid but it does require modifying all code plus creating a separate SQL Job to periodically come through and remove the "deleted" records. This might be the way to go but there is something less intrusive to try first.
I noticed in your set of 2 indexes that neither is CLUSTERED. Can I assume that the IDENTITY field is? You might consider making the [IX2] UNIQUE index the CLUSTERED one and changing the PK (again, I assume the IDENTITY field is a CLUSTERED PK) to be NONCLUSTERED. I would also reorder the IX2 fields to put [Platform] and [ItemID] first. Since your main operation is looking for [Platform] and [ItemID] as a set, physically ordering them this way might help. And since this index is unique, that is a good candidate for being CLUSTERED. It is certainly worth testing as this will impact all queries against the table.
Also, if changing the indexes as I have suggested helps, it still might be worth trying both ideas and hence doing the IsDeleted field as well to see if that increases performance even more.
EDIT:
I forgot to mention, by making the IX2 index CLUSTERED and moving the [Platform] field to the top, you should get rid of the IX1 index.
EDIT2:
Just to be very clear, I am suggesting something like:
CREATE UNIQUE CLUSTERED INDEX [IX2]
(
[ItemId] DESC,
[platform] ASC,
[count] ASC,
[dt] DESC,
[price] ASC
)
And to be fair, changing which index is CLUSTERED could also negatively impact queries where JOINs are done on the [id] field which is why you need to test thoroughly. In the end you need to tune the system for your most frequent and/or expensive queries and might have to accept that some queries will be slower as a result but that might be worth this operation being much faster.
A: OK, here is another approach also. For a similar problem (large scan WHEN NOT MATCHED BY SOURCE then DELETE) I reduced the MERGE execute time from 806ms to 6ms!
One issue with the problem above is that the "WHEN NOT MATCHED BY SOURCE" clause is scanning the whole TARGET table.
It is not that obvious but Microsoft allows the TARGET table to be filtered (by using a CTE) BEFORE doing the merge. So in my case the TARGET rows were reduced from 250K to less than 10 rows. BIG difference.
Assuming that the above problem works with the TARGET being filtered by @itemid and @platform then the MERGE code would look like this. The changes above to the indexes would help this logic too.
WITH Transactions_CTE (itemId
,dt
,count
,price
,platform
)
AS
-- Define the CTE query that will reduce the size of the TARGET table.
(
SELECT itemId
,dt
,count
,price
,platform
FROM Transactions
WHERE itemId = @itemId
AND platform = @platform
)
MERGE Transactions_CTE AS TARGET
USING @Table AS SOURCE
ON (
TARGET.[itemId] = SOURCE.[itemId]
AND TARGET.[platform] = SOURCE.[platform]
AND TARGET.[dt] = SOURCE.[dt]
AND TARGET.[count] = SOURCE.[count]
AND TARGET.[price] = SOURCE.[price]
)
WHEN NOT MATCHED BY TARGET THEN
INSERT
VALUES (
SOURCE.[itemId]
,SOURCE.[dt]
,SOURCE.[count]
,SOURCE.[price]
,SOURCE.[platform]
)
WHEN NOT MATCHED BY SOURCE THEN
DELETE;
A: See this https://stackoverflow.com/questions/3685141/how-to-....
would the update be the same cost as a delete? No. The update would be
a much lighter operation, especially if you had an index on the PK
(errrr, that's a guid, not an int). The point being that an update to
a bit field is much less expensive. A (mass) delete would force a
reshuffle of the data.
In light of this information, your idea to use a bit field is very valid.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Text Display Jumping Left-Right due to character width difference I am using an EditText to display text received from a serial port which is updated 10 times a second, it works fine but one of the lines of text has a character that alternates beyween a digit and a dash (-). Becuase the dash is narrower than the digit the rest of the line of text after this character jumps right-left as the digit and dash alternate.
How can I prevent this so either the digit or dash could be displayed without the rest of the line jumping?
TIA
A: You should use monospace font. You can either change it with the visual designer or by code:
EditText1.Typeface = Typeface.MONOSPACE
Visual designer:
A: You then should probably use monospace font:
<EditText android:typeface="monospace" [rest of attributes] />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the propper way to use Cursor Adapters and Content Providers in android 2.2 i'm confused and i need your help.
I try to follow the instructions given by Virgil Dobjanschi on his lecture 'Developing Android REST Client Applications' given on Google IO 2010. Unfortunately, i can't find the way to implement valid communication between Content Provider and Cursor Adapter.
The problem i have here is linked with cursor adapter, so let's just assume everything is fine with the content provider. For example, let's try using Contacts ContentProvider instead of my own. I tried the simplest solution - any ContentProvider (as assumed, Contacts, provided by SDK) and SimpleCursorAdapter. The problem is that constructor of SimpleCursorAdapter containing the cursor from Contacts is deprecated. Documentations says:
This constructor is deprecated.
This option is discouraged, as it results in Cursor queries being performed on the application's UI thread and thus can cause poor responsiveness or even Application Not Responding errors. As an alternative, use LoaderManager with a CursorLoader.
My thoughts were: "Ok, i won't use it. I'll try LoaderManager with CursorLoader instead, as they are advicing me." So i went to the LoaderManager documentation site to find an example of use and what i found? Perfect example of using SimpleCursorAdapter constructor. Yes, the same i wanted to avoid becouse of it's deprecation.
// Create an empty adapter we will use to display the loaded data.
mAdapter = new SimpleCursorAdapter(getActivity(),
android.R.layout.simple_list_item_2, null,
new String[] { Contacts.DISPLAY_NAME, Contacts.CONTACT_STATUS },
new int[] { android.R.id.text1, android.R.id.text2 }, 0);
setListAdapter(mAdapter);
All the tutorials i could find are using this deprecated constructor. Can anyone provide me good answer what's the propper way to avoid using this? Or maybe i care about it too much? All i wanted was to learn good practices...
A: If you're using LoaderManager on Android 2.2 you already have the Android compatibility library in your project I assume.
In that case, don't use
android.widget.SimpleCursorAdapter
because that class only has a single, now deprecated constructor. Instead use:
android.support.v4.widget.SimpleCursorAdapter
from the compat library. It has two constructors:
SimpleCursorAdapter(Context, int, Cursor, String[], int[]) // deprecated
SimpleCursorAdapter(Context, int, Cursor, String[], int[], int) // non-deprecated
The code example in your question uses the second, non-deprecated constructor and thereby must be using the compat lib version of SimpleCursorAdapter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SQL - how to efficiently select distinct records I've got a very performance sensitive SQL Server DB. I need to make an efficient select on the following problem:
I've got a simple table with 4 fields:
ID [int, PK]
UserID [int, FK]
Active [bit]
GroupID [int, FK]
Each UserID can appear several times with a GroupID (and in several groupIDs) with Active='false' but only once with Active='true'.
Such as:
(id,userid,active,groupid)
1,2,false,10
2,2,false,10
3,2,false,10
4,2,true,10
I need to select all the distinct users from the table in a certain group, where it should hold the last active state of the user. If the user has an active state - it shouldn't return an inactive state of the user, if it has been such at some point in time.
The naive solution would be a double select - one to select all the active users and then one to select all the inactive users which don't appear in the first select statement (because each user could have had an inactive state at some point in time). But this would run the first select (with the active users) twice - which is very unwanted.
Is there any smart way to make only one select to get the needed query? Ideas?
Many thanks in advance!
A: What about a view such as this :
createview ACTIVE as select * from USERS where Active = TRUE
Then just one select from that view will be sufficient :
select user from ACTIVE where ID ....
A: Try this:
Select
ug.GroupId,
ug.UserId,
max(ug.Active) LastState
from
UserGroup ug
group by
ug.GroupId,
ug.UserId
If the active field is set to 1 for a user / group combination you will get the 1, if not you will get a 0 for the last state.
A: I'm not a big fan of the use of an "isActive" column the way you're doing it. This requires two UPDATEs to change an active status and has the effect of storing the information about the active status several times in the different records.
Instead, I would remove the active field and do one of the following two things:
*
*If you already have a table somewhere in which (userid, groupid) is (or could be) a PRIMARY KEY or UNIQUE INDEX then add the active column to that table. When a user becomes active or inactive with respect to a particular group, update only that single record with true or false.
*If such a table does not already exist then create one with '(userid, groupid)as thePRIMARY KEYand the fieldactive` and then treat the table as above.
In either case, you only need to query this table (without aggregation) to determine the users' status with respect to the particular group. Equally importantly, you only store the true or false value one time and only need to UPDATE a single value to change the status. Finally, this tables acts as the place in which you can store other information specific to that user's membership in that group that applies only once per membership, not once per change-in-status.
A: Try this:
SELECT t.* FROM tbl t
INNER JOIN (
SELECT MAX(id) id
FROM tbl
GROUP BY userid
) m
ON t.id = m.id
A: Not sure that I understand what you want your query to return but anyway. This query will give you the users in a group that is active in the last entry. It uses row_number() so you need at least SQL Server 2005.
Table definition:
create table YourTable
(
ID int identity primary key,
UserID int,
Active bit,
GroupID int
)
Index to support the query:
create index IX_YourTable_GroupID on YourTable(GroupID) include(UserID, Active)
Sample data:
insert into YourTable values
(1, 0, 10),
(1, 0, 10),
(1, 0, 10),
(1, 1, 10),
(2, 0, 10),
(2, 1, 10),
(2, 0, 10),
(3, 1, 10)
Query:
declare @GroupID int = 10
;with C as
(
select UserID,
Active,
row_number() over(partition by UserID order by ID desc) as rn
from YourTable as T
where T.GroupID = @GroupID
)
select UserID
from C
where rn = 1 and
Active = 1
Result:
UserID
-----------
1
3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: \r\n Not Working in text email coding? I am sending an email which attaches a pdf.
This is the code:
$mpdf->WriteHTML($html);
$content = $mpdf->Output('', 'S');
$content = chunk_split(base64_encode($content));
$mailto = $email;
$from_name = $yourname;
$from_mail = $fromwho;
$replyto = $replyto;
$uid = md5(uniqid(time()));
$subject = 'Horse Details';
$message = 'Please find attached details about the horse medical treatment.';
$filename = 'Horse';
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/pdf; name=\"".$filename."\"\r\n";
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
I would like to add more details in the message and use \r\r for new paragraphs etc.
But for some reason the \r\r or \n will not work? Suspect it is because of some of the header info but not sure which one? Had a bit of a play but could not work it out.
Can you see the problem?
Thank you.
A: well i don't seem to get it wrong when i sent it , here's the source of the sent message
Subject: Horse Details
From: elibyy Reply-To: [email protected]
MIME-Version: 1.0 Content-Type: multipart/mixed;
boundary="660d0865650c12fa07c8430814690009"
This is a multi-part message in MIME format.
--660d0865650c12fa07c8430814690009 Content-type:text/plain;
charset=iso-8859-1 Content-Transfer-Encoding: 7bit
Please find attached details about the horse medical treatment.
--660d0865650c12fa07c8430814690009 Content-Type: application/pdf;
name="Horse" Content-Transfer-Encoding: base64 Content-Disposition:
attachment; filename="Horse"
--660d0865650c12fa07c8430814690009--
Please find attached details about the horse medical treatment.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626724",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Fluent nHibernate and interfaces Does fluent nHibernate play well when using interfaces instead of concrete classes as properties?
E.g. A sports stadium has a reference to a city that it is in, so our interfaces/concrete classes looks as follows
Interface:
ICity
int Id;
string Name;
IStadium
int Id;
string Name;
ICity City;
Concrete class:
class City: ICity;
...
class Stadium: IStadium;
public virtual int Id {get; private set; }
public virtual string Name { get; set; }
public virtual ICity City { get; set; } //<- NOTE: Reference to interface instead of the class
Mapper:
public class StadiumMap : ClassMap<Stadium>
{
public StadiumMap()
{
...
References(x => x.City).Column("Id");
...
}
}
So will the above work fine in fluent nhibernate or will I have to replace my "ICity" with "City"?
A: A little off topic but I doubt your domain classes are benefiting from implementing interfaces. James Gregory said it best.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Flash Gets Blocked By ISP I have developed a set of flash games which are being used by several schools across the UK. For some odd reason, the school cannot seem to load the Flash games....
Upon contacting the ISP (SWGFL) - I was told that the network would automatically block flash games. This is all well and good BUT the school in question is able to load the following flash game:
http://www.bbc.co.uk/cbbc/games/deadly-scramble-game
I am currently using a PHP layer to communicate between Flash and a MySQL database. I was wondering if anyone knew any reasons as to why this might occur? Is there some kind of header() protocol I need to add to bypass this flash blocking?
This happens in IE FF & Safari (other browsers have not been tested).
A: You could also try to use HTTPS, since the data will be encrypted as its transferred to the browser and requests to the server are encrypted, the ISP won't be able to determine that there is a flash game and the school should be able to run the game just fine as long as the browsers themselves are not configured to block flash content.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Error with setCompressionType Is there someone that can help to correct this code?
I'm working with JAI and I'm trying to compress JPG file to Losse-less
here's my code
`ImageWriter writer= (JPEGImageWriter) ImageIO.getImageWritersByFormatName("jpeg").next();
javax.imageio.plugins.jpeg.JPEGImageWriteParam param = (JPEGImageWriteParam)
writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("JPEG-LOSSLESS");`
It's always error in this part param.setCompressionType("JPEG-LOSSLESS");
the error is java.lang.IllegalArgumentException: Unknown compression type!
at javax.imageio.ImageWriteParam.setCompressionType(ImageWriteParam.java:1023)
A: You can only use compression types that are supported. Check which are supported by param.getCompressionTypes().
Other then that, try this code (using newer jpeg lossless standard JPEG-LS):
ImageWriter writer =
(ImageWriter) ImageIO.getImageWritersByFormatName("jpeg").next();
ImageWriteParam param= writer.getDefaultWriteParam();
param.setCompressionMode(param.MODE_EXPLICIT);
param.setCompressionType("JPEG-LS");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Sidepanel with Qt I'd like to implement a sidepanel in my Qt window. I search something like the one that is used in the Visual Studio (see below).
Important notes:
*
*The widgets don't have to be moveable
*resizing should be possible
*each widget should be clearly separated from the other layout
Does anyone have an idea how I could build such a sidepanel? (Maybe there even exists a library)
Or does anyone know a project which uses Qt and some kind of sidepanel?
A: One option would be to use QDockWidgets. That's the type of thing they are intended for inside a QMainWindow.
You can put toolbars, QTreeViews and QTableViews (or related) widgets inside your dock widget to simulate the screenshot you posted.
For an example usage: Dock Widgets Example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Extending ruby in C - how to specify default argument values to function? I'm trying to write a C extension to ruby that'll generate a class. I'm looking on how to define some default arguments to a class. For example, if I have this class decleration in ruby:
class MyClass
def initialize(name, age=10)
@name = name
@age = age
end
end
You can initialize it with mc = MyClass.new("blah"), and the age parameter will be set internally. How do I do this in C? So far I got this, but this forces entering the other argument:
require "ruby.h"
static VALUE my_init(VALUE self, VALUE name, VALUE age)
{
rb_iv_set(self, "@name", name);
rb_iv_set(self, "@age", age);
return self;
}
VALUE cMyClass;
void Init_MyClass()
{
// create a ruby class instance
cMyClass = rb_define_class("MyClass", rb_cObject);
// connect the instance methods to the object
rb_define_method(cMyClass, "initialize", my_init, 2);
}
I thought about checking the value of age against Qnil or using if ( TYPE(age) == T_UNDEF ), but I just get segfaults from there. Reading through README.EXT leads me to believe I can accomplish this through rb_define_method using the value of argc, but this wasn't too clear. Any ideas? Thanks.
A: You do need to use the argc of rb_define_method. You should pass -1 as the argc to rb_define_method and use rb_scan_args to handle optional arguments. For example, matt's example could be simplified to the following:
static VALUE my_init(int argc, VALUE* argv, VALUE self) {
VALUE name, age;
rb_scan_args(argc, argv, "11", &name, &age); // informs ruby that the method takes 1 mandatory and 1 optional argument,
// the values of which are stored in name and age.
if (NIL_P(age)) // if no age was given...
age = INT2NUM(10); // use the default value
rb_iv_set(self, "@age", age);
rb_iv_set(self, "@name", name);
return self;
}
Usage
Derived from the Pragmatic Bookshelf:
int rb_scan_args (int argcount, VALUE *argv, char *fmt, ...
Scans the argument list and assigns to variables similar to scanf:
fmt A string containing zero, one, or two digits followed by some flag characters.
The first digit indicates the count of mandatory arguments; the second is the count of optional arguments.
A * means to pack the rest of the arguments into a Ruby array.
A & means that an attached code block will be taken and assigned to the given variable
(if no code block was given, Qnil will be assigned).
After the fmt string, pointers to VALUE are given (as with scanf) to which the arguments are assigned.
Example:
VALUE name, one, two, rest;
rb_scan_args(argc, argv, "12", &name, &one, &two);
rb_scan_args(argc, argv, "1*", &name, &rest);
Furthermore, in Ruby 2, there is also a : flag that is used for named arguments and the options hash. However, I have yet to figure out how it works.
Why?
There are many advantages of using rb_scan_args:
*
*It handles optional arguments by assigning them nil (Qnil in C). This has the side effect of preventing odd behaviour from your extension if someone passes nil to one of the optional arguments, which does happen.
*It uses rb_error_arity to raise an ArgumentError in the standard format (ex. wrong number of arguments (2 for 1)).
*It's usually shorter.
The advantages of rb_scan_args are further elaborated here: http://www.oreillynet.com/ruby/blog/2007/04/c_extension_authors_use_rb_sca_1.html
A: You're right - you can do this using rb_define_method and a negative value for argc.
Normally argc specifies the number of arguments your method accepts, but using a negative value specifies that the method accepts a variable number of arguments, which Ruby will pass in as an array.
There are two possibilities. First, use -1 if you want the arguments passed in to your method in a C array. Your method will have a signature like VALUE func(int argc, VALUE *argv, VALUE obj) where argc is the number of arguments, argv is a pointer to the arguments themselves, and obj is the receiving object, i.e. self. You can then manipulate this array as you need to mimic default arguments or whatever you need, in your case it might look something like this:
static VALUE my_init(int argc, VALUE* argv, VALUE self) {
VALUE age;
if (argc > 2 || argc == 0) { // there should only be 1 or 2 arguments
rb_raise(rb_eArgError, "wrong number of arguments");
}
rb_iv_set(self, "@name", argv[0]);
if (argc == 2) { // if age has been included in the call...
age = argv[1]; // then use the value passed in...
} else { // otherwise...
age = INT2NUM(10); // use the default value
}
rb_iv_set(self, "@age", age);
return self;
}
The alternative is to have a Ruby array passed into your method, which you specify by using -2 in your call to rb_define_method. In this case, your method should have a signature like VALUE func(VALUE obj, VALUE args), where obj is the receiving object (self), and args is a Ruby array containing the arguments. In your case this might look something like this:
static VALUE my_init(VALUE self, VALUE args) {
VALUE age;
long len = RARRAY_LEN(args);
if (len > 2 || len == 0) {
rb_raise(rb_eArgError, "wrong number of arguments");
}
rb_iv_set(self, "@name", rb_ary_entry(args, 0));
if (len == 2) {
age = rb_ary_entry(args, 1);
} else {
age = INT2NUM(10);
}
rb_iv_set(self, "@age", age);
return self;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: How to match a string with an optional "/" at the end? I am trying to match a URL such as;
http://www.testing.com/documents/dashboard
What I want is to match "/documents/dashboard" or "/documents/dashboard/". How can be this done?
preg_match('/^\/documents\/dashboard[\/|]$/i', $_SERVER['REQUEST_URI']);
This doesn't work? What should I enter after pipe (|) character in [] block to cover "nothing" as well?
A: [\/|]$ is wrong, because [] creates a character class. So what you are matching there is / or | followed by end of string. To do what you were thinking of:
preg_match('~^/documents/dashboard(/|$)$~', $_SERVER['REQUEST_URI']);
Although I think it's easier to use:
preg_match('~^/documents/dashboard/?$~', $_SERVER['REQUEST_URI']);
/? means match the / character 1 or 0 times.
Tip: If you use a delimiter other than /, you won't have to escape forward slashes in the pattern.
A: preg_match('/^\/documents\/dashboard\/?$/i', $_SERVER['REQUEST_URI']);
People often use it at the end of their regex, but it can in fact be used anywhere. Although in your case it's just simpler to use the ? quantifier.
Or, if you absolutely want to use $, the following would work too:
/^\/documents\/dashboard(\/|$)$/i
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Necessary to retain controller for datasource and delegate of uiPickerview? As I understood, I should not be retaining a controller which is a delegate or datasource. I have made a UIPickerView, created in a property accessor as such:
-(UIPickerView *)projectPicker {
if (_projectPicker != nil) {
return _projectPicker;
}
//Create Picker View
UIPickerView *picker = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 185, 0, 0)];
picker.showsSelectionIndicator = YES;
//Create source and delegate
NSString *titleForRow0 = NSLocalizedString(@"<<Make Selection>>", @"projectPicker nil Label 0");
NSArray *titlesForFirstRows = [[NSArray alloc] initWithObjects:titleForRow0, nil];
ProjectPickerDatasource *pickerSource = [[ProjectPickerDatasource alloc] initWithManagedObjectContext:self.managedObjectContext
selectedProject:self.currentProject
andTitlesForFirstRows:titlesForFirstRows];
[titlesForFirstRows release];
picker.delegate = pickerSource;
picker.dataSource = pickerSource;
self.projectPicker = picker;
[pickerSource release];
[picker release];
return _projectPicker;
}
This crashes reporting an attempt to access an unallocated instance of pickerSource.
If I break the pickerSource component out as another property, thereby retaining it within this controller, it works perfectly.
I did not think that was the proper implementation. Doesn't the pickerView retain it's delegate and datasource until it is destroyed?
A: If the Picker instantiates the datasource it is fine to retain it, it needs to be retained somewhere. Just be sure to release it.
Note, datasources are handled differently that delegates.
A: Mostly (as for as I know) the delegates are not retained by their classes. They are just assigned like this,
@property(nonatomic, assign) id <TheDelegateClass> delegate;
Its the responsibility of the caller to retain the delegate until the delegates job is over.
The answer for your question is UIPickerView doesn't retain its delegate. It expects you to retain it instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Query optimization in massive tables I have a table containing brick and mortar shops. The table is about 15 million rows with 30 columns.
For now, the query time to retrieve a shop when the user types the name of the shop is about 15 to 20 seconds (we display an autocomplete list so the user can directly select from the list).
I would like to reach a query time of 2-3 seconds so users don't feel frustrated.
What are the actions I should take to reach this goal? (I am currently on Linode with a MySql database... maybe being on Simple DB would help?)
A: If all you are doing is a simple equi-search or prefix-search on a particular field, adding an index on that field should do the trick.
If you are doing anything more complex than that, then you'll have to be aware that there are no silver bullets when it comes to database performance tuning. You'll need to understand both:
*
*nature of your data (how it is accessed and modified)
*and how indexes and other database techniques actually work under the covers.
For the introduction on the subject, I warmly recommend reading Use The Index Luke.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: IE6,IE7 css menu ul I think this is a trivial problem:
All browsers and IE 8+ display my ul menu :
but IE6 and IE7 display:
Any soltion for this problem?
CSS:
div.art-nav
{
position: relative;
height: 25px;
z-index: 100;
}
.art-nav .l, .art-nav .r
{
position: absolute;
z-index: -1;
top: 0;
height: 25px;
background-image: url('images/nav.png');
}
.art-nav .l
{
left: 0;
right: 15px;
}
.art-nav .r
{
right: 0;
width: 1040px;
clip: rect(auto, auto, auto, 875px);
}
/* begin MenuSeparator */
ul.art-menu ul.art-menu-li-separator
{
display: block;
width: 1px;
height: 25px;
}
.art-nav ul.art-menu-separator
{
display: block;
margin:0 auto;
width: 1px;
height: 25px;
background-image: url('images/menuseparator.png');
}
/* end MenuSeparator */
ul.art-menu ul a
{
display: block;
text-align: center;
white-space: nowrap;
height: 32px;
width: 180px;
overflow: hidden;
line-height: 32px;
background-image: url('images/subitem.png');
background-position: left top;
background-repeat: repeat-x;
border-width: 0;
border-style: solid;
}
ul.art-menu ul a, ul.art-menu ul a:link, ul.art-menu ul a:visited, ul.art-menu ul a:hover,ul.art-menu ul a:active, .art-nav ul.art-menu ul span, .art-nav ul.art-menu ul span span
{
text-align: left;
text-indent: 12px;
text-decoration: none;
line-height: 32px;
color: #FFFFFF;
margin-right: 10px;
margin-left: 10px;
font-size: 13px;
margin:0;
padding:0;
}
ul.art-menu ul li a:hover
{
color: #000000;
background-position: 0 -32px;
}
ul.art-menu ul li:hover>a
{
color: #000000;
background-position: 0 -32px;
}
.art-nav ul.art-menu ul li a:hover span, .art-nav ul.art-menu ul li a:hover span span
{
color: #000000;
}
.art-nav ul.art-menu ul li:hover>a span, .art-nav ul.art-menu ul li:hover>a span span
{
color: #000000;
}
************************/
HTML:
<div class="art-nav">
<a href="javascript:__doPostBack('ctl00$lbLang','')" id="ctl00_lbLang"><span class="l"></span><span class="r"></span><span class="t"><img border="0" src="slm/me.jpg"></span></a>
<a href="javascript:__doPostBack('ctl00$lbLangJez2','')" id="ctl00_lbLangJez2"><span class="l"></span><span class="r"></span><span class="t"><img border="0" src="slm/UNKG1.jpg"></span></a>
<div class="l"></div>
<div class="r"></div>
<ul class="art-menu">
<li>
<a href="News.aspx" class="active" id="ctl00_hlNovosti"><span class="l"></span><span class="r"></span><span class="t">Novosti</span></a>
</li><li class="art-menu-li-separator"><span class="art-menu-separator"></span></li><li>
<a href="roules.aspx" class="active" id="ctl00_hlPravilaKladjenja"><span class="l"></span><span class="r"></span><span class="t">Pravila kladjenja</span></a>
</li><li class="art-menu-li-separator"><span class="art-menu-separator"></span></li><li>
<a href="onama.aspx" class="active" id="ctl00_hlOnama"><span class="l"></span><span class="r"></span><span class="t">O nama</span></a>
</li><li class="art-menu-li-separator"><span class="art-menu-separator"></span></li><li>
<a href="UplatnaMesta.aspx" class="active" id="ctl00_hlUplatnaMesta"><span class="l"></span><span class="r"></span><span class="t">Uplatna mesta</span></a>
</li>
</ul>
</div>
A: Might have something to do with this
clip: rect(auto, auto, auto, 875px);
in
.art-nav .r
IE doesn't do well with clip
http://reference.sitepoint.com/css/clip
See if removing that fixes it... and if so, you can send a modified css to IE using conditional comments.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Multiple Definition errors in c++ Here's some code that I wrote in DevCpp (windows), now I'm trying to get it to run in linux without much success.
Here is the source code
screen.h
#ifndef SCREEN_H
#define SCREEN_H
#include <graphics.h>
class Screen
{
private:
int max_x,max_y,grid_size;
int delta_x,delta_y;
int origin_x,origin_y;
public:
// Default Constructor to Initialize the screen with the grid
Screen(int xcoord=641, int ycoord=641, int grid=8)
{
//variable initialization
max_x = xcoord;
max_y = ycoord;
grid_size = grid;
delta_x = max_x / grid_size;
delta_y = max_y / grid_size;
origin_x = grid_size / 2 * delta_x;
origin_y = grid_size / 2 * delta_y;
//plotting the initial grid
int gd,gm;
initgraph(&gd,&gm,NULL);
//draw the x component of the grid
for(int i=0; i<max_x; i += delta_x)
{
if( i != max_x / 2)
setcolor(GREEN);
else
setcolor(RED);
line(i,0,i,max_y);
}
//draw the y component of the grid
for(int i=0; i<max_y; i += delta_y)
{
if( i != max_y / 2)
setcolor(GREEN);
else
setcolor(RED);
line(0,i,max_x,i);
}
//mark the origin with a white dot to acertain its coordinates for future use
putpixel(origin_x,origin_y,WHITE);
std::cout<<origin_x<<"\t"<<origin_y<<"\n";
}
//Method prototypes
void plot_pixel(int xcoord,int ycoord,int col=WHITE)
{
int l,t,r,b;
l = origin_x + xcoord * delta_x;
r = l + delta_x;
b = origin_y - ycoord * delta_y;
t = b - delta_y;
setcolor(col);
bar(l,t,r,b);
setcolor(WHITE);
}
};
#endif
circles.cpp
#include<iostream>
#include<cmath>
#include "screen.h"
using namespace std;
void draw_midpoint_circle(Screen ob, int radius);
void circlepointplot(Screen ob, int m, int n);
void trigonometric_circle(Screen ob, int radius);
int main() {
Screen scr = Screen(641, 641, 16);
int choice, rad;
cout << "Menu\n 1. Midpoint Circle Drawing Algorithm\n 2. Bresenham's Circle Drawing Algorithm \n 3. Trigonometric Method\n";
cin>>choice;
cout << "Enter Radius \t";
cin>>rad;
switch (choice) {
case 1:
draw_midpoint_circle(scr, rad);
break;
case 2:
draw_midpoint_circle(scr, rad);
break;
case 3:
trigonometric_circle(scr, rad);
break;
default:
cout << "Wrong Choice\n";
break;
}
getch();
return 0;
}
void trigonometric_circle(Screen ob, int radius) {
double angle = 0.0;
while (angle <= 360) {
int dx = 641 / 16;
int x = int(radius * cos(angle));
int y = int(radius * sin(angle));
angle = angle + 5;
ob.plot_pixel(x, y, 0);
cout << "Point Plotted " << x << "\t" << y << endl;
char buffer[50];
sprintf(buffer, "%d,%d", x, y);
outtextxy(320 + ((x + 1) * dx), 320 - ((y - 1) * dx), buffer);
getch();
}
}
void draw_midpoint_circle(Screen ob, int radius) {
float dp;
int x, y;
x = 0;
y = radius;
dp = 1 - radius;
while (x < y) {
circlepointplot(ob, x, y);
if (dp < 0)
dp = dp + 2 * x + 3;
else {
dp = dp + 2 * (x - y) + 5;
y--;
}
x++;
circlepointplot(ob, x, y);
}
}
void circlepointplot(Screen ob, int m, int n) {
ob.plot_pixel(m, n, 0);
ob.plot_pixel(n, m, 0);
ob.plot_pixel(m, -n, 0);
ob.plot_pixel(n, -m, 0);
ob.plot_pixel(-m, n, 0);
ob.plot_pixel(-n, m, 0);
ob.plot_pixel(-m, -n, 0);
ob.plot_pixel(-n, -m, 0);
cout << "Point Plotted" << m << "\t" << n << endl;
cout << "Point Plotted" << n << "\t" << m << endl;
cout << "Point Plotted" << m << "\t" << -n << endl;
cout << "Point Plotted" << n << "\t" << -m << endl;
cout << "Point Plotted" << -m << "\t" << n << endl;
cout << "Point Plotted" << -n << "\t" << m << endl;
cout << "Point Plotted" << -m << "\t" << -n << endl;
cout << "Point Plotted" << -n << "\t" << -m << endl;
int dx = 641 / 16;
char buffer[50];
sprintf(buffer, "%d,%d", m, n);
outtextxy(320 + ((m + 1) * dx), 320 - ((n - 1) * dx), buffer);
getch();
}
I'm using graphics.h for linux. Basic programs run fine.
The errors that I get are
g++ -c screen.cpp -o screen.o
g++ -c circles.cpp -o circles.o
g++ screen.o circles.o -o "circle.exe" -lgraph
circles.o:(.bss+0x0): multiple definition of `screen'
screen.o:(.bss+0x0): first defined here
circles.o:(.bss+0x8): multiple definition of `Font_surface'
screen.o:(.bss+0x8): first defined here
circles.o:(.bss+0x10): multiple definition of `_fgcolor'
screen.o:(.bss+0x10): first defined here
circles.o:(.bss+0x14): multiple definition of `_bgcolor'
screen.o:(.bss+0x14): first defined here
circles.o:(.bss+0x18): multiple definition of `_fontcolor'
screen.o:(.bss+0x18): first defined here
circles.o:(.bss+0x1c): multiple definition of `_pid'
screen.o:(.bss+0x1c): first defined here
circles.o:(.bss+0x20): multiple definition of `CP'
screen.o:(.bss+0x20): first defined here
circles.o:(.bss+0x40): multiple definition of `InternalFont'
screen.o:(.bss+0x40): first defined here
circles.o:(.bss+0x850): multiple definition of `TP'
screen.o:(.bss+0x850): first defined here
circles.o:(.bss+0x860): multiple definition of `_last_arc'
screen.o:(.bss+0x860): first defined here
circles.o:(.bss+0x878): multiple definition of `_internal_linestyle'
screen.o:(.bss+0x878): first defined here
circles.o:(.bss+0x888): multiple definition of `_scanlist'
screen.o:(.bss+0x888): first defined here
collect2: ld returned 1 exit status
What am I doing wrong, how do I get this to work?
Updated errors after moving the code into the class.
/tmp/ccB2RO2Q.o: In function `main':
circles.cpp:(.text+0x111): undefined reference to `grgetch'
/tmp/ccB2RO2Q.o: In function `trigonometric_circle(Screen, int)':
circles.cpp:(.text+0x242): undefined reference to `outtextxy'
circles.cpp:(.text+0x247): undefined reference to `grgetch'
/tmp/ccB2RO2Q.o: In function `circlepointplot(Screen, int, int)':
circles.cpp:(.text+0x6f2): undefined reference to `outtextxy'
circles.cpp:(.text+0x6f7): undefined reference to `grgetch'
/tmp/ccB2RO2Q.o: In function `Screen::Screen(int, int, int)':
circles.cpp:(.text._ZN6ScreenC2Eiii[_ZN6ScreenC5Eiii]+0xd0): undefined reference to `initgraph'
circles.cpp:(.text._ZN6ScreenC2Eiii[_ZN6ScreenC5Eiii]+0xf7): undefined reference to `setcolor'
circles.cpp:(.text._ZN6ScreenC2Eiii[_ZN6ScreenC5Eiii]+0x103): undefined reference to `setcolor'
circles.cpp:(.text._ZN6ScreenC2Eiii[_ZN6ScreenC5Eiii]+0x11c): undefined reference to `line'
circles.cpp:(.text._ZN6ScreenC2Eiii[_ZN6ScreenC5Eiii]+0x15e): undefined reference to `setcolor'
circles.cpp:(.text._ZN6ScreenC2Eiii[_ZN6ScreenC5Eiii]+0x16a): undefined reference to `setcolor'
circles.cpp:(.text._ZN6ScreenC2Eiii[_ZN6ScreenC5Eiii]+0x182): undefined reference to `line'
circles.cpp:(.text._ZN6ScreenC2Eiii[_ZN6ScreenC5Eiii]+0x1b9): undefined reference to `putpixel'
/tmp/ccB2RO2Q.o: In function `Screen::plot_pixel(int, int, int)':
circles.cpp:(.text._ZN6Screen10plot_pixelEiii[Screen::plot_pixel(int, int, int)]+0x6d): undefined reference to `setcolor'
circles.cpp:(.text._ZN6Screen10plot_pixelEiii[Screen::plot_pixel(int, int, int)]+0x80): undefined reference to `bar'
circles.cpp:(.text._ZN6Screen10plot_pixelEiii[Screen::plot_pixel(int, int, int)]+0x8a): undefined reference to `setcolor'
collect2: ld returned 1 exit status
Here's the graphics.h file it has a reference to an SDL_Image *screen
/* libgraph - TurboC graphics API on GNU/Linux
* graphics.h: Core initialization and configuration functions
*
* Copyright (C) 2003 Faraz Shahbazker
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free
* Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA
*
* Author: Faraz Shahbazker <[email protected]>
*/
/* Graphic functions using SDL */
#ifndef GRAPHICS_H
#define GRAPHICS_H 1
#include <SDL/SDL.h>
#include <unistd.h>
#include <sys/types.h>
#include <signal.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/* graphic drivers */
enum _driver{DETECT=0, USER, VGA=9};
enum graphics_modes{VGALO=0, VGAMED, VGAHI, VGAMAX, VGA640, VGA800, VGA1024, USERMODE};
/* 16 colors */
enum _color{BLACK=0, BLUE, GREEN, CYAN, RED, MAGENTA, BROWN, LIGHTGRAY, DARKGRAY,LIGHTBLUE, LIGHTGREEN, LIGHTCYAN, LIGHTRED, LIGHTMAGENTA, YELLOW, WHITE};
/* global variables */
SDL_Surface *screen; //main drawing screen
SDL_Surface *Font_surface; //font screen
Uint32 _fgcolor, _bgcolor, _fontcolor; //global color numbers
pid_t _pid; //Don't bother with this
/* function prototypes */
void initgraph(int *graphdriver,int *graphmode,char *pathtodriver);
void closegraph(void);
void setgraphmode(int gmode);
int getgraphmode(void);
void restorecrtmode(void);
int getmaxx(void);
int getmaxy(void);
void putpixel(int x, int y, int color);
int getpixel(int, int);
void setbkcolor(int color);
int getbkcolor(void);
void setcolor(int color);
int getcolor(void);
int getmaxcolor(void);
char* getdrivername(void);
char* getmodename(int mode_number);
int getmaxmode(void);
void detectgraph(int* graphdriver, int* graphmode);
void getmoderange(int graphdriver, int* lomode, int* himode);
int delay(float);
void setfontcolor(int color);
int getfontcolor(void);
/*** library specific functions - not for users ***/
void initialize_settings (void);
void mappixel(int, int); //marks a pixel without updating screen
void clippixel(int *, int *); /* Clip pixel (x,y) to current
screen size*/
void mapword(int,int,int);
void mapvword(int,int,int);
int colorrev(const Uint8); // maps 0..255 8-bit color to 0..15 TC color
Uint8 colortrans(const int); // maps 0..15 TC color to 0..255 8-bit color
void ctrlbreak(void); // To detect user interrupt
void inthandler(int); // clean up on user interrupt
void safe_update(int top, int left, int right, int bottom);
/* update screen within boundary */
#define CHECK_INITIALIZATION\
if (!getenv("LIBGRAPHICS_ACTIVE")) \
{ \
fprintf(stderr, "*** The graphics system has not been initialized!\n"); \
fprintf(stderr, "*** Call initgraph() before trying to use graphics functions.\n"); \
exit(-1); \
}
struct {int x;int y;}CP;
#include "grtext.h"
#include "shapes.h"
#include "polygon.h"
#ifdef __cplusplus
}
#endif /* __cplusplus */
#endif /* LIBGRAPH_H */
A: Your first error message is
circles.o:(.bss+0x0): multiple definition of `screen'
In your code, as I write this, there is nothing called "screen".
Hence, the problem appears to be solved already.
EDIT: now that you have added the contents of (someone else's) graphics.h, the author's ignorance of the following is the cause of the problem:
C++98 §7.5/7
The form of linkage specification that contains a braced-enclosed declaration-seq does
not affect whether the contained declarations are definitions or not (3.1).
So the pointer variable declarations there are definitions.
Unfortunately it appears that not only the author of that header, but also the current C++ standard got it wrong:
C++11 §7.5/7:
A declaration directly contained in a linkage-specification is treated as if it contains
the extern specifier (7.1.1) for the purpose of determining the linkage of the declared
name and whether it is a definition.
According to that normative text it is as if each pointer variable was declared as
extern and thus would
be only a declaration (not a definition). However, even in C++11 the non-normative example
shows the intent, that it is a definition.
All that said, this was news to me too, and I'm an old hand at this. It seems to be just
a meaningless quirk in the standard, a needless gotcha. But possibly it's because in C++
there is no other way to express pure declaration versus definition for an object.
Cheers & hth.,
A: graphics.h contains the following lines:
/* global variables */
SDL_Surface *screen; //main drawing screen
SDL_Surface *Font_surface; //font screen
Uint32 _fgcolor, _bgcolor, _fontcolor; //global color numbers
pid_t _pid; //Don't bother with this
This is a bit strange, but this h-file creates global variables. This means, if you include this file to more than one .cpp files, you have multiple definition error. I don't know why this h-file is written by such way, the program will be linked only if graphics.h is included to only one cpp file. If your can change this file, add extern keyword before every global variable, and create these variables (if necessary) in some .cpp file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626774",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Blank PHP/Index Page on Android HTTP Post Request Upon using the code samples below, I try to send a HTTP request to validate a username and password entry to a PHP script (returning either 1 or 0 in an echo).
Using HTTP Assistant, testing the HTTP Post request has the expected results... But for some reason, when logging the 'res' String (the HTTP response) in the java code, I get a blank PHP/Index page:
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML3.2Final//EN"><html><title>Indexof/</title></head><body><h1>Indexof/</h1><ul><li><ahref="cgi-bin/">cgi-bin/</a></li></ul></body></html>
Code: HomeActivity.java and Http.java
Have I done something wrong code-wise? Or is this a server issue?
A: What you are seeing there is the standard webserver listing of a directory. So you probably have the wrong URL you're hitting. Is there any redirect magic involved?
[edit] As you have controll of the PHP page yourself, do the following: Edit it so that it accepts parameters per GET and try to call the page via your android browser with the username and password as GET parameters . If that works, you've at least a clue that it's possible from your phone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make a panel transparent like glass How to give c# panel glass like transparency something similar to this (image after clicking on show desktop of windows 7) ? And will it work properly under windows XP ?
A: Take a look at this code project GlassPanel.
This tutorial may also help ExtendGlass
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Deleting a pointer In C++, whats the recommended way of deleting a pointer? For example, in the following case, do I need all three lines to delete the pointer safely (and if so, what do they do)?
// Create
MyClass* myObject;
myObject = new MyClass(myVarA, myVarB, myVarC);
// Use
// ...
// Delete
if(myObject) {
delete myObject;
myObject = NULL;
}
A: No you do not need to check for NULL.
delete takes care if the pointer being passed is NULL.
delete myObject;
myObject = NULL;
is sufficient.
As a general policy, avoid using freestore allocations wherever you can, and if you must use Smart Pointers(RAII) instead of raw pointers.
C++03 Standard Section §3.7.3.2.3:
The value of the first argument supplied to one of the deallocation functions provided in the standard library may be a null pointer value; if so, the call to the deallocation function has no effect. Otherwise, the value supplied to operator delete(void*) in the standard library shall be one of the values returned by a previous invocation of either operator new(size_t) or operator new(size_t, const std::nothrow_t&) in the standard library, and the value supplied to operator delete in the standard library shall be one of the values returned by a previous invocation of either operator new or operator new[](size_t, const std::nothrow_t&) in the standard library.
A: No, you don't need that.
Just write delete p, and be sure to not accept advice about anything else from anyone advocating that you do more.
General advice: avoid raw new and delete. Let some standard container deal with allocation, copying and deallocation. Or use a smart-pointer.
Cheers & hth.,
A: Best to use a resource-managing class and let the library take care of that for you:
#include <memory>
void foo() // unique pointer
{
std::unique_ptr<MyClass> myObject(new Myclass(myVarA, myVarB, myVarC));
// ...
} // all clean
void goo() // shared pointer -- feel free to pass it around
{
auto myObject = std::make_shared<MyClass>(myVarA, myVarB, myVarC);
// ...
} // all clean
void hoo() // manual -- you better know what you're doing!
{
MyClass * myObject = new MyClass(myVarA, myVarB, myVarC);
// ...
delete myObject; // hope there wasn't an exception!
}
A: Just to add that setting the pointer to NULL after it's been delete'd is a good idea so you don't leave any dangling pointers around since attempts to dereference a NULL pointer is likely to crash your application straight away (and so be relatively easy to debug), whereas dereferencing a dangling pointer will most likely crash your application at some random point and be much more difficult to track down and fix.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting "set statistics io on" results in t-sql for tuning I want to add monitoring capabilities to a complex process involving many stored procedures.
In some cases I want to capture the number of logical reads produced by a single statement.
In other words, I would like to turn on the set statistics io on, access (and save the results to a log table) what is usually displayed in the SSMS in the "messages" tab.
I saw that it can be done in .Net with SqlInfoMessageEventHandler. I'm sure that it can also be done in T-SQL but i didn't find it yet.
Thanks!
Logical_reads in sys.dm_exec_requests is not increasing as well...
The perfect solution for me would be a way of somehow capturing the "set statistics io on" information :
select name, id
from sysobjects
union all
select name,id
from sysobjects ;
(120 row(s) affected)
Table 'sysschobjs'. Scan count 2, logical reads 6, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
A: One way is to use dynamic management views, available in 2008 and up. For example, to determine the number of reads done by your query, you could:
declare @start_reads bigint
select @start_reads = reads from sys.dm_exec_requests where session_id = @@spid
-- Your query here
select reads - @start_reads from sys.dm_exec_requests where session_id = @@spid
There's basically two types of counters:
*
*The _session_ views have counters that are incremented after your current batch completes.
*The _exec_ counters start at 0 and increment while your batch is running.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Generating routes in javascript with Twig and Symfony2 Quite odd problem, sorry for asking, i'm quite new to Symfony/Twig. My route requires a mandatory region_id paramenter:
ajax_provinces_by_region:
pattern: /ajax/region/{region_id}/provinces
defaults: {_controller: SWAItaliaInCifreBundle:Ajax:provincesByRegion }
requirements: {region_in: \d+}
The question is: how can i generate this route based on a select element in javascript (code below)?
The problem is: i can't use path and url helpers from Symfony as they require to specify the region_id parameter (this.value) i can't access because it's a javascript variable (and Twig is compiled server-side).
$(document).ready(function() {
$('select#regions').change(function(){
// Make an ajax call to get all region provinces
$.ajax({
url: // Generate the route using Twig helper
});
});
});
A: I know it's an old question, but just in case you don't want to install a bundle like FOSJsRoutingBundle, here's a little hack:
var url = '{{ path("yourroute", {'region_id': 'region_id'}) }}';
url = url.replace("region_id", this.value);
'region_id' is just used as a placeholder, then you replace it in JS with your actual variable this.value
A: You can use the FOSJsRoutingBundle.
A: url: "{{ path('SampleBundle_route',{'parameter':controller_value}) }}"
Where SampleBundle_route is a valid path defined in routing.yml or annotatins.
For testing, write this in the twig template:
<script>
var url= "{{ path('SampleBundle_route') }}";
alert(url);
</script>
A: * @Route("/{id}/edit", name="event_edit", options={"expose"=true})
A: You can use data attribute in your HTML:
<select id="regions">
{% for region in regions %}
<option data-path="{{ path('ajax_provinces_by_region', {'region_id': region.id}) }}">...</option>
{% endfor %}
</select>
then in your javascript:
$('select#regions').on('change', function() {
let path = $(this).find(':selected').data('path')
$.ajax({
'url': path
})
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
} |
Q: How do i "version" a C binary file on linux platforms usually the practice is not to include binaries in source control repositories, i am using mercurial, and would like to know if anyone has experience with embedding version (minor + major) in a C Binary, so that when its distributed if i use a command line argument like mybinaryApp --version, i will get a unique version, which i can control at build time.
A: Are you looking for something like the KeywordExtension?
A: The usual way is to use the autotools (autoconf & automake & autoheader & al.). They make an include file config.h available, and this file defines the PACKAGE_VERSION macro that you can print out with --version.
This process is independent from version control. The simple reason for this is that you will want to distribute your project as a source code tarball, and people have to build that tarball without access to your version control.
A: The way that I embed version numbers in the code is to #define _VERSION_MAJOR in a separate header file, include them in files that need the version number, and then use that macro where needed. Then, you are free to control the version number in a different source file, without having to continually modify the original file.
This is the essence of what most advanced tools do.
Alternatively, if you wanted a build-specific tag, then you can use __DATE__ and __TIME__ to insert build time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: XML save all children to variable I am using jQuery AJAX to get a XML file with:
$.ajax({
type: "GET",
url: phoneXmlPath,
dataType: "xml",
contentType: "text/xml; charset=utf-8",
success: function(xml){
$(xml).find("phone[phone_id="+phone_id+"]").each(function(index, value){
var tis = $(this);
tis.children().each(function(){
alert($(this).nodeName);
});
});
},
error:function(xhr,type){
if(type == null){
var errorMsg = "There was an error loading the phone.xml file!<br/>Please make sure the path to the xml file <strong>'"+phoneXmlPath+"'</strong> is correct.";
}else if(type == "parsererror"){
var errorMsg = "There is an error in the file <strong>'"+phoneXmlPath+"'</strong>.";
}else{
var errorMsg = "An error has been detected.";
}
popup.removeClass("loading").html("<p><strong>Error:</strong> "+errorMsg+"</p><p><strong>Type of error:</strong> "+type+".</p>");
}
});
In this part: alert($(this).nodeName); how could I save everything to a variables that I can later access. E.g further down the code I would like to be able to do: "phone.title" and access all of the phone children elements.
XML file
<phones>
<phone>
<phone_id>123</phone_id>
<title>Phone title</title>
etc....
A: Use the JavaScript XML parser - http://www.w3schools.com/xml/xml_parser.asp
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626798",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Finding regular expressions for languages otherwise described Letting {a b} be the alphabet set, write a regular expression for:
1) The language of all those words in which the number of a's and the number of b's are both odd;
2) The language of all those words whose length is odd and which contain the substring ab.
Also, if possible, please help me find two different expressions for each so as to help strengthen my understanding of how to go about solving such problems.
A: For the first one, there's an easy 4-state DFA you can construct to recognize the language. Then, you can use the algorithm recoverable from Kleene's theorem (the part where he says all languages recognized by a FA are generated by a RE) to get an RE that works... or just reason it out from the diagram.
For the second one, you know that (ab) is part of the RE; now, you need to think of all the unique ways you could add an odd number of characters to this (front or back), and connect all those possibilities with + for an easy, correct RE.
I don't think anybody particularly likes the idea of just giving you the answer.
EDIT:
So now that some time has passed, I'll work through the answer to the first one to show interested readers how it can be done.
Our first FA is this:
Q s f(Q, s)
-- - -------
EE a OE
EE b EO
OE a EE
OE b OO
EO a OO
EO b EE
OO a EO
OO b OE
We will remove states from this and replace s with a regular expression to cover that state. We start with an easy one... let's get rid of OE. Here's the table for that...
Q regex f(Q, s)
-- ---------------------- -------
EE aa EE
EE ab OO
EE b EO
EO a OO
EO b EE
OO a EO
OO ba EE
OO bb OO
Convince yourself this is correct before continuing. Next, we get rid of EO:
Q regex f(Q, s)
-- ---------------------- -------
EE aa+bb EE
EE ab+ba OO
OO ab+ba EE
OO aa+bb OO
To make the next step simpler, we introduce a new start set X and a new accepting state Y; OO is no longer accepting. We eliminate the need for OO:
Q regex f(Q, s)
-- ---------------------------- -------
X empty EE
EE aa+bb+(ab+ba)(aa+bb)*(ab+ba) EE
EE (ab+ba)(aa+bb)* Y
Therefore, the final regex is
(aa+bb+(ab+ba)(aa+bb)*(ab+ba))*(ab+ba)(aa+bb)*
We can begin trying to list the smallest strings this generates, just as a basic sanity check: {ab, ba, aaab, aaba, bbab, bbba, abaa, abbb, baaa, babb, ...} Looks good to me!
The rules for reducing at each step can be formalized, or you can just apply careful reasoning to ensure that you're getting the right thing. Check a proof of Kleene's theorem for a careful analysis. Also, Martin's Introduction to Formal Languages or something has good examples of using this algorithm.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626800",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Custom PowerShell Cmdlet does not accept Variables I have a custom PowerShell cmdlet that has the following attributes on one of the input properties. The property is a get/set of type float . I want to be able to supply this property with either a float value or a variable.
[Parameter(
ValueFromPipeline=true,
ValueFromPipelineByPropertyName = true,
Mandatory = true)]
public float MyProperty
{
get { return _myProp; }
set { _myProp = value; }
}
Declaring and assigning a variable in my script like this results in the following error.
[float]$r=0.05
--or--
$r=0.05
PS C:>get-mycmdlet
cmdlet Get-mycmdlet at command pipeline position 1
Supply values for the following parameters:
(Type !? for Help.)
myPropperty: $r
Cannot recognize "$r" as a System.Single due to a format error.
myProperty:
What is needed in my PS cmdlet to get it to accept my variables?
Thanks
A: This should work just fine if you specify the parameter on the command line, i.e:
get-mycmdlet -MyProperty $r
I don't think that the interactive prompts accept variables.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to position these CSS elements without defining height and width I am trying to create a little graphical box for a time element on a website. What I would like to have is something like this:
I have this HTML:
<div class="entry-meta">
<time class="entry-date" datetime="2011-09-16T09:59:48+00:00" pubdate="">
<span class="date-day">16</span>
<span class="date-month">Sep</span>
<span class="date-year">2011</span>
</time>
</div>
And this CSS so far:
.entry-meta {
display: block;
color: white;
float: left;
background: #aaa;
}
.date-day {
display: block;
font-size: 30px;
background: #444;
float: left;
}
.date-month {
display: block;
font-size: 12px;
background: #666;
float: left;
}
.date-year {
display: block;
font-size: 12px;
background: #888;
float:left;
}
My problem is that I cannot achieve two things:
*
*To align the text to the corners of the box and forget about the baseline. I would like to align 16 to the top left corner and cut it's box at the bottom right corner. I am looking for eliminating all the spacing pixels.
*To move the year under the month, without specifying exact width and height properties. If I delete float: left then it goes under the day. What I would like to have is to move it right of the day and under the month. Do I need to create an other div or spand for the month + year?
*Also, it seems that it doesn't matter if I remove display: block from the span CSS-es why is it?
Here is a jsFiddle I created:
http://jsfiddle.net/ESbqY/3/
An update one based on Kolink's suggestion:
http://jsfiddle.net/ESbqY/5/
A: The following:
<span style="font-size: 2em;">16</span><span style="display: inline-block;">Sep<br />2011</span>
Will produce, more or less exactly, the result shown in the image.
A: This seems to work as required:
time span {
display: block;
font-size: 1em;
margin-left: 2.5em;
}
time span.date-day {
float: left;
position: absolute;
font-size: 2em;
margin: 0;
}
.entry-meta {
border: 2px solid #ccc;
display: block;
float: left;
position: relative;
}
JS Fiddle demo.
Edited to amend/use the colours from the question, and to remove the (possibly unwanted) margin between the date-day and the other span elements:
time span {
display: block;
font-size: 1em;
margin-left: 2em;
}
time span.date-day {
float: left;
position: absolute;
font-size: 2em;
margin: 0;
background-color: #444;
}
time span.date-month {
background-color: #666;
}
time span.date-year {
background-color: #888;
}
.entry-meta {
border: 2px solid #ccc;
display: block;
float: left;
position: relative;
background-color: #ccc;
}
JS Fiddle demo.
A: Fully customizable:
http://jsfiddle.net/5MMc9/8/
html:
<div class="entry-meta">
<time class="entry-date" datetime="2011-09-16T09:59:48+00:00" pubdate="">
<div class="date-day">16</div>
<div class="container">
<div class="date-month">Sep</div>
<div class="date-year">2011</div>
</div>
</time>
</div>
css:
.entry-meta {position: relative; font-family: Trebuchet MS;}
.container {float: left;}
.date-day {font-size: 70px; line-height: 55px; float: left; background: #fa7d7d;}
.date-month {font-size: 25px; line-height: 25px; background: #627cc6; padding: 0 0 5px 0;}
.date-year {font-size: 25px; line-height: 25px; background: #3ce320;}
Furthermore, you can add display: inline-block; to the month css if you want the div to be same width as text inside.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to run ruby files? Example I have the file test.rb:
puts "test test test"
How do I run this file in the ruby console?
A: load("test.rb")
should do the trick in irb.
A: load 'test.rb'
Do you mean Rails console? (Same thing, but the question is tagged rails.)
A: On Mac you can run in three different ways from the terminal
Method 1
On Terminal irb (Interactive Ruby Shell) for line by line execution then quit command to be out of irb.
Method 2
As ruby is Interpreted language we can run by one command on terminal
*
*Save the text editor code with .rb extension.
*Change the directory in terminal by cd command (cd drag and drop the folder on terminal so that you can be directed to the directory).
*ruby hello.rb
Method 3
ruby -v to know the version of ruby
ruby -e 'puts WVU' #line by line execution on terminal
A: Any ruby file can be run with just ruby <your_ruby_file.rb>, supposing that you are in the same directory as the ruby file; If not, just provide a path to the file:
ruby path/to/your_file.rb
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626807",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Algorithm to find special point k in O(n log n) time Give an n log n time lower bound for an algorithm to check if a set of points has a special point k.
k is defined as:
for a set A of points, if for every point m in A, there is a point q in A such that k is in the middle of the line segment mq such a k does not have to belong to A.
For example, this set has a special point k = (0.5, 0.5) for a set of four points (1,0), (0,1), (1,1), (0,0).
I was totally poker faced when they asked me this, nothing came to my mind. I guess it needs some strong geometrical background.
A: O(nlogn) solution (I'm still not clear why you're looking for a lower bound solution. You might as well just do an exhaustive check, and then just run an nlogn loop to make sure of the lower bound. Not very difficult. I think you must mean upper bound):
Find the only valid candidate point by averaging all the points. I.e. summing their co-ordinates and dividing by the number of points. If such a k exists, this is it. If no such k exists, we'll find that the point found is invalid in the final step.
Create a new array (set) of points, where we shift our axes so they centre on the point k. I.e. if k = (xk,yk), a point (x,y) will become (x-xk, y-yk). Sort the points according to the ratio x/y and the norm sqrt(x2+y2). As the next step shows, it doesn't matter how this sort is done, i.e. which is the main criterion and which the secondary.
We could search for each point's complement, or better, simply traverse the array and verify that every two adjacent points are indeed complements. I.e. if this is a solution then every two complementary points in this new array are of the form (x,y) and (-x,-y) since we re-centered our axes, which means they have the same ratio ("gradient") and norm, and after the sort, must be adjacent.
If k is not valid, then the there is a point who we will arrive at in this traversal, and find that it's neighbour is not of the right/complementary form ==> there is no such k.
Time =
O(n) for finding the candidate k +
O(n) for building the new array, since each new point can be calculated in O(1) +
O(nlogn) for the sort +
O(n) for the verifying traversal
= O(nlogn)
A: I'd say you just compute the center of mass (having removed duplicates first) and check if it is your k. Probably the only thing that cause it to be O(n log n) would be searching for a point at specified location.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: AJAX call to a WebMethod I have the following Webmethod in my C#/.NET web-application, file lite_host.aspx.cs:
[WebMethod]
public static bool UpdatePage(string accessCode, string newURL)
{
bool result = true;
try {
HttpContext.Current.Cache[accessCode] = newURL;
}
catch {
result = false;
}
return result;
}
It should get the values of "accessCode" and "newURL" from a JavaScript function via a jQuery AJAX call with and make the appropriate changes in Cache:
function sendUpdate() {
var code = jsGetQueryString("code");
var url = $("#url_field").val();
var options = { error: function(msg) { alert(msg.d); },
type: "POST", url: "lite_host.aspx/UpdatePage",
data: {'accessCode': code, 'newURL': url},
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(response) { var results = response.d; } };
$.ajax(options);
}
However when I call the sendUpdate() function, I my script ends on $.ajax error and I'm getting an alert text "undefined".
A: Undefined means that msg.d doesn't exist. Try doing a console.log(msg) and use Chrome's debugger to see what is outputted (yeah, I know) to the console.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails: How to receive non-model form input, convert it to a model attribute, and then save that model Background:
*
*I have a form_for mapped to a model called List.
*List has attributes: name, id, receiver_id, assigner_id.
*I want the user( or list assigner) to be able to choose a list receiver.
*I want the assigner to input an e-mail, rather than the receiver's id.
Problem:
*
*I am not sure how to use a form to receive an e-mail address, run a "User.find_by_email(xx).id" query using that e-mail address, and then assign the returned id to the List's receiver_id attribute.
Current Code:
lists_conroller.rb
class ListsController < ApplicationController
before_filter :current_user
def new
@list = List.new
end
def create
@list = List.new(params[:list])
@list.assigner = @current_user
#@list.receiver = User.find_by_id(:receiver_id)
@list.save
redirect_to @list
end
def show
@list = List.find(params[:id])
end
def update
@list = List.find(params[:id])
end
end
lists\new.html.erb
<%= form_for @list do |f| %>
<%= f.label :name, 'Name'%>
<%= f.text_field :name %>
<%= f.label :receiver_id, 'Receiver ID'%>
**I want this to be the e-mail input, rather than the integer id.**
<%= f.text_field :receiver_id %><br />
<%= f.submit :submit %>
<% end %>
A: User creates new list, with him as the assigner. In that creation process there must be a receiver too. Did I get this right?
I think the receiver should be selected from a list of possible receivers (maybe a select box? this will depend on the number of possible receivers though, wouldn't want to list 1000+ users in there - if there are many users you could do an ajax search when the user types a few letters)
The assigner then selects a user (with the corresponding id as the value) and everything should be ok.
A: The answer to my question is "Virtual Attributes..."
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: sqlite multiple databases insert/update/delete I was wondering how SQLite behaves when it's given multiple databases to insert/update/delete in at the same time? Does it spawn multiple processes which can in theory have better concurrency than using a single database/single process or it utilizes the same process for each?
Searching through the documentation didn't provide e with a definitive answer. I am aware that SQLite isn't the most ideal environment for multiple writes, as the database resides in as single file. But does that mean that multiple files = different write processes?
databaseOne = connectToSqlite('databaseOne');
databaseTwo = connectToSqlite('databaseTwo');
function write()
queryDatabaseOne("INSERT SOMETHING INTO SOME_TABLE VALUES SOME_VALUES");
queryDatabaseTwo("INSERT SOMETHING INTO SOME_TABLE VALUES SOME_VALUES");
So, two different sqlite databases, and two inserts executed in parallel, towards tables in the two databases.
Thanks
A: Normally, database queries are blocking - they do not return until they are complete. This helps secure the integrity of the database. The SQLITE API is blocking.
Of course, if you have a multiple databases, then you can write a multi-threaded application with non-blocking routines that call the the SQLITE API and then code overlapping, parallel inserts to the multiple databases. You will have to be careful about all the usual things in a multithreaded application - the SQLITE API will neither help not hinder - with added complication of insuring that there in no possibility of overlapping accesses to the SAME database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Self-cloning executable with .NET reflection I'm trying a sort of experiment in C# .NET. I'd like to create a program that clones itself (eventually as a mutated clone). Finally, I want it to produce a "son" that also needs to have the ability to clone himself and so on!
I want to make something like this:
static void Main(string[] args)
{
string Son_Name = "son";
string Full_Son_Name = Son_Name + ".exe";
AssemblyName aName = new AssemblyName(Son_Name);
AssemblyBuilder aBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Save);
ModuleBuilder mBuilder = aBuilder.DefineDynamicModule("Module", Full_Son_Name, false);
TypeBuilder tBuilder = mBuilder.DefineType("Program", TypeAttributes.Public);
MethodBuilder methodBuilder = tBuilder.DefineMethod("Main", MethodAttributes.Public | MethodAttributes.Static);
ILGenerator ilGenerator = methodBuilder.GetILGenerator();
MethodInfo m_ReadLine = typeof(System.Console).GetMethod("ReadLine", BindingFlags.Public | BindingFlags.Static);
Clone_My_Main_method(methodbuilder);//I need something to do THAT
aBuilder.SetEntryPoint(methodBuilder);
tBuilder.CreateType();
aBuilder.Save(Full_Son_Name);
So, with this code I succeded in making a dynamic assembly at runtime, and save it as "son.exe" or execute it. Now I need to "build" that assembly, reading my main and copying it into the son assembly.
I started using ilgenerator.emit, but I'm going into an infinite "programming" loop. I thought to make the parent.exe, disassemble it with ildasm, translate all the CIL code in ilgenerator.emit opcodes and emit all of that with ilgenerator.emit. Simply, I think this is a tedious work and cannot...work.
In fact, I'd like to READ at runtime my own main method, and then put it onto the dynamic assembly with some trick.
Anyone has any idea?
Thanks :)
A: You should use Mono Cecil, which can read and modify .Net assemblies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Delphi action list equivalent in C# in Delphi there's action list , what's the equivalent to it in C# 3 winforms application
I searched a lot but didn't find any proper way
A: There is no equivalent in WinForms. This is one of the most common complaints when a Delphi developer switches to WinForms.
There are various third party options but I have no personal experience with which to make a recommendation. You could take a look at this for starters: http://www.codeproject.com/KB/miscctrl/actionlist.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: NSButton with an Image I have a question. I have a button on my .xib and a background image. I set an image to my button through the attributes inspector, but when I run the program and press the button, this happens:
If I don't press it, it looks fine. What's wrong?
A: This is controlled by the setHighlightsBy: property on the cell. It's probably set to NSChangeBackgroundCellMask by default. Try setting NSContentsCellMask (if you have an alternate 'pressed' image) or NSNoCellMask.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Recreating an Android View in OpenGL Android views are generally quite laggy. I was wondering if it could be possible to like recreate them in OpenGL-ES to use hardware acceleration on it. If it was possible i'd guess it would have been done already. Is it usefull or possible?
A: You can implement a GLSurfaceView and draw whatever you like. But I would not recommend recreating an existing view. I don't know which views you mean but on my device they aren't laggy at all...
Update: My statement that views are already hardware accelerated was disproved (see comment). So I did research and found this article (which underlines the contradiction). So hardware acceleration is available in android 3.0+. Still, I wouldn't recommend to reimplement default widgets. There's still a lot you could do wrong and so impact the performance in a negative way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7626833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.