text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Uncheck a checked checkbox with jquery in asp.net I have several checkboxes inside an UpdatePanel of asp.net
Let's say, I have 3 checkboxes in that panel. Each time, one checkbox is checked, the previous checked checkbox will be unchecked.
I have tried like this:
<asp:CheckBox ID="CheckBoxExport1" CssClass="checkboxSingle" />
<asp:CheckBox ID="CheckBoxExport1" CssClass="checkboxSingle" />
<asp:CheckBox ID="CheckBoxExport1" CssClass="checkboxSingle" />
In js:
$('.checkboxSingle').live('click', function (e) {
if ($(this).is(':checked')) {
$(".checkboxSingle").attr('checked', false);
$(this).attr('checked', 'checked')
}
});
The click is function but the rest does not.
A: What's happening is that on postback the page reloads and the JavaScript doesn't re-run. I'm posting from my phone so I don't have the code on me. But google "updatepanel JavaScript postback". You need to use an asp page event.
I'll edit this later if you tell me you can't find it.
Good luck
A: It is simple, (asp:CheckBox) is rendered as a (span) with label and input field with type="check".
So when you are trying to say $(".chkboxClass").removeAttr('checked'); you are actually calling the (span) tag and that is the reason it is not working. To make it works just add:
$(".chkboxClass :input").removeAttr('checked');
Good luck
A: this is similar to DigitalFox response, but this is how I got it to work:
$(".checkboxSingle input").is(":checked");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Prolog - Variable as operator I have an operator stored in a variable Op and two integers are stored in X and Y. Now, I want to do something like (Z is X Op Y), but this syntax seems not to be correct.
Does anybody know if there is a way to do this in Prolog?
Thanks for your answers
A: you can do it by building the predicate using the =.. operator.
try it like:
compute(X,Y,Op,Z) :-
Eq=..[Op, X, Y],
Z is Eq.
An operator is really just like any other functor.
A: You can mimic the effect:
operator(Z,X,plus,Y):-Z is X + Y.
operator(Z,X,times,Y):-Z is X * Y.
I tried this on ideone.com for SWI-Prolog with:
OP=times, operator(Z,3,OP,8).
And I got:
OP = times,
Z = 24.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: NetBeans: how to add ScrollBar to JPanel I am developing a small desktop application in NetBeans. On my UI, I place a JPanel and put a single JLabel on it. The content of this JLabel is generated dynamically, so if the content is very large then it goes out of screen.So is there any way in which I can specify a fixed size for the JPanel and of course ScrollBars should appear when the text exceeds the screen size.
A: You will have to just pass Component reference to the JScrollPane Constructor.
It will work fine. You can definetely use JScrollPane
The following is the sudo example of the JScrollPane for JPanel from my past project. Hope it will be useful for you.
import javax.swing.*;
import java.awt.*;
public class Frame01
{
public static void main(String[] args){
SwingUtilities.invokeLater (new Runnable ()
{
public void run ()
{
JFrame frame = new JFrame("panel demo");
frame.setDefaultCloseOperation (JFrame.DISPOSE_ON_CLOSE);
JPanel panel = new JPanel();
Container c = frame.getContentPane();
panel.setSize(100,100);
panel.setLayout(new GridLayout(1000,1));
for(int i = 0; i<1000;i++)
panel.add(new JLabel("JLabel "+i));
JScrollPane jsp = new JScrollPane(panel);
c.add(jsp);
frame.setSize(100,100);
frame.setVisible(true);
}
});
}
}
A: Use JScrollPane to contain Your big JPanel.
A: so in case when the contents are very large it goes out of screen, maybe you have to look for TextComponents as JTextArea or JEditorPane, tutorial contains example including basic usage for JScrollPane
A: In the Navigator, click on JPanel with the right mouse button --> Enclose In --> Scroll Pane.
Done!, You have now scrolls
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Rewriting url to hide index.php and to make query nice I had developed project with custom MVC architecture. And I am new to Apache world, so I would appreciate help with this matter. On a Web I had found lots of tutorials, but no one like mine interests.
I have URL like this: http://knjiskicrv.comoj.com/index.php?page=book&id=1
I would like to be display like this: http://knjiskicrv.comoj.com/book/id/1
Or this: http://knjiskicrv.comoj.com/index.php?page=faq
Into this: http://knjiskicrv.comoj.com/faq
If there is no page in query (http://knjiskicrv.comoj.com/index.php), I would like to show: http://knjiskicrv.comoj.com/
Also with no page in query (http://knjiskicrv.comoj.com/index.php?category=2), it should be like this http://knjiskicrv.comoj.com/category/2
Hope someone will help. Thanks.
A: Actually, your problem is a two step proble. You first need to understand what is "Routing" in MVC. If you have your own implementation of an MVC like framework and you don't support routing, then it probably means you didn't even know how it worked before. (Sad but true)
In an MVC framework you setup routes using a ROUTER and the router analyses the urls for you saying HEY, i found this url that matches your request, go ahead and do work with it.
So then, your controller receives a request to route into itself and PARSES the url as he sees fit. Such as using explode('/', $_SERVER['REQUEST_URI']) and then reading the different parts of the url to map to expected variables.
All of this is very theoretical because there are ZILLIONS of way to implement it in a custom way. The only thing you will have to use is a little mod_rewrite magic to pass all requests to your index.php that will route everything. Look at the url below to learn about mod_rewrite, it's a VERY COMPLEX subject:
http://www.addedbytes.com/for-beginners/url-rewriting-for-beginners/
What i usually go for but i don't have access to it from home is something like this:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^assets/
RewriteRule .* index.php
This will redirect all traffic to index.php and you can then use $_SERVER['REQUEST_URI'] to analyze the request. Everything in assets/ folder will not be touched and work correctly.
Note, i built that part off my hat, it might not work...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Add children to wrap panel I'm adding rectangles to a wrap panel like this:
For i = 0 to 20
wrapPanel.children.add()
next
I would like to use this loop because I don't want to specify the limit:
Do
wrapPanel.children.add()
Loop
But how can I break the loop when the wrap panel is filled? For example the loop would stop when the wrap panel can't display a rectangle in its full height or width.
A: this is giving error "Specified Visual is already a child of another Visual or the root of a CompositionTarget."
I want to read data from xml file using user control.
List<careeroption> qz = new List<careeroption>();
qz = KompkinDP.GetQuizList(CareerID.ToString());
foreach (careeroption q in qz)
{
UserControl1 uc = new UserControl1();
for (int i = 0; i < q.CareerOptionQuiz.Count; i++)
{
uc.QuizName = q.CareerOptionQuiz[i];
wrap1.Children.Add(uc);
}
// wrap1.Children.Add(uc);
}
A: I finally got it working! I'm using Canvas instead of Wrap Panel. Here's the working code:
for y = 0 to Canvas.height - Rectangle.height Step Rectangle.height
for x = 0 to Canvas.width - Rectangle.width Step Rectangle.width
Canvas.sety(Rectangle,y)
Canvas.setx(Rectangle,x)
Canvas.children.add(Rectangle)
next
next
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to update small portion of view in Backbone or Spine The common pattern in Backbone/Spine is to re-render the whole view from scratch when something happens.
But what do you do if you only need to update a small part of it (highlight, select, disable, animate etc)?
It doesn't make any sense to re-render everything as it might screw up the current layout (If the page has been scrolled to a certain point for example).
On the other hand if you update small parts "inline" from the View using something like $('.selected').highlight(), then you would have to duplicate the same logic in the view template and JavaScript code.
So what is the "best practice" in Backbone/Spine to do that?
A: In Spine, use the element pattern: http://spinejs.com/docs/controller_patterns
A: on the backbone side of the house, you'd end up using the same jquery... just wrapped up in a backbone view. i blogged about this, here:
http://lostechies.com/derickbailey/2011/09/26/seo-and-accessibility-with-html5-pushstate-part-2-progressive-enhancement-with-backbone-js/
ignore the pushstate, seo and accessibility language in this case. the progressive enhancement ideas are what you're after
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Updating UI / runOnUiThread / final variables: How to write lean code that does UI updating when called from another Thread I have been reading up on the UI updating when I found out that, like WinForms, Android need to do UI updates on from the main thread (too bad, I was hoping someone could once and for all solve that irritating problem).
Anyways, I need to pass that to the UI thread. Some suggest the use of the runOnUiThread method and that might have worked, if it wasn't for that irritating "final" that then came into play.
I have an Interface, with a method I cannot change. It looks like this:
@Override
public void connStateChange(ClientHandler clientHandler)
That method is called when I get a change in the connection status (network). When I do, I need to do some stuff, and in this case it is adding some text to a TextView.
So I tried this, but of course the variable "clientHandler" isn't final:
@Override
public void connStateChange(ClientHandler clientHandler) {
runOnUiThread(new Runnable()
{
public void run()
{
tv.append(clientHandler.getIP() + ", " + clientHandler.state.toString() + "\n");
if (clientHandler.state == State.Connected)
{
tv.append("Loginserver hittad");
}
}
});
}
How do I in a nice, clean and efficient way write code in this example to update the UI? I need access to all my variables etc...
A: Try it:
@Override
public void connStateChange(ClientHandler clientHandler) {
final ClientHandler temporaryHander = clientHandler;
runOnUiThread(new Runnable() {
public void run() {
tv.append(temporaryHandler.getIP() + ", " + temporaryHandler.state.toString() + "\n");
if (temporaryHandler.state == State.Connected) {
tv.append("Loginserver hittad");
}
}
});
}
By the way, code becomes more readable, if you declare not anonim class right in the method, but declare inner class out of methods. Consider it as pattern Command.
Example of more clean and reusable code.
@Override
public void connStateChange(ClientHandler clientHandler) {
final ClientHandler temporaryHander = clientHandler;
runOnUiThread(new MyRunnableCommand(temporaryHandler));
}
private class MyRunnableCommand implements Runnable {
private ClientHandler clientHandler;
public MyRunnableCommand(ClientHandler clientHandler) {
this.clientHandler = clientHandler;
}
@Override
public void run() {
tv.append(clientHandler.getIP() + ", " + clientHandler.state.toString() + "\n");
if (clientHandler.state == State.Connected) {
tv.append("Loginserver hittad");
}
}
}
Though the Runnable implementation itself was inflated a little, code became more re-usable and easy to read.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android resources not found on some devices We have an application(with moderate amount of strings) which we translate to 27+ languages. We make 2 builds of the application. These 2 builds only differ in the name of the package. So basically we first do a build of our application with package name lets say com.android.sad.app and then another one with package name com.android.even.sadder.app.
We had the chance to test our application on a great variety of Android devices and we have found out that on some devices like Samsung ACE, Samsung Galaxy S or LG Optimus 2x our application can't load/read the resources so even the application icon isn't shown and when the application is started it crashes with android.content.res.Resources.NotFoundException. On other devices everything is working just fine.
We have found out that if we reduce the overall amount of strings in the resources of the application, our application can successfully run on the above mentioned devices. However we do not think this is the real solution to our problem because the debug build with full strings in resources can be ran on the devices in question.
So my question would be does someone knows what can potentially cause this very strange behavior ?
A: After some trial and error experimenting we have found out that the problem was with the apk package itself. In our build process we add some files to our application apk right after the build has finished but before signing and aligning the apk file. Originally we were extracting and repackaging the apk with our own tool (which is written in Java and thus using the Java implementation of Zip).
We have noticed that after repackaging the apk with our tool we were able to reduce the size of the apk to half size of the original apk created by the Android build.
As we have found out this repackaging was the cause of our problem!
As our experiments have shown if the repacked apk was smaller then ~1.6 Mb, all devices were able to read and work with the newly repacked apk. However if the size of the apk have exceeded ~1.6 Mb the devices (and the emulator) mentioned in this post were not able to correctly read or work with the application apk .
I have been looking around for some specification on the apk file format(which is essentially jar), but I have found nothing that would explain this very odd behavior. So could somebody please clarify why is this strange behavior happening and what are the exact reasons?
Note: from now on we are using the Android aapt tool to insert our files to the package, instead of the tool we have been using and the final apk can be read by all devices
A: I'm going to assume a lot here, but I would put money on it being related to the amount of strings. All of your strings will consume memory and maybe these target devices don't have enough available to your application. As for your package name differences, the shorter one will consume less bytes than the longer one of course.
I suggest that you reduce the amount of strings in use and see if that resolves your issues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: ListPicker always crashes when ExpansionMode is set to FullScreenOnly How should I make my list picker open in full screen mode? When I set ExpansionMode to FullScreenOnly it crashes. I tried creating blank project and doing the same but it also crashes.
<toolkit:ListPicker Height="100" HorizontalAlignment="Left" Margin="53,37,0,0" Name="listPicker1" VerticalAlignment="Top" Width="200" ExpansionMode="FullScreenOnly">
<toolkit:ListPickerItem Content="item1"/>
<toolkit:ListPickerItem Content="item1"/>
<toolkit:ListPickerItem Content="item1"/>
<toolkit:ListPickerItem Content="item1"/>
<toolkit:ListPickerItem Content="item1"/>
<toolkit:ListPickerItem Content="item1"/>
</toolkit:ListPicker>
How should I work around this problem ?
A: There is a[n apparently known] bug where full mode causes an error when the items are defined in XAML.
As the other answer says, define your items in code and this issue is not seen.
A: Adding "item1" many times might create problem? try changing content to item1, item2...etc
If not so, try using listPicker1.Items.Add();
A: The problem is some bug in ListPicker that prevents it to display more than 5 items if they are directly provided from the XAML. Better use data binding and generate items via C#.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: what's the key sequence when enumerating an object in javascript? I already know how to enumerate an object in javascript. My question is what's the key sequence while enumerating.Is it by A-Z or time ordered?
code
var a = {
"a":""
,"b":""
,"c":""};
for (var k in a) {
console.log(k);
}
output
a,b,c
code
var a = {
"b":""
,"a":""
,"c":""};
for (var k in a) {
console.log(k);
}
output
b,a,c
code
var a = {
"b":""
,"a":""
,"c":""};
a.d = "";
for (var k in a) {
console.log(k);
}
output
b,a,c,d
A: Usually the order is the time it was added, but the specification for the for in loop says:
The mechanics and order of enumerating the properties (step 6.a in the first algorithm, step 7.a in the second) is not specified.
So you cannot really rely on one specific order.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mapping private property entity framework code first I am using EF 4.1 and was look for a nice workaround for the lack of enum support. A backing property of int seems logical.
[Required]
public VenueType Type
{
get { return (VenueType) TypeId; }
set { TypeId = (int) value; }
}
private int TypeId { get; set; }
But how can I make this property private and still map it. In other words:
How can I map a private property using EF 4.1 code first?
A: Here's a convention you can use in EF 6+ to map selected non-public properties (just add the [Column] attribute to a property).
In your case, you'd change TypeId to:
[Column]
private int TypeId { get; set; }
In your DbContext.OnModelCreating, you'll need to register the convention:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new NonPublicColumnAttributeConvention());
}
Finally, here's the convention:
/// <summary>
/// Convention to support binding private or protected properties to EF columns.
/// </summary>
public sealed class NonPublicColumnAttributeConvention : Convention
{
public NonPublicColumnAttributeConvention()
{
Types().Having(NonPublicProperties)
.Configure((config, properties) =>
{
foreach (PropertyInfo prop in properties)
{
config.Property(prop);
}
});
}
private IEnumerable<PropertyInfo> NonPublicProperties(Type type)
{
var matchingProperties = type.GetProperties(BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(propInfo => propInfo.GetCustomAttributes(typeof(ColumnAttribute), true).Length > 0)
.ToArray();
return matchingProperties.Length == 0 ? null : matchingProperties;
}
}
A: Another workaround might be to set your field as internal:
[NotMapped]
public dynamic FacebookMetadata {
get
{
return JObject.Parse(this.FacebookMetadataDb);
}
set
{
this.FacebookMetadataDb = JsonConvert.SerializeObject(value);
}
}
///this one
internal string FacebookMetadataDb { get; set; }
and add it to tour model:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<System.Data.Entity.ModelConfiguration.Conventions.ManyToManyCascadeDeleteConvention>();
///here
modelBuilder.Entity<FacebookPage>().Property(p => p.FacebookMetadataDb);
base.OnModelCreating(modelBuilder);
}
A: you can't map private properties in EF code first. You can try it changing it in to protected and configuring it in a class inherited from EntityConfiguration .
Edit
Now it is changed , See this https://stackoverflow.com/a/13810766/861716
A: Try this.
public class UserAccount
{
private string Username { get; set;}
}
public class UserAccountConfiguration :IEntityTypeConfiguration<UserAccount>
{
public void Configure(EntityTypeBuilder<UserAccount> builder)
{
builder.Property(c => c.Username);
}
}
and then in DbContext
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.ApplyConfiguration(new UserAccount.UserAccountConfiguration());
}
A: If you like Attributes (like me) and you're using EF Core. You could use the following approach.
First, Create an attribute to mark private or properties:
using System;
using System.ComponentModel.DataAnnotations.Schema;
...
[System.AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public sealed class ShadowColumnAttribute : ColumnAttribute
{
public ShadowColumnAttribute() { }
public ShadowColumnAttribute(string name): base(name) { }
}
public static class ShadowColumnExtensions
{
public static void RegisterShadowColumns(this ModelBuilder builder)
{
foreach (var entity in builder.Model.GetEntityTypes())
{
var properties = entity.ClrType
.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic)
.Select(x => new { prop = x, attr = x.GetCustomAttribute<ShadowColumnAttribute>() })
.Where(x => x.attr != null);
foreach (var property in properties)
entity.AddProperty(property.prop);
}
}
}
Then, mark the properties you would like to stay private.
public class MyEntity
{
[Key]
public string Id { get; set; }
public bool SomeFlag { get; set; }
public string Name => SomeFlag ? _Name : "SomeOtherName";
[ShadowColumn(nameof(Name))]
string _Name { get; set; }
}
Finally, in your DbContext, place this at the end of your OnModelCreating method:
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
// ...
builder.RegisterShadowColumns();
}
A: Extending @crimbo's answer above ( https://stackoverflow.com/a/21686896/3264286 ), here's my change to include public properties with private getters:
private IEnumerable<PropertyInfo> NonPublicProperties(Type type)
{
var matchingProperties = type.GetProperties(BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(propInfo => propInfo.GetCustomAttributes(typeof(ColumnAttribute), true).Length > 0)
.Union(
type.GetProperties(BindingFlags.SetProperty | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance)
.Where(propInfo => propInfo.GetCustomAttributes(typeof(ColumnAttribute), true).Length > 0
&& propInfo.GetGetMethod().IsNull())
)
.ToArray();
return matchingProperties.Length == 0 ? null : matchingProperties;
}
A: Another way to handle this is to defines a custom entity configuration and add a binding for that.
In your class add a class that inherits from EntityTypeConfiguration (This can be found in System.Data.Entity.ModelConfiguration)
public partial class Report : Entity<int>
{
//Has to be a property
private string _Tags {get; set;}
[NotMapped]
public string[] Tags
{
get => _Tags == null ? null : JsonConvert.DeserializeObject<string[]>(_Tags);
set => _Tags = JsonConvert.SerializeObject(value);
}
[MaxLength(100)]
public string Name { get; set; }
[MaxLength(250)]
public string Summary { get; set; }
public string JsonData { get; set; }
public class ReportConfiguration: EntityTypeConfiguration<Report>
{
public ReportConfiguration()
{
Property(p => p._tags).HasColumnName("Tags");
}
}
}
In your context add the following:
using Models.ReportBuilder;
public partial class ReportBuilderContext:DbContext
{
public DbSet<Report> Reports { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new Report.ReportConfiguration());
base.OnModelCreating(modelBuilder);
}
}
Wish I could say I found this on my own, but I stumbled upon it here:https://romiller.com/2012/10/01/mapping-to-private-properties-with-code-first/
A: As seen in your model you grant read access to the property. So maybe you want to block set access and map to EF using a private setter. Like this.
[Required]
private int TypeId { get; private set; }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: WorldWind Java on a Netbeans Platform TopComponent I'm trying to add a layer to WorldWind Java (version 1.2) situated on a Netbeans Platform TopComponent (using netbeans 7.0).
The TopComponent is in Editor mode, and for WWJ I use WorldWindowGLCanvas which is the single swing component on the TopComponent and it is placed with BorderLayout.CENTER.
If I add the layers using the constructor all works well, I can see the layers fine. If I add the layer using swing controls (eg a button) the layer gets added to the layer list but it is not rendered. This happens for both WMS and Renderable layer.
Same process on a pure swing application works fine which leads me to believe that the rendering process in WWJ is somehow conflicting with the TopComponent painting.
Any help with be greatly appreciated.
A: I've set up a demo using NetBeans Platform (7.0.1) with gov.nasa.worldwind.awt.WorldWindowGLCanvas and gov.nasa.worldwindx.examples.LayerPanel
Initialization Code:
private void initComponents() {
canvas = new WorldWindowGLCanvas();
Model model = (Model) WorldWind.createConfigurationComponent(AVKey.MODEL_CLASS_NAME);
canvas.setModel(model);
layerPanel = new LayerPanel(canvas);
setLayout(new BorderLayout());
add(canvas, BorderLayout.CENTER);
add(layerPanel, BorderLayout.WEST);
}
private WorldWindowGLCanvas canvas;
private LayerPanel layerPanel;
This works the same as it does running the sample as a stand alone so I would say that the problem does not lie in the NetBeans Platform. Without any code it's hard to say what's going wrong.
Note that the gov.nasa.worldwind.awt.WorldWindowGLCanvas is not a Swing component but a heavy weight component. This is irrelevant to your question but I couldn't help but point it out. The Swing component is gov.nasa.worldwind.awt.WorldWindowGLJPanel
Edit: I realize my answer is not very helpful, so to remedy that I would add a suggestion. You could try to invalidate the TopComponent and call repaint whenever you need it to render the new layer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: jQuery hover event over iframe/flash in IE6-9 not working? See the example below:
http://jsfiddle.net/sPvYk/3/
For the purpose of this demo the close button is visible, but in real life it's hidden out of view until you hover over the upper right corner. So pretend it is not there.
Move your cursor to the upper right corner of the youtube embed (not over the button), in safari and firefox this will cause the button to move/animate downwards into view.
However, in IE nothing happens.
I have made sure that the z-index of the menu panel is higher than the z-index of the div that contains the iframe.
Is this something that can be fixed?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Invoking print method from webservice How to call a print method of print document class from webservice. The application must be hosted in IIS.
I have tried implementing but the print method executes when running on development port but upon hosting in IIS , it does not prints.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how can i format numbers in a php array? Im putting values into an array.
example values:
14
15.1
14.12
I want them all to have 2 decimals.
meaning, i want the output of the array to be
14.00
15.10
14.12
How is this easiest achieved?
Is it possible to make the array automatically convert the numbers into 2 decimalplaces?
Or do I need to add the extra decimals at output-time?
A: you can try for example
$number =15.1;
$formated = number_format($number,2);
now $formated will be 15.10
A: You can use number_format() as a map function to array_map()
$array = array(1,2,3,4,5.1);
$formatted_array = array_map(function($num){return number_format($num,2);}, $array);
A: $formatted = sprintf("%.2f", $number);
A: use the number_format function before entering values into array :
number_format($number, 2)
//will change 7 to 7.00
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Want a simple quick way to make ticks of a 3D plot longer I know there are many ways even some good packages available, but I find these methods are mostly too complex for me.
So, what's a simple quick way to make ticks of a 3D plot (actually, a plot generated by RegionPlot3D) longer?
I don't care about code effiency.
Thanks! :)
A: You can control the tick lengths in the Ticks option. E.g. Here they are set to 0.06 in one direction:
ticks = {#, #, {0, 0.06}} & /@ (Range[11] - 6);
RegionPlot3D[x y z < 1, {x, -5, 5}, {y, -5, 5}, {z, -5, 5},
PlotStyle -> Directive[Yellow, Opacity[0.5]], Mesh -> None,
Ticks -> Table[ticks, {3}], AxesEdge -> {{-1, -1}, None, None}]
A: You may use a function for Ticks. This particular function comes from the Ticks documentation, (Click on Generalizations and Extensions.)
ticks[min_, max_] := Table[If[EvenQ[i], {i, i, .06, Red}, {i, i, .02, Blue}],
{i, Ceiling[min], Floor[max], 1}]
Plot3D[Sin[x + y^2], {x, -3, 3}, {y, -2, 2}, Ticks -> ticks]
You could use a variation of it to distinguish major and minor ticks (e.g. Integer values and tenths. This function is also straight out of the documentation (Under Applications).
ticks[min_, max_] :=
Join[Table[{i, Style[i, 12], {.04, 0}}, {i, Ceiling[min],
Floor[max]}],
Table[{j + .5, , {.02, 0}}, {j, Round[min], Round[max - 1], 1}]]
A: Sorry, I couldn't resist:
tick = Import["http://www.salamatvet.com/images/tick-1.jpg"];
Plot[ Sin[x], {x, 0, 10}, Method -> {"AxesInFront" -> False},
Ticks -> {Table[{i, Labeled[i, Image[tick, ImageSize -> 30]]},
{i, 2, 10, 2}]}]
A tick is a tick, is a tick ...
Thanks to Alexey for the AxesInFront suggestion.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Use copy from windows diplaying the status form with delphi, what i can display the form that display when i start a copy?
Thanks very much.
A: You should use the SHFileOperation function.
procedure TForm1.Button1Click(Sender: TObject);
var
shfileop: TSHFileOpStruct;
begin
shfileop.Wnd := Handle;
shfileop.wFunc := FO_COPY;
shfileop.pFrom := PChar('C:\myfile.txt'#0);
shfileop.pTo := PChar('C:\Copy of myfile.txt'#0);
shfileop.fFlags := 0;
SHFileOperation(shfileop);
end;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sort views in a NSMutableArray I am using a NSMutableArray to get all the subViews of a specific superView, everything works, but the log says:
superView contains (
"<UIView: 0x68795c0; frame = (20 172; 238 115); clipsToBounds = YES; autoresize = W+H; layer = <CALayer: 0x689aad0>>",
"<UIView: 0x6e67d90; frame = (143 295; 115 115); autoresize = W+H; layer = <CALayer: 0x6e67dc0>>",
"<UIView: 0x6e6f1a0; frame = (20 49; 115 115); autoresize = W+H; layer = <CALayer: 0x6e6e830>>",
"<UIView: 0x6e6fac0; frame = (143 49; 115 115); autoresize = W+H; layer = <CALayer: 0x6e6faf0>>"
)
As you can see, it appears that the views are loaded randomly into the array, but it is important for me that they are loaded in order, so it loads the views from top to bottom of the superview. So it should look like this:
superView contains (
"<UIView: 0x6e6f1a0; frame = (20 49; 115 115); autoresize = W+H; layer = <CALayer: 0x6e6e830>>",
"<UIView: 0x6e6fac0; frame = (143 49; 115 115); autoresize = W+H; layer = <CALayer: 0x6e6faf0>>"
"<UIView: 0x68795c0; frame = (20 172; 238 115); clipsToBounds = YES; autoresize = W+H; layer = <CALayer: 0x689aad0>>",
"<UIView: 0x6e67d90; frame = (143 295; 115 115); autoresize = W+H; layer = <CALayer: 0x6e67dc0>>",
)
Can anyone give me suggestions on how to accomplish this?
A: sortedArraySortedUsingFunction
A: NSArray has a variety of sorting methods; they generally involve having an additional function or method that takes one object as an argument and returns a type of NSComparisonResult. From the docs:
A selector that identifies the method to use to compare two elements
at a time. The method should return NSOrderedAscending if the
receiving array is smaller than the argument, NSOrderedDescending if
the receiving array is larger than the argument, and NSOrderedSame if
they are equal.
You specify the actual comparison parameter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to proceed with these types of project? I am going lead a project, where I have Asp.Net webapp with SQL Server 2008 database and a WCF Service with REST to expose the data of the database to clients like winform app, java apps, android apps etc.
I want to use LINQ to Sql in my project. Earlier i have experience over the n layered architecture. Please help. How to take steps?
I have 4 different projects in a single solution. Should I need to divide it parts like WebApp with Sql Server database in a single project, Service and Client in two differents projects, as we might deploy our WCF service in some other server...
**See update
to make it more clear , my project has three main aspects, a web app, service and client app. WebApp will be hosted on someserver. On the same server, i would like to deploy the service. Webapp has nothing to do with the service. It will directly interact with the database. On the other hand, the service has permission for selecting records from the database, not Insert, delete and update. Client app will be scattered to different location. It might be a winapp, wince app ,android app or java app. and it will interact with the service to fetch data only. Thats my plan.**
A: The client and the service should be in different projects if there is a need for distribution. I would generally go with a presentation layer project(web app) and a different project for DAL. But then this segregation depends on the strategic vision of your project. Do you have solid reasons to believe that once you develop this code, there would be no need for extensibility?If that's the case then have your DAL and Webapp in the same project. Else separate it out. Entity framework provides better support for testability and its the roadmap and it integrates well with WCF as compared to Linq to SQL
A: If your asking about how to architect a good n-tier application I would suggest you quickly read http://www.amazon.co.uk/Professional-Enterprise-NET-Wrox-Programmer/dp/0470447613
Really, it all depends on your requirements. I would generally have my WCF project separate from the ASP.NET project so that 'heavy' processing tasks can be passed to the WCF and not degrade the websites performance.
n-tier has been the de-facto design for years, but for smaller projects people are arguing that EF + n-tier etc, is overkill and that micro-frameworks like NancyFx and Simple.Data are more appropriate. It all depends on what you are actually building.
Or are you asking how to get started with Linq?
Mannings "Link in Action" is very good. As are the webcasts on http://shop.tekpub.com/products/linq
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to implement 64-bit integers using a 32-bit compiler? Although there are already a lots of such questions on stack overflow regarding this (almost near to what I want to know). But none of those got the answer that would have solved the case.
My question basically is about following:
Is it possible to implement 64-bit integers using a 32-bit compiler? What is the significance of bit-size of compiler in deciding size of integer? (not considering performance issues)
Somewhat related questions already asked are:
*
*integer size in c depends on what?
*Does the size of an int depend on the compiler and/or processor?
*What does the C++ standard state the size of int, long type to be?
Each of above question had some very good answers with them but in the end, no one of them gave me an exact answer.
A: int64_t is a 64b integer type and is available if you include stdint.h.
uint64_t is the unsigned version and is defined in the same header.
See Are types like uint32, int32, uint64, int64 defined in any stdlib header? for more details.
Is it possible to implement 64-bit integers on a 32-bit machine? (not considering performance issues)
Sure. There's usually no need unless you're on a really restricted instruction set, but it's definitely possible. How to implement big int in C++ explains how to do arbitrary precision integers which is a strictly harder problem to solve.
A: Yes. Even on 32 bit machines the .NET Framework provides System.Int64, many C/C++ compilers provide long long/__int64.
Obviously the operations on such types, on 32 bit machines, are somehow emulated (i.e. generally it takes more than an instruction to add two 64 bit integers). For this reason they are available, but are not used unless necessary (and the default int size defaults to 32 bit).
A: Yes
In C, their type is usually named long or long long.
Or, if your compiler is for C99, you can use the new fixed width types defined when you #include <stdint.h> (or #include <inttypes.h>): int64_t, uint64_t, ...
A: In Java, int is always 32 bit and long is 64 bit, even if on a 8bit machine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Show deafult autocompletion results when MultiAutoCompleteTextView gets foucs In MultiAutoCompleteTextView i am displaying auto completion results from my sqlite database. Means i have set custom adapter for MultiAutoCompleteTextView.
Now I want to autocomplete default results when MultiAutoCompleteTextView gets focus.
eg. if i click on MultiAutoCompleteTextView, it should autocomplete default (starting from any specific letter) results.
How can i do that ?..
A: Extend the MultiAutoCompleteTextView class, and override the onFocusChanged method:
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
if (focused) {
performFiltering(getText(), -1);
}
}
(I did this for a regular AutoCompleteTextView but I assume it will also work for a Multi...)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to format NSDate to NSString? I have an date string which looks like this:
2011-10-01 08:45:34 +0000
How can I format it with NSDate? Thanks :D
A: you can try this method in NSDateFormatter
- (NSDate *)dateFromString:(NSString *)string
an example
dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *en_US = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dateFormatter setLocale:en_US];
[en_US release];
[dateFormatter setDateFormat:@"MM/dd/yyyy h:mm:ss a"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:-60*60*7]];
NSDate *date = [dateFormatter dateFromString:dateString];
[dateFormatter release];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do we style custom login buttons without fb:login-button after fbml is deprecated? Can you help me figure this out. Are my assumptions correct here :
*
*fb:login-button will be deprecated in 2012 along with all fb: tags.
*The alternative to fb:login-button is use a html button tag (or similar) and some javascript to handle the click event which calls FB.login or FB.logout eg; http://www.fbrell.com/auth/login-button
3) I have to manually style the above Facebook login button/div because there is no "free" way of styling it to look like the soon-to-be-depracated fb:login-button does
I'm just starting to get into Facebook integration for my site and have discovered the pain
Thanks
Gareth
A: No, just FBML apps are deprecated. The XFBML tags like the fb:login button that are part of the javascript sdk or social plugins aren't deprecated. So you do not need to worry about changing them. If they were deprecated, the documentation page would reflect that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: setting properties and delegates -- when to use self? I'm working through the NSXMLParser sample code and I have a couple of questions about how delegates and properties are set, particularly in the AppDelegate.
In the interface, the AppDelegate is declared to follow the NSXMLParserDelegate protocol, but it doesn't seem to implement any of the protocol methods or to set itself as the delegate at any point. These seem to be in the ParseOperation class. Is this just a typo?
@interface SeismicXMLAppDelegate : NSObject <UIApplicationDelegate, NSXMLParserDelegate> {
UIWindow *window;
UINavigationController *navigationController;
RootViewController *rootViewController;
@private
// for downloading the xml data
NSURLConnection *earthquakeFeedConnection;
NSMutableData *earthquakeData;
NSOperationQueue *parseQueue;
}
The interface also declares some private properties. These are defined again in an interface extension in the .m file.
@interface SeismicXMLAppDelegate ()
@property (nonatomic, retain) NSURLConnection *earthquakeFeedConnection;
@property (nonatomic, retain) NSMutableData *earthquakeData; // the data returned from the NSURLConnection
@property (nonatomic, retain) NSOperationQueue *parseQueue; // the queue that manages our NSOperation for parsing earthquake data
- (void)addEarthquakesToList:(NSArray *)earthquakes;
- (void)handleError:(NSError *)error;
@end
OK, I think I understand that this means other classes can't access these properties, and that seems like a really good thing in this case. Here's the mystery - In the implementation of -applicationDidFinishLaunching: the two properties are defined using different notations.
self.earthquakeFeedConnection =
[[[NSURLConnection alloc] initWithRequest:earthquakeURLRequest delegate:self] autorelease];
vs
parseQueue = [NSOperationQueue new];
Why is one assigned using self.propertyName = and the other with propertyName = ? I know that both parseQueue and earthquakeFeedConnection end up with retain counts of 1, with the difference that earthquakeFeedConnection is part of the autorelease pool and will be released automatically whereas we'll have to release parseQueue later because of the use of +new and not calling autorelease.
The memory considerations don't explain the use of self. Is there another difference?
A: alloc and new return objects which are retained once. init have no effect on memory-management and autorelease will release that object later once.
if you write self.myProperty = ... then the synthesized setter is called which behaves like you defined in the according property nonatomic, retain. The nonatomic means that the getter and setter are not threadsafe (but fast). retain means in this case that the setter will release the old object and will retain the new object. if you wrote assign instead of retain the setter would just assign the pointer and wouldn't call release or retain on the affected objects.
The goal in your example is to create two objects which are retained once.
Example1:
self.earthquakeFeedConnection = [[[NSURLConnection alloc] initWithRequest:earthquakeURLRequest delegate:self] autorelease];
*
*after alloc: retainCount: 1
*after autorelease: retainCount: 1-1 (minus one means: released later)
*after calling the setter: retainCount: 2-1
Exmaple 2:
parseQueue = [NSOperationQueue new];
*
*after new: retainCount: 1
So in the end both cases result in the same. you could also write
earthquakeFeedConnection = [[NSURLConnection alloc] initWithRequest:earthquakeURLRequest delegate:self];
The setter-solution looks more complicated but there are some side-effects. If you notice later that you need special behaviour inside either the getter or setter (for instance: triggering some other methods or do some value-checking: NSString which only should contains eMail-Addresses) then you only have to overwrite the getter or setter. If you dont use self.myProp = ... then you have to search for usage and have to change that code-snippet as well.
The delegate-stuff: yes, you are right: normally you have to (or should) list alle implemented protocols in the interface-definition but the NSURLConnectionDelegate is an exception. I dont know why (I dont find the implementation-point in NSObject-class-reference) but every NSObject implements that delegate already. So as a result you dont have to mention that your class is implementing that delegate.
A: Summary:
Thomas's answer does confirm the delegate protocol mystery. The declaration is, as I suggested originally, just a typo. So I'm not missing the boat, which is nice, so I'm accepting his answer.
The answer about the use of -alloc, -init vs +new is less satisfying. The phrase 'just a coding style' seems to dismiss something important, so I've come up with my own analysis. Basically, I think this is a defensive element of the authors style: this approach makes no assumptions about the initialized object.
verbose=N
Combining +new and a custom setter could lead to trouble. If the custom implementation of the setter assumes that the initialized object has a particular state (such as something that might have been done in a custom -init method), there could be bad effects. Avoid any conflicts by making no assumptions about the object. Make sure that a custom setter is not called unless the customization has clearly been done. Thus, safely call [self setPropCustom] = [[PropClass alloc] initWithCustomization], and avoid calling [self setPropCustom] on [[PropClass alloc] init]. Since -init is often overriden, get a bare minimum object by +new instead of -alloc,-init.
vervose=Y
I'm a noobie of a sort. I have background in getting things done, but very little in doing it elegantly or in a CS fashion. So I'm interested in coding styles. Why might the author 'love' to do it that a particular way? It she's experienced, I really doubt it's just a 'mood'.
There's a lot of discussion of coding style at Wil Shipley's blog, particularly the 'Pimp my code' series, which is a sort of gem. It includes a rather detailed discussion of +new vs -alloc,-init. I'll quote one of the comments:
corwin said...
[edited] Code is a craft. It's inexact. Writing code that follows everyone
else's style is like writing poetry in the same meter and pattern as
everyone else. Think a little, realize that every little quirk your
code imparts is a little part of you, and get over making it
"perfect". Read others' code like you would poetry- take inspiration
from it, learn from it, sometimes imitate it, but never take it as a
personal affront.
At the end of the day, you should ask yourself: Did the code I write
make art? Will it make a user's life easier? Did it make me feel good? If you can answer those questions yes, you're OK. All else is void.
August 25, 2005 12:08 AM
So, in this vein, what can I learn from the coding style in NSXMLParser? What inspiration can I get out of it? Well…
The point of having a coding style is to give yourself extra information in the way that you choose to do something, and to use consistent patterns to avoid known pitfalls. There are generally multiple ways of achieving a desired result. Allocating memory is something at programmers do continuously. It gets called so much that it helps to be consistent in how you go about it. Gee, if I was consistent about where I put the baby's shoes, I wouldn't have to hunt around for 10 minutes every morning. Consistency is a shortcut, and a coding style gives your code consistency.
Poetry is about multiple meanings. It's about not just invoking a word, but invoking an emotion or a sensation at the same time.
… so juicy and so sweet.
So developing a coding style is developing a concise and consistent means of communicating with another programmer or with your future self. You shouldn't have to ask 'what was I doing here'. It should be part of your coding style.
So back to NSXMLParser. According to Thomas, this author 'loves to use new without calling the setter except he wants to use an initWith...-method: then he also uses the setter.' (thomas, Oct 4). What I want to know is why did the author choose this convention as part of his coding style? What is the sense of it?
Of course, I wouldn't be writing this except that I think I understand.
When you write a class, you can override -init, but you don't override +new. When you write a class, you may override the synthesized setters and getters -setProperty and -property.
By consistently assigning the property directly when using +new, the author uses syntax to emphasize that this is a 'nude' object. Empty. The barest minimum. Then he makes sure to assign it without calling the setter. This seems like a good idea. After all, combining +new and a custom setter could lead to trouble if the custom implementation of the setter assumed anything about the state of the initialized object (such as something that might have been done in the custom -init method).Better to avoid the problem. Ah. There it is. The answer I was looking for.
So what can I, in my ragged noobie state take from this 'coding style'. Hmmm…
that one will have to stew for a while. Take number 1:
*
*Calling +new and avoiding any custom setters is defensive coding.
*Customizing -init and the default setters should be done with
care.
*If a custom -init method is desired, it might be better to rename
it -initWithDefaults or something. On the other hand, if you
consistently use +new with assignment without calling self, then you
can probably get away with more customization, but you will have to
be consistent.
I am old enough to know for a fact that I am not consistent. The shoe hunt occurs at least once a week, despite some effort on my part. So I need a coding style that is defensive. To this end, I should do both: 1) develop a love of +new with direct assignment when a bare object is desired and 2) try to avoid overriding the default implementations of init and the synthesized setters and getters.
As Thomas says:
'there are some side-effects. If you notice later that you need
special behaviour inside either the getter or setter (for instance:
triggering some other methods or do some value-checking: NSString
which only should contains eMail-Addresses) then you only have to
overwrite the getter or setter. If you dont use self.myProp = ... then
you have to search for usage and have to change that code-snippet as
well.'
Fair enough. If I avoid customizing the setters and getters, I end up having to make sure that my extra behavior occurs somewhere else. But, actually, I already tend to do that by implementing things like
-changeLocationTo:(CLLocation *)aPlace inTimeZone:(NSTimeZone *)timeZone'.
The checking goes in there and it's pretty obvious what it does from the naming, and it's existence reminds me that when I change aPlace, I also want to make sure I check its timeZone. I call the default self.setTimeZone and self.setAPlace from there, and do any cleanup.
The beginnings of a style. But it probably has some downsides...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7619994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MySQL silent install (using NSIS) not working properly I am trying to make a custom installer that silently installs MySQL but I am encountering the same problem for days. After installing the MySQL server, the initialization fails thus, when I try to type the password it closes instantly(meaning that the password was either wrongly set or even worse, wasn`t set at all).
Here is the code for the installer:
!define PRODUCT_NAME "Soft1"
!define PRODUCT_VERSION "1.0"
!define PRODUCT_PUBLISHER "Zaco"
SetCompressor lzma
!include "MUI2.nsh"
!define MUI_ABORTWARNINGS
!define MUI_ICON "${NSISDIR}\Contrib\Graphics\Icons\modern-install.ico"
!define MUI_WELCOMEPAGE_TEXT "Welcome txt"
!insertmacro MUI_PAGE_WELCOME
!insertmacro MUI_PAGE_LICENSE "${NSISDIR}\Lic.txt"
!insertmacro MUI_PAGE_COMPONENTS
!insertmacro MUI_PAGE_INSTFILES
!insertmacro MUI_PAGE_FINISH
!insertmacro MUI_LANGUAGE "English"
Name "${PRODUCT_NAME} ${PRODUCT_VERSION}"
OutFile "Soft1.exe"
InstallDir "$PROGRAMFILES\Soft1"
ShowInstDetails show
Section -Settings
SetOutPath "$INSTDIR"
SetOverwrite ifnewer
SectionEnd
Section "MySQL" SEC_01
File mysql.msi
ExecWait 'msiexec /i "$INSTDIR\mysql.msi" /quiet'
SetOutPath "$PROGRAMFILES\MySQL\MySQL Server 5.1"
File my.ini
File mysql-init.txt
ExecWait '"$PROGRAMFILES\MySQL\MySQL Server 5.1\bin\mysqld" --defaults-file = "$PROGRAMFILES\MySQL\MySQL Server 5.1\my.ini" '
ExecWait '"$PROGRAMFILES\MySQL\MySQL Server 5.1\bin\mysqld" --init-file = "$PROGRAMFILES\MySQL\MySQL Server 5.1\mysql-init.txt" '
ExecWait "Net Start MySQL"
SectionEnd
The content of the my.ini file is copied from the my.ini file created after manually installing and configuring MySQL Server using the MySQL Server Instance Configuration Wizard. The mysql-init.txt contains the following code:
CREATE USER root IDENTIFIED BY PASSWORD 'New_Password';
GRANT ALL PRIVILEGES ON * . * TO 'root'@ 'localhost' IDENTIFIED BY 'New_Password' WITH GRANT OPTION ;
I also tried using this code for the mysql-init.txt but I get the same result:
UPDATE mysql.user SET Password=PASSWORD(’New_Password’)
WHERE User=’root’;
FLUSH PRIVILEGES;
Furthermore, if try to configure the Server using the MySQL Server Instance Configuration Wizard, it let me choose those options as if the initialization commands from the installer had no effect at all on the Server.
Any suggestions on how I could solve this problem are welcome.
Thanks in advance for your concern!
A: I find that when calling a command line app that requires parameters that contain quotes, it is best to call cmd.exe with the /S parameter and pass the command line itself as parameters. So using your example you would use this:
ExpandEnvStrings $ComSpec %COMSPEC%
ExecWait '"$ComSpec" /S /C ""$PROGRAMFILES\MySQL\MySQL Server 5.1\bin\mysqld" --defaults-file = "$PROGRAMFILES\MySQL\MySQL Server 5.1\my.ini""'
ExecWait '"$ComSpec" /S /C ""$PROGRAMFILES\MySQL\MySQL Server 5.1\bin\mysqld" --init-file = "$PROGRAMFILES\MySQL\MySQL Server 5.1\mysql-init.txt""'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you tell pyximport to use the cython --cplus option? pyximport is super handy but I can't figure out how to get it to engage the C++ language options for Cython. From the command line you'd run cython --cplus foo.pyx. How do you achieve the equivalent with pyximport? Thanks!
A: Here's a hack.
The following code monkey-patches the get_distutils_extension function in pyximport so that the Extension objects it creates all have their language attribute set to c++.
import pyximport
from pyximport import install
old_get_distutils_extension = pyximport.pyximport.get_distutils_extension
def new_get_distutils_extension(modname, pyxfilename, language_level=None):
extension_mod, setup_args = old_get_distutils_extension(modname, pyxfilename, language_level)
extension_mod.language='c++'
return extension_mod,setup_args
pyximport.pyximport.get_distutils_extension = new_get_distutils_extension
Put the above code in pyximportcpp.py. Then, instead of using import pyximport; pyximport.install(), use import pyximportcpp; pyximportcpp.install().
A: A more lightweight/less intrusive solution would be to use setup_args/script_args, which pyximport would pass to distutils used under the hood:
script_args = ["--cython-cplus"]
setup_args = {
"script_args": script_args,
}
pyximport.install(setup_args=setup_args, language_level=3)
Other options for python setup.py build_ext can be passed in similar maner, e.g. script_args = ["--cython-cplus", "--force"].
The corresponding part of the documentation mentions the usage of setup_args, but the exact meaning is probably clearest from the code itself (here is a good starting point).
A: You can have pyximport recognize the header comment # distutils : language = c++ by having pyximport make extensions using the cythonize command. To do so, you can create a new file filename.pyxbld next to your filename.pyx:
# filename.pyxbld
from Cython.Build import cythonize
def make_ext(modname, pyxfilename):
return cythonize(pyxfilename, language_level = 3, annotate = True)[0]
and now you can use the distutils header comments:
# filename.pyx
# distutils : language = c++
Pyximport will use the make_ext function from your .pyxbld file to build the extension. And cythonize will recognize the distutils header comments.
A: One way to make Cython create C++ files is to use a pyxbld file. For example, create foo.pyxbld containing the following:
def make_ext(modname, pyxfilename):
from distutils.extension import Extension
return Extension(name=modname,
sources=[pyxfilename],
language='c++')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Need to make my code faster. Storing results of repeating statements in array of Boolean My project deals with historical and real time data analysis. Contains several complex algorithms (over 800) at its last stage. Overall the analysis stages are roughly as follows:
*
*Basic formulas calculation->results storage
*Second stage formulas using above formulas->results storage
*Third stage formulas which decide upon desired action.
These third stage formulas are large blocks of complex conditionals. These complex conditionals though, use a finite number of simpler statements. And as a result these simpler statements get repeated a lot of times among the complex conditionals. Let me give you a greatly simplified example.
if ((var1[0]<var2[0]*0.5)and(var3[0]=1))or(var15[1]<>var15[0]))
....lots of similar statements....
then take action.
Now, Statements like
"(var3[0]=1)" or "(var15[1]<>var15[0])"
get used over and over again in other if blocks. My idea is to parse all these unique simple statements and automatically create some code that calculates their result (true/false) and stores them in an array of Boolean, once before Third stage commences. Like so:
arr[12]:=var1[0]<var2[0]*0.5;
arr[13]:=var3[0]=1;
...
arr[128]:=var15[1]<>var15[0];
Then (again by parsing my code before compiling) substitute the simpler statements with their corresponding array elements.
So, instead of
if ((var1[0]<var2[0]*0.5)and(var3[0]=1))or(var15[1]<>var15[0]))
it would look like
if ((arr[12])and(arr[13]))or(arr[128])
Would these changes in my code speed up my execution(calculation) time? Or the compiler already does something similar and I will just be wasting my time? Keep in mind that these simple statements get repeated tens or hundreds of times during each calculation cycle. And there is a minimum of 300,000 cycles to be calculated before real time data kick in. So, every little helps. In essence I am asking if a comparison between variables is slower than the retrieval of a Boolean array element's value;
UPDATE
Since some people asked for some real code, here is one part of real code. 98% of code is variables (everything with [0] is a variable allowing access to previous variable values). 2% is functions. Variables are calculated in previous stage. Almost all variables are integers. There are over 800 similar blocks overall. Minimum 300,000 cycles of calculation. Average time is about 45 seconds. For reasons I don't need to explain here, I should make it 2x faster. Code could be in different form if the people writing the algorithms were programmers. But they aren't. They can handle up to some basic stuff like conditional blocks. This is something that can't be changed.
I noticed some people coming here with intend to express irony. Please stay away. I need not your help. People who are willing to offer a constructive opinion are more than welcome to do so. In fact I thank them in advance for just making the effort to read such a long post. I am sorry for the bad code formatting, It was a failed effort to post it as code here.
if ( ZEChT01Pc[0] < ZEChT02Pc[0])
and( ZEChP01Pc[0] < ZEChP02Pc[0])
and( ZEChT01Bn[0] > ZEChP01Bn[0])
and( BncUp_TL_P_1_2[0] > ZEChT01Bn[0])
and( higSncZEChT01[0] < HZigCh30[0])
and( ((ZEChT01Pc[0] < LZigCh30[0]) )
or
( (ZEChT01Pc[0] < LZigCh3002[0] ) and( LZigCh30[0] < LZigCh3002[0] ) and( ZEChT01Pc[0] <= Bnc_Up_HZigCh_Pr[0]) )
or
( (ZEChT01Pc[0] < LZigCh3002[0] ) and( LZigCh30[0] < LZigCh3002[0] ) and( ZEChT01Pc[0] > Bnc_Up_HZigCh_Pr[0] ) and( ZEChP02Pc[0] < TFZ11EndPc[0])) )
and( ((TL_Pks_1_2.tl_getvalue(0) < LZigCh30[0] + ((HZigCh30[0] - LZigCh30[0] )*0.80)) )
or
( (ZEChT01Pc[0] < ULX2dly[0] ) and( C[0] > DLX2dly[0])) )
and (( (ZECoP01Bn[0] > ZEChP01Bn[0]) and (ZECoP01Bn[0] < ZEChT01Bn[0])
and (( (ZECoP01Pc[0] <= ZECoP02Pc[0]) and (C[0] > TL_ECo_Trs_1_2.tl_getvalue(0) )) or ( (ZECoP01Pc[0] > ZECoP02Pc[0]) )) )
or
( (ZECoP01Bn[0] = ZEChP01Bn[0]) and (ZECoP02Bn[0] < ZEChT02Bn[0]) ))
and (( (C[0] > ULX30[0]) and (C[1] <= ULX30[0]) and (ULX30[0] > TL_Pks_1_2.tl_getValue(0))
and (( (BrUpULX30[1] < ZEchT01Bn[0]) ) or ( (chgZigLCh[0] > BrUpULX30[1]) )) )
or
( (C[0] > TL_Pks_1_2.tl_getvalue(0)) and (C[1] <= TL_Pks_1_2.tl_getvalue(0)) and ( TL_Pks_1_2.tl_getValue(0) > ULX30[0]) and (BncUp_TL_P_1_2[1] < ZEchT01Bn[0]) ))
and( ((uniBrUpULX3002_bn[0] > ZEChT01Bn[0] ) and( uniBrUpULX30[0] > TL_Pks_1_2.tl_getvalue(0) ) and( uniBrUpULX3002[0] < TL_Pks_1_2.tl_getvalue(0)) )= false)
and( ((uniBrUpULX3002_bn[0] > ZEChT01Bn[0] ) and( uniBrUpULX30[0] > TL_Pks_1_2.tl_getvalue(0) ) and( uniBrUpULX3002[0] > TL_Pks_1_2.tl_getvalue(0)) )= false)
and( NoLong[0] = 0)
and( ((TL_Pks_1_2.tl_getvalue(0) < LZigCh30[0] ) and( chgZigLCh[0] < ZEChT01Bn[0] ) and( ULX30[0] > LZigCh30[0]) )= false)
and( ((((C[0] < DLXdly[0] ) and( HZigCh30[0] < DLXdly[0] - Tk(0.0050)) = false)))
or
( (ZEChT01Bn[0] = TFZ10EndBnum[0] ) and( ZEChT01Pc[0] < TFZ20EndPc[0] ) and( higSncZEChT01[0] > TFZ40EndPc[0])) )
and( ((ZEChP01Pc[0] > DLXdly[0] ) and( ZEChT01Pc[0] < DLXdly[0] ) and( HZigCh30[0] < DLXdly[0] )) = false)
and( ((higSncZEChT01[0] > HZigCh30[0] -Tk(0.0010) ) and( Bnc_Dn_HZigCh[0] > higbarSncZEChT01[0]) )= false)
and( ((TFZ10EndBnum[0] > TFZ11EndBnum[0] ) and( TFZ10Type[0]= 5 ) and( TFZ10Extension[0] = 0 ) and( ULX30[0] < LZigCh30[0]) )= false)
and( ((Bnc_Dn_LZigCh[0] > ZEChT01Bn[0] ) and( C[0] < LZigCh30[0]) )= false)
and( ((ZEChP01Pc[0] > DLXdly[0] ) and( ZEChT01Pc[0] < DLXdly[0] ) and( C[0] < DLXdly[0] ) and( First[0] = -1) )= false)
and( ((LZigCh3002[0] > DLXdly[0] ) and( LZigCh30[0] < DLXdly[0] ) and( C[0] < DLXdly[0]) and( HZigCh3002[0] > DLXdly[0] ) and( HZigCh30[0] < DLXdly[0] )) = false)
and( ((LZigCh3003[0] > DLXdly[0] ) and( LZigCh3002[0] < DLXdly[0] ) and( C[0] < DLXdly[0])
and( HZigCh3002[0] > DLXdly[0] ) and( HZigCh30[0] < DLXdly[0] ) and( LZigCh30[0] < DLXdly[0] ) and( currentbar - chgZigLCh[0] <= 3 )) = false)
and( ((((TFZ10EndBnum[0] > TFZ11EndBnum[0] ) and( C[0] > higSncShFrm[0] - ((higSncShFrm[0] - TFZ10EndPc[0])*0.5) ) and( higBarSncShFrm[0] <= ZEChP02Bn[0]) = false)))
or
( (ZEChT01Pc[0] < DLXdly[0] ) and( C[0] > DLXdly[0])) )
and( ((C[0] <= LZigCh30[0] ) and( H[0] > LZigCh30[0]) = false))
and( ((ZEChT01Pc[0] < ULXdly[0] ) and( ZEChT02Pc[0] < ULXdly[0] ) and( ZEChP01Pc[0] > ULXdly[0] )
and( ZEChP02Pc[0] > ULXdly[0] ) and( ZEChT01Pc[0] < ZEChT02Pc[0]) and (BncUpDLXdly[0] < ZEchT01Bn[0]) )= false)
and( ((((TFZ11EndBnum[0] > TFZ10EndBnum[0] ) and( ZEChT01Pc[0] > TFZ11EndPc[0] - ((TFZ11EndPc[0] - TFZ10EndPc[0])*0.382)) = false)))
or
( (C[0] > ULXdly[0])) )
and( ((((TFZ10EndBnum[0] > TFZ11EndBnum[0] ) and( TFZ20EndBnum[0] < TFZ11EndBnum[0] ) and( ZEChT01Pc[0] > TFZ11EndPc[0] - ((TFZ11EndPc[0] - TFZ20EndPc[0])*0.382)) )= false))
or
( (C[0] > ULXdly[0])) )
and( ((((TFZ20EndBnum[0] > TFZ11EndBnum[0] ) and( TFZ30EndBnum[0] < TFZ11EndBnum[0] ) and( ZEChT01Pc[0] > TFZ11EndPc[0] - ((TFZ11EndPc[0] - TFZ30EndPc[0])*0.382)) )= false))
or
( (C[0] > ULXdly[0])))
and( ((((TFZ30EndBnum[0] > TFZ11EndBnum[0] ) and( TFZ40EndBnum[0] < TFZ11EndBnum[0] ) and( ZEChT01Pc[0] > TFZ11EndPc[0] - ((TFZ11EndPc[0] - TFZ40EndPc[0])*0.382)) )= false))
or
( (C[0] > ULXdly[0])))
and( ((ZEChP01Pc[0] > ZEChP03Pc[0] ) and( ZEChP01Pc[0] > ZEChP04Pc[0] ) and( C[0] < DLXdly[0]) = false) )
and (( (( (LZigCh30[0] < DLXdly[0] ) and( LZigCh3002[0] > DLXdly[0] ) and( ZEChP01Pc[0] < DLXdly[0] ) and( C[0] < DLXdly[0]) ) = false))
or
( (ZEchT01Pc[0] = TFZ10EndPc[0]) or (ZEchT02Pc[0] = TFZ20EndPc[0]) or (ZEchT03Pc[0] = TFZ30EndPc[0]) ))
and( NoLong2[0] = 0 )
and( ((ZEChP02Pc[0] > ULX2dly[0] ) and( ZEChP01Pc[0] < ULXdly[0] ) and( C[0] < ULX2dly[0] ) and( BrDnDLXdly[0] < BrUpULXdly[0])
and( Min(ZEChT01Pc[0],ZEChT02Pc[0]) > ULXdly[0] - ((ULXdly[0] - DLXdly[0]) * 0.618)) )= false)
and( ((BrDnDLXdly[0] < BrUpULXdly[0] ) and( Min(ZEChT01Pc[0],ZEChT02Pc[0]) > ULXdly[0] - ((ULXdly[0] - DLXdly[0]) * 0.4))
and( TFZ10EndBnum[0] > TFZ11EndBnum[0] ) and( C[0] < ULX2dly[0] ) and( ULXdly[0] > ULX2dly[0] ) )= false)
and( ((BrDnDLXdly[0] < BrUpULXdly[0] ) and( TFZ10EndPc[0] > ULXdly[0] - ((ULXdly[0] - DLXdly[0]) * 0.4))
and( TFZ10EndBnum[0] < TFZ11EndBnum[0] ) and( C[0] < ULX2dly[0] ) and( ULXdly[0] > ULX2dly[0] ) )= false)
and( ((ZEChP02Pc[0] > ULX2dly[0] ) and( ZEChP01Pc[0] < ULXdly[0] ) and( C[0] < ULX2dly[0] ) and( BrDnDLXdly[0] < BrUpULXdly[0])
and( C[0] > LZigCh30[0] + ((HZigCh30[0] - LZigCh30[0]) * 0.768) ) and( C[0] < ULX2dly[0]) )= false)
and( ((LZigCh30[0] < DLXdly[0] ) and( DLXdly[0] < HZigCh30[0] ) and( C[0] > LZigCh30[0] + ((DLXdly[0] - LZigCh30[0])*0.618))
and( DLXdly[0] - C[0] < Tk(0.0040) ) and( C[0] < DLXdly[0] ) )= false)
and( ((((ZEChT01Bn[0] <> TFZ10EndBnum[0] ) and( ZEChT01Pc[0] >= LZigCh30[0])) = false))
or
( (ZEChT01Pc[0] < LZigCh30[0] ) and( C[0] > LZigCh30[0] ) and( LZigCh30[0] > ULXdly[0]))
or
( (LZigCh30[0] < LZigCh3002[0] ) and( chgZigLCh[0] > ZEChT01Bn[0] ) and( ZEChP01Pc[0] < LZigCh3002[0] ) and( C[0] > ZEChT02Pc[0] ) )
or
( (ZEChT01Pc[0] <= DLXdly[0] ) and( C[0] > DLXdly[0])))
and( ((C[0] < TFZ20EndPc[0] ) and( C[0] < LZigCh3002[0] ) and( TFZ20Type[0] > 3 ) and( ((TFZ20EndBnum[0] = ZEChT02Bn[0]) )or( (TFZ20EndBnum[0] = ZEChT03Bn[0]))) )= false)
and( ((((ZEChT01Bn[0] <> TFZ10EndBnum[0] ) and( ZEChT01Pc[0] < LZigCh30[0] ) and( LZigCh30[0] > ULXdly[0]) )= false))
or
( (C[0] < LZigCh30[0] + ((HZigCh30[0] - LZigCh30[0] )*0.618) ) and( HZigCh30[0] - C[0] >= Tk(0.0040)) ))
and( ((LZigCh30[0] < DLXdly[0] ) and( LZigCh3002[0] > DLXdly[0] ) and( ZEChP02Pc[0] < DLXdly[0] + Tk(0.0050) )
and( ZEChP02Pc[0] < LZigCh3002[0] ) and( C[0] < LZigCh3002[0] ) = false))
and ( (( (HZigCh30[0] < DLXdly[0]) and (HZigCh3002[0] > DLXdly[0]) and (ZEchT01Bn[0] = TFZ10EndBnum[0])
and (TFZ10Type[0] = 5 ) and (TFZ10Extension[0] = 0) and (DLXdly[0] < DLX2dly[0]) ) = false) )
and (( (( (chgULXdly[0] > ZEchP01Bn[0]) and (ULXdly[0] > ULX2dly[0]) and (C[0] < ULXdly[0]) and (ZEchT01Pc[0] > ULX2dly[0]) )=false))
or
( (TFZ10EndBnum[0] = ZEchT01Bn[0]) and (TFZ10Type[0] > 3) ))
and (( (( (chgULXdly[0] > ZEchP01Bn[0]) and (ULXdly[0] > ULX2dly[0]) and (C[0] < ULXdly[0]) and (C[0] < ULX2dly[0]))= false))
or
( ( ZechT01Pc[0] < ULXdly[0] - ((ULXdly[0] - DLXdly[0])*0.75)) and (C[0] > LZigCh30[0]) and (DLX30[0] > LZigCh30[0]) ))
and (( (( (chgULXdly[0] > ZEchP01Bn[0]) and (ULXdly[0] < ULX2dly[0]) and (C[0] < ULXdly[0]) ) = false))
or
( ( ZechT01Pc[0] < ULXdly[0] - ((ULXdly[0] - DLXdly[0])*0.75)) and (C[0] > LZigCh30[0]) and (DLX30[0] > LZigCh30[0]) ))
and (( (TFZ11EndBnum[0] = ZEchP02Bn[0]) and (TFZ11Type[0] > 3) and (min(ZEchT01Pc[0],ZechT02Pc[0]) = TFZ10EndPc[0]) and (C[0] < ULXdly[0])
and (TFZ10Type[0] = 3) and (TFZ10Extension[0] = 2) and (TFZ10EndPc[0] > ULXdly[0] - ((ULXdly[0] - DLXdly[0])*0.5)) ) = false)
and (( (TFZ11EndBnum[0] = ZEchP02Bn[0]) and (TFZ11Type[0] > 3) and (min(ZEchT01Pc[0],ZechT02Pc[0]) = TFZ10EndPc[0]) and (C[0] < ULXdly[0])
and (( (TFZ10Type[0] = 3) and (TFZ10Extension[0] = 2) )= false) and (TFZ10EndPc[0] > ULXdly[0] - ((ULXdly[0] - DLXdly[0])*0.8)) ) = false)
and (( (( (TFZ11EndBnum[0] = ZEchP02Bn[0]) and (TFZ11Type[0] > 3) and (min(ZEchT01Pc[0],ZechT02Pc[0]) <> TFZ10EndPc[0])) = false))
or
( (min(ZEchT01Pc[0],ZechT02Pc[0]) < ULXdly[0] - ((ULXdly[0] - DLXdly[0])*0.8)) )
or
( (Bnc_Up_LZigCh[0] > ZEchT01Bn[0]) and (ZEchT01Pc[0] > ZechP03Pc[0]) ))
and (( (ZechT01Pc[0] < ZechT02Pc[0]) and (ZechP01Pc[0] < ZechP02Pc[0]) and (ZEchT01Pc[0] > ULXdly[0]) and (C[0] < ZEchT02Pc[0]) and (C[0] > ULXdly[0]) ) = false)
and (( (ZechT01Pc[0] < ZechT02Pc[0]) and (ZechP01Pc[0] < ZechP02Pc[0]) and (ZEchT01Pc[0] > ULXdly[0]) and (ZEchP02Bn[0] = TFZ11EndBnum[0])
and (ZEchT02Bn[0]= TFZ20EndBnum[0]) and (ZEchT01Bn[0]= TFZ10EndBnum[0]) and (TFZ10Type[0] = 3) and (C[0] > ULXdly[0]) )= false)
and (( (ZechT01Pc[0] < ZechT02Pc[0]) and (ZechP01Pc[0] < ZechP02Pc[0]) and (ZEchT01Pc[0] > ULXdly[0]) and (ZEchP03Bn[0] = TFZ11EndBnum[0])
and (ZEchT02Bn[0]= TFZ20EndBnum[0]) and (ZEchT01Bn[0]= TFZ10EndBnum[0]) and (TFZ10Type[0] = 3) and (C[0] > ULXdly[0]) )= false)
and (((( (TFZ10Type[0] = 7) and (TFZ20type[0] = 5) and (TFZ10Extension[0] = 0) and (TFZ20Extension[0] = 0) and (TFZ10EndPc[0] > ULXdly[0] - ((ULXdly[0] - DLXdly[0])*0.5))) = false))
or
( (C[0] > ULXdly[0]) ) or ( (ZechT01Pc[0] < ULX2dly[0] ) and (C[0] > ULX2dly[0]) and (ULX2dly[0] < ULXdly[0]) ))
and (( (max(HZigCh30[0],HZigCh3002[0]) - LZigCh30[0] < Tk(0.0100)) and (C[0] > LZigCh30[0] + ((max(HZigCh30[0],HZigCh3002[0]) - LZigCh30[0])*0.618)) ) = false)
and (( (ZEchP02Pc[0] > ULXdly[0] - ((ULXdly[0] - DLXdly[0])*0.236)) and (ZEchT01Bn[0] <> TFZ10EndBnum[0]) and (BncUpDLXdly[0] < ZEchT01Bn[0])) = false)
and (( (Bnc_Dn_LZigCh[0] > ZEChT01Bn[0] ) and (C[0] < LZigCh30[0]) ) = false)
and (( (TFZ41EndBnum[0] > TFZ10EndBnum[0]) and (C[0] < ULXdly[0]) and (BncUpDLXdly[0] < ZEchT01Bn[0]) ) = false)
and ( GenL01[0] = false)
and ( GenL02[0] = false)
and ( GenL03[0] = false)
and ( GenL04[0] = True)
then
Thank you for reading.
A: Your approach sounds deeply flawed from a software development perspective. Code like if ((arr[12])and(arr[13]))or(arr[128]) is essentially unreadable and unmaintainable.
You should create properties for the commonly used boolean values and give them meaningful names. If you find it hard to name a property then don't be afraid to write
if height>CriticalHeight then
The performance benefits of caching the results of these tests will be unmeasurable in my experience. Your current approach is sure to result in defects and incorrect code.
A: I would definitely store the results in array as you pointed. Compiler don't know the values you are computing and doesn't store the results in some temporary stack in case of repetitive formulas. That's what are variables for.
So yes, this will speed up your calculation time.
Update
Here is the simple example and dissasembly generated by Delphi 2009. As you can see in dissasembly storing results to the variables takes some CPU cycles though but comparing of booleans from the array takes only 4 instructions. So if you save your results once then your comparisions will take only these 4 instructions instead of 14 each time.
You can see the dissasembly by entering the breakpoint at debug mode and showing the Dissasembly window from View/Debug Windows/CPU Windows/Dissasembly.
Please note that this may differ a bit depending on your Delphi version.
procedure TForm1.Button1Click(Sender: TObject);
var
Result: Boolean;
X: array [0..1] of Double;
Y: array [0..1] of Double;
begin
X[0] := 0.25;
X[1] := 0.75;
Y[0] := 0.25;
Y[1] := 0.75;
if (X[0] < X[1] * 0.5) and (Y[0] < Y[1] * 0.5) then
Result := True;
if Result then
ShowMessage('Result = True'); // to prevent optimization
end;
procedure TForm1.Button2Click(Sender: TObject);
var
Result: Boolean;
X: array [0..1] of Double;
Y: array [0..1] of Double;
Z: array [0..1] of Boolean;
begin
X[0] := 0.25;
X[1] := 0.75;
Y[0] := 0.25;
Y[1] := 0.75;
Z[0] := (X[0] < X[1] * 0.5);
Z[1] := (Y[0] < Y[1] * 0.5);
if Z[0] and Z[1] then
Result := True;
if Result then
ShowMessage('Result = True'); // to prevent optimization
end;
And the dissasembly
At Button1Click you can see the direct comparision
if (X[0] < X[1] * 0.5) and (Y[0] < Y[1] * 0.5) then
-----------------------------------------------------
fld qword ptr [esp+$08]
fmul dword ptr [$0046cdbc]
fcomp qword ptr [esp]
wait
fstsw ax
sahf
jbe $0046cda7
fld qword ptr [esp+$18]
fmul dword ptr [$0046cdbc]
fcomp qword ptr [esp+$10]
wait
fstsw ax
sahf
jbe $0046cda7
Result := True;
-----------------------------------------------------
mov dl,$01
At Button2Click storing of the results takes some time but comaprision itself takes only 4 instructions
Z[0] := (X[0] < X[1] * 0.5);
-----------------------------------------------------
fld qword ptr [esp+$10]
fmul dword ptr [$0046ce78]
fcomp qword ptr [esp+$08]
wait
fstsw ax
sahf
setnbe al
mov [esp],al
Z[1] := (Y[0] < Y[1] * 0.5);
-----------------------------------------------------
fld qword ptr [esp+$20]
fmul dword ptr [$0046ce78]
fcomp qword ptr [esp+$18]
wait
fstsw ax
sahf
setnbe al
mov [esp+$01],al
if Z[0] and Z[1] then
-----------------------------------------------------
cmp byte ptr [esp],$00
jz $0046ce63
cmp byte ptr [esp+$01],$00
jz $0046ce63
Result := True;
-----------------------------------------------------
mov dl,$01
A: In both case you'll have some tests (what you call 'retrieval of Boolean' still recquires a test) but the optimized version will be bit faster. Because you always test a true/false state, the compiler will generate some TEST/SETNZ and much lesser conditional jumps that if you repeat the whole test.
if ((arr[12])and(arr[13]))or(arr[128])
will generate something like ( without memory operations, pseudo asm code):
TEST arr[12] arr[12]
SETNZ bytePtr[esp+4] // local variable
TEST arr[13] arr[13]
SETNZ bytePtr[esp+5]// local variable
TEST arr[128] arr[128]
SETNZ bytePtr[esp+6]// local variable
AND bytePtr[esp+4],bytePtr[esp+5]
OR bytePtr[esp+4],bytePtr[esp+6]
TEST bytePtr[esp+4],bytePtr[esp+4],
JNZ // wrong
...// processing
A: I think your idea of pre-calculating all sub-expressions could work, but that's not the end of it, not by a long shot!
First, you should re-order the expression in such a way that the condition that has the highest (measured) chance of failure is evaluated first. This prevents lots of unnecessary evaluations that will be discarded anyway. (As soon as one of the steps in a big "if X and Y and Z" expression fail, the following steps won't be executed, hence you can take advantage of that fact by evaluating the worst conditions first.)
This could be troublesome to do by hand, so another idea could be, to create a list for all your expressions, and keep count of how often they are evaluated, and how often they fail. (Also, don't forget to reset these counts after some time.) If you (bubble-)sort this list regularly, the evaluations will speed up, as you only evaluate the steps that (currently) have the best chance of failure.
Next, you could try to use on-demand fetching of the variables. Instead of calculating everything up-front, only evaluate the variables that are needed for each part of your expression, by using a callback method. (This may also help for the first stage, as for some expressions, you might only use part of the second stage, which in turn might only need part of the first stage).
Summarizing :
*
*create a record for each expression, containing a callback, a hit-count and a failure count
*put these records in an array, and sort the array once every 100 iterations or so
*evaluate the expressions top-down, simply by invoking the callback and keeping counts
*each callback could be implemented using "dynamic variables" (which can also be kept in a record, using a callback to get the actual value)
PS: instead of resetting all values, I often use a tick-counter : each variable that doesn't meet the current "tick" needs an update. By remembering the 'tick' at which a variable is calculated, you can see if it's already up-to-date or not, and save on clearing the variables in the same time! (Just increase the tick right before each iteration, and you're set)
Good luck!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to run command in the process which is executed with admin rights? I want to create a self signed certificate and install it using through c# program.
I use makecert to make certificate i run it as administrator and i pass command in the ProcessStartInfo.argument but the command doesn't executes what is the problem in the code?
Here is my code:
public void Createasnewadmin()
{
ProcessStartInfo info = new ProcessStartInfo();
Process p = new Process();
info.FileName = Application.StartupPath+@"\makecert.exe";
info.UseShellExecute = true;
info.Verb = "runas"; // Provides Run as Administrator
info.Arguments = "makecert testCert_admin_check.cer";
//i just create sample certificate but it doesn't get created
//The problem is above line the command doesn't get execute
p.StartInfo=info;
p.Start()
}
Please Tell me where is the problem is it not executing as administrator? or the command to be executed is not passed properly?
I think it is executing as admin as i myself click on yes button to execute as admin that is prompted by windows
Why is command not executing? is there any other way?
A: Taking a look at your code, I suspect you are getting an error because your arguments are incorrect.
You line
info.Arguments = "makecert testCert_admin_check.cer";
should be
info.Arguments = "testCert_admin_check.cer";
A: I believe you need to supply credentials to invoke process in admin mode.
UserName = "Administrator", Password = ,
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to validate using Javascript an input tag of type text in an html form that the content of it will be Arabic/Englsih/Number? How to validate using Javascript an input tag of type text in an html form that the content of it will be one of the following:-
*
*Arabic or English Characters ONLY -OR-
*Arabic and English Characters ONLY -OR-
*Arabic characters only -OR-
*English Characters only -OR-
*Number only -OR-
*Arabic Characters and Number only -OR-
*English Characters and Number only -OR-
*Arabic or Number ONLY -OR-
*English Characters or Number ONLY -OR-
*Arabic or English Characters or Number ONLY -OR-
*Phone Number -OR-
*Email -OR-
*English string that starts with specific character like 'A' -OR-
*English string that ends with specific character like 'A' -OR-
*English string that contains specific character like 'A' -OR-
*English string that does not contain specific character like 'A'
Thanks in advance ..
A: First, I need a definition of "English", "Arabic" and "Numbers" characters.
*
*The definition of the English character boundary should at least include a-z, A-Z. Non-word characters (comma, dot, parentheses) should also be included, but since you didn't specify the purpose of your validation, I will limit these to a-z, A-Z.English RegExp: [a-zA-Z]
*I'm not skilled in the Arabian language, so I grab include all characters as definied at this source.RegExp: /[\u0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff]/
*The numbers are defined as \d (in JavaScript: 0-9).RegExp: \d (equals [0-9] in JavaScript)
*The beginning and the end of a string are matched by a ^ and $, using Regular expressions.
Brought together:
*
*Arabic and/or English Characters ONLY -OR-/^[a-zA-Z\u0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff]+$
*Arabic characters only -OR-/^[\u0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff]+$/
*English Characters only -OR-/^[a-zA-Z]+$/
*Number only -OR-/^\d+$/
*Arabic Characters and/or Number only -OR-/^[\du0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff]+$
*English Characters and/or Number only -OR-/^[\dA-Za-z]+$/
*Arabic and/or English Characters and/or Number ONLY -OR-/^[a-zA-Z\d\u0600-\u06ff\ufb50-\ufdff\ufe70-\ufeff]+$/
*Phone Number -OR- Phone numbers are too locale-dependent, construct your own RE
*Email -OR-^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$ source 2 (very basic mail RegExp)
*English string that starts with specific character like 'A' -OR-/^A/
*English string that ends with specific character like 'A' -OR-/A$/
*English string that contains specific character like 'A' -OR-/A/
*English string that does not contain specific character like 'A'^[^A]+$
Of course, the English character set should include more characters than a-zA-Z if you're validating sentences. I recommend to use [\x20-\x7e] instead of [a-zA-Z], so commonly used punctuation characters are also available.
References / See also
*
*MDN: Regular expressions - A guide to use Regular Expressions in JavaScript
*Regulsr Expressions.info - Summary of character boundaries
*UTF8-chartable.de - Browser through all characters
*Unicode.org/charts - An official reference which documents all boundaries in a deeper detail
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Accessing Facebook Cookie data through Java (without php-sdk) I am using the server side flow for FB authentication (as mentioned on http://developers.facebook.com/docs/authentication/) and I am able to get the authentication token successfully. Now I want to implement this - 1) The server side is able to identify the user 2) When the user logs out of FB, my server code is able to detect this when the next request comes from the client.
The only way I could think of doing this was to save the Auth token as a cookie on the users end, associate the token with the userID on the server, and delete the cookie in the OnLogout event handler through the FB JavaScript SDK. I wanted to know if there is a better (recommended?) way for doing this. In particular, I wanted to use the FB cookies (cookies which FB.init creates) to do this. That cookie appears encrypted to me, and I can't find any documentation about decrypting it apart from Where to find the Facebook cookie?. I remember reading about some PHP SDK function which decrypts the cookie (GetUser) but I can't use that since my code is in Java. If possible, I'd want to avoid using 3rd party Facebook Java SDKs. I'd be grateful for any pointers about this.
A: Why do you want to avoid using a Java API that has already done all of this work for you?!
In any case, take a look at any of the existing Java/FB APIs--if you're unable to translate PHP to Java, might as well reinvent the wheel using code that already exists.
http://restfb.com/
If I were going about this I'd take an API that is known to work (like Koala for Rails) and work backwards. Make sure to pick one that implements the mandatory OAuth 2 stuff, though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is non static members inside public static class thread safe? Can you check this function for me. Is it thread safe or not to be used. I am trying to understand how exactly public static classes are working.
This function will be used to get userId of visitor from database by username. So many concurrent call may happen. Also would this be the best performance way and sql injection secure.
ASP.net 4.0 - C# - MSSQL 2008 R2 - IIS 7.5
using System;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data;
public static class csGetUserId
{
public static string srCommandText = "select UserId from tblUsersProfile where userName=@userName";
public static string ReturnUserId (string srUserName)
{
string srUserId = "0";
using (SqlConnection connection = new SqlConnection(DbConnection.srConnectionString))
{
try
{
SqlCommand cmd = new SqlCommand(srCommandText, connection);
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@userName", srUserName);
SqlDataReader dsReader = null;
connection.Open();
dsReader = cmd.ExecuteReader();
if (dsReader.HasRows)
{
while (dsReader.Read())
{
srUserId=dsReader["UserId"].ToString();
}
}
else
{
}
}
catch
{
srUserId="-1";
}
}
return srUserId;
}
}
A: Assuming that the database supports multiple connections and that you change srCommandText to be readonly then this method is thread safe.
Making srCommandText read-only will also make it safe against SQL injections.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Lazylist Layout I created my own Lazylist which originally created by Fedor here(Lazy load of images in ListView). I am trying to make my own custom Layout which looks like the image below. Is there anyway to accomplish this?
A: modify your item.xml like this way
<RelativeLayout android:layout_height="55sp"
android:layout_width="fill_parent" android:padding="5sp" android:layout_marginLeft="6sp"
android:layout_marginRight="6sp" android:layout_marginBottom="3sp"
android:layout_marginTop="3sp">
<ImageView android:layout_alignParentTop="true"
android:layout_alignParentBottom="true" android:layout_marginRight="6dip"
android:id="@+id/image" android:layout_height="50sp"
android:layout_width="50sp" android:src="@drawable/icon"/>
<TextView android:id="@+id/title" android:layout_width="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true" android:ellipsize="marquee"
android:layout_toRightOf="@+id/image" android:maxLines="1"
android:gravity="center_vertical" android:layout_height="wrap_content" android:text="Hello"/>
<TextView android:layout_width="fill_parent"
android:id="@+id/desc"
android:layout_alignParentRight="true" android:layout_alignParentTop="true"
android:layout_above="@+id/title"
android:layout_alignWithParentIfMissing="true" android:gravity="center_vertical"
android:textStyle="bold" android:layout_toRightOf="@+id/image"
android:layout_height="fill_parent" android:textSize="15sp" android:text="Title"/>
</RelativeLayout>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620026",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RCurl, error: connection time out I use the XML and RCurl packages of R to get data from a website.
The script needs to scrap 6,000,000 pages, so I created a loop.
for (page in c(1:6000000)){
my_url = paste('http://webpage.....')
page1 <- getURL(my_url, encoding="UTF-8")
mydata <- htmlParse(page1, asText=TRUE, encoding="UTF-8")
title <- xpathSApply(mydata, '//head/title', xmlValue, simplify = TRUE, encoding="UTF-8")
.....
.....
.....}
However, after a few loops I get the error message:
Error in curlPerform(curl = curl, .opts = opts, .encoding = .encoding)
: connection time out
The problem is that I don't understand how the "time out" works. Sometimes the process ends after 700 pages while other times after 1000, 1200 etc pages. The step is not stable.
When the connection is timed out, I can't access this webpage from my laptop, for 15 minutes.
I thought of using a command to delay the process for 15 minutes every 1000 pages scrapped
if(page==1000) Sys.sleep(901)
, but nothing changed.
Any ideas what is going wrong and how to overcome this?
A: You could make a call in R to a native installation of curl using the command System(). This way, you get access to all the curl options not currently supported by RCurl such as --retry <num>. The option --retry <num> will cause an issued curl query to repeatedly try again at ever greater lengths of time after each failure, i.e. retry 1 second after first failure, 2 seconds after second failure, 4 seconds after third failure, and so on. Other time control options are also available at the cURL site http://curl.haxx.se/docs/manpage.html.
A: I solved it. Just added Sys.sleep(1) to each iteration.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Function to stop a setInterval call leaving the width style static The code below (found here) shows a kind of progress bar that moves very fast towards the right side re-starting non stop. This is done by changing the element's width within a setInterval.
How can I build a function that freezes the progress bar motion when called (stops the width from changing freezing it in the moment the function is called)?
I'm working with prototype/javascript (the jQuery line in the code is a fast way to add a class in order to publish this post, but I'm not using jQuery).
<style>
.thepower {
opacity: 0;
background-color: #191919;
padding: 4px;
position: absolute;
overflow: hidden;
width: 300px;
height: 24px;
top:150px;
left:84px;
-webkit-border-radius: 16px;
border-radius: 16px;
-webkit-box-shadow: inset 0 1px 2px #000, 0 1px 0 #2b2b2b;
box-shadow: inset 0 1px 2px #000, 0 1px 0 #2b2b2b;
}
.visible.thepower {
opacity: 1;
}
.thepower .inner {
background: #999;
display: block;
position: absolute;
overflow: hidden;
max-width: 97.5% !important;
height: 24px;
text-indent: -9999px;
-webkit-border-radius: 12px;
border-radius: 12px;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.3),
inset 0 -1px 3px rgba(0, 0, 0, 0.4),
0 1px 1px #000;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.3),
inset 0 -1px 3px rgba(0, 0, 0, 0.4),
0 1px 1px #000;
}
.green .inner {
background: #7EBD01;
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#7EBD01), to(#568201));
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
// How it works:
/*
var counter = 0 (inside a function, window.onload) - A local variable is defined and initialised at zero.
window.setInterval(function(){ ... }, 50) - An interval is defined, activating the function (first argument) every 50 milliseconds (20x a second, adjust to your own wishes)
(++counter % 101) - Increments the counter by one, modulo 101:
The modulo operator calculates the remainder after division, ie: 0 % 101 = 0, 100 % 101 = 100 and 200 % 101 = 99, 201 % 101 = 100, 202 % 101 = 100
*/
window.onload = function(){
var counter = 0;
window.setInterval(function(){
$(".green").addClass("visible") ;
document.querySelector('.green.thepower.visible .inner').style.width = (++counter % 101) + '%';
}, 10);
}
</script>
<div id="thepower" ad-outlet="thepower">
<div class="green thepower"><div class="inner"></div></div>
</div>
A: You can use clearInterval method to stop executing of the method which was set with setInterval. First save the result of setInterval to some variable:
var interval;
window.onload = function(){
var counter = 0;
interval = window.setInterval(function(){
$(".green").addClass("visible") ;
document.querySelector('.green.thepower.visible .inner').style.width = (++counter % 101) + '%';
}, 10);
}
After that call clearInterval somewhere passing saved value as parameter:
clearInterval(interval);
A: Here's a way to stop and continue from where you left off:
Add this to your HTML:
<button id="toggleProgress">Click</button>
and change your javascript to this:
var counter = 0;
var timer = null;
function progressBar(){
if (timer) {
clearTimeout(timer);
timer = null;
return;
}
timer = window.setInterval(function(){
$(".green").addClass("visible");
document.querySelector('.green.thepower.visible .inner').style.width = (++counter % 101) + '%';
}, 10);
}
window.onload = function() {
progressBar();
$('#toggleProgress').click(function() {
progressBar();
});
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to implement business layer validation to the Linq2Sql classes I am aware of the business layer validation for the model classes in general n-layered architectures model classes, by using validation attributes.
Now, I just i want to know if its applicable to Linq2Sql classes, as if I manually add some attributes to the class or its members, then on next addition or deletion in Dbml file, it will rewrite the designer classes, erasing my changes made.
Please help me...
Any idea , sample code or site references are highly appreciated.
A: You can write a partial class and annotate that
using System.ComponentModel.DataAnnotations;
namespace MvcDA {
[MetadataType(typeof(ProductMD))]
public partial class Product {
public class ProductMD {
[StringLength(50),Required]
public object Name { get; set; }
[StringLength(15)]
public object Color { get; set; }
[Range(0, 9999)]
public object Weight { get; set; }
// public object NoSuchProperty { get; set; }
}
}
}
Validate Model Data Using DataAnnotations Attributes
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Update only first record from duplicate entries in MySQL Problem SOLVED!
Update:
Not quite right what I need, lets do example on simple table with fields ID,NAME,COVER
I have got 100 entries with 100 names, some of the names are duplicated, but I want only update first one from duplicates.
Trying to update all the 1st rows from all the duplicates in database, really hard to do it, any idea how I can make it? Below is the code I am trying to rebuild, but this code replace every 1st one with the last one for all the duplicates.
Schema, how I want it work below
ID NAME COVER
1 Max 1
2 Max 0
3 Andy 1
4 Andy 0
5 Andy 0
UPDATE table t
JOIN (
SELECT MinID, b.Name LatestName
FROM table b
JOIN (
SELECT MIN(ID) MinID, MAX(ID) MaxID
FROM table
GROUP BY tag
HAVING COUNT(*) > 1
) g ON b.ID = g.MaxID
) rs ON t.ID = rs.MinID
SET t.Name = LatestName;
A: It's not clear at all what you want. Perhaps this:
UPDATE table AS t
JOIN
( SELECT MIN(ID) MinID
FROM table
GROUP BY Name
HAVING COUNT(*) > 1
) AS m
ON t.ID = m.MinID
SET t.Cover = 1 ;
For this (and future) question, keep in mind, when you write a question:
1. a description of your problem, as clear as possible --- you have that
2. data you have now (a few rows of the tables) --- ok, nice
3. the code you have tried --- yeah, but better use same names
--- as the data and description above
4. the error you get (if you get an error) --- doesn't apply here
5. the result you want (the rows after the update in your case)
--- so we know what you mean in case we
--- haven't understood from all the rest
A: Use a subquery as selection criterium:
UPDATE table t SET t.Name = LatestName
WHERE ID =
(SELECT ID FROM table WHERE
(
SELECT COUNT(DISTINCT(Name)) FROM table WHERE Name = 'duplicate'
) > 1
LIMIT 1)
A: I did this recently in PostgreSQL. Are you in a position to use a temporary table? If so, for each duplicate set, insert the MIN() primary key into your temp table, and then do your UPDATE using a where clause using the PKs in the temp table.
Edit: following your comment, here is something I did recently.
CREATE TEMPORARY TABLE misc_updates (
temp_oid INTEGER,
job INTEGER,
run CHARACTER VARYING(8),
quantity INTEGER
);
INSERT INTO misc_updates (temp_oid, job, run, quantity)
SELECT
MAX(runjob.oid) temp_oid, runjob.job, runjob.run, SUM(runjob.quantity) sum_quantity
FROM
runjob
INNER JOIN job ON (runjob.job = job.code)
INNER JOIN
(SELECT run, job FROM runjob GROUP BY run, job HAVING COUNT(*) > 1) my_inner
ON (runjob.run = my_inner.run AND runjob.job = my_inner.job)
GROUP BY
runjob.job, runjob.run, job.quantity
;
/* Do updates on one of the duplicated runjob rows */
UPDATE runjob
SET quantity = mu.quantity
FROM
misc_updates mu
WHERE
runjob.oid = mu.temp_oid;
You can swap 'oid' for your primary key (my problem was that the table had no primary key!). Also the critical thing is the where clause in the UPDATE, so only some rows are updated. You'll need to swap out MAX() for MIN(), and of course change the rows to the ones in your use-case. Bear in mind that this is for PostgreSQL, but the approach should be much the same.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Call onchange handler function I have this OnChange function:
$("select[id^=type]").change(function(){/*...*/});
The question is: How can I call this from the following function:
$("#all_db").change(function()
{
/*...*/
$("select[id^=type]").each.trigger("change"); //I have tried this
});
A: $("select[id^='type']").change();
is all you need. I would quote the value you pass to the startsWith selector.
A: You have to declare the function separately. In your example you are saying to JQuery to trigger the function change when it is the time. Nevertheless, such a function doesn't exist. To do it try to declare your function as a separate one. Like this:
function myDesiredFunc(){ /*console.log("Inside it");*/ }
$("#all_db").change(myDesiredFunc);
$("select[id^=type]").change(myDesiredFunc);
Note that I commented console.log because this will only work if you have firebug installed.
I hope it helps.
A: $("select[id^=type]").trigger("change");
should do the trick. Otherwise, that one should:
$("select[id^=type]").each(function(i){
$(this).trigger("change");
});
A: See this :
$("#all_db").change(function()
{
/*...*/
$("select[id^=type]").change();
});
Usually in Jquery , the same name to create a trigger , runs to fire it.
A: $('select').change(); then you can do $('select[id='yourIdHere']').change(); or whatever you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to share an object with the entire project? For example, if I create an UILabel in an class, how can I use it wherever I want to?
I already know how to share between two classes. But I need to call the value of an object in all my classes. Is it possible?
A: Is a singleton what you want? Basically a singleton is just a class that only returns the same instance no matter what. Here's a website that shows you how to do them. http://funwithobjc.tumblr.com/post/3478903440/how-i-do-my-singletons
A: The best way is to write it to the temporary files folder like this:
NSString *pathtmp = [NSTemporaryDirectory() stringByAppendingPathComponent:@"tmpString.txt"];
NSString *stringToWrite = [NSString stringWithFormat:@"%@",Label.text];
[stringToWrite writeToFile:pathtmp atomically:YES encoding:NSStringEncodingConversionExternalRepresentation error:nil];
and to read it:
NSString *pathtmp = [NSTemporaryDirectory() stringByAppendingPathComponent:@"tmpString.txt"];
NSString *stringToWrite = [NSString stringWithContentsOfFile:pathtmp encoding:NSStringEncodingConversionExternalRepresentation error:nil];
A: You asked that "I need to call the value of an object in all my classes. Is it possible?" and mentioned a UILabel.
You should really avoid view layer components poking at other view layer components. It creates coupling which makes it (1) really hard to change - simple changes break large areas of the code in unpredictable ways (see ref to spaggeti code above) and (2) hard to test since there's no layers in the system.
You should look into the principles of MVC. In MVC, you have views, controllers and models. You should push as much down as possible. Multiple views and controllers can operate on the same model that controls the data and business logic.
The model is the data and the operations you perform on the data. Make all you different views work off that data instead of poking at each other.
I would suggest create a set of model classes and to allow common access to that model. A common pattern is for that class to be a singleton.
So, the multiple views & controllers would do.
MyModel *model = [MyModel sharedInstance];
Then multiple controllers can operate on it.
Here's a good article on the topic: http://cocoawithlove.com/2008/11/singletons-appdelegates-and-top-level.html
singleton from apple: http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CocoaFundamentals/CocoaObjects/CocoaObjects.html#//apple_ref/doc/uid/TP40002974-CH4-SW32
Hope that helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to install SolrNet.NHibernate? I tried Install-Package Solrnet.NHibernate on a new console application but it failed with this error:
Attempting to resolve dependency 'NHibernate.Core (≥ 2.1.2.4000)'.
Install-Package : Unable to resolve dependency 'NHibernate.Core (≥ 2.1.2.4000)'.
At line:1 char:16
+ install-package <<<< solrnet.nhibernate
+ CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException
+ FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand
Is this broken, and how do I fix this?
A: The "NHibernate.Core" package was renamed to "NHibernate" a while ago. Heck, I even supported that decision in a related discussion. Yet I forgot to update the SolrNet.NHibernate package. I guess I thought the NuGet team would batch transform all existing packages, but that never happened.
Anyway I just fixed the package and pushed it to the NuGet feed, so it all should work now.
A: I would try to install the NHibernate package via NuGet before installing the SolrNet.NHibernate package as it appears that the Solrnet.NHibernate package is having trouble installing the NHibernate.Core package as a dependency and I do not see an NHibernate.Core package listed in NuGet. This may or may not work, but is worth a shot at least.
If this does not work. I would recommend getting the latest SolrNet binaries from the SolrNet Google Code site and then following the NHibernate Integration guidance.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: field :published_on, :type => Date; not showing in MongoID + Devise I have created Model "House".
I followed this tutorial.
I created my scaffold and I go to my model after I add:
field :published_on, :type => Date;
Then I see the calendar in views for update the views like tutorial, but when I update the DATE in not appear the date.
I followed the tutorial, but to create or update date not appear.
What's the problem?
A: Problem fixed!
For every people that working with Date and DateTime in mongoid 2.0 or higher, must add to your model the next code:
include Mongoid::MultiParameterAttributes
The problem is fixed in this link:
https://github.com/mongoid/mongoid/issues/30#issuecomment-1211911
A: You manually added the field :published_on, did you also add it to attr_accessible?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: where is the bugtracker of Git? I was searching for the bug tracker for Git but I didn't really found it on their homepage and their issue tracker on GitHub is disabled.
A: Git bugs should be reported to: [email protected] as indicated on the Git Community page. The mailing list archive can be viewed and searched here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: testing a model mixin in Rails 3.1 I'm upgrading to Rails 3.1 and have a problem with testing a module that we include in several ActiveRecord models. We previously used a test model, like this:
describe FundTransfer do
class TestFundTransfer < ActiveRecord::Base
include FundTransfer
# stub db columns
class << self
def columns() FundReturn.columns; end
end
end
subject { TestFundTransfer.new }
it { should belong_to(:admin) }
it { should belong_to(:bank_account) }
it "is not valid without bank account and moneybookers account" do
fund_transfer = TestFundTransfer.new
fund_transfer.should_not be_valid
end
(complete spec: https://gist.github.com/1255960)
This breaks, because it doesn't find the table. I could probably find a way to stub the columns (like we did before) but my question is: does anyone have experience in doing this in a better way? In this form we cannot test anything that involves saving/loading the model.
I'm thinking about the following options:
*
*create a table with polluting the main schema
*create a table in the test, before the transaction is started
*stub columns (doesn't allow save/find)
Does anyone has any experience with this or have a better idea?
Note: The mixin specifies belongs_to associations, so I cannot use ActiveModel modules for my test model, it needs to be an ActiveRecord model.
A: This is a nice question, something I have struggled with myself as well. I tend to go for a different solution. While it is intended that your module is included in a class that inherits from ActiveRecord::Base, this is not explicit requirement. So I tend to manufacture a class that can include the class.
So something like this:
class TestFundTransfer
cattr_accessor :belongs_to_relations
def self.belongs_to(relation)
@@belongs_to_relations ||= []
@@belongs_to_relations << relation
end
include FundTransfer
end
context "on included" do
it "adds the correct belongs_to relations" do
TestFundTransfer.belongs_to_relations.should == [:your_relations]
end
end
Granted this could become complex, but on the other hand it is very explicit, and the dependencies are clear.
Secondly there is no need to do fake magic to get the ActiveRecord::Base working.
Inside remarkable_activerecord I did see a different approach: they use helper methods to create dummy tables and classes (and delete the table after use). In their case they need to test actual active-record behaviour, so the extra miles really make sense. Not sure if I would use the same approach in a rails project.
A: Does it help to declare the class as abstract?
class TestFundTransfer < ActiveRecord::Base
include FundTransfer
def self.abstract_class?; true; end
end
A: I managed to get the test passing:
# stub db columns
class << self
def columns() FundReturn.columns; end
def columns_hash() FundReturn.columns_hash; end
def column_defaults() FundReturn.column_defaults; end
end
But I'd like to hear if anyone has a nicer solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: using the .val attr in jquery Basically when i type something in the textarea, i can change the font either by inputting a size in a input box with id font_size or clicking the 64px button, once the font changes and i click done, i appended the value of what's in the textarea to the image in the div with an id image_conv but the problem here is that it doesn't take the formatted value of the text in the textarea to the div, i want the output in the div to be the formatted text value. Does anyone know how i can solve this?
Many thanks in advance.
ps: i uploaded the backgroung image of the text area on image shack so everyone could use it, i don't know if it works though cos i haven't tried it :)
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function sixty_four() {
var text_input = $('#textarea');
text_input.css("font-size", "64px");
}
function append_font() {
var text_input = $('#textarea');
var font = $('#font_size').val();
text_input.css("font-size", font + "px");
}
function text_manual() {
var text_value = $('#textarea').val();
$('#image_conv').append(text_value);
$('#image_conv').fadeIn('slow');
}
</script>
<style type="text/css">
#textarea {
height:300px;
width:300px;
resize: none;
}
#image_conv {
background: url(http://imageshack.us/photo/my-images/97/sliverc.png/) no-repeat left top;
border: 3px solid #000;
height:300px;
width:300px;
}
</style>
</head>
<body>
<textarea id="textarea"> </textarea><br/><br/>
Font size:<input type="text" id="font_size"/><input type="button" id="font_size" value="Append Font" onClick="append_font()"/>
<input type="button" id="64px" value="64px" onClick="sixty_four()" /><br/><br/>
<input type="button" id="manual_text" value="Done" onClick="text_manual()"/>
<div id="image_conv" >
</div>
</body>
</html>
A: The text in the textarea isn't formatted, it's the textarea element that is.
If you want to display the text from the textarea in another element with the same style as in the textarea, you have to apply the same style to the element as the textarea.
A: From what I understand, you would like to have the same font size in the div as you have set for the textarea?
Couldnt you just include the img_div in your js like this:
function sixty_four() {
var text_input = $('#textarea');
var img_div = $('#image_conv');
text_input.css("font-size", "64px");
img_div.css("font-size", "64px");
}
function append_font() {
var text_input = $('#textarea');
var img_div = $('#image_conv');
var font = $('#font_size').val();
text_input.css("font-size", font + "px");
img_div.css("font-size", font + "px");
}
function text_manual() {
var text_value = $('#textarea').val();
$('#image_conv').append(text_value);
$('#image_conv').fadeIn('slow');
}
I am not sure if I understood your question correctly, so I might be completly wrong here...
A: This is how you should do it:
$('#sixty_four').click(function(){
$('#textarea').css('font-size', '64px');
});
$('#font_size_btn').click(function() {
$('#textarea').css('font-size', $('#font_size').val() + 'px');
});
$('#manual_text').click(function(){
var $textarea = $('#textarea');
$('#image_conv')
.html($textarea.val())
.css('font-size', $textarea.css('font-size'))
.fadeIn('slow');
});
Demo
A: Try this:
http://jsfiddle.net/krdAy/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sencha Touch Panel setActiveItem not working I am building an app with Sencha touch. I have my viewport as a Carousel and inside that carousel there are 2 panels.
The second panel in that viewport is also a container for 2 nested panels.
App.views.Viewport = Ext.extend(Ext.Carousel, {
fullscreen: true,
indicator: false,
layout: 'card',
cardSwitchAnimation: 'slide',
initComponent: function() {
Ext.apply(App.views, {
mainWindow: new App.views.MainWindow(),
categories: new App.views.Categories()
});
Ext.apply(this, {
items: [
App.views.mainWindow,
App.views.categories
]
});
App.views.Viewport.superclass.initComponent.apply(this, arguments);
}
});
App.views.Categories = Ext.extend(Ext.Panel, {
fullscreen: true,
layout: 'card',
cardSwitchAnimation: 'slide',
initComponent: function() {
Ext.apply(App.views, {
categoriesList: new App.views.CategoriesList(),
categoryDetail: new App.views.CategoryDetail()
});
Ext.apply(this, {
items: [
App.views.categoryDetail,
App.views.categoriesList
]
});
App.views.Viewport.superclass.initComponent.apply(this, arguments);
}
});
Here's the code for the categoriesList
Ext.regModel('Contact', {
fields: ['firstName', 'lastName']
});
App.ListStore = new Ext.data.Store({
model: 'Contact',
sorters: 'firstName',
getGroupString : function(record) {
return record.get('firstName')[0];
},
data: [
{firstName: 'Julio', lastName: 'Benesh'},
]
});
App.views.catsList = new Ext.List({
store: App.ListStore,
itemTpl: '<div class="contact"><div class="app_icon"><img src="images/angry-birds.png" width="50" height="50" /></div><div class="app_name"><strong>{firstName}</strong> {lastName}<br /><img src="images/rating-icon.gif" /></div></div>',
onItemDisclosure: function(record, btn, index) {
App.views.categories.setActiveItem(
App.views.categoryDetail, options.animation
);
}
});
App.views.CategoriesList = Ext.extend(Ext.Panel, {
layout: 'fit',
items: [App.views.catsList],
initComponent: function() {
App.views.Categories.superclass.initComponent.apply(this, arguments);
}
});
onItemDisclosure of the list elements is being triggered. however, the setActiveItem for the App.views.categories is not switching to categoryDetail. I've been struggling to get this working. Any idea what i am doing wrong?
A: The problem lies in this line:
App.views.categories.setActiveItem(
App.views.categoryDetail, options.animation
);
You see you have an options object that it's undefined. You should use this instead:
App.views.categories.setActiveItem(
App.views.categoryDetail, {type:'slide', direction:'left'}
);
Or other type of animation.
Do you get some error log? Maybe there are some other issues why it's not working.
Update
Add this
onItemDisclosure: function(record, btn, index) {
console.log('onItemDis fired');
try{
Ext.dispatch({ controller: App.controllers.AppsList, action: 'show', id: record.getId(), animation: { type:'slide', direction:'left' } });
}catch(e){
console.log(e);
}
}
Then in the controller :
App.controllers.MyController = new Ext.Controller({ show: function(options) {
console.log('controller called');
try{
App.views.categories.setActiveItem( App.views.categoryDetail, options.animation );
}catch(e){console.log(e);} } });
then paste the console logs you get here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to pass model (and anything else) from view to partial view The overload for @Html.Partial takes a model, so in the "primary" view I put in this.model:
@Html.Partial("_GenericIndex", this.Model )
I tried just putting @Model in the partial view to see if anything showed up, but I got nothing.
So, how do I use that this.Model parameter in the partial view? I have seen some horrible solutions where it was prepared especially for the partial view in viewdata or something. Surely that is not necessary?
I just want to access the Html.Partial argument that I enter into it.
By the way my controller and action are like this:
public class TestController : Controller
{
IRepository<Customer> customerrepo = RepositoryFactory.GetRepository<Customer>();
//
// GET: /Test/
public ActionResult Index()
{
Customer cust = customerrepo.GetByID("1");
return View(cust);
}
}
A: Simply this line to the top of your partial view:
@model Customer
Then you can use @Model in your partial view, and it will represent the object you passed in your @Html.Partial("_GenericIndex", Model) call.
even you can call @Html.Partial("_GenericIndex"), which will passon the model of the current page to the partial page.
A: Did you set the model type in your partial view?
@{
var model = ViewContext.Controller.ViewData.Model as Customer;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Git, Mac OS X and accented characters On MacOSX with Git, there is a problem with different UTF8 representations of filename encodings. (Similar problems also exists in SVN.)
There is a patch for this here.
I wonder if there is any bug report (in their bug tracker which I haven't found yet) with any discussion about why this haven't been pulled yet or if anyone is working on it, etc.
A: This problem is very known and very understood, see, for example this one. Linus have some voice on this thread too.
There are some patch that paper over the problem, and no developer care enough / have to skill to fix it in the proper way. Maybe, i guess, it is impossible to fix this without breaking old commits.
A: Enable core.precomposeunicode on the Mac
git config --global core.precomposeunicode true
Then reclone the repository. For this to work, you need to have at least Git 1.7.12, which is bundled with Xcode 4.6.
That's it.
A: Well, it was stated here that there is no bug tracker and the common way is to send a mail to their mailing list.
I just did that here. And I messed up the thread a bit. :) Further discussion is here.
A: Besides the patch there is a workaround by translating Mac OS X the encoding for git! that seems to work for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: getting the saved password in android I am creating an android device in which there ia a login activity. how to check whether a certain id and password is saved in android device earlier and if it is saved then when the user has entered the emailid the password should get automatically set in the password field.
I have saved the email id and password as
if ((savepass).isChecked()) {
getSharedPreferences(PREFS_NAME,MODE_PRIVATE)
.edit()
.putString(PREF_USERNAME, eMailId)
.putString(PREF_PASSWORD, PWOrd)
.commit();
}
can anyone please help me..
thanks
A: *
*Get saved username and PW:
SharedPreferences pref = getSharedPreferences(PREFS_NAME,MODE_PRIVATE);
String pw = pref.getString(PREF_PASSWORD, null);
String username = pref.getString(PREF_USERNAME, null);
if either is null, then username/password are not saved.
*Set the password / username in the relevant fields:
userNameTextView.setText(username);
passwordTextView.setText(pw);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Use of exec command in process creation
Possible Duplicate:
exec and fork()
I want to know what exec command is doing.
Fork creates new memory for child process right(With parent data) and when execs is called wha it is doing? Whether overwriting datas in the newly created memory or Parent process memory.
A: As soon as you call fork, the child process cannot access the memory of the parent process anymore. A regular fork copies the complete memory stack of the parent process to the child process.
When call execve (or a derived function call), the calling process will be replaced by the newly executed program. If you're just doing a fork to do an execve, you'd better use vfork, as it's a lot friendlier for memory allocation of the newly created child.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Zend Framework - wrap dt dd in dl From another question in Change HTML output of Zend_Form does anyone know how I can produce the following html output? (Wrap each dtdd sets with dl)
<form>
<fieldset>
<dl>
<dt>label etc</dt>
<dd>input etc</dd>
</dl>
<dl>
<dt>label etc</dt>
<dd>input etc</dd>
</dl>
</fieldset>
... etc
</form>
A: Here you are:
class Default_Form_Chip extends Zend_Form
{
protected $_element_decorators = array(
'ViewHelper',
array(array('data' => 'HtmlTag'), array('tag' => 'dd', 'class' => 'form_element')),
array('Label', array('tag' => 'dt', 'class' => 'required', 'tagClass' => 'form_label')),
array('HtmlTag', array('tag' => 'dl', 'class' => 'form_wrapper')),
);
//put your code here
public function init()
{
$this->setElementDecorators($this->_element_decorators);
$this->setDecorators(array(
'FormElements',
array('HtmlTag', array('tag' => 'fieldset')),
'Form',
));
$this->addElement('text', 'username',array(
'label'=>'Username'
));
$this->addElement('text', 'password',array(
'label'=>'Password'
));
}
}
Output html:
<form enctype="application/x-www-form-urlencoded" action="" method="post">
<fieldset>
<dl class="form_wrapper">
<dt id="username-label">Username</dt>
<dd class="form_element">
<input type="text" name="username" id="username" value="">
</dd>
</dl>
<dl class="form_wrapper">
<dt id="password-label">Password</dt>
<dd class="form_element">
<input type="text" name="password" id="password" value="">
</dd>
</dl>
</fieldset>
</form>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: change transparent image color dynamically i have to change image color dynamically using php i used the following code
$imgname = "source.png";
$im = imagecreatefrompng ($imgname);
if($im && imagefilter($im, IMG_FILTER_COLORIZE, 27, 133, 85))
{
echo 'Image successfully shaded as per color.';
imagepng($im, 'Result.png');
imagedestroy($im);
}
else
{
echo 'Image create succesfully.';
}
but when i used it with transparent image it show me large thing border
can we resolve using the GD Lib or image stick any function ???
A: if you are talking about quality issue or shadow issue then I can be resolve by using imagesavealpha function before applying filter.
code should be
<?php
$imgname = "source.png";
$im = imagecreatefrompng ($imgname);
imagesavealpha($im, true);
if($im && imagefilter($im, IMG_FILTER_COLORIZE, 27, 133, 85))
{
echo 'Image successfully shaded as per color.';
imagepng($im, 'Result.png');
imagedestroy($im);
}
else
{
echo 'Image create succesfully.';
}
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Nested Prolog functions rotate(X):-
write('convert -rotate 90 '),write(X),write(' o.jpg'),
writeln(0).
beside(X,Y):-
write('convert -scale 50%%x50%% '),write(X),writeln(' 0111.jpg'),
write('convert -scale 50%%x50%% '),write(Y),writeln(' 01121.jpg'),
write('convert +append '),write(X),write(Y),writeln(' o.jpg').
above are my prolog codes for rotate and beside functions. How can i modify the codes to suit case like rotate(beside(X,Y)). which are nested
A: You can't. That's because rotate and beside are not functions, they are predicates.
Functions return values and so you nest them – use the return value of one function as an input of another function. On the other hand, when you try to evaluate a predicate in Prolog, it tries to “unify” all its unbound parameters using the rules you gave it, and returns whether that succeeded and how.
Code like rotate(beside(X,Y)). is valued, but it doesn't mean what you think. It tries to evaluate the predicate rotate on a structure beside(X,Y). It doesn't try to evaluate the beside predicate.
A: Looks like you are trying to use these like functions. The Prolog way is more like this:
rotate(X,Output):-
write('convert -rotate 90 '),write(X),write(' o.jpg'),
writeln(0),Output='o.jpg'.
beside(X,Y,Output):-
write('convert -scale 50%%x50%% '),write(X),writeln(' 0111.jpg'),
write('convert -scale 50%%x50%% '),write(Y),writeln(' 01121.jpg'),
write('convert +append '),write(X),write(Y),writeln(' o.jpg'),Output='o.jpg'.
then use
beside(X,Y,Temp),rotate(Temp,Output).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Modeling Identifying states & Modeling Validation in State Machine Diagram I am wondering what might I consider as States when I am asked to model state of a Booking Process (eg. Booking a Movie Ticket Online).
I did something like
It looks abit bloated mainly because of the validation. Should I even have a Validating XXX state? Or should it be something more like:
A: It all depends if the validation processes are synchronous or asynchronous.
For synchronous validation, there is no need for the validation state. The validation result is given immediately, the system never remains in a validation phase.
For asynchronous validation, a validation state is required because the validation result event is not immediate but is received later on. Typically an asynchronous call such as "startValidation" is invoked upon entering the validation state, and transitions handle the events "validationSuccess" and "validationError"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Retrieve Applications Requests (apprequests) through FQL? From the Requests Dialog document:
Graph API
To retrieve a single User ID from a single Request ID using the Graph API, issue an HTTP GET request to the request_id:
https://graph.facebook.com/[request_id]?access_token=USER_ACCESS_TOKEN
Is this request available through FQL?
A: Yes this is available via the apprequest fql table:
SELECT request_id, app_id, recipient_uid, sender_uid
FROM apprequest
WHERE request_id = 10150308414012941
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620090",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What's the "Rails way" to deal with a large number of controllers? In my Rails application the controllers are starting to pile up (> 30).
Would it be Java, I'd started to create sub-packages long ago, but I'm a little hesitant here.
I already have a User and an Admin namespace but I'm not sure if it is good to create a finer namespace structure, especially considering maintainability.
What's the "Rails way" in this case?
*
*Just have a more or less flat controller structure?
*Or is it better to generously bundle controllers into namespaces/modules?
Thanks in advance.
A: Don't know whether there is an ideal way, but specific to the project I deal, I have grouped it under a folder structure. Initially, again specific to my project, we were having to deal with just a couple of controllers called coach and manager. But as time went by, the size of them started bulging and we had to create few more controllers that could be grouped under a broad category. This was resulting in a flat growth.
More time went and we started grouping it in folders, example in a folder called coach all the related functionalities for a coach would go and the controller names started looking like class Coach::SchedulesController < ApplicationController.
This way of grouping would also help in writing the functional tests. You do not want to have your functional test to have insane amount of lines as well.
But the gist as always Rails suggests is to have a skinny controller and a fat model. At times, it may not be that easy to follow that up and yeah these are some ways you could overcome the difficulties.
A: In Rails, namespacing controllers (or even, ugh, models) is undesirable. Yeah, sometimes it's necessary, or just plain easiest, but I'd say it's never desirable.
As long as your controllers are skinny and represent 1 model each, I wouldn't mind even 100 controllers in a flat folder. It's when you have significantly more controllers than models that I would start worrying.
Of course this is all IMHO.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How close BackgroundWorker thread when application is deactivated? I create thread with BackgroundWorker, and in the loop I check every time if CancellationPending is true or not, like this:
public MainPage()
{
InitializeComponent();
bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;
bw.WorkerSupportsCancellation = true;
bw.DoWork += new DoWorkEventHandler(bw_DoWork);
bw.ProgressChanged += new ProgressChangedEventHandler(bw_ProgressChanged);
bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
}
private void ButtonStart_Click(object sender, RoutedEventArgs e)
{
if (bw.IsBusy != true)
{
bw.RunWorkerAsync();
}
}
private void ButtonCancel_Click(object sender, RoutedEventArgs e)
{
if (bw.WorkerSupportsCancellation)
{
bw.CancelAsync();
}
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
for (int i = 1; i <= 100; i++)
{
Debug.WriteLine("The tread is working");
if (worker.CancellationPending)
{
e.Cancel = true;
bw.CancelAsync();
break;
}
else
{
System.Threading.Thread.Sleep(500);
worker.ReportProgress(i);
}
}
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
tbProgress.Text = "Canceled";
}
else if (e.Error != null)
{
tbProgress.Text = "Error: " + e.Error.Message;
}
else
{
tbProgress.Text = "Done";
}
}
private void bw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
tbProgress.Text = e.ProgressPercentage.ToString() + "%";
}
When application is deactivated, the thread wasn't closed, it is aborted and the exception occurs. How close threads with BackgroundWorker when application is deactivated?
A: Did you set the BackgroundWorker to be cancelable?
var bg= new BackgroundWorker();
bg.WorkerSupportsCancellation = true;
From the documentation:
Set the WorkerSupportsCancellation property to true if you want the BackgroundWorker to support cancellation. When this property is true, you can call the CancelAsync method to interrupt a background operation.
Also your code seems to be wrong, you should call the CancelAsync() outside of your thread code, this will set the CancellationPending flag that you can use to exit the loop.
Although I'm not 100% sure as I don't know where the bw variable is coming from.
`
A: You should check the CancellationPending flag in your worker method and exit gracefully if the flag is set.
What is the condition for job cancellation? Cancel Button Click? Then you should put the CancelAsync(...) call there. It will set the CancellationPending flag for you which you are already checking in your code, avoiding the need for something like a ResetEvent object.
A: When an app is deactivated, every thread other than the main UI thread will throw a ThreadAbortException as soon as it becomes active. This appears to be "by design" as a way of forcing apps to quickly stop what they are doing. Threads can catch the ThreadAbortException and wrap up what they are doing, but be aware that the ThreadAbortException will be automatically raised again at the end of the catch block. Any code in a finally block will also be executed.
For your specific issue, there's no reason to attempt to cancel the BackgroundWorker when the app is deactivated because the ThreadAbortException will occur and will effectively stop the background worker. If you want to do something to clean up when this occurs, you catch the ThreadAbortException in bw_DoWork, do what you need to do, and then let it die.
To get it to start again after activation, you would have to restart the background worker, just like you did the first time the app ran.
A: I want to add one clarifying point to the answers above, based on my own observations. Background threads survive deactivation / activation when the instance is preserved.
I had code that looked like this:
private void Application_Activated(object sender, ActivatedEventArgs e)
{
if (e.IsApplicationInstancePreserved)
{
Log.write("Activating, instance preserved");
// restart long-running network requests
startBackground();
}
else // start over again
{
AppSettings.init();
Log.write("Activating, rehydrating" );
startBackground();
}
}
I also logged the hashcode of the BackgroundWorker object when it executed. What I saw was that every time I got an "Activating, instance preserved" message, I got an additional BackgroundWorker running.
Based on this it seems more likely accurate to say that threads are aborted on tombstoning, not on deactivation?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How should I use multiple UIViews to represent areas on screen? I am building an ipad app that has two basic regions on the screen:
*
*A dock on the left hand side contains "things" that you can drag onto the right side
*A free-form canvas on the right hand side
Under the presumption that the dock and the canvas views are both added as subviews to the viewcontroller's view, my question is around the mechanics of dragging the "thing" with my finger from the dock onto the canvas... who should own the view that represents the "thing"? Should it be the uiview that represents the dock (and then when it moves from the dock to the canvas I remove it from the dock and add it to the canvas)? Or should it belong the root view of the viewcontroller? Or some other pattern?
I'd be interested in peoples thoughts on the design patterns involved here.
Thanks a lot.
BTW, I've considered using something like cocos2d for this, but for the moment, I'd like to stay with the standard UIKit.
A: In Objective-C, you use UIViewControllers to control views. The logic of the program resides in these controllers. The idea is to separate view and model (data) and have a controller managed the interaction. This is called the MVC ("Model-View-Controller") design pattern.
In your case, the controller controls the main view and its subviews. So it is exactly there where you would implement the logic of dragging one object (also a UIView) from one subview to another. In your words, the dragged object "belongs" to this controller.
Maybe you have another class that keeps track of the things on the canvas, your "data model". The controller would need that to read and write the changes to it. Maybe there is some custom drawing necessary for the views. The views would implement this behavior themselves. In this way, you also follow the principle of encapsulation that helps writing re-usable code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: get List from Page to User Control i have a custom class List on my page code behind:
public List<Category> Categories = new List<Category>();
now, i have also a user control on that page which is supposed to display that list.
how can i access the list from the usercontrol,
or, can i create a list directly in the usercontrol from the page?
my User Control codebehind:
public List<Category> Categories = new List<Category>();
protected void Page_Load(object sender, EventArgs e)
{
}
public class Category
{
public string category_id { get; set; }
public string category { get; set; }
}
my Page codebehind:
public List<Category> Categories = new List<Category>();
protected void Page_Load(object sender, EventArgs e)
{
Category MyCategory = new Category();
MyCategory.category_id = 1;
MyCategory.category = "sample";
Categories.Add(MyCategory);
}
public class Category
{
public string category_id { get; set; }
public string category { get; set; }
}
A: Create a property in your user control and assign the list to that property
MyUserControl.ListProperty = theList;
OR
Put the list as a public property in the page and access it via Page property in user contorl. You'll need to cast it to your page type first.
var theList = ((MyPage)Page).ListProperty
OR
Put the list in HttpContext.Current.Items and get it from there.
HttpContext.Current.Items["theList"] = theList;
A: since Hasan Khan has started helping me,
but never answered my extra questions... i had to find my own solution.
the way i did it at the end was instead of adding items to the list on the Page,
adding them directly to the user control like so:
filterControl.Categories.Add(new widgets_filter.Category{ category_id = "", category = ""});
i dont know if this is a good solution, but at least it works.
if somebody will supply a better answer ( with sample code ) , i will try and use them, meanwhile, this is what i have.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Integrating a Bookmark App with a Social Networking Site I have a perfectly functional bookmarking app. As of now, it's non-exclusive; when I press "save" bookmark it sends the url to a general table in the DB. I need to figure out how to integrate this with an online community, so its user specific and each time a user "saves" a story, it sends the url to that user's row in the DB and outputs back to that user's profile.
Code is below.
Here's a demo:
http://demo.tutorialzine.com/2010/04/simple-bookmarking-app-php-javascript-mysql/demo.php
Bookmark.php
<?php
// Error reporting:
error_reporting(E_ALL^E_NOTICE);
require "connect.php";
require "functions.php";
// Setting the content-type header to javascript:
header('Content-type: application/javascript');
// Validating the input data
if(empty($_GET['url']) || empty($_GET['title']) || !validateURL($_GET['url'])) die();
// Sanitizing the variables
$_GET['url'] = sanitize($_GET['url']);
$_GET['title'] = sanitize($_GET['title']);
// Inserting, notice the use of the hash field and the md5 function:
mysql_query(" INSERT INTO bookmark_app (hash,url,title)
VALUES (
'".md5($_GET['url'])."',
'".$_GET['url']."',
'".$_GET['title']."'
)");
$message = '';
if(mysql_affected_rows($link)!=1)
{
$message = 'You have already saved this Headline';
}
else
$message = 'The URL was shared!';
?>
/* JavaScript Code */
function displayMessage(str)
{
// Using pure JavaScript to create and style a div element
var d = document.createElement('div');
with(d.style)
{
// Applying styles:
position='fixed';
width = '350px';
height = '20px';
top = '50%';
left = '50%';
margin = '-30px 0 0 -195px';
backgroundColor = '#f7f7f7';
border = '1px solid #ccc';
color = '#777';
padding = '20px';
fontSize = '18px';
fontFamily = '"Myriad Pro",Arial,Helvetica,sans-serif';
textAlign = 'center';
zIndex = 100000;
textShadow = '1px 1px 0 white';
MozBorderRadius = "12px";
webkitBorderRadius = "12px";
borderRadius = "12px";
MozBoxShadow = '0 0 6px #ccc';
webkitBoxShadow = '0 0 6px #ccc';
boxShadow = '0 0 6px #ccc';
}
d.setAttribute('onclick','document.body.removeChild(this)');
// Adding the message passed to the function as text:
d.appendChild(document.createTextNode(str));
// Appending the div to document
document.body.appendChild(d);
// The message will auto-hide in 3 seconds:
setTimeout(function(){
try{
document.body.removeChild(d);
} catch(error){}
},3000);
}
<?php
// Adding a line that will call the JavaScript function:
echo 'displayMessage("'.$message.'");';
?>
Connect.php
/* Database config */
$db_host = 'xxxxx';
$db_user = 'xxxxx';
$db_pass = 'xxxxx';
$db_database = 'xxxxx';
/* End config */
$link = @mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');
mysql_set_charset('utf8');
mysql_select_db($db_database,$link);
?>
Demo.php
// Error reporting:
error_reporting(E_ALL^E_NOTICE);
require "connect.php";
require "functions.php";
$url = 'http://'.$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"]);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Simple Bookmarking App With PHP, JavaScript & MySQL | Tutorialzine demo</title>
<link rel="stylesheet" type="text/css" href="styles.css" />
</head>
<body>
<h1>Bookmarking App...</h1>
<h2><a href="http://google.com">Return to the homepage »</a></h2>
<div id="main">
<div class="bookmarkHolder">
<!-- The link contains javascript functionallity which is preserved
when the user drops it to their bookmark/favorites bar -->
<a href="javascript:(function(){var jsScript=document.createElement('script');
jsScript.setAttribute('type','text/javascript');
jsScript.setAttribute('src', '<?php echo $url?>/bookmark.php?url='+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title));
document.getElementsByTagName('head')[0].appendChild(jsScript);
})();" class="bookmarkButton">Bookmark this!</a>
<em>Drag this button to your bookmarks bar and click it when visiting a web site. The title and URL of the page will be saved below.</em>
</div>
<ul class="latestSharesUL">
<?php
$shares = mysql_query("SELECT * FROM bookmark_app ORDER BY id DESC LIMIT 6");
while($row=mysql_fetch_assoc($shares))
{
// Shortening the title if it is too long:
if(mb_strlen($row['title'],'utf-8')>80)
$row['title'] = mb_substr($row['title'],0,80,'utf-8').'..';
// Outputting the list elements:
echo '
<li>
<div class="title"><a href="'.$row['url'].'" class="bookmrk">'.$row['title'].'</a></div>
<div class="dt">'.relativeTime($row['dt']).'</div>
</li>';
}
?>
</ul>
</div>
</body>
</html>
Functions.php
/* Helper functions */
function validateURL($str)
{
return preg_match('/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:\/~\+#]* [\w\-\@?^=%&\/~\+#])?/i',$str);
}
function sanitize($str)
{
if(ini_get('magic_quotes_gpc'))
$str = stripslashes($str);
$str = strip_tags($str);
$str = trim($str);
$str = htmlspecialchars($str);
$str = mysql_real_escape_string($str);
return $str;
}
function relativeTime($dt,$precision=2)
{
if(is_string($dt)) $dt = strtotime($dt);
$times=array( 365*24*60*60 => "year",
30*24*60*60 => "month",
7*24*60*60 => "week",
24*60*60 => "day",
60*60 => "hour",
60 => "minute",
1 => "second");
$passed=time()-$dt;
if($passed<5)
{
$output='less than 5 seconds ago';
}
else
{
$output=array();
$exit=0;
foreach($times as $period=>$name)
{
if($exit>=$precision || ($exit>0 && $period<60)) break;
$result = floor($passed/$period);
if($result>0)
{
$output[]=$result.' '.$name.($result==1?'':'s');
$passed-=$result*$period;
$exit++;
}
else if($exit>0) $exit++;
}
$output=implode(' and ',$output).' ago';
}
return $output;
}
// Defining fallback functions for mb_substr and
// mb_strlen if the mb extension is not installed:
if(!function_exists('mb_substr'))
{
function mb_substr($str,$start,$length,$encoding)
{
return substr($str,$start,$length);
}
}
if(!function_exists('mb_strlen'))
{
function mb_strlen($str,$encoding)
{
return strlen($str);
}
}
?>
Table.sql
CREATE TABLE `bookmark_app` (
`id` int(10) unsigned NOT NULL auto_increment,
`hash` varchar(32) collate utf8_unicode_ci NOT NULL default '',
`url` text collate utf8_unicode_ci NOT NULL,
`title` text collate utf8_unicode_ci NOT NULL,
`dt` timestamp NOT NULL default CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `hash` (`hash`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the reason for perfomance difference for substring search using "index()" vs RegEx in Perl? I am assuming there might be an efficiency difference between:
if (index($string, "abc") < -1) {}
and
if ($string !~ /abc/) {}
Could someone confirm that this is the case based on how both are implemented in Perl (as opposed to pure benchmarking)?
I can obviously make a guess as to how both are implemented (based on how I would write both in C) but would like more informed answer ideally based on actual perl sourcecode.
Here's my own sample benchmark:
Rate regex.FIND_AT_END index.FIND_AT_END
regex.FIND_AT_END 639345/s -- -88%
index.FIND_AT_END 5291005/s 728% --
Rate regex.NOFIND index.NOFIND
regex.NOFIND 685260/s -- -88%
index.NOFIND 5515720/s 705% --
Rate regex.FIND_AT_START index.FIND_AT_START
regex.FIND_AT_START 672269/s -- -90%
index.FIND_AT_START 7032349/s 946% --
##############################
use Benchmark qw(:all);
my $count = 10000000;
my $re = qr/abc/o;
my %tests = (
"NOFIND " => "cvxcvidgds.sdfpkisd[s"
,"FIND_AT_END " => "cvxcvidgds.sdfpabcd[s"
,"FIND_AT_START " => "abccvidgds.sdfpkisd[s"
);
foreach my $type (keys %tests) {
my $str = $tests{$type};
cmpthese($count, {
"index.$type" => sub { my $idx = index($str, "abc"); },
"regex.$type" => sub { my $idx = ($str =~ $re); }
});
}
A: Take a look at the function Perl_instr:
430 char *
431 Perl_instr(register const char *big, register const char *little)
432 {
433 register I32 first;
434
435 PERL_ARGS_ASSERT_INSTR;
436
437 if (!little)
438 return (char*)big;
439 first = *little++;
440 if (!first)
441 return (char*)big;
442 while (*big) {
443 register const char *s, *x;
444 if (*big++ != first)
445 continue;
446 for (x=big,s=little; *s; /**/ ) {
447 if (!*x)
448 return NULL;
449 if (*s != *x)
450 break;
451 else {
452 s++;
453 x++;
454 }
455 }
456 if (!*s)
457 return (char*)(big-1);
458 }
459 return NULL;
460 }
Compare with S_regmatch. It seems to me that there is some overhead in regmatch compared to index ;-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Hibernate: SELECT in UPDATE I need do something like that:
session.getTransaction().begin();
session.createQuery("update Pack p set p.book = (select b from Book b where ...) where p.id = :id")
.setLong("id", pack.getId())
.executeUpdate();
session.getTransaction().commit();
And have error:
Exception occurred during event dispatching:
org.hibernate.TypeMismatchException: left and right hand sides of a binary logic operator were incompatibile [java.util.Set(BookKeeper.db.Pack.book) : BookKeeper.db.Book]
But why? p.book have a Set<Book> type, same as (select b from Book b where ...) must return.
A: If you observe
p.book = (select b from Book b where ...)
The select should return a unique value. If it doesn't then things will go wrong, because you get a Set on right hand side but the left hand side is expecting a book.
This is very similar to sql syntax.
A: I don't know if it might help you, I just digged in Hibernate Source code.
Your exception occurs inside of BinaryLogicOperatorNode.java
on the following place:
if ( lhsColumnSpan != rhsType.getColumnSpan( sessionFactory ) ) {
throw new TypeMismatchException(
"left and right hand sides of a binary logic operator were incompatibile [" +
lhsType.getName() + " : "+ rhsType.getName() + "]"
);
when rhsType and lhsType are the org.hibernate.Type objects:
Type lhsType = extractDataType( lhs );
Type rhsType = extractDataType( rhs );
now let's see what getColumnSpan() is doing:
According to Hibernate docs:
public int getColumnSpan(Mapping mapping) throws MappingException
How many columns are used to persist this type.
So according to this logic you can run such type of queries only on equal size objects:
if your Set<Book> p.book has the same amount of objects as select b from Book b returns, this query would run successfully, otherwise it would fail.
Hope it helps.
A: Try this - notice the max. Without that there is no way for hibernate to know that the inner query will only return a single row.
update Pack p set p.book = (select max(b) from Book b where ...) where p.id = :id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: c++ win32 get system volume accelerator is it possible to detect which keys are used for a system volume accelerator in win32 using c++? For example: if the user presses fn + key up (and this is also the key combination to change the system volume), i would like to detect this event and response to it.
A: This is handled by the machine's BIOS. It produces a keystroke, VK_VOLUME_DOWN or VK_VOLUME_UP virtual key. DefWindowProc handling of that WM_KEYDOWN message produces WM_APPCOMMAND, APPCOMMAND_VOLUME_UP/DOWN. DefWindowProc handling of that message adjusts the volume.
A: I don't think this is possible generally. The fn-keys are usually handled by the BIOS-SMM-ACPI whatever, and that is not accesible to user programs.
Maybe, if it were translated to the standard multimedia volume-up key, you could get that, but I wouldn't bet on it.
A: see this post...
http://www.rohitab.com/discuss/topic/21252-change-volume/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ListView subitems font not working I have a listview in which I want to apply different font in different cells according to some condition. But I'm unable to do this. I tried these types of codes to add item.
ListViewItem entryListItem = listView_Standard.Items.Add("Items");
// Set UseItemStyleForSubItems property to false to change
// look of subitems.
entryListItem.UseItemStyleForSubItems = false;
// Add the expense subitem.
ListViewItem.ListViewSubItem expenseItem =
entryListItem.SubItems.Add("Expense");
// Change the expenseItem object's color and font.
expenseItem.ForeColor = System.Drawing.Color.Red;
expenseItem.Font = new System.Drawing.Font(
"Arial", 10, System.Drawing.FontStyle.Italic);
// Add a subitem called revenueItem
ListViewItem.ListViewSubItem revenueItem =
entryListItem.SubItems.Add("Revenue");
revenueItem.BackColor = System.Drawing.Color.Red;
// Change the revenueItem object's color and font.
revenueItem.ForeColor = System.Drawing.Color.Blue;
revenueItem.Font = new System.Drawing.Font(
"KF-Kiran", 25, System.Drawing.FontStyle.Bold);
and
ListViewItem NewItem = new ListViewItem();
NewItem.UseItemStyleForSubItems = false;
NewItem.Text = "foo";
NewItem.SubItems.Add("bar");
NewItem.SubItems.Add("1111111");
NewItem.SubItems[1].Font = new Font("KF-Kiran", 20);
listView_Standard.Items.Add(NewItem);
When I use 0th subitem to change font, new font is applied to whole row. But I want only particluarl cells to apply font.
A: ListViewItem.UseItemStyleForSubItems = false;
This denies first subitem's font style to be applied automatically on all subitems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Display or hide an XML tag within a table I am trying to do a basic if/else statement to display or hide content within a table. It's also important to note that this content is being fed from an XML document. I am looking for an XML tag called .
I have the following code and cannot figure out how to make this work. Whatever I try, it displays nothing on the page. My logic seems right, but I'm also not a great script writer; so any guidance would be greatly appreciated. Thank you for your time and help.
n = xmlDoc.getElementsByTagName("note")[0].childNodes[0].nodeValue
if (n != NONE){
document.write("<tr>");
document.write("<td colspan='4' id='notation'>");
document.write(y[j].getElementsByTagName("note")[0].childNodes[0].nodeValue);
document.write("</td>");
document.write("</tr>");
}else{
document.getElementsByTagName("note").style.display = 'none';
}
}
....or what if I toggle the visibility of a div on and off?:
if (none != NONE){
document.write("<div id='test' style='background-color: #999;'>")
document.write(y[j].getElementsByTagName("note")[0].childNodes[0].nodeValue);
document.write("</div>");
}else{
document.getElementById('test').style.display = 'none';
}
A: Below i give a sample example.book.xml page is written below.you can check it.
<script>
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","book.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
n = xmlDoc.getElementsByTagName("dow")[0].childNodes[0].nodeValue;
var y=xmlDoc.getElementsByTagName("canceledDate");
for (j=0;j<y.length;j++){
if (n){
document.write("<tr>");
document.write("<td colspan='4' id='notation'>");
document.write(y[j].getElementsByTagName("dow")[0].childNodes[0].nodeValue);
document.write("</td>");
document.write("</tr>");
}else{
document.getElementsByTagName("dow").style.display = 'none';
}
</script>
<cancellations>
<canceledDate>
<dow>Tuesday</dow>
<month>10</month>
<day>07</day>
<year>11</year>
<canceledClass>
<title>title</title>
<course>course</course>
<section>section</section>
<days>days</days>
<instructor>Doe</instructor>
<note>NONE</note>
</canceledClass>
</canceledDate>
<canceledDate>
<dow>Wednesday</dow>
<month>10</month>
<day>07</day>
<year>11</year>
<canceledClass>
<title>title</title>
<course>course</course>
<section>section</section>
<days>days</days>
<instructor>Doe</instructor>
<note>this is a note</note>
</canceledClass>
</canceledDate>
</cancellations>
A: For those interested, my condition was incorrect. It should have been something like this:
(y[j].getElementsByTagName("note")[0].childNodes[0].nodeValue != "NONE")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: RCurl, error: couldn't connect to host I use Rstudio server, and the packages RCurl and XML. I tried to scrape a webpage, but after having done it once successfully, I got the error message:
Error in curlPerform(curl = curl, .opts = opts, .encoding = .encoding) :
couldn't connect to host
when trying to get the URL:
getURL(my_url, encoding="UTF-8", followLocation = TRUE)
Any ideas why this is happening?
A: Maybe you should try setting your RCurlOptions:
options(RCurlOptions = list(proxy = "my.proxy", proxyport = my.proxyport.number))
I hope it helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript refuses to return anything getGood = function(v,x) {
$.getJSON('json/products.json', function(data) {
$.each(data, function(key, val) {
if (v.toLowerCase() == key.toLowerCase()) {
$.each(val.products, function(ckey, cval) {
if (x.toLowerCase() == ckey.toLowerCase()) {
var dval=new Date().getDay();
var qHash=hex_md5(v+x+qs('cst')+dval).toLowerCase();
if (qHash == qs('hash')) {
return dval;
} else {
window.location.replace('/errors/418.html');
}
}
});
}
});
});
}
$(document).ready(function() {
var owner=getGood(qs('cat'),qs('subp'));
alert(owner==null);
$('.content_title').html(qs('subp'));
$('.description').html(owner.descripion);
})
The above code is supposed to read a JSON file, compare some query strings to test for validity and then return the object if the request is valid. Problem is, no matter what I do, getGood refuses to return any value to my owner variable. I've tried having it return the different values around it. I was just trying to get it to return anything I could. It needs to return cval. The alert at the bottom, however, always says "undefined/null".
EDIT
Because apparently people think I am just that retarded:
YES, it gets to the return statement. Yes, qHash == qs('hash'), I'm not asking you to check every if/loop/etc. I already know all of that works. I'm asking, why does my return statement not end up setting owner to what it is supposed to.
A: The callback passed to "$.getJSON()" is executed asynchronously. It is therefore just not possible to return a value from it.
Instead, pass in the code that needs to act on the value as a function parameter. The callback function can then pass the value into that function as a parameter.
function getGood(v, x, handleOwner) {
$.getJSON('json/products.json', function(data) {
$.each(data, function(key, val) {
if (v.toLowerCase() == key.toLowerCase()) {
$.each(val.products, function(ckey, cval) {
if (x.toLowerCase() == ckey.toLowerCase()) {
var dval=new Date().getDay();
var qHash=hex_md5(v+x+qs('cst')+dval).toLowerCase();
if (qHash == qs('hash')) {
handleOwner(dval); // calling the handler function here
} else {
window.location.replace('/errors/418.html');
}
}
});
}
});
});
}
//
getGood(qs('cat'),qs('subp'), function(owner) {
alert(owner);
});
A: JavaScript isn't "refusing to return" anything. You're just not asking it to.
You're doing
var owner=getGood(qs('cat'),qs('subp'));
but getGood does not return any value. The only return statement is in the function (key, val) inside getGood which returns from that function, not from getGood.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Open Graph: Facebook crawler name and ip’s to white list I am prepping up for the open graph release.
One of the features from open graph is to crawl the site’s meta data and pull relevant info for the timeline.
My sitemap.xml runs into gigs and is protected by rate limiting and ip whitlisting for popular crawlers like Googlebot & Slurp.
Can someone pass me the robot names and ips that will be crawling for facebook? This is not just for sitemap.xml, but for general rate limit(whole site) white listing too.
A: The current user agent is: facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)
Facebook publishes their IP range here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Record Internal Sound using iPhone SDK I am making an app that requires internal sound to be recorded.
Any solution?
A: The is no public iOS API that will allow you to record all internal sound that an app or the device can make. Only certain types of internal sound can be recorded, for instance sounds produced by an app using Audio Queues or the RemoteIO Audio Unit.
For recording external sound, Apple's SpeakHere sample code might be appropriate.
A: ReplayKit framework records screen video and audio from the app and microphone. However ReplayKit is incompatible with AVPlayer content. It's available in iOS 9.0 and higher.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620131",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Firefox adds 1px on my submit button I'm trying to design my form via CSS.
Problem is that I need a "standard" submit and a hyperlink which is styled like a button with CSS.
My CSS currently looks like that:
form .buttons input[type=submit], form .buttons a { padding: 0; margin: 0; }
form .buttons input[type=submit], form .buttons a { font-family: Tahoma, sans-serif; font-size: 14px; text-decoration: none; font-weight: bold; color: #565656; }
form .buttons input[type=submit] { border: 1px solid black; }
form .buttons a { border: 1px solid black; }
In Firefox I have the problem that there is a 1px padding added around the submit button (like you can see on the screenshot).
Is there a solution how I can solve this problem?
A: input[type="submit"]::-moz-focus-inner {
border: 0px;
padding: 0px;
}
A: Try also "line-height: normal;" it fixed a bug in IE as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Can I develop Lego Mindstorms in Scala? Is there a Java SDK for Lego Mindstorms? Can I compile Scala code to JAR and run it in Lego Mindstorms?
A: Likely no, but difficult to say. Mindstorm JVMs aren't complete JVMs, though they're not bad.
That said:
Even assuming all the classes you needed were available, Scala "lets" you use large quantities of memory before you realize what's happening. It's not certain–you can control what parts of Scala you use. Restricting yourself eliminates some of Scala's advantages, though.
My approach would be to run a server (or client) on the bot and use Scala on a real machine to control the bot over wireless. Obviously this has its own set of disadvantages.
A: Maybe it's not valid anymore, but you can develop in Scala for Mindstorms EV3, here is an example:
https://github.com/t3hnar/ev3.helloworld
A: I'm not sure about Lego Mindstorms (never seen it), but generally, yes. You can compile your scala code to JAR, add scala-library.jar, and run it just like normal Java program.
If your program accepts only one jar, you can combine your JAR with scala-library.jar and create a single file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: How to set camelCase to code generated by code templates in Flash Builder 4.5? I'm trying to change the default event handler code generator, so that it generates the name of the function as onComponentidEventname For example:
<s:Button id="myButton"
click="onMyButtonClick(event)" />
The code template I use is:
${namespace} ${modifiers}function ${:method_name('on${component_id}${event_name}')}(${event}:${event_type}):${return_type}{${cursor}}
But the result is onmyButtonclick instead of onMyButtonClick.
Any ideas if that is possible and how to do that?
Thanks in advance,
Blaze
A: It's not possible to apply transformations on the code variables...you can submit a feature request if you really need it - go to http://bugs.adobe.com/jira/browse/FB/component/10660 and click on "Feature Request" (you need to be logged in for that).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620141",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Passing a function to a variable I'm trying to pass a function to variable (req):
var req;
$('#complete-field').bind('keyup', function() {
var url = prefixUrl + escape($('#complete-field').val());
req = function() {
if (window.XMLHttpRequest) {
if (navigator.userAgent.indexOf('MSIE') != -1) {
isIE = true;
}
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
return new ActiveXObject("Microsoft.XMLHTTP");
}
};
req.open("GET", url, true);
req.onreadystatechange = callback;
req.send(null);
});
But i always get the following error:
req.open is not a function
req.open("GET", url, true);
Any Idea how to solve this pls.
Many thanks
A: You should name your function and call it ..
var req;
$('#complete-field').bind('keyup', function() {
var url = prefixUrl + escape($('#complete-field').val());
function ajaxObject() {
if (window.XMLHttpRequest) {
if (navigator.userAgent.indexOf('MSIE') != -1) {
isIE = true;
}
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
return new ActiveXObject("Microsoft.XMLHTTP");
}
};
req = ajaxObject();
req.open("GET", url, true);
req.onreadystatechange = callback;
req.send(null);
});
Your code would store the entire function to the req variable.. not its returned value (it was never called in the first place..)
A: Your req variable refers to a function. This means you can invoke it using parentheses, as in
req()
The result will be an XmlHttpRequest, which you can then call open and other functions on.
Also, be aware that it looks like you're trying to reinvent the wheel here, jquery already supports cross-browser XHR through $.ajax and similar APIs.
A: You need to write req() instead of just req., because so you execute req which will return you object you need:
var request = req();
request.open("GET", url, true);
request.onreadystatechange = callback;
request.send(null);
A: You want to execute the function and save the result to the variable:
req = (function() {
if (window.XMLHttpRequest) {
if (navigator.userAgent.indexOf('MSIE') != -1) {
isIE = true;
}
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
return new ActiveXObject("Microsoft.XMLHTTP");
}
})();
A: At the point you call req.open() the variable req contains a function, not an XMLHTTP object. The function has not yet been executed.
To execute the function as it's declared, add () to the end.
req = function() {
...
}();
A: You are putting the reference to the function in the variable all right. Using this:
var req;
req = function() {
...
}
is basically the same as:
function req() {
...
}
(The scope will of course differ in this case, as you declared the variable outside the event hander.)
The problem is with how you use the function. The function and it's return value are not the same, you have to call the function to get the return value:
var xhr = req();
Now you can use the return value:
xhr.open("GET", url, true);
xhr.onreadystatechange = callback;
xhr.send(null);
A: I use this for native AJAX:
(window.ActiveXObject) ? httpRequest = new ActiveXObject("Microsoft.XMLHTTP") : httpRequest = new XMLHttpRequest();
httpRequest.open('POST', 'btAppendX.php', true);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
httpRequest.onreadystatechange = function () { (httpRequest.readyState == 4 && httpRequest.status == 200) ? responseData(httpRequest) : window.status = httpRequest.statusText;}
httpRequest.send(zAllInOne);
compressed ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Shorter Scala Script header It's possible to write shell scripts in Scala by starting a text file with:
#!/bin/sh
exec scala "$0" "$@"
!#
To ease script creation, I would like to write an executable called scalash (perhaps a BASH script) allowing to shorten Scala script header to just one line:
#!/bin/scalash
Is it possible ? Extra points if I can pass optional parameters to scalash, for instance to add classpath dependencies.
A: See this pull request (was this). There's no issue associated with it -- if you feel like it, you could open an issue and comment on the pull request.
You can also use SBT to start the scripts. See information about scalas here.
EDIT
The pull request was accepted, so this should work:
#!/usr/bin/env /path/to/scala
etc
A: In Scala 2.11, you can do it as follows (exactly as with most other languages):
#!/usr/bin/env scala
println(args.mkString(" "))
In Scala 2.9.0.1, you can simply create the following script:
test.scala
#!/usr/bin/scala
!#
println(args.mkString(" "))
and make it executable. (change the first line to path to your executable)
Usage:
# ./test.scala Hello world!
Hello world!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How can I draw an animated view in android? I created a custom view from scratch. Extended View and overrided onDraw().
When comes down in animating the view i generate a custom animation using offsets.
eg.
while(!isOnTop){
mOffset++;
//draw the component a a it higher using the offset
if(position == 0)
isOnTop==true;
invalidate();
}
The thinking is that my frames come from invalidate it self. The problem is that invalidation of this view can come just by scrolling a listview at the same screen.
This "shared invalidation()" causes lag to my animation.So is there a way out of that lag?
Do you have any other suggestion of performing animations in that shared enviroment?
Creating an animation using a seperate thread that calculates the offset also needs forced invalidation() calls to display the animation (correct me if i'm wrong).
Is the only solution to perform the animation in eg 10 invalidation requests with a larger step? It will ease the lag out but i think i can use a different approach on that.
A: Since this question has some interest I will reply.
The best way to to that is to have a separate canvas thread. A "separate" canvas can only be achieved with a SurfaceView. LunarLanding is an excelent example of that use. Each frame is calculated separately than the main view sharing only CPU time, not drawing time. Therefore is faster, even with the combination of for e.g a regular view at the top and an animating view at the bottom.
But you have to set an interval if you are in that shared environment. That interval is used for the FPS cap. If you don't set FPS cap then the CPU will running wild managing to get good animation to the SurfaceView if it was alone. Capping it at 60fps or even less will do the trick to draw all views efficiently with no CPU overload.
So see the drawing thread of the Lunar Landing from the API demos and set a FPS cap.
private long timeNow;
private long timeDelta;
private long timePrevFrame;
private void capFps(int fps) {
timeNow = System.currentTimeMillis();
timeDelta = timeNow - timePrevFrame;
try {
//ps you can always set 16 instead of 1000/fps for 60FPS to avoid the calculation every time
Thread.sleep((1000 / fps) - timeDelta);
} catch (InterruptedException e) {
}
timePrevFrame = System.currentTimeMillis();
}
and then the drawing thread will look something like this:
@Override
public void run() {
Canvas c;
while (run) {
c = null;
sleepFps(60, false);
try {
synchronized (surfaceHolder) {
c = surfaceHolder.lockCanvas(null);
widgetView.doDraw(c);
}
} finally {
if (c != null) {
surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
A: "What is best" of course depends greatly on exactly what you are trying to do. You haven't said what you are trying to accomplish, so we can only guess at what may be best for you.
Here are some simple things:
*
*If you want to animate bitmap frames, use AnimationDrawable: http://developer.android.com/reference/android/graphics/drawable/AnimationDrawable.html
*If you want to animate the movement of views within your hierarchy, use the view animation framework: http://developer.android.com/guide/topics/graphics/view-animation.html
*The new more general animation framework can do a lot more stuff an is often easier to use: http://developer.android.com/guide/topics/graphics/animation.html. This is natively available in Android 3.0+ but can also be used in Android API level 7 with the support v7 library.
*If you want to write a custom widget that is an integrated part of its view hierarchy and manually does its own animation drawing, you can use a Handler to time the updates (usually you'll want 60fps or 20ms between each invalidate()) and then in your onDraw() method draw your view's state based on SystemClock.uptimeMillis() as a delta from when the animation started.
Here's a simple repeated invalidate using Handler:
long mAnimStartTime;
Handler mHandler = new Handler();
Runnable mTick = new Runnable() {
public void run() {
invalidate();
mHandler.postDelayed(this, 20); // 20ms == 60fps
}
}
void startAnimation() {
mAnimStartTime = SystemClock.uptimeMillis();
mHandler.removeCallbacks(mTick);
mHandler.post(mTick);
}
void stopAnimation() {
mHandler.removeCallbacks(mTick);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Can i automatically send SMS (Without the user need to approve) I'm rather new to Android.
Im trying to send SMS from Android application.
When using the SMS Intent the SMS window opens and the user needs to approve the SMS and send it.
Is there a way to automatically send the SMS without the user confirming it?
Thanks,
Lior
A: Yes, you can send SMS using the SmsManager. Please keep in mind that your application will need the SEND_SMS permission for this to work.
A: You can use this method to send an sms. If the sms is greater than 160 character then sendMultipartTextMessage is used.
private void sendSms(String phonenumber,String message, boolean isBinary)
{
SmsManager manager = SmsManager.getDefault();
PendingIntent piSend = PendingIntent.getBroadcast(this, 0, new Intent(SMS_SENT), 0);
PendingIntent piDelivered = PendingIntent.getBroadcast(this, 0, new Intent(SMS_DELIVERED), 0);
if(isBinary)
{
byte[] data = new byte[message.length()];
for(int index=0; index<message.length() && index < MAX_SMS_MESSAGE_LENGTH; ++index)
{
data[index] = (byte)message.charAt(index);
}
manager.sendDataMessage(phonenumber, null, (short) SMS_PORT, data,piSend, piDelivered);
}
else
{
int length = message.length();
if(length > MAX_SMS_MESSAGE_LENGTH)
{
ArrayList<String> messagelist = manager.divideMessage(message);
manager.sendMultipartTextMessage(phonenumber, null, messagelist, null, null);
}
else
{
manager.sendTextMessage(phonenumber, null, message, piSend, piDelivered);
}
}
}
Update
piSend and piDelivered are Pending Intent They can trigger a broadcast when the method finish sending an SMS
Here is sample code for broadcast receiver
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String message = null;
switch (getResultCode()) {
case Activity.RESULT_OK:
message = "Message sent!";
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
message = "Error. Message not sent.";
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
message = "Error: No service.";
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
message = "Error: Null PDU.";
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
message = "Error: Radio off.";
break;
}
AppMsg.makeText(SendMessagesWindow.this, message,
AppMsg.STYLE_CONFIRM).setLayoutGravity(Gravity.BOTTOM)
.show();
}
};
and you can register it using below line in your Activity
registerReceiver(receiver, new IntentFilter(SMS_SENT)); // SMS_SENT is a constant
Also don't forget to unregister broadcast in onDestroy
@Override
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
A: Yes, you can send sms without making user interaction...But it works, when user wants to send sms only to a single number.
try {
SmsManager.getDefault().sendTextMessage(RecipientNumber, null,
"Hello SMS!", null, null);
} catch (Exception e) {
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(this);
AlertDialog dialog = alertDialogBuilder.create();
dialog.setMessage(e.getMessage());
dialog.show();
}
Also, add manifest permission....
<uses-permission android:name="android.permission.SEND_SMS"/>
A: If your application has in the AndroidManifest.xml the following permission
<uses-permission android:name="android.permission.SEND_SMS"/>
you can send as many SMS as you want with
SmsManager manager = SmsManager.getDefault();
manager.sendTextMessage(...);
and that is all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: iPhone:How can I store UIImage using NSUserDefaults? I cannot save image using nsuserdefaults and crash my app and I also used custom class UserInfo which used
-(void)encodeWithCoder:(NSCoder *)encoder
{
NSData *imageData = UIImagePNGRepresentation(categoryImage);
[encoder encodeObject:categoryName forKey:@"name"];
[encoder encodeObject:imageData forKey:@"image"];
}
-(id)initWithCoder:(NSCoder *)decoder and userInfo.categoryImage is UIImage variable.
reason: '-[UIImage encodeWithCoder:]: unrecognized selector sent to instance 0x7676a70'
userInfo = [[UserInfo alloc] init];
userInfo.categoryName = categoryName.text;
NSLog(@"Category Name:--->%@",userInfo.categoryName);
userInfo.categoryImage = image;
appDelegate.categoryData = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
userInfo.categoryName, @"name",userInfo.categoryImage,@"image", nil] mutableCopy];
[appDelegate.categories addObject:appDelegate.categoryData];
NSLog(@"Category Data:--->%@",appDelegate.categories);
[appDelegate.categories addObject:userInfo.categoryName];
[appDelegate.categories addObject:userInfo.categoryImage];
[self saveCustomObject:userInfo.categoryName];
[self saveCustomObject:userInfo.categoryImage];
-(void)saveCustomObject:(UserInfo *)obj
{
appDelegate.userDefaults = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:obj];
[appDelegate.userDefaults setObject:myEncodedObject forKey:@"myEncodedObjectKey"];
}
So Please help me how can i store and retrieve uiimage using nsusedefaults???
A: Image Save on NSUserDefaults :
[[NSUserDefaults standardUserDefaults] setObject:UIImagePNGRepresentation(image) forKey:@"image"];
Image retrieve on NSUserDefaults:
NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"image"];
UIImage* image = [UIImage imageWithData:imageData];
A: If I were you, I'll save the UIImage into a file (use the [myImage hash]; to generate a file name), and save the file name as NSString using NSUserDefault ;-)
A: UIImage does not implement NSCoding protocol, this is why you have the error.
Store:
NSData* imageData = UIImagePNGRepresentation(image);
NSData* myEncodedImageData = [NSKeyedArchiver archivedDataWithRootObject:imageData];
[appDelegate.userDefaults setObject:myEncodedImageData forKey:@"myEncodedImageDataKey"];
}
Restore:
NSData* myEncodedImageData = [appDelegate.userDefaults objectForKey:@"myEncodedImageDataKey"];
UIImage* image = [UIImage imageWithData:myEncodedImageData];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620165",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: fired event when user allow the app This event is fired when user login
FB.Event.subscribe('auth.login', function(response) {
//
});
But i am just looking for the event that is fired when user allows the app from auth dialog ?
A: FB.Event.subscribe('auth.authResponseChange', function(response) {
alert('The status of the session is: ' + response.status);
});
auth.authResponseChange - fired when the authResponse changes, so in theory when a user allows the app from the auth dialog this will fire.
from http://developers.facebook.com/docs/reference/javascript/FB.Event.subscribe/
Also, in the code to prompt the user to allow the app:
FB.getLoginStatus(function(response) {
if (response.authResponse) {
// logged in and connected user, someone you know
} else {
// no user session available, someone you dont know
FB.login(function(response) {
if (response.authResponse) {
console.log(reponse);
// here will be all the response details from confirmed app
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: 'email'});
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: tinyMCE alert what you just wrote In the tinyMCE init editor,
How can i in setup do:
ed.onKeyDown.add(function (ed, evt) {
// alert the character you just typed
});
Say if you type "a" a alert should come up with "a"
A: The evt.keyCode property contains the code of the pressed key, so you can do this:
alert(String.fromCharCode(evt.keyCode));
Note, however, that this will also trigger an alert when a special key is pressed (e.g. shift), so you might want to prevent that by checking other properties of the evt object (which is an instance of DOM Event). See the documentation for keyboard event objects at https://developer.mozilla.org/en/DOM/KeyboardEvent.
Edit: Use onKeyPress instead of onKeyDown, as onKeyDown might return incorrect key codes in some browsers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620170",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Pause and Resume Subscription on cold IObservable Using Rx, I desire pause and resume functionality in the following code:
How to implement Pause() and Resume() ?
static IDisposable _subscription;
static void Main(string[] args)
{
Subscribe();
Thread.Sleep(500);
// Second value should not be shown after two seconds:
Pause();
Thread.Sleep(5000);
// Continue and show second value and beyond now:
Resume();
}
static void Subscribe()
{
var list = new List<int> { 1, 2, 3, 4, 5 };
var obs = list.ToObservable();
_subscription = obs.SubscribeOn(Scheduler.NewThread).Subscribe(p =>
{
Console.WriteLine(p.ToString());
Thread.Sleep(2000);
},
err => Console.WriteLine("Error"),
() => Console.WriteLine("Sequence Completed")
);
}
static void Pause()
{
// Pseudocode:
//_subscription.Pause();
}
static void Resume()
{
// Pseudocode:
//_subscription.Resume();
}
Rx Solution?
*
*I believe I could make it work with some kind of Boolean field gating combined with thread locking (Monitor.Wait and Monitor.Pulse)
*But is there an Rx operator or some other reactive shorthand to achieve the same aim?
A: Here it is as an application of IConnectableObservable that I corrected slightly for the newer api (original here):
public static class ObservableHelper {
public static IConnectableObservable<TSource> WhileResumable<TSource>(Func<bool> condition, IObservable<TSource> source) {
var buffer = new Queue<TSource>();
var subscriptionsCount = 0;
var isRunning = System.Reactive.Disposables.Disposable.Create(() => {
lock (buffer)
{
subscriptionsCount--;
}
});
var raw = Observable.Create<TSource>(subscriber => {
lock (buffer)
{
subscriptionsCount++;
if (subscriptionsCount == 1)
{
while (buffer.Count > 0) {
subscriber.OnNext(buffer.Dequeue());
}
Observable.While(() => subscriptionsCount > 0 && condition(), source)
.Subscribe(
v => { if (subscriptionsCount == 0) buffer.Enqueue(v); else subscriber.OnNext(v); },
e => subscriber.OnError(e),
() => { if (subscriptionsCount > 0) subscriber.OnCompleted(); }
);
}
}
return isRunning;
});
return raw.Publish();
}
}
A: Here is my answer. I believe there may be a race condition around pause resume, however this can be mitigated by serializing all activity onto a scheduler. (favor Serializing over synchronizing).
using System;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using Microsoft.Reactive.Testing;
using NUnit.Framework;
namespace StackOverflow.Tests.Q7620182_PauseResume
{
[TestFixture]
public class PauseAndResumeTests
{
[Test]
public void Should_pause_and_resume()
{
//Arrange
var scheduler = new TestScheduler();
var isRunningTrigger = new BehaviorSubject<bool>(true);
Action pause = () => isRunningTrigger.OnNext(false);
Action resume = () => isRunningTrigger.OnNext(true);
var source = scheduler.CreateHotObservable(
ReactiveTest.OnNext(0.1.Seconds(), 1),
ReactiveTest.OnNext(2.0.Seconds(), 2),
ReactiveTest.OnNext(4.0.Seconds(), 3),
ReactiveTest.OnNext(6.0.Seconds(), 4),
ReactiveTest.OnNext(8.0.Seconds(), 5));
scheduler.Schedule(TimeSpan.FromSeconds(0.5), () => { pause(); });
scheduler.Schedule(TimeSpan.FromSeconds(5.0), () => { resume(); });
//Act
var sut = Observable.Create<IObservable<int>>(o =>
{
var current = source.Replay();
var connection = new SerialDisposable();
connection.Disposable = current.Connect();
return isRunningTrigger
.DistinctUntilChanged()
.Select(isRunning =>
{
if (isRunning)
{
//Return the current replayed values.
return current;
}
else
{
//Disconnect and replace current.
current = source.Replay();
connection.Disposable = current.Connect();
//yield silence until the next time we resume.
return Observable.Never<int>();
}
})
.Subscribe(o);
}).Switch();
var observer = scheduler.CreateObserver<int>();
using (sut.Subscribe(observer))
{
scheduler.Start();
}
//Assert
var expected = new[]
{
ReactiveTest.OnNext(0.1.Seconds(), 1),
ReactiveTest.OnNext(5.0.Seconds(), 2),
ReactiveTest.OnNext(5.0.Seconds(), 3),
ReactiveTest.OnNext(6.0.Seconds(), 4),
ReactiveTest.OnNext(8.0.Seconds(), 5)
};
CollectionAssert.AreEqual(expected, observer.Messages);
}
}
}
A: Here's a reasonably simple Rx way to do what you want. I've created an extension method called Pausable that takes a source observable and a second observable of boolean that pauses or resumes the observable.
public static IObservable<T> Pausable<T>(
this IObservable<T> source,
IObservable<bool> pauser)
{
return Observable.Create<T>(o =>
{
var paused = new SerialDisposable();
var subscription = Observable.Publish(source, ps =>
{
var values = new ReplaySubject<T>();
Func<bool, IObservable<T>> switcher = b =>
{
if (b)
{
values.Dispose();
values = new ReplaySubject<T>();
paused.Disposable = ps.Subscribe(values);
return Observable.Empty<T>();
}
else
{
return values.Concat(ps);
}
};
return pauser.StartWith(false).DistinctUntilChanged()
.Select(p => switcher(p))
.Switch();
}).Subscribe(o);
return new CompositeDisposable(subscription, paused);
});
}
It can be used like this:
var xs = Observable.Generate(
0,
x => x < 100,
x => x + 1,
x => x,
x => TimeSpan.FromSeconds(0.1));
var bs = new Subject<bool>();
var pxs = xs.Pausable(bs);
pxs.Subscribe(x => { /* Do stuff */ });
Thread.Sleep(500);
bs.OnNext(true);
Thread.Sleep(5000);
bs.OnNext(false);
Thread.Sleep(500);
bs.OnNext(true);
Thread.Sleep(5000);
bs.OnNext(false);
It should be fairly easy for you to put this in your code with the Pause & Resume methods.
A: It just works:
class SimpleWaitPulse
{
static readonly object _locker = new object();
static bool _go;
static void Main()
{ // The new thread will block
new Thread (Work).Start(); // because _go==false.
Console.ReadLine(); // Wait for user to hit Enter
lock (_locker) // Let's now wake up the thread by
{ // setting _go=true and pulsing.
_go = true;
Monitor.Pulse (_locker);
}
}
static void Work()
{
lock (_locker)
while (!_go)
Monitor.Wait (_locker); // Lock is released while we’re waiting
Console.WriteLine ("Woken!!!");
}
}
Please, see How to Use Wait and Pulse for more details
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Get actual date into seconds on iOS SDK I'm making an app where I need to get the actual date ([NSDate date]) into seconds since 1970 (timeIntervalSince1970). But I don't manage to get it working, how should it be done?
A: NSTimeInterval seconds = [[NSDate date] timeIntervalSince1970]
Note that NSTimeInterval is actually a double value, not an object.
A: double intrval=[[NSDate date] timeIntervalSince1970];
-(NSDate*)dateFromDouble:(double) intrval{
return [NSDate dateWithTimeIntervalSince1970:intrval];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Activity variable increment while calling again I have 2 activity
*
*Tranning Activity
*Question Activity
i have set one integer variable in question activity like :: int a=0;at the end of activity i jump from Question part to Training part.i call from question part to training part 5 time.But confusion is that how can i increment "a" variable each time while Question part call?
Is it possible by this?
if(yes)
{
how ?
}
else if(no)
{
any other Option are there? how?
}
Update ::
confusion ?
let me explain run project >> tranning is start >> question is start and variable a is 0 >> tranning is start >>question is start and variable a is 1 >> tranning is start >> question is start and variable a is 2 like that .... a is 5
A: If it should be incremented only for the current run, you can use a static field, and increment it in onCreate(), or onResume(). if it should be incremented even when the application is restarted, you might want to use SharedPreferences.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ZF disable optgroup lable in select To show a list of categories, I use the 'select' in a form.
I insert the categories from the database.
When I look through the select list I get something like this:
0
art
The optgroup has a label with a number value. I want to remove the label
from it so I have just in the list:
art
Without the 0 from the optgroup label.
Thanks in advice.
Nicky
A: *
*This is a parent element - you can't have that not to be visible and all children visible - doesn't work
*You would compromise the use of the optgroup
Conclusion:
Just don't use optgroups if you don't want them...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How should I resolve my appspot backup failure? I'm trying to make a backup but it won't:
2011-10-01 09:22:43.706 /remote_api 302 5ms 0cpu_ms 0kb
213.89.134.0 - - [01/Oct/2011:05:22:43 -0700] "GET /remote_api HTTP/1.1" 302 0 - - "montaoproject.appspot.com" ms=6 cpu_ms=0 api_cpu_ms=0 cpm_usd=0.000032
$ python ./appcfg.py download_data --application=montaoproject --url=http://montaoproject.appspot.com/remote_api --filename=montao.data
Downloading data records.
[INFO ] Logging to bulkloader-log-20111001.122234
[INFO ] Throttling transfers:
[INFO ] Bandwidth: 250000 bytes/second
[INFO ] HTTP connections: 8/second
[INFO ] Entities inserted/fetched/modified: 20/second
[INFO ] Batch Size: 10
[INFO ] Opening database: bulkloader-progress-20111001.122234.sql3
[INFO ] Opening database: bulkloader-results-20111001.122234.sql3
[INFO ] Connecting to montaoproject.appspot.com/remote_api
Please enter login credentials for montaoproject.appspot.com
Email: niklasro
Password for niklasro:
[INFO ] Authentication Failed
app.yaml:
- url: /remote_api
script: remote_api.py
remote_api.py:
from google.appengine.ext.remote_api import handler
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
import re
MY_SECRET_KEY = 'thetopsecret'
cookie_re = re.compile('^"([^:]+):.*"$')
class ApiCallHandler(handler.ApiCallHandler):
def CheckIsAdmin(self):
login_cookie = self.request.cookies.get('dev_appserver_login', '')
match = cookie_re.search(login_cookie)
if (match and match.group(1) == MY_SECRET_KEY
and 'X-appcfg-api-version' in self.request.headers):
return True
else:
self.redirect('/_ah/login')
return False
application = webapp.WSGIApplication([('.*', ApiCallHandler)])
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
Update
The server status is 302 and the method in remote_api.pyis not reached:
2011-11-08 09:02:40.214 /remote_api?rtok=935015419683 302 12ms 0kb
213.89.134.0 - - [08/Nov/2011:03:02:40 -0800] "GET /remote_api?rtok=935015419683 HTTP/1.1" 302 0 - - "montaoproject.appspot.com" ms=13 cpu_ms=0 api_cpu_ms=0 cpm_usd=0.000026
A: When using this approach to get remote API to work with open ID (from http://blog.notdot.net/2010/06/Using-remote-api-with-OpenID-authentication), I think you need to specify the secret key (ie 'thetopsecret') as the email when prompted (and then just hit enter when prompted for the password).
A: Use correct credentials. niklasro is not your email address.
A: If your app is using the High-replication datastore then your App-ID will be 's~montaoproject' (and probably needs to be in quotes on the command line? It certainly won't hurt to do so...).
A: [INFO ] Authentication Failed
It is nothing to do with GAE core , Authentication failed => either your login request failed or you are not providing the right credentials .
You are working behind proxy ? https is trouble behind squid proxy .
A: MY_SECRET_KEY corresponds with your login, not your password. You shouldn't need to actually enter a password (just hit return). So when you authenticate use:
Email: thetopsecret
Password for thetopsecret: (nothing)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620200",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Setting first field in a combo box to null I have a databound ComboBox on my form. Is there any way that I can make the first field blank.
I can do this with a DropDownList in the HTML part of .Net but is there a way to do it for a ComboBox?
Thanks
A: This is the code I used to overcome the problem...
ComboBox1.SelectedValue = -1
A: ComboBox1.SelectedValue = -1
didn't work for me but this did:
ComboBox1.SelectedIndex = -1
I would have though -1 would have been an invalid index value, but obviously not.
Kristian
A: You can insert a blank entry into data source.
Public Class Data
Public Property No() As Integer
Public Property Name() As String
End Class
and List(of Data),
Dim mlist As New List(Of Data)() From
{
New Data() With {.Name = "", .No = 0},
New Data() With {.Name = "One", .No = 1},
New Data() With {.Name = "Two", .No = 2}
}
ComboBox1.DataSource = mlist
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "No"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use shared location of assemblies by multiple applications I've just took over a bunch of windows services (on server no. 1) and web applications (on server no.2) on two servers. All those application use a great deal of the same core libraries. I would like to start fixing that mess and make my life easier. This is the first thing that popped into my head:
There are many libraries there and I'm getting anoyed when I have to:
*
*update web/windows service application in all locations
*remember to update all applications
Those libraries are not strongly named, and also are preety often recompiled, so I would like to avoid using GAC. Is there any other way to store common assemblies in one directory like c:\libs\services.core (on server no.1, and do the same on server no.2) and force application to look for missing libraries in that location?
Thanks
A: Unfortunately, GAC is meant exactly for this scenario even if you want to avoid it. If your assemblies will be very fluent and will require constant updates, this means that they are better of in their private project folders or else it will be impossible to keep track of breaking changes across all projects which depend on the shared assemblies.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: In the Unix/Linux shell programming:the difference between > and >& int main(void)
{
char buf[] = "standard err, output.\n";
printf("standard output.\n");
if (write(STDERR_FILENO,buf, 22) != 22)
printf("write err!\n");
exit(0);
}
Compile using:
gcc -Wall text.c
Then running in the shell:
*
*./a.out > outfile 2 >& 1
Result:outfile´s content are:
standard err, output.
standard output.
*./a.out 2 >& 1 >outfile
Result:
This first prints to the terminal: standard err, output.
and the content of outfile are: standard output.
Questions:
*
*I want to ask the difference between 2 >& fd and 2 > file.
Are they all equal to the function dup()?
*Another question: why are the contents of outfile:
standard err, output.
standard output.
I expected the content of outfile to be:
standard output.
standard err, output
A: Actually, in bash, >& is quite similar to dup2. That is, the file descriptor to which it is applied will refer to the same file as the descriptor to the right. So:
$ ./a.out > outfile 2>& 1
It will redirect stdout(1) to the file outfile and, after that, will dup2 stderr(2) to refer to the same file as stdout(1). That is, both stdout and stderr are being redirected to the file.
$ ./a.out 2>& 1 >outfile
It will redirect stderr(2) to refer to the same file as stdout(1), that is, the console, and after that, will redirect stdout(1) to refer to the file outfile. That is, stderr will output to the console and stdout to the file.
And that's exactly what you are getting.
A: Paradigm Mixing
While there are reasons to do all of these things deliberately, as a learning experience it is probably going to be confusing to mix operations over what I might call "domain boundaries".
Buffered vs non-buffered I/O
The printf() is buffered, the write() is a direct system call. The write happens immediately no matter what, the printf will be (usually) buffered line-by-line when the output is a terminal and block-by-block when the output is a real file. In the file-output case (redirection) your actual printf output will happen only when you return from main() or in some other fashion call exit(3), unless you printf a whole bunch of stuff.
Historic csh redirection vs bash redirection
The now-forgotten (but typically still in a default install) csh that Bill Joy wrote at UCB while a grad student had a few nice features that have been imported into kitchen-sink shells that OR-together every shell feature ever thought of. Yes, I'm talking about bash here. So, in csh, the way to redirect both standard output and standard error was simply to say cmd >& file which was really more civilized that the bag-of-tools approach that the "official" Bourne shell provided. But the Bourne syntax had its good points elsewhere and in any case survived as the dominant paradigm.
But the bash "native" redirection features are somewhat complex and I wouldn't try to summarize them in a SO answer, although others seem to have made a good start. In any case you are using real bash redirection in one test and the legacy-csh syntax that bash also supports in another, and with a program that itself mixes paradigms. The main issue from the shell's point of view is that the order of redirection is quite important in the bash-style syntax while the csh-style syntax simply specifies the end result.
A: The 2>&1 part makes the shell do something like that:
dup2(1, 2);
This makes fd 2 a "copy" of fd 1.
The 2> file is interpreted as
fd = open(file, ...);
dup2(fd, 2);
which opens a file and puts the filedescriptor into slot 2.
A: There are several loosely related issues here.
Style comment: I recommend using 2>&1 without spaces. I wasn't even aware that the spaced-out version works (I suspect it didn't in Bourne shell in the mid-80s) and the compressed version is the orthodox way of writing it.
The file-descriptor I/O redirection notations are not all available in the C shell and derivatives; they are avialable in Bourne shell and its derivatives (Korn shell, POSIX shell, Bash, ...).
The difference between >file or 2>file and 2>&1 is what the shell has to do. The first two arrange for output written to a file descriptor (1 in the first case, aka standard output; 2 in the second case, aka standard error) to go to the named file. This means that anything written by the program to standard output goes to file instead. The third notation arranges for 2 (standard error) to go to the same file descriptor as 1 (standard output); anything written to standard error goes to the same file as standard output. It is trivially implemented using dup2(). However, the standard error stream in the program will have its own buffer and the standard output stream in the program will have its own buffer, so the interleaving of the output is not completely determinate if the output goes to a file.
You run the command two different ways, and (not surprisingly) get two different results.
*
*./a.out > outfile 2>&1
I/O redirections are processed left to right. The first one sends standard output to outfile. The second sends standard error to the same place as standard output, so it goes to outfile too.
*./a.out 2>&1 >outfile
The first redirection sends standard error to the place where standard output is going, which is currently the terminal. The second redirection then sends standard output to the file (but leaves standard error going to the terminal).
The program uses the printf() function and the write() system call. When the printf() function is used, it buffers its output. If the output is going to a terminal, then it is normally 'line buffered', so output appears when a newline is added to the buffer. However, when the output is going to a file, it is 'fully buffered' and output does not appear until the file stream is flushed or closed or the buffer fills. Note that stderr is not fully buffered, so output written to it appears immediately.
If you run your program without any I/O redirection, you will see:
standard output.
standard err, output
By contrast, the write() system call immediately transfers data to the output file descriptor. In the example, you write to standard error, and what you write will appear immediately. The same would have happened if you had used fprintf(stderr, ...). However, suppose you modified the program to write to STDOUT_FILENO; then when the output is to a file, the output would appear in the order:
standard err, output
standard output.
because the write() is unbuffered while the printf() is buffered.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Writing JUNIT for servlet? I am using glassfish application server. I need to write the junits for some servlet. My question here is how can i create simulated container, mock request and response with core java libraries or i need to use some kind of tool here ?Any pointers would be helpful?
A: As hvgotcodes notes, it's entirely possible to write JUnit tests for servlets. But I'd advise you to think carefully before you do so.
Servlets are HTTP request listeners; they run in a servlet container, respond to any HTTP requests that come their way, and package up results to send back. That's all they should be doing, in my opinion. The real work is best left to other objects that the servlet can marshal. These can be POJOs, most likely interface-based, which will mean easier testing without having to start up a servlet container to run the test. If you decide that you need the same functionality in a non-web-based setting, it's easy to do because it already resides in objects other than a servlet.
I'd reconsider the design. Putting a lot of functionality in a servlet might be a bad decision.
A: 1) Its not a bad idea to abstract your application logic into objects that are called by the servlet, so you can test your business logic separate from your servlet interactions.
2) Spring provides some mock classes for tests, including requests and responses. Even if you are not using Spring, you can still use those classes just for tests.
A: You may find Arquillian from JBoss interesting - http://community.jboss.org/wiki/Arquillian.
Test in-container!
Arquillian provides a easy mechanism to test your application code inside a remote or embedded container or by interacting as a client of the container.
Mission Statement
The mission of the Arquillian project is to provide a simple test harness that developers can use to produce a broad range of integration tests for their Java applications (most likely enterprise applications). A test case may be executed within the container, deployed alongside the code under test, or by coordinating with the container, acting as a client to the deployed code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: postback for one row in a gridview I put the gridview inside an UpdatePanel. the gridview contains number of columns:
<UpdatePanel>
<GridView>
<asp:TemplateField HeaderText="View"> // column1
<asp:TemplateField HeaderText="View"> // column2
<asp:TemplateField HeaderText="View"> // column3
<GridView>
</UpdatePanel>
At the moment, If I click on the buttons of the 3 columns, they are AsyncPostBackTriggers. Would it be possible to make one the of the columns, for example: columm1 with a button that is PostbackTrigger?
Thanks in advance.
A: You can utilize a ScriptManager for registering button as postback control. Place the code below into Page_Load method after gridView binding instructions:
var scriptManager = ScriptManager.GetCurrent(this);
foreach (GridViewRow row in GridView1.Rows)
{
var syncPostBackButton = row.FindControl("ButtonID") as Button;
if(syncPostBackButton != null)
{
scriptManager.RegisterPostBackControl(syncPostBackButton);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: OpenGL mipmapping: level outside the range? I'm going deeper on OpenGL texture mipmapping.
I noticed in the specification that mipmap levels less than zero and greater than log2(maxSize) + 1 are allowed.
Effectively TexImage2D doesn't specify errors for level parameter. So... Probably those mipmaps are not accessed automatically using the standard texture access routines...
How could be effectively used this feature?
A: For the negative case, the glTexImage2D's man page says:
GL_INVALID_VALUE is generated if level is less than 0.
For the greater than log2(maxsize) case, the specification says what happens to those levels in Raterization/Texturing/Texture Completeness. The short of it is that, yes, they are ignored.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I get iphone device type? I want to get iphone device type if it is iphone 2 or 3G or 4 in xcode 4.0.
Is there any way to get it?
If it is, please tell me.
A: Caleb is right, you shouldn't check for device type, but for functionality. For example, you can check whether the device supports multitasking like so:
UIDevice *device = [UIDevice currentDevice];
if ([device respondsToSelector:@selector(isMultitaskingSupported)] && [device isMultitaskingSupported]) {
// ...code to be executed if multitasking is supported.
// respondsToSelector: is very useful
}
If you must, you can check the iOS version, but know this is not a substitute for checking whether an object respondsToSelector:.
#define IOS4_0 40000
// You'd probably want to put this in a convenient method
NSArray *versions = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
NSInteger major = [[versions objectAtIndex:0] intValue];
NSInteger minor = [[versions objectAtIndex:1] intValue];
NSInteger version = major * 10000 + minor * 100;
if (version >= IOS4_0) {
// ...code to be executed for iOS4.0+
}
As far as I know, there is no documented way to check the device model.
A: I have added a static method to my project to check the device type: iPad, iPhone4(or less), and iPhone5 to handle the different screen sizes.
+ (DeviceType) currentDeviceType
{
DeviceType device = DEVICE_TYPE_IPAD ;
if( [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone )
{
if( [[UIScreen mainScreen] bounds].size.height >= 568 || [[UIScreen mainScreen] bounds].size.width >= 568 )
{
device = DEVICE_TYPE_IPHONE5 ;
}
else
{
device = DEVICE_TYPE_IPHONE4 ;
}
}
return device ;
}
You can also use the type UIUserInterfaceIdiomPad.
From what I can tell, the iPod and iPhone are intended to be treated equally. But if you need to determine if it is an iPod, check to see if it makes phone calls.
A: Check this out https://github.com/erica/uidevice-extension/
[[UIDevice currentDevice] platformString] //@"iPhone 4"
A: This post helped me to distinguish between iPhone/iPad types:
You can get the model type (iPhone, iPad, iPod) as shown above:
[[UIDevice currentDevice] model]
And to further specify you can import and find the specific model type returned as char array by the following code:
struct utsname u;
uname(&u);
char *type = u.machine;
And convert it to NSString by:
NSString *strType = [NSString stringWithFormat:@"%s", type];
A: I found some new algorithm to get device type and iOS version.
#include <sys/sysctl.h>
#include <sys/utsname.h>
- (NSString *) platformString{
NSLog(@"[UIDevice currentDevice].model: %@",[UIDevice currentDevice].model);
NSLog(@"[UIDevice currentDevice].description: %@",[UIDevice currentDevice].description);
NSLog(@"[UIDevice currentDevice].localizedModel: %@",[UIDevice currentDevice].localizedModel);
NSLog(@"[UIDevice currentDevice].name: %@",[UIDevice currentDevice].name);
NSLog(@"[UIDevice currentDevice].systemVersion: %@",[UIDevice currentDevice].systemVersion);
NSLog(@"[UIDevice currentDevice].systemName: %@",[UIDevice currentDevice].systemName);
NSLog(@"[UIDevice currentDevice].batteryLevel: %f",[UIDevice currentDevice].batteryLevel);
struct utsname systemInfo;
uname(&systemInfo);
NSLog(@"[NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding]: %@",[NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding]);
NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 1G";
if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4 CDMA";
if ([platform isEqualToString:@"iPhone3,3"]) return @"Verizon iPhone 4";
if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5 (GSM)";
if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5 (GSM+CDMA)";
if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c (GSM)";
if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c (GSM+CDMA)";
if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s (GSM)";
if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s (GSM+CDMA)";
if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
if ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
if ([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
if ([platform isEqualToString:@"iPod5,1"]) return @"iPod Touch 5G";
if ([platform isEqualToString:@"iPad1,1"]) return @"iPad";
if ([platform isEqualToString:@"iPad2,1"]) return @"iPad 2 (WiFi)";
if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2 (Cellular)";
if ([platform isEqualToString:@"iPad2,3"]) return @"iPad 2 (Cellular)";
if ([platform isEqualToString:@"iPad2,4"]) return @"iPad 2 (WiFi)";
if ([platform isEqualToString:@"iPad2,5"]) return @"iPad Mini (WiFi)";
if ([platform isEqualToString:@"iPad2,6"]) return @"iPad Mini (Cellular)";
if ([platform isEqualToString:@"iPad2,7"]) return @"iPad Mini (Cellular)";
if ([platform isEqualToString:@"iPad3,1"]) return @"iPad 3 (WiFi)";
if ([platform isEqualToString:@"iPad3,2"]) return @"iPad 3 (Cellular)";
if ([platform isEqualToString:@"iPad3,3"]) return @"iPad 3 (Cellular)";
if ([platform isEqualToString:@"iPad3,4"]) return @"iPad 4 (WiFi)";
if ([platform isEqualToString:@"iPad3,5"]) return @"iPad 4 (Cellular)";
if ([platform isEqualToString:@"iPad3,6"]) return @"iPad 4 (Cellular)";
if ([platform isEqualToString:@"iPad4,1"]) return @"iPad Air (WiFi)";
if ([platform isEqualToString:@"iPad4,2"]) return @"iPad Air (Cellular)";
if ([platform isEqualToString:@"i386"]) return @"Simulator";
if ([platform isEqualToString:@"x86_64"]) return @"Simulator";
return @"Unknown";
}
A: Actually, the UIDevice class does not have a method platformString. With undocumented methods your app will get rejected by Apple.
[[UIDevice currentDevice] model] // e.g. "iPod touch"
will do the trick.
A: The usual advice is to not worry about what kind of device you're running on, but instead to test for the features you need. If you look at the device type, you're bound to make assumptions that are incorrect. The versions of each model sold in different markets may vary, for example, and new devices may come along that report the same type but have different features. So, test for features rather than model.
A: You could define some macros extending off of @csb 's answer to this thread.
#define IS_IPHONE4 ([[UIScreen mainScreen] bounds].size.width == 480 || [[UIScreen mainScreen] bounds].size.height == 480)
#define IS_IPHONE5 ([[UIScreen mainScreen] bounds].size.width == 568 || [[UIScreen mainScreen] bounds].size.height == 568)
#define IS_IPAD ([[UIScreen mainScreen] bounds].size.width == 768 || [[UIScreen mainScreen] bounds].size.height == 768)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How do I convert a hex color in an NSString to three separate rgb ints in Objective C? I may be making something incredibly simple incredibly complicated, but nothing I've tried so far seems to work.
I have NSStrings like @"BD8F60" and I would like to turn them into ints like: r = 189, g = 143, b = 96.
Have found ways to convert hex values that are already ints into rgb ints, but am stuck on how to change the NSString with the letters in it into an int where the letters have been converted to their numerical counterparts. Apologize in advance if this is incredibly basic--I'm still learning this stuff at an incredibly basic level.
A: This method turns the given hex-string into a UIColor:
- (UIColor *)colorWithHexString:(NSString *)stringToConvert {
NSScanner *scanner = [NSScanner scannerWithString:stringToConvert];
unsigned hex;
if (![scanner scanHexInt:&hex]) return nil;
int r = (hex >> 16) & 0xFF;
int g = (hex >> 8) & 0xFF;
int b = (hex) & 0xFF;
return [UIColor colorWithRed:r / 255.0f
green:g / 255.0f
blue:b / 255.0f
alpha:1.0f];
}
A: You need to parse the NSString and interpret the hex values.
You may do this in multiple ways, one being using an NSScanner
NSScanner* scanner = [NSScanner scannerWithString:@"BD8F60"];
int hex;
if ([scanner scanHexInt:&hex]) {
// Parsing successful. We have a big int representing the 0xBD8F60 value
int r = (hex >> 16) & 0xFF; // get the first byte
int g = (hex >> 8) & 0xFF; // get the middle byte
int b = (hex ) & 0xFF; // get the last byte
} else {
NSLog(@"Parsing error: no hex value found in string");
}
There are some other possibilities like splitting the string in 3 and scan the values separately (instead of doing bitwise shift and masking) but the idea remains the same.
Note: as scanHexInt: documentation explains, this also works if your string is prefixed with 0x like @"0xBD8F60". Does not automatically work with strings prefixed by a hash like @"#BD8F60". Use a substring in this case.
A: a category on UIColor that also deals with alpha values rrggbbaa and short forms as rgb or rgba.
use it it like
UIColor *color = [UIColor colorFromHexString:@"#998997FF"]; //#RRGGBBAA
or
UIColor *color = [UIColor colorFromHexString:@"998997FF"]; //RRGGBBAA
or
UIColor *color = [UIColor colorFromHexString:@"0x998997FF"];// 0xRRGGBBAA
or
UIColor *color = [UIColor colorFromHexString:@"#999"]; // #RGB -> #RRGGBB
or
UIColor *color = [UIColor colorFromHexString:@"#9acd"]; // #RGBA -> #RRGGBBAA
@implementation UIColor (Creation)
+(UIColor *)_colorFromHex:(NSUInteger)hexInt
{
int r,g,b,a;
r = (hexInt >> 030) & 0xFF;
g = (hexInt >> 020) & 0xFF;
b = (hexInt >> 010) & 0xFF;
a = hexInt & 0xFF;
return [UIColor colorWithRed:r / 255.0f
green:g / 255.0f
blue:b / 255.0f
alpha:a / 255.0f];
}
+(UIColor *)colorFromHexString:(NSString *)hexString
{
hexString = [hexString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if ([hexString hasPrefix:@"#"])
hexString = [hexString substringFromIndex:1];
else if([hexString hasPrefix:@"0x"])
hexString = [hexString substringFromIndex:2];
int l = [hexString length];
if ((l!=3) && (l!=4) && (l!=6) && (l!=8))
return nil;
if ([hexString length] > 2 && [hexString length]< 5) {
NSMutableString *newHexString = [[NSMutableString alloc] initWithCapacity:[hexString length]*2];
[hexString enumerateSubstringsInRange:NSMakeRange(0, [hexString length])
options:NSStringEnumerationByComposedCharacterSequences
usingBlock:^(NSString *substring,
NSRange substringRange,
NSRange enclosingRange,
BOOL *stop)
{
[newHexString appendFormat:@"%@%@", substring, substring];
}];
hexString = newHexString;
}
if ([hexString length] == 6)
hexString = [hexString stringByAppendingString:@"ff"];
NSScanner *scanner = [NSScanner scannerWithString:hexString];
unsigned hexNum;
if (![scanner scanHexInt:&hexNum])
return nil;
return [self _colorFromHex:hexNum];
}
@end
use it in swift:
*
*add #include "UIColor+Creation.h" to Bridging Header
*use
UIColor(fromHexString:"62AF3C")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Lazarus error - how to store result of integer in textbox? I'm trying out a very simple program in LAZARUS to multiply two text box values and store the result in a third one. This line is what I'm using.
txtA.Text = IntToStr( StrToInt(txtA.Text ) + StrToInt(txtB.Text) );
Unfortunately I get an error stating it's illegal.
Is this a fault on my part or a bug in Pascal?
Thanks for any tips!
A: The assigments in Pascal uses :=
try this
txtA.Text := IntToStr( StrToInt(txtA.Text ) + StrToInt(txtB.Text) );
A: I also tend to use IntToStr() also, but you also have the option of using format() - which is preferred for strings that might be translated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Rails Geocoder - Still learning I'm sure it's a simply issue due to me not fully understanding how bits fit together in Rails...
I've followed the rails cast but I'm having trouble implementing it into my app (I've had it working stand-alone).
The error I get is
undefined method `nearbys'
Here's what I've got:
user.rb
geocoded_by :full_address
after_validation :geocode
def full_address
[address1, address2, address3, city, country, postcode].compact.join(', ')
end
users_controller.rb
def index
@title = "All users"
if params[:search].present?
@users = User.near(params[:search], 50, :order => :distance)
else
@users = User.all
end
end
index.html.erb
<h3>Nearby locations</h3>
<ul>
<% for user in @users.nearbys(10) %>
<li><%= link_to user.address1, user %> (<%= user.distance.round(2) %> miles)</li>
<% end %>
</ul>
_sidebar.html.erb
<%= form_tag users_path, :method => :get do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search Near", :name => nil %>
</p>
<% end %>
Thanks
If I comment out the .nearbys
<% for user in @users#.nearbys(10) %>
<li><%= link_to user.latitude, user %> (<%= user.distance.round(2) %> miles)</li>
<% end %>
The search works. Could this be a problem with the install of geocoder?
A: The function nearbys is a function on your model, not on a collection of models. The variable @users contains a collection of User models. You need to call the function on a single model instance, for example for each user in @users.
As an example, but not sure if you really want this:
<% @users.each do |user| %>
<% user.nearbys(10).each do |near_user| %>
<li><%= link_to near_user.latitude, near_user %> (<%= near_user.distance.round(2) %> miles)</li>
<% end %>
<% end %>
(Note that I also changed the for user in @users to use @users.each do |user|, which is more "Rubyish".)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Invalid label WCF Rest Service Jsonp response I'm trying to get json from wcf rest service and I getting json, but with *invalid label*
, I've tried the callback wrapper but still getting the same error message
here is the code
<html>
<head>
<script src="js/jquery-1.5.min.js"></script>
<script type="text/javascript">
var JSONCall = function(_url,callback)
{
$.ajax({
type: "GET",
cache: false,
url: _url,
data: '{}',
contentType: "application/javascript",
dataType: "jsonp",
success: function(result) {
alert('sfss');
//console.log(result);
callback(result);
},
error: function (data, status, e)
{
alert("EError:"+e);
}
});
};
/*GET ALL DATA*/
//invalid label to Rest Service jsonp
function getAllData()
{
JSONCall('http://svc.somedomain.com/RestServiceImpl.svc/?callback=?',function(data){
console.log(data);
});
}
</script>
</head>
<body>
<input type="button" value="Get Json" onclick="getAllData()" />
</body>
</html>
How can I get proper response, thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Best way to implement busy loop? What is the best way to implement the busy loop ? correct me if i am wrong ?
while (1); // obviously eats CPU.
while (1) { sleep(100); } // Not sure if it is the correct way ?
A: To do an infinite wait, for a signal (what else) there is the pause() system call. You'll have to put it in a loop, as it returns (always with -1 and errno set to EINTR) every time a signal is delivered:
while (1)
pause();
As a curious note, this is, AFAIK the only POSIX function documented to always fail.
UPDATE: Thanks to dmckee, in the comments below, sigsuspend() also fails always. It does just the same as pause(), but it is more signal-friendly. The difference is that it has parameters, so it can fail with EFAULT in addition to EINTR.
A: Busy loop is loop that never blocks and continuously checks some condition. Small sleep is good enough to avoid 100% cpu usage.
The best way to implement busy wait is to not implement it. Instead of it you can use blocking calls or callbacks.
A: Linux has had the (POSIX 1.g) pselect for some time now. If you are using signal handlers or user-defined signals, I think this is worth investigating. It also addresses some subtle race conditions that manifest in other approaches.
I know you mentioned the 'busy loop', but I think a 'blocking loop' is what you're after.
A: How to prevent it from being optimized away with data dependencies
First of course, you should only use busy loops if you have very good reason to not use non-busy ones, which are generally more efficient, see: https://codereview.stackexchange.com/questions/42506/using-a-for-loop-or-sleeping-to-wait-for-short-intervals-of-time
Now, focusing only on busy loops, if you just write something like:
while (1);
or:
for (unsigned i = 0; i < 100; i++);
then both of those can be optimized away as mentioned at: Are compilers allowed to eliminate infinite loops?
For this reason, as explained in detail at: How to prevent GCC from optimizing out a busy wait loop? I would write them as:
while (1) asm("");
or:
for (unsigned i = 0; i < 100; i++) {
__asm__ __volatile__ ("" : "+g" (i) : :);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: OpenGL Extensions in Qt 4 it's possible enable/use OpenGL (specific version) in Qt 4 (on Desktop) or I have to use glew, etc?
A: Rather than Glew you can include gl3.h, it's probably the simplest and most pain free way and works with compatibility mode as well as core. It's also well worth checking out GLXX it's a newer lib written in C++ so its more object orientated and provides handy functions for querying capabilities and so on.
You could look at manually binding just the extensions you need, possibly making your own Qt classes.
Other alternatives are Glee (A bit out of date now, only up to OpenGL 3.0) and gl3w (a script to generate header files for you, but only seems to support OpenGL 3/4 core).
Also if you want a object orientated library for OpenGL itself OGLplus looks good, doesn't do extensions though.
A: Qt has wrappers for some extentions like QPixelBuffers otherwise you can just use glew to enable the extentions
A: My way to do that (Windows)... You need www.opengl.org/registry/api/glext.h
I'm using this python script to generate glex.h (p_glext.h) and glex.cpp from glext.h
p_glext.h is copy of glext.h without prototypes.
//glex.h
#ifndef GLEX_H
#define GLEX_H
#include "p_glext.h"
extern void glexInit();
extern PFNGLBLENDCOLORPROC glBlendColor;
extern PFNGLBLENDEQUATIONPROC glBlendEquation;
extern PFNGLDRAWRANGEELEMENTSPROC glDrawRangeElements;
...
//glex.cpp
...
void glexInit() {
glBlendColor = (PFNGLBLENDCOLORPROC)wglGetProcAddress("glBlendColor");
glBlendEquation = (PFNGLBLENDEQUATIONPROC)wglGetProcAddress("glBlendEquation");
glDrawRangeElements = (PFNGLDRAWRANGEELEMENTSPROC)wglGetProcAddress("glDrawRangeElements");
...
}
that's simple enough to me
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Hibernate search and JPA with JTA transaction I want to use the Hibernate Search full text search capabilities. I have a simple Java EE application. I annotated the entity classes and here is my persistence.xml:
<persistence-unit name="library">
<jta-data-source>jdbc/webrarydb</jta-data-source>
<class>net.hcpeter.webrary.entities.Author</class>
<class>net.hcpeter.webrary.entities.Book</class>
<class>net.hcpeter.webrary.entities.Request</class>
<class>net.hcpeter.webrary.entities.User</class>
<properties>
<property name="hibernate.search.default.directory_provider" value="org.hibernate.search.store.FSDirectoryProvider"/>
<property name="hibernate.search.indexing_strategy" value="manual"/>
<property name="hibernate.search.default.indexBase" value="/Users/hcpeter/Documents/workspace/indexes"/>
<property name="hibernate.current_session_context_class" value="org.hibernate.context.JTASessionContext"/>
</properties>
</persistence-unit>
And I try to search this way:
EntityManager em = authorFacade.getEntityManager();
FullTextEntityManager ftem = org.hibernate.search.jpa.Search.getFullTextEntityManager(em);
ftem.getTransaction().begin();
QueryBuilder qb = ftem.getSearchFactory().buildQueryBuilder().forEntity(Author.class).get();
org.apache.lucene.search.Query query = qb.keyword().onFields("firsName", "lastName").matching("Author#1").createQuery();
javax.persistence.Query persistenceQuery = ftem.createFullTextQuery(query, Author.class);
List<Author> result = persistenceQuery.getResultList();
em.getTransaction().commit();
em.close();
for (Author author : result) {
System.out.println(author.getLastName() + " " + author.getFirstName());
}
return result;
Then I gave Cannot use an EntityTransaction while using JTA.
So my question is how can I use hibernate Search with JTA?
A: You have jta-data-source configured (contrast to non-jta-data-source). So most likely authorFacade.getEntityManager() returns EntityManager that uses JTA-transactions. Now you have entity manager which plays with JTA transactions in your hand. You pass it as argument to getFullTextEntityManager. Likely ftem.getTransaction().begin()
just passes call to your original (JTA) EntityManager. Then you are in problems, because getTransaction is supposed to be used only when you use application managed transactions, and one EntityManager will not play with two types of transactions.
Your options are:
*
*If you are happy with JTA transactions, just use them as you use
them elsewhere. I cannot see anything special with using
them with Hibernate Search. If you simply don't know JTA
transactions (and do not want to learn them now) and want about same
transaction behavior as in your code now, annotate bean method with
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) and
remove transaction handling from your code.
*Configure non-jta-data-source and use it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: cannot create any C++ project I have Visual Studio 2010 Ultimate on Windows 7 Enterprise running on a x86 box. I cannot create any C++ project from VS although I can create C# project. On the new project dialog I press OK button and nothing happens. I don't get any error but no solution or project is created either. Not sure if it helps but I log in as Administrator. Any ideas?
A: Did you check the thing called C++ runtimes which is required by VS to run properly?
I guess the idea to reinstall is good.
This will even repair some missing or corrupt which may have been accidentally deleted or corrupted.
A: Most probably you did not check the C++ language option during installation. If you re-run the Visual Studio installer and check the C++ language option (maybe choose custom setup to make sure you see the option and are able to include it), everything will run file.
In case you already did that, there might be a problem with the C++ project type registration in VS. Please come back to this forum if you still have problems after re-installation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android: How can I create a box? I'm lloking for something that looks like a text box except
I don't want the user to be able to type inside the box.
How can I do it ?
A: disable EditText view by android:enabled="false"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get Main Window (App Delegate) from other class (subclass of NSViewController)? I'm trying to change my windows content, from other class , that is subclass of NSViewController.I'm trying code below, but it doesn't do anything.
[NSApplication sharedApplication]mainWindow]setContentView:[self view]]; //code in NSViewController
[NSApplication sharedApplication]mainWindow] // returns null
I tried to add
[window makeMainWindow];
in App Delegate class, but it won't help.
Did I miss something?
P.S. Also I'm using code below to call any delegate function in my class,
[(appDelegate *) [[NSApplication sharedApplication]delegate]MyMethod];
but I wonder is there something better, wihtout importing delegate class. Something like this
[[NSApplication sharedApplication]delegate]MyMethod];
(it gives warning)
A: For the mainWindow method the docs say:
This method might return nil if the application’s nib file hasn’t finished loading, if the receiver is not active, or if the application is hidden.
I just created a quick test application and I placed the following code:
NSLog(@"%@", [[NSApplication sharedApplication] mainWindow]);
into my applicationDidFinishLaunching:aNotification method, and into an action method which I connected to a button in the main window of my application.
On startup, the mainWindow was nil, but when I click the button (after everything is up and running and displayed), the mainWindow was no longer nil.
NSApplication provides other methods which you may be useful to you:
*
*- windows - an array of all the windows;
*– keyWindow - gives the window that is receiving keyboard input (or nil);
*– windowWithWindowNumber: - returns a window corresponding to the window number - if you know the number of the window whose contents you wish to replace you could use this;
*– makeWindowsPerform:inOrder: - sends a message to each window - you could use this to test each window to see if it's the one you are interested in.
With regard to calling methods on the delegate, what you say gives a warning works fine for me. For example, this works with no warnings:
NSLog(@"%@", [[[NSApplication sharedApplication]delegate] description]);
What exactly is the warning you receive? Are you trying to call a method that doesn't exist?
A: Fighting with MacOS just figured this out.
Apple's quote:
mainWindow
Property
The app’s main window. (read-only)
Discussion
The value in this property is nil when the app’s storyboard or nib file has not yet finished loading. It might also be nil when the app is inactive or hidden.
If you have only one window in your application (which is the most used case) use next code:
NSWindow *mainWindow = [[[NSApplication sharedApplication] windows] objectAtIndex:0];
Promise it won't be nil, if application has windows.
A: Swift flavored approaches for getting the main window (if present)
Application Main Window
guard let window = NSApplication.shared.mainWindow,
else {
// handle no main window present
}
// ... access window here
Application Window Array
let windowArray: [NSWindow] = NSApplication.shared.windows
guard windowArray.count > 0 else {
// hand case where no windows are present
}
let window = windowArray[0]
// ... access window here
A: If the window property isn't set yet, try delaying things until the app has finished loading, like so:
[myObject performSelector:@selector(theSelector) withObject:nil afterDelay:0.1];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
} |
Q: how to search in eclipse inside the documentation of local java/android/j2me I want to get information about selected text when I press F1. But always it returns information about to using eclipse. You can look at the screen capture below.
A: You can't get API information by pressing F1, but you can use javadoc view in eclipse.
In Eclipse Help page( http://help.eclipse.org/indigo/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Freference%2Fref-export-javadoc.htm ) , see "Javadoc view" and "Open and configure external Javadoc documentation" secrtion.
A: According the kingori's answer I visited the help.eclipse.org link and found this shortcut:
Open Attached Javadoc in a Browser (Shift+F2) => Opens the attached javadoc of current input of the Javadoc view in a browser.
When you selected some text in editor, you can get access to the resource by clicking Shift + F2 .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7620253",
"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.