text
stringlengths 8
267k
| meta
dict |
---|---|
Q: marquee show 5 pics max when i pass 10 pics i use marquee to show pics but when i pass 10 pics it show 5 pics only
here's My Code :
<marquee align="right" behaviour="alternate" scrollamount="4" direction="left" onmouseover="this.scrollAmount=0"
onmouseout="this.scrollAmount=4">
<a href="#" target="_blank"> <img src="Slide_Images/sample01.jpg" /> </a>
<a href="#" target="_blank"> <img src="Slide_Images/sample02.jpg" /> </a>
<a href="#" target="_blank"> <img src="Slide_Images/sample03.jpg" /> </a>
<a href="#" target="_blank"> <img src="Slide_Images/sample04.jpg" /> </a>
<a href="#" target="_blank"> <img src="Slide_Images/sample05.jpg" /> </a>
<a href="#" target="_blank"> <img src="Slide_Images/sample06.jpg" /> </a>
<a href="#" target="_blank"> <img src="Slide_Images/sample07.jpg" /> </a>
<a href="#" target="_blank"> <img src="Slide_Images/sample08.jpg" /> </a>
<a href="#" target="_blank"> <img src="Slide_Images/sample09.jpg" /> </a>
</marquee>
A: My guess would be because it's styled as an alternate. It can only bounce when there's room enough to do so (and, from what you're explaining, 5 images takes up that much real-estate). Maybe switch to a scroll?
(I also don't know how big the images are, so if you can provide that information I can update my answer.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Understanding Viewstate working procedure In order to enhance performance of my application, I started setting Viewstate of controls to false. So now I'm getting:
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJNzU3OTU5NDI1ZGTBCxumGHfzsISSVDAeBMbSE7Fvfw==" />
After this I added 3 more labels and likewise set the Viewstate property for all of these labels to false, but now I am getting same Viewstate bytes.
So I'm a bit confused now in understanding the Viewstate concept.
A: Let me clarify.
First what is viewstate?
View state's purpose in life is simple: it's there to persist state across postbacks. (By Scott Mitchel)
What does disabling viewstate for Label means?
Disabling viewstate does not mean that when you add Label for the first time in your original aspx file code the values of label will not be added in the viewstate. Disabling actually means the values of viewstate for that particular control will not be changed in the viewstat after the postback.
To elaborate further, when you have disabled viewstate it still save the properties of label. Like the text property that was there for the very first time page was loaded. Also the font it was displayed in and so forth.
What disabling does is when you postback and change the text of Label lets say from Label to "Bye Bye" that information is not going to be saved in the viewstate.
Let me demonstrate with viewstate disabled for Label.
When the page initially loads viewstate value is this,
value="/wEPDwULLTExNjMzNDIxNjRkZIajtQgaZZlXAyolkhYpfGy2SBoV"
Then I click on change Label button and in change label button event handler change the labels text to "Bye Bye" viewstate is this,
value="/wEPDwULLTExNjMzNDIxNjRkZIajtQgaZZlXAyolkhYpfGy2SBoV"
Then I click on Empty postback (no code written for this button) button and Label Text changes back to
Label
viewstate value is still,
value="/wEPDwULLTExNjMzNDIxNjRkZIajtQgaZZlXAyolkhYpfGy2SBoV"
Lesson Learned
*
*Disabling viewstate does one thing which is not saving the new state of control after the postback but it doesn't mean it will not save the initial properties.
*Disabling viewstate has disadvantage in those situations where the control should persist its state during the postback.
*If you know already the control like label text will never be changed, why use Label at all? why don't simply use regular html like
Did you know when label is rendered it html is translated to <span></span>.
Interesting Questions are following
Since we had Label viewstate disabled initially why when we clicked the Change Label button it showed the text changed to "Bye Bye"?
Ans. You have to learn how the viewstate works during the page life cycle. For example, following happens when Change Label Button is clicked.
*
*Initialization state: Page is initialized from scratch so Label text
is set to "Label"
*View State Load event is called: Nothing happens since viewstate was disabled for Label
*Raise PostBack events are called: Like the one for Change Button Button_Click() event and Label Text is changed to "Bye Bye".
then some other things follow and page is shown with "Bye Bye" text for label.
*Why does Label text changes back to Label when you click Empty Postback button above.
Ans.
*
*Initialization state: Page is initialized from scratch so Label text is set to "Label"
*View State Load event is called: Nothing happens since viewstate was disabled for Label
*Raise PostBack events are called: Like the one for Empty Button's Button_Click() event and since it is not doing anything nothing happens then some other things follow but Label's text is not changed from "Label" during any of those stages.
However if you had Label Viewstate Enabled. Each time postback would have happened Label would have persisted its new state since it would have been changed to new state during Load Viewstate/Save Viewstate phase of page life cycle.
A: All controls in your webform will add information in ViewState insted you set EnalbedViewState to false. It's the way of asp.net keep the state of the components in the page after each postback because the web and http protocoll is stateless, so the motor of asp.net need to keep the state to create this kind of programmimg (events, components and its properties). Every property of every component that you change of the default value will be on viewstate (if EnabledViewState is true (by default)).
There's a way to compress your viewstate in server-side and descompress it on client-side, transfering data between them easly. Take a look at this: http://www.hanselman.com/blog/ZippingCompressingViewStateInASPNET.aspx
In Asp.Net 4.0 the control of ViewState is more flexible, so I recommend you read it: http://www.codeproject.com/Articles/81489/ViewState-Control-in-ASP-NET-4-0
I recommend you read this to understand the asp.net life cycle better:
http://msdn.microsoft.com/en-us/library/ms178472.aspx
I hope it helps!
Chees
A: There are plenty of general articles on viewstate so I won't go into that.
To answer your specific question as to why you aren't seeing a variance in the value of the viewstate hidden field when you add Labels with viewstate enabled/disabled is that viewstate is differential. It tracks non default state in your controls. IE you won't see a change in the viewstate hidden field unless you enable viewstate and make a change to the server control (try just setting the text field).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: add fade effect to image swap I'm looking for a solution to add a nice fade effect to a few images when I swap them. I'm new to jquery and have seen many solutions but only for a single image instead of multiples ones.Tried the z-index technique but that placed all the images on top of each other.
I'm using this jquery code to swap the images.
$(document).ready(function(){
// jQuery image change on hover
$("ul#aside li a img")
.mouseover(function() {
var src = $(this).attr("src").match(/[^\.]+/) + "over.png";
$(this).attr("src", src);
})
.mouseout(function() {
var src = $(this).attr("src").replace("over", "");
$(this).attr("src", src);
});
});
Any help or tips is much appreciated.
A: $("ul#aside li a img")
.mouseover(function() {
var src = $(this).attr("src").match(/[^\.]+/) + "over.png";
var $this = $(this);
$this.fadeOut("fast", function() {
$this.attr("src", src).fadeIn("slow");
});
})
.mouseout(function() {
var src = $(this).attr("src").replace("over", "");
var $this = $(this);
$this.fadeOut("fast", function() {
$this.attr("src", src).fadeIn("slow");
});
});
});
A: try something like this
$(this).hide();
$(this).attr("src", src);
$(this).fadeIn();
.fadeOut() will fade an image out
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Batch : label length I was wondering about the maximum length of a label in a batch file.
I found this Microsoft article stating:
MS-DOS recognizes only the first eight characters of a batch file label; subsequent characters are ignored.
They also provide an example :
@echo off
goto latestch
:latestchanges
echo two
:latestch
echo three
which is supposed to output
two
three
instead of
three
But on my system, I get
three
I tried on Windows 7 (6.1.7600) and WindowsXP (5.1.2600), and get the same result on both of them.
It looks to me there is no eight characters limitation!
Am I missing something?
A: The limits are 2047 and 8192, depending on your OS. See this KB article.
A: The example is true for MS-DOS not cmd.exe. The version of your cmd.exe is higher than MS-DOS. Feel free to use any length of label.
According to that article, this limitation is valid for :
Microsoft MS-DOS 4.01 Standard Edition
Microsoft MS-DOS 5.0 Standard Edition
Microsoft MS-DOS 5.0a
Microsoft MS-DOS 6.0 Standard Edition
Microsoft MS-DOS 6.2 Standard Edition
Microsoft MS-DOS 6.21 Standard Edition
Microsoft MS-DOS 6.22 Standard Edition
A: I'm pretty sure the 8 character limitation went away when Windows moved away from the MS-DOS platform after Windows 98. All Microsoft OSes starting with Windows 2000 no longer have the limitation. The command window that we see today in Windows 7 and others is an application that runs on top of Windows, rather than the older implementation where the command window accessed the MS-DOS layer running beneath Windows.
A: Windows cmd.exe supports label lengths up to 128 characters long (including the leading colon). Any characters after 128 are simply ignored.
So a label length 500 will match a label length 300 if the first 128 characters of both labels is the same.
Here is a batch script that demonstrates the behavior:
@echo off
call :xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 125
call :xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 126
call :xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 127
call :xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 128
call :xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 129
call :xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 130
exit /b
:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
echo %1 finds 125
exit /b
:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
echo %1 finds 126
exit /b
:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
echo %1 finds 127
exit /b
:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
echo %1 finds 128
exit /b
:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
echo %1 finds 129
exit /b
:xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
echo %1 finds 130
exit /b
-- OUTPUT --
125 finds 125
126 finds 126
127 finds 127
128 finds 128
129 finds 128
130 finds 128
A: Windows 7 CMD and BAT batch commands that use the GOTO :LABEL are not limited to 8 characters following the ":" character as initially noted by the original poster when they are executed directly or CALLed from another batch file.
i.e.,
@echo off
SET VARIABLE=2
if %VARIABLE%.==. GOTO :LABELNUMBERZERO
if %VARIABLE%.==1. GOTO :LABELNUMBERONE
if %VARIABLE%.==2. GOTO :LABELNUMBERTWO
if %VARIABLE%.==3. GOTO :LABELNU
if %VARIABLE%.==4. GOTO :LABELN
GOTO :ENDTHISLONGTHING
:LABELNUMBERZERO
echo your variable was " "
GOTO :ENDTHISLONGTHING
:LABELNUMBERONE
echo your variable was "1"
GOTO :ENDTHISLONGTHING
:LABELNUMBERTWO
echo your variable was "2"
:ENDTHISLONGTHING
:LABELNU
echo your variable was "3"
:ENDTHISLONGTHING
:LABELN
echo your variable was "4"
:ENDTHISLONGTHING
The result of this is:
your variable was "2"
If I set the VARIABLE=4 the result is:
your variable was "4"
So DOS now sees even similarly named (beginning characters) as unique labels even if the same contents of a shorter label exist in the batch file beforehand.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Postgres - ERROR: prepared statement "S_1" already exists When executing batch queries via JDBC to pgbouncer, I get the following error:
org.postgresql.util.PSQLException: ERROR: prepared statement "S_1" already exists
I've found bug reports around the web, but they all seem to deal with Postgres 8.3 or below, whereas we're working with Postgres 9.
Here's the code that triggers the error:
this.getJdbcTemplate().update("delete from xx where username = ?", username);
this.getJdbcTemplate().batchUpdate( "INSERT INTO xx(a, b, c, d, e) " +
"VALUES (?, ?, ?, ?, ?)", new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
ps.setString(1, value1);
ps.setString(2, value2);
ps.setString(3, value3);
ps.setString(4, value4);
ps.setBoolean(5, value5);
}
@Override
public int getBatchSize() {
return something();
}
});
Anyone seen this before?
Edit 1:
This turned out to be a pgBouncer issue that occurs when using anything other than session pooling. We were using transaction pooling, which apparently can't support prepared statements. By switching to session pooling, we got around the issue.
Unfortunately, this isn't a good fix for our use case. We have two separate uses for pgBouncer: one part of our system does bulk updates which are most efficient as prepared statements, and another part needs many connections in very rapid succession. Since pgBouncer doesn't allow switching back and forth between session pooling and transaction pooling, we're forced to run two separate instances on different ports just to support our needs.
Edit 2:
I ran across this link, where the poster has rolled a patch of his own. We're currently looking at implementing it for our own uses if it proves to be safe and effective.
A: This turned out to be a pgBouncer issue that occurs when using anything other than session pooling. We were using transaction pooling, which apparently can't support prepared statements. By switching to session pooling, we got around the issue.
Unfortunately, this isn't a good fix for our use case. We have two separate uses for pgBouncer: one part of our system does bulk updates which are most efficient as prepared statements, and another part needs many connections in very rapid succession. Since pgBouncer doesn't allow switching back and forth between session pooling and transaction pooling, we're forced to either run two separate instances on different ports just to support our needs, or to implement this patch. Preliminary testing shows it to work well, but time will tell if it proves to be safe and effective.
A: New, Better Answer
To discard session state and effectively forget the "S_1" prepared statement, use server_reset_query option in PgBouncer config.
Old Answer
See http://pgbouncer.projects.postgresql.org/doc/faq.html#_how_to_use_prepared_statements_with_transaction_pooling
Switching into session mode is not an ideal solution. Transacion pooling is much more efficient. But for transaction pooling you need stateless DB calls.
I think you have three options:
*
*Disable PS in jdbc driver,
*manually deallocate them in your Java code,
*configure pgbouncer to discard them on transaction end.
I would try option 1 or option 3 - depending on actual way in which your app uses them.
For more info, read the docs:
http://pgbouncer.projects.postgresql.org/doc/config.html (search for server_reset_query),
or google for this:
postgresql jdbc +preparethreshold
A: Disabling prepared statements in JDBC.
The proper way to do it for JDBC is adding "prepareThreshold=0" parameter to connect string.
jdbc:postgresql://ip:port/db_name?prepareThreshold=0
A: In our case the issue was not related to pgbouncer. Since we did were not able to append prepareThreshold=0 to the URL what we did to fix was the following
View the prepared statements
select * from pg_prepared_statements;
Deallocate the faulty table
select * from pg_prepared_statements;
deallocate "S_1";
A: I had this problem, we have pgbouncer configurated in transaction level, we were using psql 11.8, we just upgraded the psql jar to the latest version, it got fixed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "37"
} |
Q: Use of lock keyword and the new async functionality of C# 5.0 Is it still necessary to use the lock keyword on resources like SQL Compact database in methods called with async (AsyncCtpLibrary.dll)? As i understand from the talk given by Anders, the async processing all happens within the same thread, so they shouldn't be a need for it, or am I wrong? I cannot find any info on this anywhere on the internet at the moment.
Thanks
A: AFAIK async is based on the TPL and Tasks - and so no they won't be running on the same thread every time (or continue on the same thread) and yes you have to design with concurency in mind still. Async only helps you to put the pieces together in a much nicer way.
To be clear: everything inside your methods (if started only once) will run in a thread at a time but if you share resources you will have to think on locking or other synchronization methods just as you used to do all the time.
If you can go for immutable data - this way you can strip all this to a mere minimum, but you allway have to remember that your processes will run on many threads (dispatch for UI comes to mind).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Practical Implementation for Data Warehouse Data warehousing seems to be a big trend these days, and is very interesting to me. I'm trying to acquaint myself with its concepts, and am having a problem "seeing the forest through the trees" because all of the data warehouse models and descriptions I can find online are theoretical, but don't gives examples with actual technologies being used. I'm a contextual learner, so abstracted, theoretical explanations don't really help me out all that much.
Now there seem to be many "data warehousing models", but all of them seem to have some similar characteristics. There is ually an "ODS" (operational data store that aggregates data from multiple sources into the same place. A process known as "ETL" then converts data in this ODS into a "data vault", and again into "data" and/or "strategy marts."
Can someone provide an example of the technologies that would be used for each of these components (ODS, ETL, data vault, data/strategy marts)?
It sounds like the ODS could just be any ordinary database, but the data vault seems to have some special things going on because it is used by these "marts" to pull data from.
ETL is the biggest thing I'm choking on by far. Is this a language? A framework? An algorithm?
I think once I see a concrete example of what's going on at each step of the way, I'll finally get it. Thanks in advance!
A: ETL is a process. The abbreviation stands for Extract-Transform-Load which describes what is being done with data during the process. The process can be implemented anywhere where you need to create a bridge between two systems with differenet data formats. First, you need to pull (exract) data from a source system (database, flat files, web service etc.), Then data are being processed (transform) to comply with format of a target storage (again it can vary: databases, files, API calls). During the transform step, further actions can be performed on the data set as enrichment with data from other sources, cleansing and improving its quality. The last step is loading transformed data into a target storage.
Typically, an ETL process is employed for loading a datawarehouse, migrating data from one system or database to another during moving from a legacy system to new one, synchronizing data between two or more systems. It is also used as an intermediate layer in broader MDM and BI solutions.
In terms of specific software, there are many ETL tools on the market ranging from robust solutions from big players as Informatica, IBM DataStage, Oracle Data Integrator, to more affordable and open source providers as CloverETL, Talend, or Pentaho. The most of these tools offer a GUI where flow and processing of data is defined through diagrams.
A: For Microsoft SQL Server 2005 and later the ETL tool is called SSIS (SQL Server Integration Services). If you install at least the Standard version of the SQL Server you get the Business Intelligence Developer Studio with which you can design your data flows. Basically what an ETL tool does is take data from one or more sources (tables, flat files, ...) then transform it (add columns, join, filter, map to different data types, etc.) and finally store it again to one or more tables or files.
To get a basic understanding of how something works you can watch e.g. this video or this one (both from midnightdba). They're a bit lengthy, but you get an idea. They certainly helped me in understanding the basic functionality of an ETL tool.
Unfortunately I have not yet digged into other platforms or tools.
A: I'd highly recommend checking out some of the books by Ralph Kimball and Margy Ross (The Data Warehouse Toolkit, The Data Warehouse Lifecycle Toolkit) for an introduction to data warehousing.
My company's data warehouse is built using the Oracle Warehouse Builder tool for ETL. The OWB is a GUI tool that generates PL/SQL code on the database to manipulate the data. After manipulation and cleansing, the data is published to an Oracle datamart. The datamart is a database instance that users access for ad-hoc querying via Oracle Discoverer (Java software).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to open attached email image through App I want to create an app which opens image from email attachment. Here I able to open pdf which is an attachment to my email, I know the setting in info.plist only for open pdf file through my app. Can anyone tell me how to open png or jpg format image through app?
Can anyone tell me setting in info.plist for opening images through app?
A: Check out this answer regarding how to associate file types with an application:
How do I associate file types with an iPhone application?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: VB.NET - Remove Item From Multi-Dimensional ArrayList By Query? I am looking to remove an element from an ArrayList using a query, E.g.
DELETE FROM arraylist WHERE (0) = "User1"
(Where (0) is the index of the second dimension).
Code:
Dim Users As New ArrayList
Users.Add({"User0", "Details"})
Users.Add({"User1", "Details"})
Users.Remove("User1")
The reason I am looking for a query way to do this is because I will not know what the second dimension value will be.
A: Dim Users As New ArrayList
Users.Add(new String(){"User0", "Details"})
Users.Add(new String(){"User1", "Details"})
Dim userToRemove = Users.Cast(Of String()).Where(Function(i) i(0).Equals("User1")).Single()
Users.Remove(userToRemove)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unusual Lighting Effects - Random Polygons Coloured I am working on creating an object loader for use with iOS, I have managed to load the vertices, normals and face data from and OBJ file, and then place this data into arrays for reconstructing the object. But I have come across an issue with the lighting, at the bottom is a video from the simulation of my program - this is with the lighting in the following position:
CGFloat position[] = { 0.0f, -1.0f, 0.0f, 0.0f };
glLightfv(GL_LIGHT0, GL_POSITION, position);
This is specified in both the render method each frame and the setup view method which is called once at setup.
Various other lighting details are here, these are called once during setup:
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
CGFloat ambientLight[] = { 0.2f, 0.2f, 0.2f, 1.0f };
CGFloat diffuseLight[] = { 1.0f, 0.0f, 0.0, 1.0f };
glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
CGFloat position[] = { 0.0f, -1.0f, 0.0f, 0.0f };
glLightfv(GL_LIGHT0, GL_POSITION, position);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_NORMALIZE);
The video of the issue can be found here:
http://youtu.be/dXm4wqzvO5c
Thanks,
Paul
[EDIT]
for further info normals are also supplied by the following code, they are currently in a large normals array or XYZ XYZ XYZ etc...
// FACE SHADING
glColorPointer(4, GL_FLOAT, 0, colors);
glEnableClientState(GL_COLOR_ARRAY);
glNormalPointer(GL_FLOAT, 3, normals);
glEnableClientState(GL_NORMAL_ARRAY);
glDrawArrays(GL_TRIANGLES, 0, 3*numOfFaces);
glDisableClientState(GL_COLOR_ARRAY);
A: I now feel incredibly stupid... All part of being a student programmer I guess. I will leave an answer to this so if anyone else gets this problem they can solve it too! The mistake was simply down to a typo:
glNormalPointer(GL_FLOAT, 3, normals);
Should have read
glNormalPointer(GL_FLOAT, 0, normals);
The second argument being the STRIDE which is only used if the array contains other values e.g. Vert Coords / Normals / Texture Coords. As mine are in single arrays the stride between the values should be 0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: When using an IoC container, how to pass dynamic data / objects to a class? I have an Order class with the below constructor
public Order(IProduct product, short count)
{
this._product = product;
this._count = count;
}
I'm trying to setup Unity IoC container and obviously to construct the order object I'd need to know the count and product but these are determined at run time; the count could be any value and product can be any product e.g. Carrot, Melon, etc.
So how to apply IoC for this?
One approach I thought was that my constructor only accepts object dependencies then any other required property to be added using a new Initialize() method:
public Order (IProduct product)
{
this._product = product;
}
public Initialize(short count)
{
this._count = count;
}
in this way whoever creates the Order object, has to call the Initialize() method afterwards so that other properties that can't be handled by the IoC container be added to it.
Is it the approach that you recommend/use?
A: This doesn't seem like an appropriate situation for an IoC container to me. Presumably Orders can be instantiated regularly with different Products (and counts) throughout the life of the application based on the behavior of the user, which suggests a container would need to be configured for each context in which Orders might be created - that is, for each Product page.
IoC containers work best when you can make decisions about dependencies seldom and early on, say at application start-up. If the decision on which dependency to inject always takes place at about the same time as the creation of the dependent object, then an IoC container just adds unnecessary complexity.
A: With Unity you should be able to set up a ParameterOverride to pass in your extra parameters :
container.Resolve<IOrder>(new ParameterOverrides { { "Count", 1 } });
Ok, alternatively create a factory class :
class OrderFactory : IOrderFactory
{
public OrderFactory ( IProduct product );
public Order GetOrder (count)
{
return new Order ( product, count );
}
}
Use the container to resolve the factory. Then use the factory to resolve your orders.
A: Count should probably just be a property of Order. What does count represent? The number of order lines or the quantity of product? I'm not quite sure how you plan on implementing and IoC container here.
Something like this:
public class Order
{
private IProduct _product;
public Order(IProduct product)
{
_product = product;
}
public int Count {get;set;}
}
A: @scottm
This is the actual code that I have in my aspx page:
private IStoresRankingReportPresenter _presenter;
protected void Page_Init(object sender, EventArgs e)
{
this._presenter = ServiceLocator.Current.GetInstance<IStoresRankingReportPresenter>();
this._presenter.Initialize(this, this.Count);
this._presenter.OnPageInit();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611940",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Spring/Flex on Websphere I have a simple hibernate/spring/flex project. The project was developed under apache tomcat6. Can anyone point me how to proceed to deploy it on IBM webshphere v6.1? thanks
A: In general it should work if you project is J2EE 1.4 and JDK 5 compatible.
The most important step is to wrap an EAR around your WAR.
And on think I remember (I have such a port some time ago), is that you will need to change the Class loader order of the WAR!! in WAS to "parent last" (else you will get a lot of strange errors do to not compatible classes.)
And then you need to go form one problem to the next (sorry).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jquery parent element is hidden with child element on mouseout I am having a problem where the parent list element is being hidden along with the child, when I only want the child to hide on mouseout. Below is my code, any help is greatly appreciated!
$(document).ready(function(){
$('#home').hover(
function() {
$(this).children().stop().show();
},
function() {
$(this).children().stop().hide();
}
);
});
A: I think I might know what the issue is (having the list markup would help).
You're hiding all of the children of the parent list element, which will "hide" the parent element, since it has nothing to display:
<div>
<ul id="home">
<li>Test</li>
<li>Test</li>
<li>Test</li>
</ul>
<ul>
<li>Test</li>
<li>Test</li>
<li>Test</li>
</ul>
<ul>
<li>Test</li>
<li>Test</li>
<li>Test</li>
</ul>
</div>
$(document).ready(function(){
$('#home').hover(
function() {
$(this).children().stop().show();
},
function() {
$(this).children().stop().hide();
console.log(this);
}
);
});
http://jsfiddle.net/sK36C/2/
Use Chrome Console or Firebug in Firefox to view the HTML tab for that element after it's hidden, and you'll notice each of the LIs for the UL#home are display: none. There is nothing to display in the UL, so it appears to have disappeared.
Here's another demonstration where I tell it to skip the :first child and hide the rest:
<div>
<ul id="home">
<li>This is #home text</li>
<li>Test</li>
<li>Test</li>
<li>Test</li>
</ul>
<ul>
<li>Test</li>
<li>Test</li>
<li>Test</li>
</ul>
<ul>
<li>Test</li>
<li>Test</li>
<li>Test</li>
</ul>
</div>
$(document).ready(function(){
$('#home').hover(
function() {
$(this).children(':not(:first)').stop().show();
},
function() {
$(this).children(':not(:first)').stop().hide();
console.log(this);
}
);
});
http://jsfiddle.net/sK36C/3/
Note how the first element isn't hidden, and the UL#home is still visible.
See: http://api.jquery.com/children/
A: Better you can have this using simple CSS:
HTML:
<div>
<ul id="home"><p>MENU</p>
<li>li1</li>
<li>li2</li>
<li>li3</li>
<li>li4</li>
</ul>
</div>
CSS:
#home:hover li{
display: block;
}
#home li {
display: none;
}
Fiddle1
Incase if you want to try using jQuery
When you use jQuery try doing it using .toggle()
$(document).ready(function(){
$('#home p').hover(
function(e) {
$(this).parent().children(':not(:first)').toggle();
;
}
);
});
Fiddle2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create a catch all function on a jQuery object? I was previously using the jQuery autosave plugin but have recently removed it. Some code is still trying to use this function, so how can I temporarily extend the jQuery object so there is an empty function to prevent errors until I can get through all of the code that is trying to use the function?
The plugin is called in this way:
jQuery().autosave.restore();
jQuery().autosave.save();
I think those are the only two functions that exist, so it would be OK to create two empty functions, but is there a way to create a catch-all function on this type of object?
Note
This is a temporary solution until I can go through a lot of code. I do believe the question is a valid coding question even if you think this workaround is not ideal (it isn't).
A: There is a way to do this. You can create a dummy plugin (check out jQuery's documentation for creating plugins):
(function( $ ){
$.fn.autosave = {
restore: function() {};
save: function() {};
};
})( jQuery );
I would highly recommend against doing this, however. Instead, you should look at those errors and fix them, i.e., stop your code from using them. Otherwise you're simply hiding the problem.
A: Nope. Standard JavaScript does not support "catch-all" methods.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Jquery only processing first function/block of code I have a page with three different snippets of jquery code, all doing different things. The problem is that when they are all on the page, only the first one works. I've changed the order, and regardless of the snippet, only the first one works. Is there an internal jquery conflict I'm missing?
My code:
<script type="text/javascript">
jQuery(document).ready( function() {
$("#main-menu li").mouseenter(function() {
$(this).find("ul").fadeIn();
}).mouseleave(function(){
$(this).parent().find("ul").fadeOut();
});
jQuery( ".text-resize a" ).textresizer({
target: ".content",
type: "fontSize",
sizes: [ "12px", "16px" ],
selectedIndex: 0
});
jQuery( ".text-resize a" ).textresizer({
target: ".title",
type: "fontSize",
sizes: [ "11px", "16px" ],
selectedIndex: 0
});
jQuery( ".text-resize a" ).textresizer({
target: ".show-more",
type: "fontSize",
sizes: [ "12px", "16px" ],
selectedIndex: 0
});
jQuery( ".text-resize a" ).textresizer({
target: "#footer",
type: "fontSize",
sizes: [ "12px", "16px" ],
selectedIndex: 0
});
jQuery( ".text-resize a" ).textresizer({
target: ".copyright",
type: "fontSize",
sizes: [ "11px", "16px" ],
selectedIndex: 0
});
$(".slidetabs").tabs(".images > div", {
// enable "cross-fading" effect
effect: 'fade',
fadeOutSpeed: "2000",
// start from the beginning after the last tab
rotate: true
// use the slideshow plugin. It accepts its own configuration
}).slideshow( {autoplay: true, interval:3000});
});
</script>
Thank you
A: I assume you are using this textResizer plugin. You really should be using type="cssClass" if you are going to target different sections of the page with different sizes.
jQuery( ".text-resize a" ).textresizer({
target: "body",
type: "cssClass",
sizes: [ "size1", "size2" ],
selectedIndex: 0
});
You CSS would look something like
body.size1 .content { font-size: 12px;}
body.size2 .content { font-size: 16px;}
body.size1 .title { font-size: 11px;}
body.size2 .title { font-size: 16px;}
body.size1 .show-more { font-size: 12px;}
body.size2 .show-more { font-size: 16px;}
body.size1 #footer { font-size: 12px;}
body.size2 #footer { font-size: 16px;}
body.size1 .copyright { font-size: 11px;}
body.size2 .copyright { font-size: 16px;}
It would be better to combine the CSS for the ones that are the same
body.size1 .title,
body.size1 .copyright { font-size: 11px;}
body.size1 .content,
body.size1 #footer,
body.size1 .show-more { font-size: 12px;}
body.size2 .content,
body.size2 .title,
body.size2 .show-more,
body.size2 #footer,
body.size2 .copyright { font-size: 16px;}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can't get jquery to set value of select input when value of first select changes I'm trying to update the value of a select input when I change the value of another select input. I cannot get anything to happen on the page and want to make sure I don't have a syntax error or some other dumb thing in this code.
<div class="group">
<div class="inputs types">
<strong style="font-size:13px;">Category:</strong>
<select name="id" id="ctlJob">
<option value="1">Automotive</option>
<option value="2">Business 2 Business</option>
<option value="3">Computers</option>
<option value="4">Education</option>
<option value="5">Entertainment & The Arts</option>
<option value="6">Food & Dining</option>
<option value="7">Government & Community</option>
<option value="8">Health & Beauty</option>
<option value="9">Home & Garden</option>
<option value="10">Legal & Financial Services</option>
<option value="11">Professional Services</option>
<option value="12">Real Estate</option>
<option value="13">Recreation & Sports</option>
<option value="14">Retail Shopping</option>
<option value="15">Travel & Lodging</option>
</select>
<select name="type" id="ctlPerson"></select>
</div>
</div>
<script>
$(function() {
$("#ctlJob").change(function() {
//Get the current value of the select
var val = $(this).val();
$('#ctlPerson').html('<option value="123">ascd</option>');
});
});
</script>
A: Try using append instead:
$(function() {
$("#ctlJob").change(function() {
//Get the current value of the select
var val = $(this).val();
var ctl = $('#ctlPerson').append('<option value="123">'+val+'</option>')[0].options;
ctl.selectedIndex = ctl.length-1;
});
});
http://jsfiddle.net/J69q8/
A: I think you also need to set the 'selected' property. Add
$('#ctlPerson option[value="123"]').attr('selected', 'selected');
to the end of the script. You are currently adding the option to the select list, but are not changing the select list to show it.
A: <div id="test">
<select name="sel" id="sel">
<option name="1" id="1" value="1">Automotive</option>
<option name="2" id="1 value="2">Business 2 Business</option>
<option name="3" id="1 value="3">Computers</option>
</select>
<select name="sel2" id="sel2"></select>
</div>
<script>
$("#sel").change(function() {
var val = $(this).val();
$('#sel2').html('<option value="1">NEW</option>');
)};
</script>
this works fine for what you need to do.
it's something like what you have
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting System.NotSupportedException when running WCF Service in Visual Studio 2010 I have created a WCF service using Visual Studio 2010. When i try to run the service, i get the following error
File name: 'file:///H:\Personal\Visual Studio
2010\Projects\WPFBrowser\DatabaseService\bin\Debug\DatabaseService.dll'
---> System.NotSupportedException: An attempt was made to load an
assembly from a network location which would have caused the assembly
to be sandboxed in previous versions of the .NET Framework. This
release of the .NET Framework does not enable CAS policy by default,
so this load may be dangerous. If this load is not intended to sandbox
the assembly, please enable the loadFromRemoteSources switch. See
http://go.microsoft.com/fwlink/?LinkId=155569 for more information.
at System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName,
String codeBase, Evidence assemblySecurity, RuntimeAssembly
locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound,
Boolean forIntrospection, Boolean suppressSecurityChecks) at
System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String
codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint,
StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean
forIntrospection, Boolean suppressSecurityChecks) at
System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName
assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark,
Boolean forIntrospection, Boolean suppressSecurityChecks) at
System.Reflection.Assembly.Load(AssemblyName assemblyRef) at
Microsoft.Tools.SvcHost.ServiceHostHelper.LoadServiceAssembly(String
svcAssemblyPath)
I even tried setting
<configuration>
<runtime>
<loadFromRemoteSources enabled="true" />
</runtime>
</configuration>
in the app.config file, but the problem remains.
Any help will be appreciated....
A: I think you should take a look at the: "file:///H:\Personal\Visu...". Why the file://? The WCF service should be hosted in the "developer iis" included in Visual Studio. This should result in something like: "http://localhost/abc..."
A: Moved my solution from the network drive to the local C:\ and it started working fine
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611960",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Making report footer to appear just below the last page records I am using Crystal Reports with VS-2005.
I have a report with a report footer section comprising of sum totals of a column. The problem is that in some cases, the records consume the entire page and the report footer alone appears on the next page. It looks awkward. I want the report footer to appear just below the last record row ended.
Is there any trick to make the report footer section fit on the last page itself?
A: If you aren't using grouping, try this:
*
*Add an additional section below your last detail section.
*In Section Expert, mark the detail section Keep Together.
*For the suppress formula for the new section, specify Not OnLastRecord.
*Move the content from the report footer to the new detail section.
If you are using grouping, do this in the last group footer instead, and in Group Expert, mark the group Keep Group Together.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: RPN Problems (Order of Operations) I'm trying to make a simple calculator with order of operations.
I had read in the Internet and found the algorithm of RPN (Reverse Polish notation).
EDIT:
Lets take an example:
2 * 5 - 3 + 4
Ok, I did as you both said check it out now:
Proc is string array of both numbers and operations.
Proc will be {2, *, 5, -, 3, +, 4}
This is the code:
int tempt = 0;
Stack <Double> stc = new Stack <Double>();
while (tempt < proc.length)
{
try
{
Double num = Double.parseDouble(proc[tempt]);
stc.push(num);
tempt++;
}
catch (Exception e)
{
char [] stcs = proc[tempt].toCharArray();
switch (stcs[0])
{
case '+':
{
double a2 = stc.pop();
double a1 = stc.pop();
stc.push(a1 + a2);
tempt++;
break;
}
case '-':
{
double a2 = stc.pop();
double a1 = stc.pop();
stc.push(a1 - a2);
tempt++;
break;
}
case 'x':
{
double a2 = stc.pop();
double a1 = stc.pop();
stc.push(a1 * a2);
tempt++;
break;
}
case '÷':
{
double a2 = stc.pop();
double a1 = stc.pop();
stc.push(a1 / a2);
tempt++;
break;
}
}
}
STILL DOESNT WORK
How can I make it work as well?
HELP ME PLS!
A: You've got the algorithm wrong. 2 * 5 - 3 + 4 in RPN translates to: 2 5 * 3 - 4 +. I don't know why you are treating numbers and symbols independently in two separate lists: in Reverse Polish notation:
2 3 + 4 * === (2 + 3) * 4
while
2 3 4 + * === 2 * (3 + 4)
That being said your program is almost correct except that for input you should take a series of symbols (both values and operators). Now you read symbols from left to right. If it is a number, push it onto the stack. If operator: pop top two values and push the result. That's it!
UPDATE: Example
Input: 2 5 * 3 - 4 +
Stack: []
Iteration I: (reading 2 from input)
Input: 5 * 3 - 4 +
Stack: [2]
Iteration II: (reading 5 from input)
Input: * 3 - 4 +
Stack: [2, 5]
Iteration III: (reading * from input)
Input: 3 - 4 +
Stack: [2 * 5] == [10]
Iteration IV: (reading 3 from input)
Input: - 4 +
Stack: [10, 3]
Iteration V: (reading - from input)
Input: 4 +
Stack: [10 - 3] == [7]
Iteration VI: (reading 4 from input)
Input: +
Stack: [7, 4]
Iteration VII: (reading + from input)
Input: ``
Stack: [7 + 4] == [11]
Result: 11 (no further input, one and only element on the stack is the result)
UPDATE 2: C'mon!
You are writing a program to interpret RPN but you are feeding it with infix notation! Try with this input:
String[] proc = new String[]{"2", "5", "x", "3", "-", "4", "+"};
There are several other flaws in your code (duplication, exception driven flow control, no error handling), but essentially with this input it should work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-6"
} |
Q: Links not working in IE8 when Application accessed with Fully Qualified Domain name My application works perfectly fine in Firefox and Chrome. But In case of IE8, everything is fine if I access the application using localhost or the IPAddress. But when I access the Application with the Fully Qualified Domain Name(Computer Name), then some of the links on the page do not work. They are not recognized as links at all. Has anybody experienced a similar issue?
Thanks,
Leela.
A: This was because of some overlapping divs. Fixed it. But still do not understand why it works with ipconfig and gives problem only with the domain name
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to skip one activity in startActivityForResult?
Possible Duplicate:
How do you skip parts of an Activity stack when returning results in Android?
I have the following activity stack A->B->C.
A activity has a ui element which starts activity B.
B - is an activity which displays a list and starts activity C. In the activity C user selects some info which should be returned to activity A(B should be dismissed).
Is it possible to call startActivityForResult so that the result will be returned from Activity C to activity A?
A: Duplicate of this question
Look at using FLAG_ACTIVITY_CLEAR_TOP there and in the Android docs here.
A: Why not just delegate the result B gets from C to A? Just call finish() after you set the result you received from C on B.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: GWT 2.4 CellTable issue Upgrading from GWT 2.3 to 2.4 caused a client-side exception in a class of mine that extends CellTable. There has been no loss of functionality, but the exception is a constant development annoyance.
com.google.gwt.core.client.JavaScriptException: (TypeError): this.insertBefore is not a function
I’ve identified the line that causes this, though the exception doesn't get thrown until the table is rendering later. In a row change handler, MyCellTable removes the header Element when there are no rows in the CellTable. Here's some example code that causes the exception in 2.4, but not in 2.3.
CellTable<String> table = new CellTable<String>();
table.addColumn(new TextColumn<String>() {
@Override
public String getValue(String object) {
return object;
}
}, "Col");
List<String> list = new ArrayList<String>();
list.add("abc");
list.add("def");
table.setRowData(list);
NodeList<Element> els = table.getElement().getElementsByTagName("THEAD");
if (els.getLength() == 0) {
return;
}
final Element e = els.getItem(0);
e.removeFromParent();
Downgrading to GWT 2.3 fixes the problem. I tried calling headerElement.setAttribute("style", "display: none") instead of removing the element, but that doesn't look the same (it still keeps a few pixels there). I'm aware that creating a CellTable and then ripping out pieces of it is probably a bad practice.
Are there any known changes in GWT 2.4 that could be causing this problem? Can anyone think of a workaround?
A: You can achieve the same result (hiding the header) by using the CSS property: "display: none" on the "thead" css attribute of the celltable.
Here's how:
1. Create a css file with the following entry in it:
Globalstyles.css:
.hiddenHeader thead {
display: none;
}
2. Add this file to a client resource bundle:
GlobalResources.java
public interface GlobalResources extends ClientBundle {
public static final GlobalResources RESOURCE = GWT.create(GlobalResources.class);
@Source("GlobalStyles.css")
GlobalStylesheet styles();
}
3. In your code, you can programatically set the style when there are no rows:
cellTable.addStyleName(GlobalResources.RESOURCE.styles().hiddenHeader());
And to remove the style call this:
cellTable.removeStyleName(GlobalResources.RESOURCE.styles().hiddenHeader());
Done!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to check the configured Xmx value for a running java application I'm creating an NSIS script, where the Xmx value for the java application being installed can be set during the installation process. I'm not sure if this parameter is being set correctly. Is there a way to check the configured Xmx value when the application is running?
A: Doron Gold gave the correct answer for Java 8 and below. For Java 9 and above you can get the same info by using
jhsdb jmap --heap --pid <pid>
A: I'm a big fan of kill -3 < pid > , which will give you details on the current memory and garbage collections along with stacks for all threads.
A: In my case, jmap is the best solution I could find:
jmap -heap <pid>
The above command shows full heap configuration + current usage.
The jmap command is included inside the jdk in the bin directory.
A: Cheap and dirty (not sure on reliability):
Runtime.getRuntime().maxMemory();
Have also used the following with success:
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
memoryBean.getHeapMemoryUsage().getMax();
A: jps is a good solution, just run
jps # shows pids
jps -v <pid> # shows params
remember to run it as the user that launched the process though, or it will not work properly.
A: The following worked for me for JVM version 11.0.16 (I had installed OpenJDK 11)
sudo jhsdb jinfo --flags --pid <pid>
It may work for you without using "sudo".
I had to do this after sudo jhsdb jmap --heap --pid <pid> was giving me the following error message:
Exception in thread "main" sun.jvm.hotspot.types.WrongTypeException: No suitable match for type of address
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611987",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: How could I redirect or deny users from a particular country with my htaccess file? I looked at countryipblocks.net, and need to clarify...
If I want to block users from, say, Andorra from visiting my site, what exactly needs to be added to my (already existing) .htaccess file?
Do I need to simply add this block of text to my .htaccess?
<Limit GET HEAD POST>
order allow,deny
deny from 85.94.160.0/19
deny from 91.187.64.0/19
deny from 194.117.123.178/32
deny from 194.158.64.0/19
deny from 195.112.181.196/32
deny from 195.112.181.247/32
allow from all
</LIMIT>
On the other hand, if I want to redirect users from, say, Croatia, from http://mywebsite.com to http://google.com or a landing page, what exactly needs to be added to my .htaccess file?
Finally - how would "deny" appear to the user being denied access?
Thanks.
A: Visitors who are within a IP range that is banned by deny will be served with a 403 error. If you want to them to see a nice page, instead of the standard Apache error, then you will need something like
ErrorDocument 403 /errors/403.html
in your .htaccess file. It is fairly easy to check rules based on IP addresses are working in your .htaccess by setting the blocked IP to be 127.0.0.1 (i.e. localhost); when you then look at the page in question on localhost, you should see the result of the page being blocked.
In answer to your question about redirecting users, blocking all users from any 1 country seems a little bit overkill; however, try reading up on the RewriteCond directive.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# regulate number of emails sent I was wondering if anyone knows a good way to regulate how many emails are sent through C#?
Here is my scenario. I have a windows service that monitors three other windows services. I am using a service controller to get the status of all 3 services and if the status of any of these services change to stopped, it sends an email. My issue is, I run this on a 60 second timer so it sends an email every 60 seconds until someone starts the service back up.
My first thought was, when first email is sent, create a text file and use a counter to number it. Do this while counter < 6 so I will only receive 5 emails max. I think this will work but it seems kind of silly.
Does anyone have an alternative to this or should I just go with my first thought and perform clean up on the files?
Thank you
EDIT: The reason that I was trying to limit the number of emails sent is because the people who receive these emails do not react very quickly. At the same time, those who handle Exchange do not want the service to spam people. I felt 5 would be enough to appease both sides.
A: I would suggest that you should track the down time of each service.
So every 60 seconds you check, if a service is down, store the DateTime that the service is down. The on the next 60 second interval you can check to see if the service was already down. i.e. you can tell if the service just went down or has been down a while. You can also add another flag to determine if the the last check was UP or DOWN.
Then when the program first finds the service down it can send the email. Once the service is back up it can reset this flag values so the next down time it knows to send a new email.
You can then also use these flags to delay email frequency if desired. Just add a new DateTime field for LastEmailSentTime and compare that with whatever interval you want for error emails (say 10 minutes)
Hope that gives you some ideas
EDIT: Some Sample...
bool ServiceWasDown = false;
DateTime ServiceDownTime = DateTime.Now;
DateTime LastEmailTime = DateTime.Now;
void OnTimerElapsed()
{
if(IsServiceDown())
ServiceDown();
else
ServiceUp();
}
void ServiceDown()
{
if(ServiceWasDown)//already know about service
{
//if LastEmailTime more than 10 minutes ago send another email and update LastEmailTime
}
else//service just went down
{
//send new email
LastEmailTime = DateTime.Now;
ServiceWasDown = true;
ServiceDownTime = DateTime.Now;
}
}
void ServiceUp()
{
ServiceWasDown = false;
}
A: If you use a System.Timers.Timer then You can add a int variable for count Elapsed events.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you implement users and group security in a web application? using php if that matters.
If you create a website that has users and groups. Where do you put this in the web application? Do you just put a function at the top of every page (pseudo):
if someone is in a group then they can see this page
or
if someone is in this group they can see this button
That sure seems wrong. I wouldn't want to edit the web app code just to change who can see what group-wise. I'm not sure what I should do or how to implement something like this.
Thanks.
A: In MySQL, I always create these 4 tables: users, user_groups, permissions and user_groups_permissions which are linked using Foreign Keys.
So, user A can be in a user group B, which this user group permissions are in user_groups_permissions.
Now, I just do a INNER JOIN on this 4 tables (or better, three: users, user_groups_permissions and permissions), the results are permissions that user have. all we need is selecting permissions.key by INNER JOIN.
Now, before processing request, I need to check that Client::has_permissin('send_post') returns true or not. And better, also on top of each user-group-related function.
Note: Client is a class that loads all user permissions just one time, before processing request, and then uses that permissions for whole request-life-time, without needing to access to database several times in that request. Use static methods and $permissions property for this class so you never need to send it's object over your applications classes/methods/functions :)
A: You can have a utility function which takes user id and group code and return true or false.
You can use that utility function as pseudo at the top of each page and the same function also be used to hide or show sections in your page.
If your web application is in MVC, embed user authorization logic in your controller.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7611993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MySQL Query - Trouble with joins, filtering results I'm in way over my head with this query. Any help would be immensely appreciated. I'll try and break it down as simply as I can, but please let me know if I'm being too vague.
There are four sections: criminal, family, civil, and business. Each has a judgeID and a userID of the user who last updated the report, along with report information.
Then there is a users table, with userID and userType.
There is a judges table with a judgeID and judge name.
What I'm trying to do: Get all current reports from one of the four sections ($court) based on current month and year, find the name of each judge that corresponds with each judgeID on the reports found, and then (this is where I'm having trouble) filter the reports based on the userIDs that are of userType 'user' (rather than admin).
Here's what I have (a little bit of PHP in there):
$query = "SELECT Name FROM judges LEFT JOIN $court
ON ($court.JudgeID = judges.JudgeID)
where Month='$month' and Year='$year' order by Name asc;";
It's just the subsequent filtering of userIDs by userType that I'm having trouble with.
A: Tim,
I'm not sure I totally understand the requirements, but let's start with this query and see what happens.
$query = "SELECT Name FROM judges LEFT JOIN $court
ON ($court.JudgeID = judges.JudgeID)
LEFT JOIN users
ON ($court.userid = users.userid) and user.userType='user'
where Month='$month' and Year='$year' order by Name asc;";
A: Try this:
SELECT Name
FROM judges
LEFT JOIN $court ON ($court.JudgeID = judges.JudgeID)
LEFT JOIN users ON ($court.userID = users.userID)
WHERE Month='$month' AND Year='$year' AND users.userType = 'user'
ORDER BY Name ASC;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612000",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JPA/Hibernate with InheritanceType.JOINED doing select on subclass I have a basic inheritance hierarchy setup using JPA and Hibernate that looks something like the following:
@Entity
@Table(uniqueConstraints=@UniqueConstraint(columnNames="email"))
@Inheritance(strategy = InheritanceType.JOINED)
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
protected String firstName;
protected String surname;
protected String email;
protected String organization;
...
}
with subclasses like this one
@Entity
@PrimaryKeyJoinColumn(name="UserId", referencedColumnName="id")
public class Coach extends User{
public Coach(){
}
}
This creates a Base User table and a table for Players and other derived subclasses, but now I am not able to do EJQ-QL queries on the Coach entity. I am trying to return a list of coaches in a unit test with the following:
public List<Coach> getCoachByName(String firstName) {
return getJpaTemplate().find("select c from Coach c where c.firstName='"+firstName+"'");
}
But I get a GenericJDBC Exception.
Any suggestions?
Here is the stack trace as requested:
org.springframework.orm.hibernate3.HibernateJdbcException: JDBC exception on Hibernate data access: SQLException for SQL [select coach0_.UserId as id0_, coach0_1_.firstName as firstName0_, coach0_1_.surname as surname0_, coach0_1_.email as email0_, coach0_1_.organization as organiza5_0_, coach0_1_.hashedPassword as hashedPa6_0_, coach0_1_.confirmedRegistration as confirme7_0_ from Coach coach0_ inner join User coach0_1_ on coach0_.UserId=coach0_1_.id]; SQL state [3D000]; error code [1046]; could not execute query; nested exception is org.hibernate.exception.GenericJDBCException: could not execute query
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:642)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:95)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:212)
at org.springframework.orm.jpa.JpaAccessor.translateIfNecessary(JpaAccessor.java:152)
at org.springframework.orm.jpa.JpaTemplate.execute(JpaTemplate.java:189)
at org.springframework.orm.jpa.JpaTemplate.executeFind(JpaTemplate.java:151)
at org.springframework.orm.jpa.JpaTemplate.find(JpaTemplate.java:311)
at org.springframework.orm.jpa.JpaTemplate.find(JpaTemplate.java:307)
at com.playermetrics.dao.impl.CoachDaoImpl.getCoachByName(CoachDaoImpl.java:25)
at com.playermetrics.entities.CoachDaoTest.testSaveCoach(CoachDaoTest.java:43)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:616)
at junit.framework.TestCase.runTest(TestCase.java:154)
at junit.framework.TestCase.runBare(TestCase.java:127)
at org.springframework.test.ConditionalTestCase.runBare(ConditionalTestCase.java:76)
at org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests.access$001(AbstractAnnotationAwareTransactionalTests.java:71)
at org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests$1.run(AbstractAnnotationAwareTransactionalTests.java:175)
at org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests.runTest(AbstractAnnotationAwareTransactionalTests.java:283)
at org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests.runTestTimed(AbstractAnnotationAwareTransactionalTests.java:254)
at org.springframework.test.annotation.AbstractAnnotationAwareTransactionalTests.runBare(AbstractAnnotationAwareTransactionalTests.java:172)
at org.springframework.test.jpa.AbstractJpaTests.runBare(AbstractJpaTests.java:174)
at org.springframework.test.jpa.AbstractJpaTests.runBare(AbstractJpaTests.java:255)
at junit.framework.TestResult$1.protect(TestResult.java:106)
at junit.framework.TestResult.runProtected(TestResult.java:124)
at junit.framework.TestResult.run(TestResult.java:109)
at junit.framework.TestCase.run(TestCase.java:118)
at junit.framework.TestSuite.runTest(TestSuite.java:208)
at junit.framework.TestSuite.run(TestSuite.java:203)
at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:130)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: org.hibernate.exception.GenericJDBCException: could not execute query
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at org.hibernate.loader.Loader.doList(Loader.java:2214)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2095)
at org.hibernate.loader.Loader.list(Loader.java:2090)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:388)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:338)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:172)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1121)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:64)
at org.springframework.orm.jpa.JpaTemplate$9.doInJpa(JpaTemplate.java:319)
at org.springframework.orm.jpa.JpaTemplate.execute(JpaTemplate.java:184)
... 31 more
Caused by: java.sql.SQLException: No database selected
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3597)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3529)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1990)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2151)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2625)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2119)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2281)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:186)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1778)
at org.hibernate.loader.Loader.doQuery(Loader.java:662)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
at org.hibernate.loader.Loader.doList(Loader.java:2211)
... 41 more
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Jenkins File Viewer I'm in the process of setting up our builds on our new Jenkins CI server. One thing I've noticed, which I don't really like is that I can't see a difference in the changes.
Jenkins knows what files have been modified/deleted but I cannot see where I can see the diff of those files?
A: Jenkins does not calculate diffs itself, but instead lets you link to a tool that does, such as a diff on GitHub, or a ViewSVN instance etc.
For example, on Apache's Jenkins instance, you can see a "ViewSVN" link next to each change:
https://builds.apache.org/job/ActiveMQ/changes
It depends on your SCM and the tool you normally use for browsing diffs, but there should be a Jenkins plugin available for you.
If not, it should be trivial to write your own :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is this a cast or a construction? I'm a little confused after reading something in a textbook. Regarding the code:
void doSomeWork(const Widget& w)
{
//Fun stuff.
}
doSomeWork(Widget(15));
doSomeWork() takes a const Widget& parameter. The textbook, Effective C++ III, states that this creates a temporary Widget object to pass to doSomeWork. It says that this can be replaced by:
doSomeWork(static_cast<Widget>(15));
as both versions are casts - the first is just a function-style C cast apparently. I would have thought that Widget(15) would invoke a constructor for widget taking one integer parameter though.
Would the constructor be executed in this case?
A: Short: Yes.
Long:
You can always test those things yourself, by doing e.g.:
#include <iostream>
struct W
{
W( int i )
{
std::cout << "W(" << i << ")\n";
}
};
int main(int argc, const char *argv[])
{
W w(1);
W(2);
static_cast<W>(3);
}
which is outputting
W(1)
W(2)
W(3)
A: Yes, it is both :). A cast is a syntactic construct (i.e. something you type). In this case, a constructor is invoked as a consequence of the cast. Much like a constructor would be invoked as a consequence of typing
Widget w(15);
A: Both Widget(15) and static_cast<Widget>(15) are casts, or conversion
operators, if you prefer. Both create a new object of the designated
type, by converting 15 into a Widget. Since 15 doesn't have any
conversion operators, the only way to do this conversion is by
allocating the necessary memory (on the stack) and calling the
appropriate constructor. This is really no different that double(15)
and static_cast<double>(15), except that we usually don't think of
double as having a constructor (but the resulting double is a new
object, distinct from the 15, which has type int).
A: In C++ this kind of expression is a form of a cast, at least syntactically. I.e. you use a C++ functional cast syntax Widget(15) to create a temporary object of type Widget.
Even when you construct a temporary using a multi-argument constructor (as in Widget(1, 2, 3)) it is still considered a variation of functional cast notation (see 5.2.3)
In other words, your "Is this a cast or a construction" question is incorrectly stated, since it implies mutual exclusivity between casts and "constructions". They are not mutually exclusive. In fact, every type conversion (be that an explicit cast or something more implicit) is nothing else than a creation ("construction") of a new temporary object of the target type (excluding, maybe, some reference initializations).
BTW, functional cast notation is a chiefly C++ notation. C language has no functional-style casts.
A: You said:
the first is just a function-style C cast apparently
The first would not compile in C, it's not C-style. C-style looks like (Widget)15. Here, the temporary object is created, using Widget::Widget(int).
Therefore, it is not a C-style cast.
A: Yes, of course. Any constructor takes a single parameter would be considered as CONVERSION CONSTRUCTOR. Your constructor is already taking a single int parameter, so that the compiler can "implicitly" call this constructor to match the argument (with the value 15, which is int).
There is a simple trick to prevent such errors, just use the keyword explicit before your constructor.
Check this for more information.
A: Yeeeah. You can replace
Widget(15)
with
static_cast<Widget>(15)
Because it will be replaced back by compiler :D
When you cast int to Widget compiler looks for Widget::Widget(int); and place it there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Complete function before starting next (fadeIn/fadeOut) UPDATED (see notes at bottom)
I have created an image map and when you hover over a specific section of this image map a description will appear in a designated area (the sidebar) of my website.
Each description is of varying length therefore I have not set any maximum height level for my sidebar area so that the display can grow vertically to accomodate each description.
The problem I am having is that when you rapidly hover over areas of the image map the display produces some weird results; showing blocks up content from another hot spot for a split second in full beneath the newly hovered over area and corresponding description (hope that makes sense)
Is there anyway to complete one function in full before displaying the next to avoid this nasty display/animation?
Here is my code:
$(document).ready(function() {
$("#a-hover").hide();
$("#a").hover(function() {
$("#a-hover").fadeIn();
}).mouseleave(function() {
$("#a-hover").fadeOut();
});
$("#b-hover").hide();
$("#b").hover(function() {
$("#b-hover").fadeIn();
}).mouseleave(function() {
$("#b-hover").fadeOut();
});
$("#c-hover").hide();
$("#c").hover(function() {
$("#c-hover").fadeIn();
}).mouseleave(function() {
$("#c-hover").fadeOut();
});
And my CSS;
#a-hover,#b-hover,#c-hover {
z-index: 2;
float: left;
position: relative;
}
#a-hover,#b-hover,#c-hover,{
position: relative;
top: 0px;
left: 0px;
z-index: 1;
width:326px;
min-height:603px;
background-color:#dedddd;
}
*
*I have shortened my code for readability (I have 9 image map hot spots)
*I am a novice when it comes to jQuery but I am making a committment to learn so please go easy as my code may not be up to scratch!
*I have tried to solve this myself before posting here, but I am out of my depth and need some expert advice
I appreciate any responses.
Thank You,
Wp.
UPDTAE: I tried the majority of what was provided here as answers and whilst I believe these answers are on the right track I couldn't get the problem to stop however I did notice improvement in the animations overall.
I ended up using a combination .stop(true,true); and **resize font automatically.
**Ultimately not getting the desired result is due to my lack of polish with jQuery but being in a rush I managed to find another way to handle this issue (auto resizable font).****
Thanks to all who took the time out to answer and for those reading this for a similar solution at least know the .stop(true,true); properties did in fact work for me to solve one part of this problem.
A: Try adding .stop before each fadeIn and fadeOut. You should pass true, true to stop to complete the animating instantly rather than leave it half faded in:
$("#a").hover(function() {
$("#a-hover").stop(true, true).fadeIn();
}).mouseleave(function() {
$("#a-hover").stop(true, true).fadeOut();
});
You can also get rid of all of the repetition by binding on a class instead of id's:
$(".imageMapElement").hover(function() {
$("#" + $(this).attr("id") + "-hover").stop(true, true).fadeIn();
}).mouseleave(function() {
$("#" + $(this).attr("id") + "-hover").stop(true, true).fadeOut();
});
A: May be you can try Jquery Hover Intent plugin.
A: Try adding .stop() before each .fadeIn and .fadeOut -- that will cancel any previous animations and immediately begin your new one.
You also have a problem with using .hover() -- that actually encapsulates two actions, mouseover and mouseout. When you assign two functions to it, the first is mouseover and the second is mouseout, but when you assign only one function to it, that one function is used for both mouseover and mouseout. So, in effect, your code is causing the element to fadeIn and fadeOut on mouseout.
Incidentally, you can shorten your code a lot using standard jQuery techniques:
$("#a-hover,#b-hover,#c-hover").hide().hover(function() {
$(this).stop().fadeIn();
}, function() {
$(this).stop().fadeOut();
});
...or even better yet, assign a class to each of those three IDs and select it instead.
A: try stopping the other functions:
$("#a").hover(function() {
$("#b-hover").stop().hide();
$("#c-hover").stop().hide();
$("#a-hover").fadeIn();
}).mouseleave(function() {
$("#a-hover").fadeOut();
});
A: You have to chain all the jQuery function calls!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Can you enable Sql Cache Dependency on a database and/or table solely via Sql scripts? We would like to enable Sql Cache Dependency on a database and a few tables, but we would like to avoid using aspnet_regsql.exe if possible. The database is already in our staging environment and it will be easier to just send the admins a Sql script instead of requiring batch files as well. Is it possible to enable Sql Cache Dependency entirely through Sql scripts, and if so, how?
Thanks!
A: aspnet_reqsql.exe doesn't really do anything to 'enable' SqlCacheDependency. SqlCacheDependency is based on SqlDependency which uses SqlNotificationRequest which is the .net side of a Query Notification. Query Notifications are enabled always and cannot be disabled. Query Notifications uses Service Broker to deliver the notification, which is also enabled by default, but which can be disabled in a database. The typical operation that will disable Service Broker in a database is attach or restore. To make sure you do not fall victim to this problem, all you need to do (and this is exactly what aspnet_regsql does) is to run this:
ALTER DATABASE [<dbname>] SET ENABLE_BROKER WITH ROLLBACK IMMEDIATE;
Another problem that might occur is that the EXECUTE AS context required by Service Broker message delivery may be busted. For a lengthy discussion on how the EXECUTE AS can get busted, see SQL Server stops loading assembly, and the solution is trivial:
ALTER AUTHORIZATION ON DATABASE::[<dbname>] TO sa;
And finally, if you want to understand how all these work, read The Mysterious Notification.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to get a variable from a file to another file in Node.js Here is my first file:
var self = this;
var config = {
'confvar': 'configval'
};
I want this configuration variable in another file, so I have done this in another file:
conf = require('./conf');
url = conf.config.confvar;
But it gives me an error.
TypeError: Cannot read property 'confvar' of undefined
What can I do?
A: Edit (2020):
Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.
*
*For Node v13.9.0 and beyond, experimental modules are enabled by default
*For versions of Node less than version 13.9.0, use --experimental-modules
Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:
*
*Files ending in .mjs.
*Files ending in .js when the nearest parent package.json file contains a top-level field "type" with a value of "module".
*Strings passed in as an argument to --eval or --print, or piped to node via STDIN, with the flag --input-type=module.
Once you have it setup, you can use import and export.
Using the example above, there are two approaches you can take
./sourceFile.js:
// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default.
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary.
// You can actually omit declaring what variableName is here.
// { variableName } is equivalent to { variableName: variableName } in this case.
export default { variableName: variableName }
./consumer.js:
// There are three ways of importing.
// If you need access to a non-default export, then
// you use { nameOfExportedVariable }
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'
// Otherwise, you simply provide a local variable name
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'
./sourceFileWithoutDefault.js:
// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'
./consumer2.js
// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'
console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'
// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'
// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }
// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue
You can re-export anything from another file. This is useful when you have a single point of exit (index.{ts|js}) but multiple files within the directory.
Say you have this folder structure:
./src
├── component
│ ├── index.js
│ ├── myComponent.js
│ └── state.js
└── index.js
You could have various exports from both store.js and my-component.js but only want to export some of them.
./src/component/myComponent.js:
import createState from "./state";
export function example(){ };
./src/component/state.js:
export default function() {}
./src/component/index.js
export { example as default } from "./myComponent";
export * from "./myComponent"
./src/index.js
export * from "./component"
Original Answer:
You need module.exports:
Exports
An object which is shared between all instances of the current module
and made accessible through require(). exports is the same as the
module.exports object. See src/node.js for more information. exports
isn't actually a global but rather local to each module.
For example, if you would like to expose variableName with value "variableValue" on sourceFile.js then you can either set the entire exports as such:
module.exports = { variableName: "variableValue" };
Or you can set the individual value with:
module.exports.variableName = "variableValue";
To consume that value in another file, you need to require(...) it first (with relative pathing):
const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);
Alternatively, you can deconstruct it.
const { variableName } = require('./sourceFile');
// current directory --^
// ../ would be one directory down
// ../../ is two directories down
If all you want out of the file is variableName then
./sourceFile.js:
const variableName = 'variableValue'
module.exports = variableName
./consumer.js:
const variableName = require('./sourceFile')
A: File FileOne.js:
module.exports = { ClientIDUnsplash : 'SuperSecretKey' };
File FileTwo.js:
var { ClientIDUnsplash } = require('./FileOne');
This example works best for React.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612011",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "82"
} |
Q: Evaluating expressions contained as strings I've a database which returns vaild CL expressions within double quotes.
Is it possible to convert these strings to expressions.
For example, I make a query from this DB via CLSQL and as a result it returns me:
"(foo a b)"
How should I convert this expression to:
(foo a b)
and further evaluate it?
A: * (read-from-string "(+ 1 2)")
(+ 1 2)
7
There is a security problem. See the variable *read-eval*.
* (read-from-string "#.(+ 1 2)")
3
9
You really need to make sure that *read-eval* is NIL, so that reading will not evaluate code.
* (let ((*read-eval* nil)) (read-from-string "#.(+ 1 2)"))
debugger invoked on a SB-INT:SIMPLE-READER-ERROR:
can't read #. while *READ-EVAL* is NIL
Additionally calling EVAL on arbitrary input from a database is not a good idea.
Usually you want to make sure that the code does only call allowed functions.
A: > (read-from-string "(foo a b)")
(FOO A B) ;
9
The 9 is the second of multiple values produced by read-from-string; you can ignore it:
(eval (read-from-string "(foo a b)"))
will do what you want given the proper definitions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Lucas Kanade Optical Flow, Direction Vector I am working on optical flow, and based on the lecture notes here and some samples on the Internet, I wrote this Python code.
All code and sample images are there as well. For small displacements of around 4-5 pixels, the direction of vector calculated seems to be fine, but the magnitude of the vector is too small (that's why I had to multiply u,v by 3 before plotting them).
Is this because of the limitation of the algorithm, or error in the code? The lecture note shared above also says that motion needs to be small "u, v are less than 1 pixel", maybe that's why. What is the reason for this limitation?
A: @belisarius says "LK uses a first order approximation, and so (u,v) should be ideally << 1, if not, higher order terms dominate the behavior and you are toast. ".
A: A standard conclusion from the optical flow constraint equation (OFCE, slide 5 of your reference), is that "your motion should be less than a pixel, less higher order terms kill you". While technically true, you can overcome this in practice using larger averaging windows. This requires that you do sane statistics, i.e. not pure least square means, as suggested in the slides. Equally fast computations, and far superior results can be achieved by Tikhonov regularization. This necessitates setting a tuning value(the Tikhonov constant). This can be done as a global constant, or letting it be adjusted to local information in the image (such as the Shi-Tomasi confidence, aka structure tensor determinant).
Note that this does not replace the need for multi-scale approaches in order to deal with larger motions. It may extend the range a bit for what any single scale can deal with.
Implementations, visualizations and code is available in tutorial format here, albeit in Matlab not Python.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Using Ruby to send SMSs I'm trying to code for an sms server using the following tutorial.
http://lukeredpath.co.uk/blog/sending-sms-messages-from-your-rails-application.html
Here they advice us to use clickatell but i have a gateway that i can use which i would like to use. However i wouldn't know how to write the bits of code that says require clickatell or sudo gem install clickatell. I'm new to ruby and rails hence any help would be appreciated :)
A: In Gemfile:
gem 'clickatell`
Then run bundle install.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Sorting an array of unique random numbers at insertion I found a piece of code that works well to fill an array with a unique random numbers.
My problem now is, that I want to sort these numbers, but not after the array is full but
as new numbers are being inserted. So as each new number is inserted into the array, if finds the position it is meant to be in. The code I have for creating unique random numbers is below, thank you in advance:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
using namespace std;
#define MAX 2000 // Values will be in the range (1 .. MAX)
static int seen[MAX]; // These are automatically initialised to zero
// by the compiler because they are static.
static int randomNum[1000];
int main (void) {
int i;
srand(time(NULL)); // Seed the random number generator.
for (i=0; i<1000; i++)
{
int r;
do
{
r = rand() / (RAND_MAX / MAX + 1);
}
while (seen[r]);
seen[r] = 1;
randomNum[i] = r + 1;
}
for (i=0; i<1000; i++)
cout << randomNum[i] << endl;
return 0;
}
A: You're looking for insertion sort.
Once you got that working, you should switch to binary insertion sort. Binary insertion sort is much faster if the array is big.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the best way to secure/link an Air Application to a specified system I have to build (obviously using flex) an AIR application that must be linked to a given hardware (i.e. hard-disk), so it can't be copied elsewhere..
Usually using others languages, every time you open the application, a comparison between HardDisk or CPU ID and the value stored in the application itself...
Using Flex this is not possible (as far as I know)...
User/Password check obviously won't work..
I can't use a webservice, the application needs to work offline too..
How could I do?
A: With AIR you can integrate native apps - either indirectly (start a process and get its result) or directly (as a library).
Any of these techniques allow you to achieve your goal the same way you would in the case you described as "other languages"... BUT BEWARE: this makes your app platform-dependent AND can potentially lead to problems since it is prone to permissions issues etc.
Another point: no such technique is 100% secure (can be circumvented AND can lead to unsatisfied legitimate users!) - so you should really consider whether this is the way to go...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: zc.buildout is using the wrong python I'm using zc.buildout to generate a script called "test". I'm using that script to call my own test runner. (The available test runners for buildout do not yet use the new "discovery" feature in Python 2.7.)
Anyhow, here's the relevant section in my .cfg file:
[test]
recipe = buildout_script
template = runtests.sh.in
target = test
Here is what my runtests.sh.in template looks like
#!/bin/bash
python %(directory)s/src/runtests.py
And here is the resulting output that is placed in my bin folder as bin/test.
!/bin/bash
python /Users/myname/projects/myproject/trunk/www/src/desktop/src/runtests.py
When I execute this script, it's using the system Python instead of the Python in my bin folder.
The relevant section for that in my .cfg file is:
[python]
recipe = zc.recipe.egg
interpreter = python
eggs = ${buildout:eggs}
How do I get my script to use bin/python instead of the system python?
A: In your bash script, your are relying upon $PATH to determine which python to use. To change which python is invoked, you have several choices:
*
*Modify your environment to prefer a different version, i.e. in ~/.bashrc, add export PATH=/path/to/desired/python/bin:$PATH (of course with the appropriate substitutions
*Modify your bash script to explicitly state the path to python, thus avoiding using $PATH at all.
*Remove the explicit invocation of python, and change the sha-bang in the python script to select the appropriate version. (also, make sure the python script is marked executable).
A: You need to substitute the value of ${buildout:executable} into the template. I'm not sure how you refer to that using the buildout_script recipe, perhaps %(executable)s?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: With Capybara, how do I switch to the new window for links with "_blank" targets? Perhaps this isn't actually the issue I'm experiencing, but it seems that when I "click_link" a link with target="_blank", the session keeps the focus on the current window.
So I either want to be able to switch to the new window, or to ignore the _blank attribute - essentially, I just want it to actually go to the page indicated by the link so I can make sure it's the right page.
I use the webkit and selenium drivers.
I submitted my findings thus far below. A more thorough answer is much appreciated.
Also, this only works with selenium - the equivalent for the webkit driver (or pointing out where I could discover it myself) would be much appreciated.
A: Capybara >= 2.3 includes the new window management API. It can be used like:
new_window = window_opened_by { click_link 'Something' }
within_window new_window do
# code
end
A: I know this is old post, but for what its worth in capybara 2.4.4
within_window(switch_to_window(windows.last)) do
# in my case assert redirected url from a prior click action
expect(current_url).to eq(redirect['url'])
end
A: Seems like it is not possible with capybara-webkit right now: https://github.com/thoughtbot/capybara-webkit/issues/271
:-(
At the same time https://github.com/thoughtbot/capybara-webkit/issues/129 claims it is possible to switch windows with within_window.
Also https://github.com/thoughtbot/capybara-webkit/issues/47 suggests that page.driver.browser.switch_to().window(page.driver.browser.window_handles.last) works. Ah well, on to code reading.
The code at https://github.com/thoughtbot/capybara-webkit/blob/master/lib/capybara/webkit/browser.rb at least has some references that suggest that the API that works for webdriver / firefox is also working for webkit.
A: Now within_window implemented for capybara-webkit http://github.com/thoughtbot/capybara-webkit/pull/314 and here you can see how to use it http://github.com/mhoran/capybara-webkit-demo
A: As of May 2014 the following code works on capybara-webkit
within_window(page.driver.browser.window_handles.last) do
expect(current_url).to eq('http://www.example.com/')
end
A: To explicitly change window, you use switch_to_window
def terms_of_use
terms_window = window_opened_by do
click_link(@terms_link)
end
switch_to_window(terms_window)
end
An after that method browser will work in the new page, instead of wrap everything in a within_window block
A: This solution only works for the Selenium driver
All open windows are stores in Selenium's
response.driver.browser.window_handles
Which seems to be an array. The last item is always the window that was most recently opened, meaning you can do the following to switch to it.
Within a block:
new_window=page.driver.browser.window_handles.last
page.within_window new_window do
#code
end
Simply refocus for current session:
session.driver.browser.switch_to.window(page.driver.browser.window_handles.last)
Referenced on the capybara issues page: https://github.com/jnicklas/capybara/issues/173
More details on Selenium's window switching capabilities: http://qastuffs.blogspot.com/2010/10/testing-pop-up-windows-using-selenium.html
A: This works for me in capybara-webkit:
within_window(windows.last) do
# code here
end
(I'm using capybara 2.4.1 and capybara-webkit 1.3.0)
A: You can pass a name, url or title of the window also
(But now its dipricated)
let(:product) { create :product }
it 'tests' do
visit products_path
click_link(product.id)
within_window(product_path(product)) do
expect(page).to have_content(product.title)
end
end
You can pass a labda or a proc also
within_window(->{ page.title == 'Page title' }) do
click_button 'Submit'
end
wish it stretches the method usage to more clearly understaing
A: I had this issue when opening links in an gmail window: I fixed it like this:
Given /^(?:|I )click the "([^"]*)" link in email message$/ do |field|
# var alllinks = document.getElementsByTagName("a");
# for (alllinksi=0; alllinksi<alllinks.length; alllinksi++) {
# alllinks[alllinksi].removeAttribute("target");
# }
page.execute_script('var alllinks = document.getElementsByTagName("a"); for (alllinksi=0; alllinksi<alllinks.length; alllinksi++) { alllinks[alllinksi].removeAttribute("target"); }')
within(:css, "div.msg") do
click_link link_text
end
end
A: The best idea is to update capybara to the latests version (2.4.1) and just use
windows.last
because page.driver.browser.window_handles is deprecated.
A: This is now working with Poltergeist. Although window_handles is still not implemented (you need a window name, i.e. via a JavaScript popup):
within_window 'other_window' do
current_url.should match /example.com/
end
Edit: Per comment below, Poltergeist now implements window_handles since version 1.4.0.
A: Capybara provides some methods to ease finding and switching windows:
facebook_window = window_opened_by do
click_button 'Like'
end
within_window facebook_window do
find('#login_email').set('[email protected]')
find('#login_password').set('qwerty')
click_button 'Submit'
end
More details here: Capybara documentation
A: The main implementation (window_opened_by) raises an error for me:
*** Capybara::WindowError Exception: block passed to #window_opened_by opened 0 windows instead of 1
So, I resolve it by this solution:
new_window = open_new_window
within_window new_window do
visit(click_link 'Something')
end
page.driver.browser.window_handles
# => ["CDwindow-F7EF6D3C12B68D6B6A3DFC69C2790718", "CDwindow-9A026DEC65C3C031AF7D2BA12F28ADC7"]
A: I personally like the following approach since it works correctly regardless of JS being enabled or not.
My Spec:
it "shows as expected" do
visit my_path
# ...test my non-JS stuff in the current tab
switch_to_new_tab
# ...test my non-JS stuff in the new tab
# ...keep switching to new tabs as much as necessary
end
# OR
it "shows as expected", js: true do
visit my_path
# ...test my non-JS stuff in the current tab
# ...also test my JS stuff in the current tab
switch_to_new_tab
# ...test my non-JS stuff in the new tab
# ...also test my JS stuff in the new tab
# ...keep switching to new tabs as much as necessary
end
Test helpers:
def switch_to_new_tab
current_browser = page.driver.browser
if js_enabled?
current_browser.switch_to.window(current_browser.window_handles.last)
else
visit current_browser.last_request.fullpath
end
end
def js_enabled?
Capybara.current_driver == Capybara.javascript_driver
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612038",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "83"
} |
Q: how to detect colour from an image matlab? we are doing a mat lab based robotics project.which actually sorts objects based on its color so we need an algorithm to detect specific color from the image captured from a camera using mat lab.
it will be a great help if some one can help me with it.its the video of the project
A: In response to Amro's answer:
The five squares above all have the same Hue value in HSV space. Selecting by Hue is helpful, but you'll want to impose some constraints on Saturation and value as well.
HSV allows you to describe color in a more human-meaningful way, but you still need to look at all three values.
A: As a starting point, I would use the rgb space and the euclidian norm to detect if a pixel has a given color. Typically, you have 3 values for a pixel: [red green blue]. You also have also 3 values defining a target color: [255 0 0] for red. Compute the euclidian norm between those two vectors, and apply a decision threshold to classify the color of your pixel.
Eventually, you want to get rid of the luminance factor (i.e is it a bright red or a dark red?). You can switch to HSV space and use the same norm on the H value. Or you can use [red/green blue/green] vectors. Before that, apply a low pass filter to the images because divisions (also present in the hsv2rgb transform) tend to increase noise.
A: You probably want to convert to the HSV colorspace, and detect colors based on the Hue values. MATLAB offers the RGB2HSV function.
Here is an example submission on File Exchange that illustrate color detection based on hue.
A: For obtaining a single color mask, first of all convert the rgb image gray using rgb2gray. Also extract the desired color plane from the rgb image ,(eg for obtaining red plain give rgb_img(:,:,1)). Subtract the given plane from the gray image........
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: make a label textbox after click i have amount column in a table that shows on web page.
what i want to do is when page open up to show amount as label.
when user clicks on the amount it becomes editable like textbox.
A: Do you mean something like this (using jQuery):
<span id="amount">3.25</span>
<input id="amount_entry" name="amount" style="display:none;"></input>
$('#amount').click(function() {
$('#amount').css('display', 'none');
$('#amount_entry')
.val($('#amount').text())
.css('display', '')
.focus();
});
$('#amount_entry').blur(function() {
$('#amount_entry').css('display', 'none');
$('#amount')
.text($('#amount_entry').val())
.css('display', '');
});
Sample demo: http://jsfiddle.net/LFgxr/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Template for a single dimension array with Knockout.js and ko.mapping I have a JSON string that I am mapping with ko.mapping plugin and I need to create observable bindings for one of the mapped arrays. The array is in the JSON as [1,2,3,4,5] so it has no index.
I have the following code working to a certain point:
<script id="statRowTemplate" type="text/html">
{{if type() != "column"}}
<tr>
<td><label>Name: </label><input data-bind="value: name" /></td>
<td><label>Plot Points: </label><ul data-bind="template: {name: 'dataTemplate' , foreach: data}"></ul> </td>
</tr>
{{/if}}
</script>
<script type="text/html" id="dataTemplate">
<li>
<p>${this.data}</p>
<input data-bind="value: this.data" />
</li>
</script>
<button data-bind="click: saveChanges">Save Changes</button>
So everything is working as expected except <input data-bind="value: this.data" /> That field remains blank ... ${this.data} Shows the correct value however.
Overall, I am tying to update a JSON string and re-save it in a flat file. I can bind the data array: [1,2,3,4] directly to the input value but then it does not update as an array.
Here is the viewModel:
var viewModel = {};
$.getJSON('/data-forecast-accuracy.json', function(result) {
viewModel.stats = ko.mapping.fromJS(result);
console.log(result)
viewModel.saveChanges = function() {
var unmapped = ko.mapping.toJSON(viewModel.stats);
console.log(unmapped);
$.post('save-changes.php', {data: unmapped})
.success(function() { console.log("second success"); })
.error(function() { console.log("error"); })
.complete(function() { console.log("complete"); });
}
ko.applyBindings(viewModel);
});
Here is the JSON:
[
{
"type":"spline",
"marker":{
"symbol":"diamond"
},
"name":"Cumulative",
"data":[10,17,18,18,16,17,18,19]
},
{
"type":"spline",
"marker":{
"symbol":"circle"
},
"name":"Monthly",
"data":[10,22,20,19,8,20,25,23]
}
]
Any help would be greatly appreciated. Also open to suggestions if I am approaching this from the wrong angle. Ultimately just want to be able to modify the JSON sting through a UI and then save it.
Thanks in advance.
A: To properly edit a value in the array, you will want to map the original array to a structure that contains an actual property to bind against [1,2,3] becomes [{val: 1}, {val: 2}, {val: 3}]. Binding against $data will not work, as KO is not able to determine how to update it from user input (currently not able to understand that it is located at some index in an array).
I like to do something like: http://jsfiddle.net/rniemeyer/vv2Wx/
This uses this technique to make the array look like the original automatically when it is turned into JSON.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: onLongClickListener never get trigered I have a custom listView defined like this
public class DDListView extends ListView implements OnScrollChangedListener {
than I make an instance of it with name mExampleList I set onLongClickListener but it never get called, where is my problem ?
mExampleList.setOnLongClickListener(new OnLongClickListener() {
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
Log.v("vvv", "sdfsdf");
return false;
}
});
A: I think you want to be using OnItemLongClickListener instead of OnClickListener.
A: Mmmmm , are you trying to make all ListView longclckeable?
Some tips:
-Try first to see if normal OnClick gets fired;
-Try to see if you have setClickeable(true); on it;
-Try to see if you are really trying to do that and not an usual onItemClick() of the items in the list (to do this @override the function :
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Binding on privileged ports (ports < 1024) on Mac OS X 10.6 Do you know how to remove restriction on binding to ports < 1024 with a user account that is not root on Mac OS X?
A: The best way is to leverage launchd. The restriction on binding to ports < 1024 will still be there and is not likely to go anywhere, but if your app requests elevated privileges once in order to add the necessary launchd configuration, then you can let launchd do the actual listening on the privileged port and pass the socket to your app when appropriate.
See the section on launchd in this OS X Developer Library reference, and the further references given there for learning more about launchd and how to use it safely.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Cron Kohana action and prevent CSRF I need to call a Kohana action through cron. I can use this code to limit only to the server IP:
$allowedIps = array('127.0.0.1','::1');
if(in_array($_SERVER['REMOTE_ADDR'],$allowedIps))
Do I need CSRF prevention, like tokens? The server is a Parallel's VPS. I wouldn't think there would be any users on a network browsing other pages making them susceptible to CSRF.
The only way I can think of preventing this, if needed, is to create a non-accessible PHP script outside of Kohana called by cron, generate a token and save to flat file, and pass that token to Kohana via an outside include using this
http://forum.kohanaframework.org/discussion/1255/load-kohana-from-external-scriptapp/p1
A: If the script is going to be called via the local machine (which it is according to your code sample) then you could simplify that by making sure the code is called via the CLI.
if (Kohana::$is_cli)
{
// Run function
}
As for CSRF tokens, you don't need them for this. CSRF works by exploiting someone to click a link which initiates an action on their behalf. Since you can't access the cron controller/action via a browser (you shouldn't be able to) you don't need to worry about it.
A: I'm pretty sure you want to use this module for any CLI-related tasks. It'll probably be included as official Kohana module since 3.3 version as it's very popular and supported.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Strange Android Permissions Issue I recently decided to provide haptic feedback for the buttons in my app. I looked up how to get the Vibrator from the activity and arranged for my button object to call vibrate().
Truth be told, the first time around, I had in fact forgotten to set the permission android.permission.VIBRATE, but I quickly put that into the manifest once the exception was thrown.
The problem is that the app continues to throw a security exception claiming the app does not have the VIBRATE permission. I've uninstalled the app on the test phone. I've done a clean build of the project, even restarted Eclipse just for giggles, but nothing makes this exception go away.
Can anyone think of a reason why this would happen?
A: The only time this has ever happened to me, it was due to Eclipse creating bad APKs. Maybe try deleting your bin folder entirely and then rebuild?
Also, I double check your manifest to be absolutely sure you spelled the permission properly.
A: Are you sure you used <uses-permission android:name="android.permission.VIBRATE"/> and not just <uses-permission name="android.permission.VIBRATE"/>?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get text from an EditText In my app I have an EditText that I want to get the value out of when it looses focus. How should I do this?
Thanks!
A: Along the lines of this should work.
EditText.setOnFocusChangeListener(new View.OnFocusChangeListener()
{
@override
public void onFocusChange(View v, boolean hasFocus)
{
if (!hasFocus) {
string value = (EditText) v.getText().ToString();
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Inheritance... C++ syntax I have to make a trivial class that has a few subclasses and one of those subclasses has it's own sublcass.
AccountClass.h
#ifndef Account_h
#define Account_h
class Account{
public:
//Account(){balance = 0.0;}; Here's where the problem was
Account(double bal=0.0){ balance = bal;};
double getBal(){return balance;};
protected:
double balance;
};
#endif
SavingsAccount.h
#ifndef SavingsAccount_h
#define SavingsAccount_h
#include "AccountClass.h"
class SavingsAccount : public Account{
public:
//SavingsAccount(); And here
SavingsAccount(double bal = 0.0, int pct = 0.0){ balance = bal; rate = pct; } : Account(bal);
void compound(){ balance *= rate; };
void withdraw(double amt){balance -= amt;};
protected:
double rate;
};
#endif
CheckingAccount.h
#ifndef CheckingAccount_h
#define CheckingAccount_h
#include "AccountClass.h"
class CheckingAccount : public Account{
public:
//CheckingAccount(); Here also
CheckingAccount(double bal = 0.0, double lim = 500.0, double chg = 0.5){ balance = bal; limit = lim; charge = chg;} : Account(bal);
void cash_check(double amt){ balance -= amt;};
protected:
double limit;
double charge;
};
#endif
TimeAccount.h
#ifndef TimeAccount_h
#define TimeAccount_h
#include "SavingsAccount.h"
class TimeAccount : public SavingsAccount{
public:
//TimeAccount(); ;)
TimeAccount(double bal = 0.0, int pct = 5.0){ balance = bal; rate = pct;} : SavingsAccount(bal,pct);
void compound(){ funds_avail += (balance * rate); };
void withdraw(double amt){funds_avail -= amt;};
protected:
double funds_avail;
};
#endif
I keep getting errors that default constructors are defined as well as all the variables not existing...
Help!
Edit:
Fixed the preprocessor ifndef's
Also, this was solved. Thanks @Coincoin!
A: You didn't define your default constructors, but they're being called by default when you derive new classes. It looks like TimeAccount will be the culprit of that issue since it uses the default constructor of SavingsAccount. They all however, should be defined and not just declared.
A: These:
SavingsAccount();
CheckingAccount();
TimeAccount();
need to have definitions so:
SavingsAccount(){};
CheckingAccount(){};
TimeAccount(){};
should work
A: There are multiple errors in the way you defined your constructors.
*
*Some of them don't have a body defined
*The intialisation lists are syntaxicaly not at the right place
*You try to define two default constructor by using default valued parameters.
The initialisation list goes between the signature and the body.
Like so:
SavingsAccount(double bal = 0.0, int pct = 0.0)
:Account(bal)
{
balance = bal; rate = pct;
}
Also, you already have a default constructor yet you have parameter list with all parameters with default values, which means you are trying to define two default constructors. You either need to remove the default value for the bal parameter or remove the default constructor and use the entirely default valued constructor as the default constructor.
Like so:
Account(){balance = 0.0;};
Account(double bal){ balance = bal;}
or
Account(double bal=0.0){ balance = bal;}
A: If you have defaults for all the constructor's arguments, how does the compiler know which to call when you write:
TimeAccount t;
You are probably seeing "ambiguous function call" type errors. Also, why is pct an int in TimeAccount()? The default argument is a double and it stores that value into a field of type double.
A: You need to write default constructors for everything. Plus make sure you obey the rule of three if you need to define copy constructor/destructor/assignment operator.
TimeAccount():
bal(0),
pct(5.0)
{
}
TimeAccount(double bal, int pct)
{
balance = bal;
rate = pct;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to use C++11 uniform initialization syntax? I cannot understand when and how to use the new uniform initialization syntax in C++11.
For example, I get this:
std::string a{"hello world"}; // OK
std::string b{a}; // NOT OK
Why does it not work in the second case? The error is:
error: no matching function for call to ‘std::basic_string<char>::basic_string(<brace enclosed initializer list>)’
with this version of g++ g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2.
And with primitive data, what syntax should I use?
int i = 5;
int i{5};
int i = {5};
A: It doesn't work because you forgot the semicolon:
std::string b{a};
^^^
Otherwise this syntax is fine, and it calls the copy constructor.
For the second question, use int i{5}; if you want to be uniform, though int i = 5; is probably more readable.
A: The compile error for
// T t{u};
std::string a;
std::string b{a};
Is a combination of four things
*
*The draft until not long ago said that if T has an initializer list constructor (std::string has one, taking char elements), that the initializer list is passed itself as an argument. So the argument to the constructor(s) is not a, but {a}.
*The draft says that an initializer list initializing a reference is done not by direct binding, but by first constructing a temporary out of the element in the initializer list, and then binding the target reference to that temporary.
*The draft says that when initializing a reference by an initializer list, when the initialization of the reference is not direct binding, that the conversion sequence is a user defined conversion sequence.
*The draft says that when passing the initializer list itself when considering constructors of class X as candidates in an overload resolution scenario in a context like the above, then when considering a first constructor parameter of type "reference to cv X" (cv = const / volatile) - in other words highly likely a copy or move constructor, then no user defined conversions are allowed. Otherwise, if such a conversion would be allowed, you could always run in ambiguities, because with list initialization you are not limited to only one nested user defined conversion.
The combination of all the above is that no constructor can be used to take the {a}. The one using initializer_list<char> does not match, and the others using string&& and const string& are forbidden, because they would necessitate user defined conversions for binding their parameter to the {a}.
Note that more recent draft changed the first rule: They say that if no initializer list constructor can take the initializer list, that then the argument list consists of all the elements of the initializer list. With that updated rule, your example code would work fine.
A: The first example is supposed to work, calling the copy constructor. If you're using GCC, this has been fixed in 4.6.
The last examples have a slight non stylistic difference.
int i = 5.0; // fine, stores 5
int i{5.0}; // won't compile!
int i = {5.0}; // won't compile!
The difference is that uniform initialization syntax does not allow narrowing conversions. You may want to take this into consideration when choosing between them.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: With ASP.Net MVC3 unobtrusive validation, is it possible to activate real time validation before the form is submitted? When using MVC3 unobtrusive validation, the user initially fills in the form without any validation occurring. After the form is submitted and validation errors occur, validation then occurs in real-time as the user types and moves between fields. Is it possible to have this real-time validation behaviour switched on before the form is submitted?
A: You could call $form.valid() to validate the whole form on page load but then they get a validation summary at the top (assuming you've enabled it) along with validation messages next to each input.
How about validating each field as it is changed? You could attach to the change event like so: $fields.change(function (event) { $(event.target).valid() }); which would run valid() on the field after it is changed. You can of course substitute another event for change to match more closely the function you need.
I don't know of an official way to mimic the post-submit-attempt validation exactly...
A: Make sure both ClientValidationEnabled and UnobtrusiveJavaScriptEnable are set to true in your web.config.
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
A: Try this:
var isValid = $('#formId').validate().form();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: efficient disk storage of decimal numbers in C (C89) I am writing functions that serialize/deserialize a large data structure for efficient reloading later on. There is a particular set of decimal numbers for which precision is not a huge deal, and I would like to store them in 4 bytes of binary data.
For most, reading the bytes into a buffer and using memcpy to place them into a float is sufficient, and is the most common solution I've found. However, this is not portable, as floats on the systems this software is meant for are not guaranteed to be 4 bytes in size.
What I would like is something very portable (which is one of the reasons I'm limited to C89). I'm not wedded to 4 byte storage, but it is an attractive option to me. I am pretty wholly against storing the numbers as strings. I'm familiar with endianness issues, and such things are already taken into account.
What I am looking for, therefore, is a system-independent way to store and retrieve floating point numbers in a small amount of binary data (preferably around 4 bytes). I, in my foolishness, imagined this would be the easiest part of this task, since it seems like such a common problem, but popular search engines and various reference books have provided no material assistance.
A: You could store them in 32 bit IEEE float format (or a very close approximation to it, for instance you might what to restrict denorms and NaNs). Then have each platform adjust as necessary to coerce its own float type to that format and back.
Of course there will be some loss of accuracy, but that's inevitable anyway if you're transferring float values of difference precisions from one system to another.
It should be possible to write portable code to find the closest IEEE value to a native float value, and vice-versa, if that's required. You wouldn't really want to use it, though, because it would probably be far less efficient than code that takes advantage of knowing the float format. In the common case where the platform uses an IEEE representation it's a no-op or a simple narrowing/widening conversion. Even in the worst case you're likely to encounter, as long as it's a binary fraction you basically just have to extract the sign, exponent and significand bits and do the right thing with them (discard bits from the significand if it's too big, adjust the bias and possibly the width of the exponent, do the right thing with underflow and overflow).
If you want to avoid losing accuracy in the case where the file is saved and then reloaded on the same system (but that system doesn't use 32bit IEEE), you could look at storing some data indicating the format in the file (size of each value, number of bits of significand and exponent), then store each value at native precision, so that it only gets rounded if it's ever loaded onto a less-precise system. I don't know whether ASN.1 has a standard to encode floating-point values along these lines, but it's the kind of complicated trickery I'd expect from it.
A: Check this out:http://steve.hollasch.net/cgindex/coding/portfloat.html
They give a routine which is portable and doesnt add too much overhead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to get the value of a private member using reflection C# 4 I am trying to get the private member's value (Text) from NumericUpDown.
public class NumericUpDown
{
private TextBox Text;
...
...
}
I am not understanding why it's not showing as a field. Maybe someone could clarify the difference between fields and members. If it was a field I have found that using reflection I can get it by:
typeof(NumericUpDown).GetField("Text", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this) As TextBox
but it's a member so I have to get the MemberInfo by:
typeof(NumericUpDown).GetMember("Text", BindingFlags.FlattenHierarchy | BindingFlags.NonPublic | BindingFlags.Instance).GetValue(0)
this does not return the value, but a string with the type. Which would make sense, because It's the value of the memberinfo, but I want the actual value of the actual object.
Is there any way of retrieving it like FieldInfo.GetValue(object)? Any help or suggestions. Thanks in advance.
A: This is because you are using Silverlight.
Quote:
Silverlight reflection cannot be used to bypass access level restrictions and (for example) invoke private members.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Creating symbols inline that use images and text I have a circle image that's fairly large in size to make it easy to resize it smaller or larger depending on where it goes. Its meant to be a background image to a character or two of text.
Basically, in a specific element, wherever the number 1 or 2 appears, I want the circle to appear behind the text, wherever the text happens to be in that element. Mixed in with the text are other images that can just be put in without an issue. I'm sizing them by ems to keep them where they need to go.
So for the sake of making this work as an example/question:
This is the image: http://gumOnShoe.net/NewCard/Frames/Mana/mana_circle.png
So, basically, I need the text to work like this:
This is a paragraph (1) of the text.
Where (1) has the image sized down appropriately with the numeral 1 centered inside of it. the image can be 1.2 em to compensate the text, but I'll size that later. I'm doing this in javascript, but if anyone could help me figure out what the CSS style is going to be I can go with it from there.
Some additional things about the page is that the symbol/text hybrid has to sit within a table cell that's floating to the right of a div, that's relatively positioned, inside of another absolutely positioned div. Not sure if any of that will mess with the display settings, but that's what I'm looking at. Thanks.
A: You will want to include the (1) inside of a span that is set to display: inline-block;
This will give the span block element capabilities (set a background-image and width) while still flowing with the text. You can change the background image size by using the property background-size and setting it to the same width of the span.
Check out this JSFiddle.
A: I can only see this working with a mono-space font. Use your image for the background-image of the element containing the text. Get the index of the '1' in the string. Set the background-position to an em value of the index + 1. If there are multiple occurrences, you will have to layer additional absolutely positioned elements below the element containing the text.
A: As far as I know, you can't change the size of a background image using CSS. If your image didn't have to be resized dynamically, you could just wrap the number in a <span> with the appropriate background-image and other CSS rules set.
However, the following will work in the latest browsers that support CSS display: inline-block;:
<p>
Lorem
<img
src="http://gumOnShoe.net/NewCard/Frames/Mana/mana_circle.png"
style="width: 1em; height: 1em;" />
<span
style="margin-left: -1em;
width: 1em;
display: inline-block;
text-align: center;">1</span>
ipsum.
</p>
Personally, though, I'd create different sized images and use them as background-images for a span around a number. Something like:
<p class="big-text">
Lorem <span class="number">1</span> ipsum
</p>
<p class="small-text">
Lorem <span class="number">1</span> ipsum
</p>
... with CSS:
p.big-text span.number {
background-image: url(/big-circle.png);
}
p.small-text span.number {
background-image: url(/small-circle.png);
}
A: Since I cant edit my comment above, I thought of posting it as an answer:
Using css3, you could probably do it like this:
font-family:monospace;
font-size:2em;
padding:5px;
background: url(http://gumonshoe.net/NewCard/Frames/Mana/mana_circle.png) no-repeat center center;
-webkit-background-size: contain;
-moz-background-size: contain;
-o-background-size: contain;
background-size: contain;
checkout the demo: http://jsfiddle.net/gWhqP/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Writing jQuery Plugins using OOP I was wondering what's the current "state-of-the-art" to write a jQuery Plugins.
I read a lot of different approaches and I don't know which one fits best.
Can you recommondation usefull links/templates for writing jQuery Plugins using OOP.
Thanks
A: the basic rules are:
*
*Don't clutter the jQuery namespace with your code - there should
only be one method per plugin added to root of the jQuery object or
to jQuery.fn
*Use an immediately executing anonymous funciton to ensure the code
is run just once
*Pass in the jQuery object as a parameter with the identifier $,
can safely use the $ in this scope then :)
*REMEMBER when you add a new method to jQuery.fn, this is
bound to a jQuery wrapped set, you don't have to wrap it again!
*use this.each to loop through all matched elements
*return this from your plugin to enable chainability (unless of course your plugin returns a distinct value)
*allow options to be passed in and overlayed over some default object (which you also expose to be overriden)
*allow for defaults to be re-set by user for global changes
(function($) { //see point 3
var defaults = {
someDefaultValues : "value"
};
$.fn.myPlugin = function(options) { // see point 1, only 1 method
var settings = $.extend({}, defaults, options); //see point 7
this.each(function() { //see point 5
var currentElement = $(this); //"this" now refers to current DOM element
//put bulk of logic here
});
return this; //see point 6
};
//see point 8, enables users to completely override defaults, rather than per call via options
$.fn.myPlugin.defaults = defaults;
})(jQuery); //see point 2
see the jQuery docs for a good guide, they go into more advanced details considering how you might want to execute more than one method per plugin, plus storing data on elements and other things. Most of the stuff i have
A: Two links/templates I refer to are Stefan Gabos jQuery Plugin Boilerplate and Oscar Godson's jQuery Plugin Skeleton
I'm not claiming they're "state of the art" but they've served me very well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612098",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: System.Object in C#, .NET I don't really understand the second question, is my answer to the second question correct?
*
*Which of the following is not a method of System.Object?
*What is the most generic (least derived) interface or subclass of System.Object of which it is a method?
a. GetType()
b. ToString()
c. Equals(object obj)
d. Clone()
My Answers:
Clone() is not a method of System.Object.
ICloneable for Clone. System.Object is the root type, the rest of the methods are its direct members.
What is the answer to the second question? What does it mean?
Any advice would be very much appreciated.
A: Your answer to the first question is of course correct. Proof.
The second question means, that if you had interface IExtendedCloneable which would derive from ICloneable (had ICloneable as parent interface), it would not be a corect answer, because ICloneable is more generic (less derived) - it is closer to object on the inheritance tree.
If there wasn't that restriction, you could say that Clone() is a member of System.Windows.Forms.Control.ControlCollection and you would be right, but the answer wouldn't be really relevant.
Thanks to that restriction, ICloneable is the answer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: convert date yyyymmdd to yyJJJ or Julian Date Need a formula in excel and c# to convert data in "yyyymmdd" format to julian date format "yyJJJ"? Where "JJJ" is the Julian date of day submitted. Is JJJ a number from 1 to 365 or 999 or 366? I don't think its 366, but we do have leap year so it could be leap year.
In Excel I'm trying to use the following:
=Year() & DAYS360("20110101","20110930")
In C# I'm using now() to get the current date. But I'm want the number of days between Jan 1st, and current date. Not sure if this is the correct prototype formula:
Prepend Two digit year format to the following
Number of Days between "20110101" and "20110930" in "YY" format
A: According to these articles, you should be using the term "Ordinal date" rather than "Julian date":
http://en.wikipedia.org/wiki/Ordinal_date
http://en.wikipedia.org/wiki/Julian_day
According to the first, the ISO standard for ordinal date specifies a 4-digit year, and that the range is from 1 to 366, so January 1st is 1.
This of course means that dates between March and December will have two possible values depending on whether the date falls in a leap year.
Bala's solution (with the + 1 option given in the comments) will therefore suffice.
EDIT: The DateTime type's own DayOfYear property, as Jim Mischel pointed out, is simpler and probably faster.
A: in c# you can do
DateTime dt = DateTime.Now;
DateTime firstJan = new DateTime(dt.Year, 1, 1);
int daysSinceFirstJan = (dt - firstJan).Days + 1;
A: I believe what you are looking for is this:
DateTime dt = DateTime.Now;
string ordinalDate = dt.ToString("yy") + dt.DayOfYear.ToString("000");
This will give you a string that is always 5 digits with a two digit year and 3 digit day of the year.
Keveks answer will give you a string that could be 3, 4, or 5 digits.
A: Instead of handling this yourself in C#, you could simply use the JulianCalendar class
And to get today in the Julian calendar, you could do:
JulianCalendar calendar = new JulianCalendar();
var today=DateTime.Today;
var dateInJulian = calendar.ToDateTime(today.Year, today.Month, today.Day, today.Hour, today.Minute, today.Second, today.Millisecond);
EDIT:
And I realized I didn't help you with a good way to get a result in the YYJJJ format you were looking for, it's quite simple:
var stringResult=string.Format("{0}{1}", dateInJulian.ToString("yy"), dateInJulian.DayOfYear);
Sadly, I don't think there's an equivalent of dateTime.ToString("JJJ"); that will give the day of the year, hence my little string.Format() work-around, but it works just as well!
EDIT2:
So Phoog educated me a bit below in the comments, and pointed out that you weren't looking for today in the Julian Calendar, which is what the above code would give in respect to the JulianCalendar class. Rather, it appears you're looking for the Ordinal date (this piece added for future reader clarification). I'm going to leave the above so that someone doesn't make the same mistake that I did. What you really want, I believe, is the code from the first edit but without the JulianCalendar business, so:
var dateToConvert = DateTime.Today // Or any other date you want!
var stringResult=string.Format("{0}{1}", dateToConvert.ToString("yy"), dateToConvert.DayOfYear);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Adding item to a list/collection (with MVC EF 4.1 code first) Having problem with adding item/object into a list/collection.
This is what I've done so far...
public abstract class Member
{
[DisplayName("ID")]
public string MemberId { get; set; }
[DisplayName("Date Applied")]
public System.DateTime? DateApplied { get; set; }
[DisplayName("Date Membered")]
public System.DateTime? DateMembered { get; set; }
[DisplayName("Member Type")]
public int MemberTypeFlag { get; set; }
private ICollection<Address> _Addresses;
public virtual ICollection<Address> Addresses
{
get { return _Addresses ?? (_Addresses = new HashSet<Address>()); }
set { _Addresses = value; }
}
}
public class Person : Member
{
[DisplayName("Last Name")]
public string LastName { get; set; }
[DisplayName("First Name")]
public string FirstName { get; set; }
[DisplayName("Date Of Birth")]
public System.DateTime DateOfBirth { get; set; }
}
And this is how I mapped it..
public class MapAddress : EntityTypeConfiguration<Address>
{
public MapAddress()
: base()
{
HasKey(a => a.MemberId).HasOptional(a => a.Member).WithMany(i => i.Addresses);
Property(p => p.Address1).HasColumnName("ADDRESS1");
Property(p => p.Address2).HasColumnName("ADDRESS2");
Property(p => p.City).HasColumnName("CITY");
Property(p => p.ZipCode).HasColumnName("ZIPCODE");
Property(p => p.AddressTypeFlag).HasColumnName("ADDRESS_TYPE_FFLG");
ToTable("MBR_ADDRESS");
}
}
And error raised upon saving..
"Validation failed for one or more entities. See 'EntityValidationErrors' property for more details."
This is how I add into a collection..
public void Apply(PersonInformation member)
{
Person person = new Person();
person = member.person;
person.MemberId = CustomID.GenerateID();
person.MemberTypeFlag = (int)Enum.Parse(typeof(EnumMemberType), "Person");
person.DateApplied = DateTime.Now;
Address baddress = new Address();
baddress = member.billingAddress;
Address paddress = new Address();
paddress = member.premiseAddress;
person.Addresses.Add(baddress);
person.Addresses.Add(paddress);
context.People.Add(person);
context.SaveChanges();
}
Or there are other elegant way to save a member with many address.
A: Why are you creating a new person and 2 new addresses then reassigning the variable 1 line later? There's a lot of redundant code in your example.
Your code basically boils down to the following:
public void Apply(PersonInformation member)
{
member.person.MemberId = CustomID.GenerateID();
member.person.MemberTypeFlag = (int)Enum.Parse(typeof(EnumMemberType), "Person");
member.person.DateApplied = DateTime.Now;
member.person.person.Addresses.Add(member.billingAddress);
person.Addresses.Add(member.premiseAddress);
context.People.Add(member.person);
context.SaveChanges();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Custom User.Identity to add property I customize RoleProvider and MembershipProvider classes
I would like to add one more property in my @User.Identity, as do so?
example:
@User.Identity.About => .About not exist yet
I thought I'd customize IIdentity but do not know where to start.
A: You need to create your own classes that implement IIdentity and IPrincipal. Then assign them in your global.asax in OnPostAuthenticate.
A: Just create a wrapper and override Page.User.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Access error creating linked Oracle table I try to create a linked table pointing to Oracle. To make it simple, I "stole" the connection string from a manually created linked table that is working well. The code breaks in the Append, where indicated below. Any clue ? Thanks !
Sub CreaOra()
Dim db As DAO.Database
Dim td As DAO.TableDef
Dim strConn As String
Set db = CurrentDb
'connection string copied from a working linked table !'
strConn = "ODBC;DRIVER={Oracle in OraClient10g_home1};SERVER=ORAJJJ0;UID=xxx;PWD=yyy;DBQ=ORAWOD0;"
Set td = db.CreateTableDef(Name:="test", SourceTableName:="ORAJJJC01.TBL_MYTBL", Connect:=strConn)
'next row -> error 3264 No field defined--cannot append TableDef or Index
db.TableDefs.Append td
Set td = Nothing
Set db = Nothing
End Sub
A: The attributes parameter must not be empty. You need to pass 0 or dbAttachSavePWD
Set td = db.CreateTableDef(Name:="test", Attributes:=0, SourceTableName:="ORAJJJC01.TBL_MYTBL", Connect:=strConn)
Or you can do this if you don't want to explicitly set it to 0
Set td = db.CreateTableDef("test")
td.SourceTableName:="ORAJJJC01.TBL_MYTBL"
td.Connect:=strConn
Note: If you look at the td in the watch window can observe that the Connect and SourceTableName get set to empty if you don't pass a value for attributes in, but remain when you do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: NetBeans: How to change the look and feel with respect to Operating System I developed a small desktop application in Netbeans using Java. The application is working as expected. I developed it under WIN7.
When i run it on Microsoft Windows, the look and feel of UI is similar to Win XP Metal theme and when i run it on MAC it shows me the same theme. I want to change that theme with respect to operating system. Right now the theme is ok for windows i am looking for solution on MAC.
A: try{UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());}
catch(Exception e){}
A: If you're using Swing, then this should work:
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
}
A: Read the secton from the Swing tutorial on How to Set the Look and Feel for information about setting/changing the LAF.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Eclipse link to external source path I have Java project that uses a JAR from another Eclipse project (open source from apache).
For debug I need access to the source.
I have no idea where to point the source path. Everything I tried fails.
All my sources are under project/src/org/apache/....
Nota : it used to work but I upgraded eclipse as well as my apache project and it ain't working anymore.
A: Right click on the jar and open its Properties dialog, then go on Java Source Attachment page and select either Workspace..., External File... or External Folder...
If sources of that jar are in the same Workspace under some other Java project, usually you can just select that project as a source reference.
A: Ctrl-click on one of the classes of the library, and you'll have a page asking you to specify the source location of the class. Or right-click on the jar, choose "Properties", and then "Java Source Attachment".
A: Take a look at http://www.cavdar.net/2008/07/14/3-ways-of-jdk-source-code-attachment-in-eclipse/
As a brief run-down try this
*
*Go to Project > Properties > Java Build Path > Libraries
*Expand JRE System Library [your jre version] then, rt.jar
*Select Source attachment
*Click Edit….
*Select the source code file (External File…) and press OK.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to hide too long texts in div elements? How can you hide the overflow in a div?
Here the text just wraps down to a new line if the text is longer than the div
<div style="width:50px; border:1px solid black; overflow-y:hidden">
test test test test
</div>
A: The CSS property text-overflow: ellipsis maybe can help you out with that problem.
Consider this HTML below:
<div id="truncateLongTexts">
test test test test
</div>
#truncateLongTexts {
width: 100px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis // This is where the magic happens
}
A: If you only want to show a single line of text in a fixed width div, give white-space:nowrap a go. Together with overflow:hidden it will force your browser not to break the line and crop the view to your forced width.
You might also add text-overflow:ellipsis to avoid cutting words and letters in half, it adds a nice ... to the end to show you there's some bits missing. I'm not sure about the browser support though, and I've never tried this one.
A: You should specify a height for your div, overflow: hidden; can only hide the vertically overflowing content if there is some kind of defined height.
In other words:
Here the text just wraps down to a new line if the text is longer than the div
But how long is that div actually?
Please check out my jsFiddle demonstration that illustrates the difference.
A: try
overflow:none;
you didn't mention if you want scrollbars or not.
EDIT:
Sorry I meant overflow:hidden.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612125",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
} |
Q: How can I do $and queries against an array in Mongo? I have a collection in mongo where objects appear as follows:
{ name:"Scott", bio:"Stumped", roles:["USR","ADM"] }
Many more roles are possible. I want to perform any combination of intersection queries, like so:
db.coll.find({$and:[{roles:"USR"},{roles:{$ne:"ADM"}}]})
Some queries may be all role =, some may be all roles !=, and some may be mixed as with the above example. I have had some measure of success with $or and $nor, but absolutely no query I can fathom works with $and. I have even tried leveraging $where and $elemMatch to emulate what I want. I am also really trying to avoid multiple queries w/ the application handling intersection. Ideas?
A: Found the answer:
db.coll.find( {roles : { $all : ["USR"], $nin : ["ADM"]}} )
Thanks Hohhi for leading me down the right path!
A: db.coll.find("roles":{$all:["USR","ADM"]}})
I think this would help you, at least it returns the result you are looking for
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Issues with variable scope I am sure I am basically having an issue with variable scope. Knowing multiple programming languages, I just can't wrap my head around obj-c sometimes.
In my webviewcontroller class I have a variable that I call using self.var
I also have some delegate methods that reference a modified UIAlertView. Why can't I reference this self.var in those methods without the entire app crashing?
I have tried everything and its been a few days and now I need help!
Thanks!
Edit:
Here is the code webviewcontroller.h
#import "SBTableAlert.h"
@interface WebViewController : UIViewController <SBTableAlertDelegate, SBTableAlertDataSource>{
NSMutableArray *bookmarks;
}
@property (nonatomic, retain) NSMutableArray *bookmarks;
here is the .m (yes I have an @synthesize for bookmarks), this is in view did load
NSMutableArray *tmpArray = [tmpDict objectForKey:@"myKey"];
self.bookmarks = tmpArray;
[tmpDict release];
[tmpArray release];
SBTableAlert *bookmarkAlert;
bookmarkAlert = [[SBTableAlert alloc] initWithTitle:@"Jump to:" cancelButtonTitle:@"Back" messageFormat:nil];
[bookmarkAlert.view setTag:1];
[bookmarkAlert setDelegate:self];
[bookmarkAlert setDataSource:self];
NSString *settingsicon = [[NSBundle mainBundle] pathForResource:@"gear" ofType:@"png"];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageWithContentsOfFile:settingsicon] style:UIBarButtonItemStylePlain target:bookmarkAlert action:@selector(show)];
and later I try to call self.bookmarks
- (NSInteger)tableAlert:(SBTableAlert *)tableAlert numberOfRowsInSection:(NSInteger)section {
return [self.bookmarks count];
}
The error I get at the self.bookmarks count is NSInvalidArgumentException
A: It's a bit hard to answer without seeing some of your code.
Like Farmer_Joe asked, how are you defining the property? Something like:
@property (nonatomic, retain) MyVar *var;
is different from
@property MyVar *var;
How are you assigning to the var?
var = value;
won't kick in the retain, but this would (if the property is defined as "retain"):
self.var = value
Edit: based on the new code you posted, it looks like you're over-releasing tmpArray. Remove this line:
[tmpArray release];
You shouldn't have to release tmpArray, because this line doesn't retain it:
NSMutableArray *tmpArray = [tmpDict objectForKey:@"myKey"];
A: By variable I assume you mean ivar (instance variable). Did you create a @property for the ivar and if so please provide the code. Did you provide a @synthesize statement for the ivar?
If not you probably need to provide them.
self.var = x; calls the var's setter the same as: [var setVar:x];
Assuming that the variable is designed to be accesses from outside the class add a @property statement to the .h file:
@property (nonatomic, retain) ClassName *var;
in the associated .m file add:
@synthesize var;
In the .m file method dealloc add:
[var release];
The all used should access var as:
In the defining class: self.var
In other classes referencing by the instantiatedVariable.var
Consider studying Apple's Memory Management Programming Guide, it will save a lot of time and frustration.
A: I see the following issues:
*
*Don't do this: [tmpArray release]. You don't own the reference to tmpArray, it's auto-released.
*Do you own the reference for tmpDict? -- also, that is an awful var name ;)
*Can you confirm [tmpDict objectForKey:@"myKey"] returns an array?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: EditText box will not invoke the soft keyboard in many circumstances My Android application runs within a TabHost. I have 5 "sub-activities" all of which run as expected with one exception. The last item is a search feature. It is such a simple interface with just a TextView for a label, an EditText for the search field and a Button.
When I launch the app for the first time and navigate to the Search tab, no matter how many times I click into the EditText field, the soft keyboard is not invoked; however, if another activity that is not a part of my TabHost is called and then I return to the Search activity and click on the Search EditText, the keyboard is invoked as expected.
I don't have any action handlers for the field, only for the button press. I have tried forcing the EditText to get focus on the onCreate event and even forcing the keyboard to show using different methods found here on StackOverflow. See my current code below:
public class Search extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
//Give the edit text focus
EditText et1 = (EditText) findViewById(R.id.editText1);
et1.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(et1, InputMethodManager.SHOW_FORCED);
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
EditText et = (EditText) findViewById(R.id.editText1);
String term = et.getText().toString();
if (term.length() > 0) {
//do stuff }
else if (term.length() <= 0) {
Toast.makeText(getApplicationContext(), "Please Enter A Search Terml", Toast.LENGTH_SHORT).show();
}
}
});
}
Here's what the TabHost looks like:
Resources res = getResources(); // Resource object to get Drawables
TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab
Intent intent; // Reusable Intent for each tab
intent = new Intent().setClass(this, Tab3.class);
// Initialize a TabSpec for each tab and add it to the TabHost
try {
//home Tab
intent = new Intent().setClass(this, Home.class);
spec = tabHost.newTabSpec("home").setIndicator("Home",
res.getDrawable(R.drawable.grade))
.setContent(intent);
tabHost.addTab(spec);
//tab 2
intent = new Intent().setClass(this, Tab2.class);
spec = tabHost.newTabSpec("tab2").setIndicator("Tab2",
res.getDrawable(R.drawable.chart))
.setContent(intent);
tabHost.addTab(spec);
//tab 3
intent = new Intent().setClass(this, Tab3.class);
spec = tabHost.newTabSpec("tab3").setIndicator("Tab3",
res.getDrawable(R.drawable.tab3))
.setContent(intent);
tabHost.addTab(spec);
//tab 4
intent = new Intent().setClass(this, Tab4.class);
spec = tabHost.newTabSpec("tab4").setIndicator("Tab4",
res.getDrawable(R.drawable.tab4))
.setContent(intent);
tabHost.addTab(spec);
//search tab
intent = new Intent().setClass(this, Search.class);
spec = tabHost.newTabSpec("search").setIndicator("Search",
res.getDrawable(R.drawable.magnify))
.setContent(intent);
tabHost.addTab(spec);
//Set tab To Home
tabHost.setCurrentTab(0);
}
catch (Exception ex) {
Toast t = Toast.makeText(getApplicationContext(), ex.getMessage(), Toast.LENGTH_LONG);
t.show();
}
Thanks in advance for your help.
A: you might try a onFocusChage listener for your editText field which i called searchBoxEditText... call inputmethodmanager to open the keyboard when focus is changed to your edit text, an then when it looses focus, close the keyboard
onFocusChange(View v, boolean hasFocus){
if(v==searchBoxEditText){
if(hasFocus==true){
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE))
.showSoftInput(myEditText, InputMethodManager.SHOW_FORCED);
}else{ //ie searchBoxEditText doesn't have focus
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE))
.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
}
}
}//end onFocusChange
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can multiple gearman servers share the same libdrizzle queue? Can multiple gearman servers share the same gearman queue, via libdrizzle?
I'm wondering if this will eliminate the gearman server as a single point of failure--if I have multiple web nodes, each talking to the same gearman server, then the site dies if gearman becomes unavailable. However, if each of the web nodes is running its own gearman server (and jobs generated by that node are queued to the gearman server running on the same node), then the single point of failure is moved to the database. (Which, in our architecture, is a single point of failure anyway.)
A: No. The queue is only used as a backup in case the in memory queue fails (if Gearman dies, the jobs will still be stored in the database). The persistent queue is only read at startup, and not during job processing.
This doesn't mean that you can't have two Gearman servers and add both the servers to your clients and workers (so that the workers register with both servers) and have redundancy that way. I can't say that I've had a gearman server die on me recently anyways, but you'll at least get an extra level of failsafe.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: C++ delete array crashes This is my code...
int* getA(int no)
{
int *a = new int[no];
return a;
}
void main()
{
int* a = getA(10);
delete []a;
}
When I delete the array a in main it crashes... what is the reason??
The error is
"Windows has triggered a breakpoint in Final.exe. This may be due to a corruption of the heap, which indicates a bug in Final.exe or any of the DLLs it has loaded..........."
But I am able to assign and access the elements of a in the main method but when I try to delete it is crashing....
A: Nothing wrong with this code. Presumably either
*
*It differs from your real code in some significant way, or
*Something unrelated in your real code is corrupting the heap before this code runs.
A: It should just work (the delete).
Possibly, the application crashes because of undefined behaviour, if your compiler accepted that code. Try the following, and run it under a debugger to verify that it crashes in the delete:
int* getA(int no)
{
int *a = new int[no];
return a;
}
int main()
{
int* a = getA(10);
delete []a;
return 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Alternative for using Intersect operator in my sql query I have 2 tables with many to many cardinality between them. So by normalization I have created this :
User
UserId UserName ....
1 a
2 b
UserObject
UserId ObjectId
1 1
1 2
2 2
Object
ObjectId ObjectName
1 c
2 d
Now I want to run a query where I want to know users which have certain objects.
For example : All the users who have both objects c and d.
One way of doing it
Select userid from UserObject where objectid=1 intersect Select userid from UserObject where objectid= 2
According to my use case, I may need to search for users having combination of 2-7 objects. It will not be prudent to write so many intersections.
I am working on postgesql 9.1.
What are the other efficient possible ways to make this happen?
A: SELECT uo.UserId
FROM UserObject uo
WHERE uo.ObjectId IN (1,2)
GROUP BY uo.UserId
HAVING COUNT(DISTINCT uo.ObjectId) = 2
Extending this concept for 7 objects:
SELECT uo.UserId
FROM UserObject uo
WHERE uo.ObjectId IN (1,2,3,4,5,6,7)
GROUP BY uo.UserId
HAVING COUNT(DISTINCT uo.ObjectId) = 7
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I don't know what this c# pattern/structure/code is called I've been trying to find out the name for something, but without knowning the name, I am having a hard time Googling for the answer. It's a bit of a catch 22. I was hoping that if I posted an example, someone out there might recognize it.
Basically, it's a way to initialize any number of public properties of an object, without using a constructor.
For example, if I wanted to dynamically add a text box to my winform, I could:
System.Windows.Forms.TextBox tb_FirstName = new System.Windows.Forms.TextBox()
{
Location = new System.Drawing.Point(0, 0),
Name = "tb_FirstName",
Size = new System.Drawing.Size(100, 20),
TabIndex = 1
};
frm_MyForm.Controls.Add(tb_FirstName);
Does anyone know what this is called? Furthermore, is there a reason why I should avoid doing this. I prefer how the above code reads, as opposed to individually setting properties as such:
System.Windows.Forms.TextBox tb_FirstName = new System.Windows.Forms.TextBox();
tb_FirstName.Location = new System.Drawing.Point(0, 0);
tb_FirstName.Name = "tb_FirstName";
tb_FirstName.Size = new System.Drawing.Size(100, 20);
tb_FirstName.TabIndex = 1;
frm_MyForm.Controls.Add(tb_FirstName);
Mostly, I jsut want to know the name of the first example, so that I can do a little reading on it.
A: It's called an object initializer.
One potential issue with their use is when using an object initializer for an object in a using statement. If any of the property setters throws an exception, or evaluating code for the value of the property does, dispose will never be called on the object.
For example:
using (Bling bling = new Bling{ThrowsException = "ooops"})
{
//Some code...
}
An instance of Bling will be created, but because property ThrowsException throws an exception, Dispose will never be called.
A: As @chibacity says, it's an object initializer. Keep in mind that using an initializer does not bypass the constructor. A constructor must still be invoked.
By the way, the () isn't necessary if you're using the default constructor for your initializer. This also works:
var tb_FirstName = new TextBox {
Location = new System.Drawing.Point(0, 0),
Name = "tb_FirstName",
Size = new System.Drawing.Size(100, 20),
TabIndex = 1
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: I cannot display dynamic page title using spring 3 and apache tiles 2.2 I have a problem using spring 3 and tiles 2.2.2 . I can't display a dynamic page title.
These are my config/jsp files:
layout.jsp
<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="tiles" uri="http://tiles.apache.org/tags-tiles"%>
<!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" xml:lang="en" lang="en">
<head>
<title><tiles:getAsString name="title" ignore="true"/></title>
</head>
<body>
<tiles:insertAttribute name="header" />
<div id="content-outer">
<div id="content-wrapper" class="container_16">
<tiles:insertAttribute name="body" />
<tiles:insertAttribute name="menu" />
</div>
</div>
<tiles:insertAttribute name="footer" />
</body>
</html>
Spring config file:
<bean id="tilesviewResolver"
class="org.springframework.web.servlet.view.tiles2.TilesViewResolver">
<property name="order" value="0" />
<property name="requestContextAttribute" value="requestContext" />
<property name="viewClass"
value="org.springframework.web.servlet.view.tiles2.TilesView" />
</bean>
<bean id="tilesConfigurer"
class="org.springframework.web.servlet.view.tiles2.TilesConfigurer">
<property name="definitions">
<list>
<value>/WEB-INF/tiles.xml</value>
</list>
</property>
<property name="tilesProperties">
<props>
<prop key="org.apache.tiles.evaluator.AttributeEvaluator">org.apache.tiles.evaluator.el.ELAttributeEvaluator
</prop>
</props>
</property>
</bean>
tiles.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN"
"http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
<definition name="base.definition" template="/WEB-INF/views/layout.jsp">
<put-attribute name="title" value="" />
<put-attribute name="header" value="/WEB-INF/views/inc/header.jsp" />
<put-attribute name="menu" value="/WEB-INF/views/inc/menu.jsp" />
<put-attribute name="body" value="" />
<put-attribute name="footer" value="/WEB-INF/views/inc/footer.jsp" />
</definition>
<definition name="item/itemDetail" extends="base.definition">
<put-attribute name="title" value="%{title}"/>
<put-attribute name="body" value="/WEB-INF/views/item/itemDetail.jsp" />
</definition>
</tiles-definitions>
the page title isn't replaced with title value rendered by controller, instead %{title}.
Thanks in advance
A: I think that your page definition should look like this (note the 'expression' attribute and '$' instead of '%'):
<definition name="item/itemDetail" extends="base.definition">
<put-attribute name="title" expression="${title}"/>
<put-attribute name="body" value="/WEB-INF/views/item/itemDetail.jsp" />
</definition>
Are you sure that there is an attribute called ${title} in a relevant scope? Have you tried rendering the value of ${title} directly in the itemDetail.jsp page?
Here's the relevant documentation, tiles uses the servlet container's EL support for this:
http://tiles.apache.org/2.1/framework/tutorial/advanced/el-support.html.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Secure data during ajax call from phonegap app to web services without cookie security I want to secure my ajax call from my app using phonegap to web services returning json.
Usually when you log in a cookie security is created but I can't use cookies in my app and I would like something more secured than HTTPS.
Do you have ideas ?
A: Many web apis will use a token generated by the server and passed back to the client application (your mobile). Then it is the responsibility of the application to provide that token on every request to maintain the "session". Then, of course, your application will need to accept that token, verify that it is good and then use it to retrieve any client specific information.
Using a web server's built-in session management with cookies is many times much easier, but does have downsides of its own. Building your own session management has benefits like sometimes making it easier to scale and being able to persist sessions beyond server restarts and across clusters. However it is harder to implement and you must make sure your app always sends back the tokens.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Encoding in JSF 2 + Tomcat 7 I have one form with only one single field. When I submit the form, the value of my field becomes strange. The word Extremação becomes Extremação.
So, I already set UTF-8 encoding in every place on my app:
<?xml version="1.0" encoding="UTF-8"?>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<f:view contentType="text/html" encoding="UTF-8">
<h:form id="formParamSupremo" prependId="false" acceptcharset="UTF-8">
I created one encoding filter too:
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
And my http header is like this:
host = localhost:8080
user-agent = Mozilla/5.0 (X11; U; Linux x86_64; pt-BR; rv:1.9.2.23) Gecko/20110921
user-agent = Mozilla/5.0 (X11; U; Linux x86_64; pt-BR; rv:1.9.2.23) Gecko/20110921 Ubuntu/10.04 (lucid) Firefox/3.6.23
accept = text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
accept-language = pt-br,pt;q=0.8,en-us;q=0.5,en;q=0.3
accept-encoding = gzip,deflate
accept-charset = ISO-8859-1,utf-8;q=0.7,*;q=0.7
keep-alive = 115
connection = keep-alive
referer = http://localhost:8080/parametros/view/xhtml/parametrosSupremo.jsf
cookie = JSESSIONID=6DC0C1D4434FB90C3F9271D6C54DC575
content-type = application/x-www-form-urlencoded
content-length = 185
A: I have the same problem.
Finally I found this error solutions. You should create a Filter to display non ascIi characters. What an annoying bugs :(
http://dertompson.com/2007/01/29/encoding-filter-for-java-web-applications/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to show validation summary per condition in MVC3 Razor View? I am not sure whether its a good practice or not but there is a need to display Validation summary conditionally. Actually, I need to display validation summary under Yellow Square so, I created a CSS class for the same and trying to do this :
@if (!Html.ViewData.ModelState.IsValid)
{
<p>
<span class="message-wrapper warning">
@Html.ValidationSummary(true)
</span>
</p>
}
else
{
@Html.ValidationSummary()
}
The problem with above is, the Yellow square is visible always which not to ?
The Yellow square should be display only when there are Validation errors and these errors should be displayed within the 'Yellow Square.
I am looking for the solution. Any help in this regard much appreciated!
A: Ideally you just can change the css class for this
.validation-summary-errors {
background-color: #D9FFB2;
border:1px solid #5CBA30;
width: 400px;
}
There are several covered methods here, so I won't repeat them all : )
Surrounding a ValidationSummary with a box via CSS
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NSNotificationCenter.PostNotificationName() with NULL object does not trigger: bug or as designed? I'm subscribing to my own notifications using code like this:
NSNotificationCenter.DefaultCenter.AddObserver("BL_UIIdleTimerFired", delegate {
Console.WriteLine("BaseFolderViewController: idle timer fired");
});
To send a notification:
NSNotificationCenter.DefaultCenter.PostNotificationName("BL_UIIdleTimerFired", null);
However, the notification will only be received correctly if the "anObject" parameter of PostNotificationName(string sString, object anObject) is not NULL.
Is this by design? Do I have to pass an object? Or is it a bug?
I don't really want to send a reference to a specific object.
A: This is a bug in MonoTouch. NSNotification is built so you can send an optional dictionary and an optional object, which is normally the sender, but can be other objects as well. Both of these can be null, but in MonoTouch passing a null as the object parameter causes a Null Pointer Exception.
Its quite clear from the iOS documentation, regarding the Object parameter:
The object associated with the notification. This is often the object that posted this notification. It may be nil.
public void SendNotification()
{
NSNotification notification = NSNotification.FromName("AwesomeNotification",new NSObject());
NSNotificationCenter.DefaultCenter.PostNotification(notification);
}
public void StartListeningForNotification()
{
NSString name = new NSString("AwesomeNotification");
NSNotificationCenter.DefaultCenter.AddObserver(this,new Selector("AwesomeNotificationReceived:"),name,null);
}
public void StopListeningForNotification()
{
NSNotificationCenter.DefaultCenter.RemoveObserver(this,"AwesomeNotification",null);
}
[Export("AwesomeNotificationReceived:")]
public void AwesomeNotificationReceived(NSNotification n)
{
}
A: I think this is by design. Apple's documentation for the other overload (postNotificationName:object:userInfo:) states that the userInfo parameter can be null. So I suppose the other two cannot be null.
The "anObject" parameter is the object that posts the notification (sender) and the one that can be retrieved from NSNotification class' Object parameter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can a primary key column have duplicated values in Oracle? I have just tried to import an Oracle DB to another and it gave an error tells that duplicated values found in a primary key column. Then I checked the source table, and yes really there are duplicate values in PK, and checked PK is enabled and normal. Now I wonder how can this happen.
Edit: I found that index is in unusable state. I don't know how did it happen, just found this:
http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1859798300346695894
A: Assuming your primary key is indeed defined on this column, and enabled, you could check if it is validated. Only validated constraints are guaranteed by Oracle to be true for all rows.
Here's a scenario with an unvalidated primary key with a duplicate value:
SQL> DROP TABLE t;
Table dropped
SQL> CREATE TABLE t (ID NUMBER);
Table created
SQL> INSERT INTO t VALUES (1);
1 row inserted
SQL> INSERT INTO t VALUES (1);
1 row inserted
SQL> CREATE INDEX t_id_idx ON t(ID);
Index created
SQL> ALTER TABLE t ADD CONSTRAINT pk_id PRIMARY KEY (ID) NOVALIDATE;
Table altered
SQL> SELECT * FROM t;
ID
----------
1
1
SQL> SELECT constraint_type, status, validated
2 FROM user_constraints
3 WHERE constraint_name = 'PK_ID';
CONSTRAINT_TYPE STATUS VALIDATED
--------------- -------- -------------
P ENABLED NOT VALIDATED
Update:
One likely explanation is that a direct path load (from SQL*Loader) left your unique index in an unusable state with duplicate primary keys.
A: A column that you think pk is applied but in reality its your mistake. PK is not defined on that column...
Or
You have applied Composite/Multi column primary key..
Try to insert same record twice it shows error that means composite key..
A: Check to see that you have the index setup as unique.
select table_name,uniqueness,index_name from all_indexes where table_name='[table_name]';
/* shows you the columns that make up the index */
select * from all_ind_columns where index_name='[index_name]';
A: You had inserted data twice
OR
The destination table is not empty.
OR
You defined a different pk on dest table.
A: Potentially the constraints were disabled to load data and then the same load has been run again- could be the index now won't validate because of the double data in the table.
Has there been a data load recently ? Does the table have any audit columns eg create date to determine if all rowa are duplicate ?
A: Using deferred constraints can cause duplicate values to be inserted into a PK column.
Check the link below. It describes a possible Oracle bug that can lead to duplicated primary key values. I just recreated the issue on Oracle 11g EE Rel 11.2.0.2.0
http://www.pythian.com/news/9881/deferrable-constraints-in-oracle-11gr2-may-lead-to-logically-corrupted-data/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: jQuery UI Dialog will not close On my web page I have a button that opens a modal jQuery dialog. The code that runs when the button is clicked is as follows:
$('#main-onoffline-container').append('<div id="dialog-modal-a"></div>');
$("#dialog-modal-a").dialog({
title:'Add Tags'
, autoOpen: false
, modal: true
, height: 540
, width:700
, close: function (ev, ui) { alert('closing'); }
,open: function() {
$("#dialog-modal-a").html('Some html will go here')
}
});
$("#dialog-modal-a").dialog("open");
As you can see, I am adding a div to the DOM, then calling the dialog method against the newly added div.
The dialog opens fine and displays the html plus the X close button. However, when I hit the X button to close the dialog it does not close. The console shows the following error from jquery-1.6.4.min.js:
Uncaught RangeError: Maximum call stack size exceeded
Anyone know what the problem is?
UPDATE:
After a lengthy session I have detected that the order of certain js libraries are influencing this:
If I include files as follows then the problem appears:
<script src="../../Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.7.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
If I included files as follows then the problem disappears:
<script src="../../Scripts/jquery.validate.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.7.min.js" type="text/javascript"></script>
This seems really strange - I thought that you should include the core jQuery stuff right at the top of the file?
(The validate lib is Jörn Zaefferer plugin)
I have raised a different question to take this forward: jQuery library include order causes error
A: The problem was due to a js library conflict - please see my final comments in the main question
A: Try to pull out of the function $.dialog the closing event handling:
$( ".selector" ).bind( "dialogclose", function(event, ui) {
...
});
A: Not sure why you're appending the dialog to the page and opening it right away. I assume you've left out code. Generally with this plugin want you want to do is:
Create the dialog container in the HTML:
<div id="dialog-modal-a"></div>
Initialize it on $().ready() (which hides it by default when autoOpen: false) then open it on an event or page load:
$().ready(function() {
$("#dialog-modal-a").dialog({
title:'Add Tags',
autoOpen: false,
modal: true,
height: 540,
width:700,
close: function (ev, ui) { alert('closing'); }
});
$('#somethinkToClick').click(function() {
$('#dialog-modal-a').html('some html');
$("#dialog-modal-a").dialog("open");
});
/* OR
$('#somethinkToClick').click(function() {
$('#dialog-modal-a').html('some html');
$("#dialog-modal-a").dialog("open");
});
*/
}
A: I had a similar error, .dialog('destroy') did the trick for me. There may still be a js version mismatch.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Launching multiple shell prompts from a single batch file I have a set of DOS commands that I need to run in different shell instances. Is there a single batch file I can write that would set of multiple cmd instances and execute the set of DOS commands in each of the prompts?
A: Your question seems to boil down to how to run a different series of commands in each instance of cmd.exe without having multiple command files.
There's a reasonably straightforward way of doing this. The idea is to run the same command file in each instance of cmd.exe, but pass it a command-line parameter that tells it which part of the job to do.
A useful trick here is to use the command-line parameter in a goto command, like this:
if not "%1" == "" goto :%1
start "Job 1" "%~dpfx0" job1
start "Job 2" "%~dpfx0" job2
goto :eof
:job1
echo Job 1
pause
exit
:job2
echo Job 2
pause
exit
Note also the use of %~dpfx0 to determine the full path and name of the current script. This has to be in quotes in case the path contains spaces, which means that (due to the odd syntax of the start command) you need to first explicitly specify a window title (also in quotes).
A: How about something like:
start cmd /c dir c:\windows
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Getting a Type Assembly in Windows 8 I'm trying to use MEF in Windows 8.
In order to build up my AssemblyCatalog for the container, I need a reference to the assembly. In the past, I would have just done this:
var catalog = new AssemblyCatalog(typeof(App).Assembly);
Mysteriously, the Assembly property no longer exists on the Type object. Anybody know of a good work around? Is there another way to get the assembly? I could load it using Assembly.Load, but I would need the name of the assembly. I can't get that from the type either.
Is using a DirectoryCatalog a possible alternate? I don't like the idea, but I'll do what I need to.
A: Found the answer after some digging through the loads of documentation on building metro style apps.
http://msdn.microsoft.com/en-us/library/windows/apps/br230302%28v=VS.85%29.aspx#reflection
The reflection aspects of the Type class have been moved to a new object called System.Reflection.TypeInfo. You can get an instance of this class by calling type.GetTypeInfo().
So to get the Assembly: typeof(App).GetTypeInfo().Assembly.
Requires using System.Reflection;
A: using System.Reflection;
Use type.GetTypeInfo().Assembly instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Get sibling rows in SQL I need to get the two sibling rows of a specified row in a query.
SELECT pkUserId, name
FROM tblUsers
ORDER BY CreateDate
Gives result:
10 User1
18 User3
25 User4
79 User8
12 User2
I want a query that gives me user3 and user8 if I supply userId 25
10 User1
18 User3 --> Output
25 User4 <-- Input
79 User8 --> Output
12 User2
If think it should be possible to get this with a single query (without Union) using ROW_NUMBER(), but Im not sure how the create it.
A: Edit: I added four remarks for the second solution.
Two solutions:
(1) The first solution is based on MAX, MIN functions:
CREATE TABLE dbo.TestData
(
PKUserID INT PRIMARY KEY
,Name VARCHAR(25) NOT NULL
,CreateDate DATETIME NOT NULL
);
CREATE UNIQUE INDEX IX_TestData_CreateDate_PKUserID
ON dbo.TestData(CreateDate, PKUserID);
INSERT dbo.TestData
SELECT 10,'User1','2011-01-01T00:00:00'
UNION ALL
SELECT 18,'User3','2011-01-01T00:10:00'
UNION ALL
SELECT 25,'User4','2011-01-01T00:20:00'
UNION ALL
SELECT 79,'User8','2011-01-01T00:30:00'
UNION ALL
SELECT 12,'User2','2011-01-01T00:40:00';
DECLARE @UserID INT;
SELECT @UserID = 25;
DECLARE @UserCreateDate DATETIME;
SELECT @UserCreateDate = a.CreateDate
FROM dbo.TestData a
WHERE a.PKUserID = @UserID;
SELECT *
FROM
(
SELECT TOP 1 a.PKUserID
FROM dbo.TestData a
WHERE a.CreateDate < @UserCreateDate
ORDER BY a.CreateDate DESC, a.PKUserID DESC
) a
UNION ALL
SELECT *
FROM
(
SELECT TOP 1 a.PKUserID
FROM dbo.TestData a
WHERE @UserCreateDate < a.CreateDate
ORDER BY a.CreateDate ASC, a.PKUserID ASC
) b
DROP TABLE dbo.TestData;
Results (10 logical reads):
PKUserID
-----------
18
79
(2) The second solution is inspired, somehow, from the quirky update method but not implies any UPDATE, it's just a simple SELECT:
CREATE TABLE dbo.TestData
(
PKUserID INT PRIMARY KEY
,Name VARCHAR(25) NOT NULL
,CreateDate DATETIME NOT NULL
);
CREATE UNIQUE INDEX IX_TestData_CreateDate_PKUserID
ON dbo.TestData(CreateDate, PKUserID);
INSERT dbo.TestData
SELECT 10,'User1','2011-01-01T00:00:00'
UNION ALL
SELECT 18,'User3','2011-01-01T00:10:00'
UNION ALL
SELECT 25,'User4','2011-01-01T00:20:00'
UNION ALL
SELECT 79,'User8','2011-01-01T00:30:00'
UNION ALL
SELECT 12,'User2','2011-01-01T00:40:00';
DECLARE @UserID INT;
SELECT @UserID = 25;
DECLARE @PreviousID INT
,@NextID INT
,@IsFound BIT
,@CountAfter INT;
SELECT @IsFound = 0
,@CountAfter = 0;
SELECT @IsFound = CASE WHEN a.PKUserID = @UserID THEN 1 ELSE @IsFound END
,@PreviousID = CASE WHEN @IsFound = 0 THEN a.PKUserID ELSE @PreviousID END
,@CountAfter = CASE WHEN @IsFound = 1 THEN @CountAfter + 1 ELSE 0 END
,@NextID = CASE WHEN @CountAfter = 2 THEN a.PKUserID ELSE @NextID END
FROM dbo.TestData a WITH(INDEX=IX_TestData_CreateDate_PKUserID)
GROUP BY a.CreateDate, a.PKUserID
ORDER BY a.CreateDate ASC, a.PKUserID ASC
OPTION (MAXDOP 1);
SELECT @UserID UserID, @IsFound IsFound, @PreviousID [Prev], @NextID [Next]
DROP TABLE dbo.TestData;
Results (2 logical reads):
UserID IsFound Prev Next
----------- ------- ----------- -----------
25 1 18 79
To prevent getting wrong results:
*
*I used MAXDOP 1 query hint to prevent "parallelism".
*I created an unique index that includes all necessary fields starting with fields used in GROUP BY and ORDER BY.
*I forced INDEX=IX_TestData_CreateDate_PKUserID index.
Or the simplest solution is to force an execution plan using OPTION (USE PLAN N'<?xml...><ShowPlanXML...').
A: Try this:
WITH CTE
AS
(
SELECT ROW_NUMBER() OVER(ORDER BY CreateDate) [rn], pkUserId, name
FROM tblUsers
)
SELECT *
FROM CTE c
WHERE c.rn =
(
SELECT c2.rn
FROM CTE c2
WHERE c2.pkUserId = 25
) - 1
OR
c.rn =
(
SELECT c3.rn
FROM CTE c3
WHERE c3.pkUserId = 25
) + 1
A: Here's the whole solution, including the virtual declarations, so that anyone can verify the solution:
declare @tblUsers table (pkUserId int, name varchar(20), createdate datetime)
insert into @tblUsers values
(10, 'User1','2011-01-01'),
(18, 'User3','2011-01-02'),
(25, 'User4','2011-01-03'),
(79, 'User8','2011-01-04'),
(12, 'User2','2011-01-05')
;with sel as(
SELECT pkUserId, name, ROW_NUMBER() over (order by createdate) rn
FROM @tblUsers
)
select sel.pkUserId, sel.name
from sel,
(
select rn from sel where pkUserId = 25
) item
where sel.rn in (item.rn -1, item.rn+1)
A: Use subqueries in the following order:
*
*Query for the input row
*Query for the foreign key
*Query for the siblings
Here is an example:
Search Text in Other Answers to Questions I've Answered
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Animation In Android and Events On my animation I have an event listener:
AnimationListener animationOutListener= new AnimationListener() {
public void onAnimationEnd(Animation fadeOutAnimation) {
}}
How can I find out the view that the animation is taking place on?
A: It is usually the case that you have the target view when creating and attaching the animation listener to the animation since you have to afterwards start the animation by calling view.startAnimation(animation). If so - if you make your view final you'll have access to it from the anonymous class and you'll be able to use it in onAnimationEnd. If that's not the case you can use a setter for the target view to set it when starting the animation by calling view.startAnimation(animation)
public class CustomAnimationListener implements AnimationListener{
private View mTarget;
public void setTarget(final View target){
mTarget = target;
}
@Override
public void onAnimationEnd(Animation animation)
{
//use the target view here - mTarget
}
...
}
animation.getAnimationListener().setTarget(view);
view.startAnimation(animation);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Google Maps API: Get zipcode Is it possible to get the zipcode of a location found using google maps api?
Currently it returns the longitude and latitude, but not the zipcode.
I found this for zipcodes: http://www.census.gov/tiger/tms/gazetteer/zips.txt
I was going to write a script to put it in a DB, but I'm unsure the kind of query you'd write to find the nearest result
A: One possible solution is to load all of your zipcode data into a table and then, when you need to get the zipcode with the nearest lat/long to the lat/long returned by Google Maps, use the Haversine formula in a query to get the distance between the lat/long from GoogleMaps and the lat/long of the zip codes. You can then select the zip code that is closest to the lat/long returned by Google Maps i.e. the one with the lowest distance from your point of interest.
Luckily there is just such a query in a previous post.
NB This will only give you the nearest zipcode in your list for a location. I do not know whether this means that you will get the correct zipcode for your location (I don't know enough about zipcodes for that!). It should give you something with which to get started though.
A: If you're interested in getting the zip code of a latitude and longitude, you can use ZipLocate, it now supports reverse geocoding.
You could either use the API or use the scripts to query the data locally.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery simple image load im getting a little issue here. Im trying to load an image, but seems it isnt correct. Im getting the data of image, but i just want to load it instead of.
Whats wrong?
var url = $(this).find("img").attr("ref");
$("#produto .main-photo .photo img").load(url, function() {
$("#produto .main-photo .loader").fadeOut();
$("#produto .main-photo .photo").fadeIn();
});
A: You should not use load for this. Simply set the src of the image:
$("#produto .main-photo .photo img").attr("src",url);
load is used to make an AJAX call.
A: $('<img/>')[0].src = yoururl;
A: It might make more sense to just use an img tag, dynamically sourced and faded in:
var img = $("#produto .main-photo .photo img");
var url = $(this).find("img").attr("ref");
img.fadeOut();
img.attr('src', url);
img.fadeIn();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Span matrix from relational table in R Often I use data stemming from a SQL database in R. Typically I do a lot of the juggling in SQL, but using plyr more and more recently I wondered whether it's easier in R to span a matrix from a relational data table. Here's an example.
I have a table like
id question answer
1 6 10
1 4 1
1 5 2003
3 6 2
#reproduce it with dput output:
structure(list(result = c(1, 1, 1, 3), question = c(6, 4, 5,
6), answer = c("10", "1", "2003", "2")), .Names = c("id",
"question", "answer"), row.names = c("1", "2", "3", "4"), class = "data.frame")
and I would like to arrange as de-normalized matrix:
id question.6 question.4 question.5
1 10 1 2003
3 2
and so on..
I fixed this in SQL using a CASE WHEN syntax but can't manage to do it in R, for example like this:
Select min((case when (question_id` = 6)
then answer end)) AS `question.6`
A: dcast in reshape2 will do that work:
> z
id question answer
1 1 6 10
2 1 4 1
3 1 5 2003
4 3 6 2
> dcast(z, id ~ question, value_var = "answer")
id 4 5 6
1 1 1 2003 10
2 3 <NA> <NA> 2
A: Try this:
> tapply(DF[,3], DF[,-3], identity)
question
id 4 5 6
1 1 2003 10
3 NA NA 2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I call a javascript function when Checkbox is checked How can I call a Javascript function when a checkbox is checked when this checkbox is inside a gridview ?
protected void AlteraStatusExpiraSeteDias_Click(object sender, EventArgs e)
{
for (int i = 0; i < grdImoveis2.Rows.Count; i++)
{
GridViewRow RowViewExpiraSeteDias = (GridViewRow)grdImoveis2.Rows[i];
CheckBox chk = (CheckBox)grdImoveis2.Rows[i].FindControl("chkExpiraSeteDias");
if (chk != null)
{
String codigo;
if (chk.Checked)
{
codigo = (String)grdImoveis2.Rows[i].Cells[0].Text;
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "Registra", "AlteraStatus(codigo);", false);
}
}
}
}
<asp:GridView ID="grdImoveis2" CssClass="StyleGrid" Width="100%" runat="server" AutoGenerateColumns="false" DataSourceID="ds" BorderWidth="0" GridLines="None">
<AlternatingRowStyle BackColor="White" CssClass="EstiloDalinhaAlternativaGrid" HorizontalAlign="Center"/>
<RowStyle CssClass="EstiloDalinhaGrid" HorizontalAlign="Center" />
<HeaderStyle BackColor="#e2dcd2" CssClass="thGrid" Height="20" />
<Columns>
<asp:BoundField HeaderText="Código" DataField="Imovel_Id" />
<asp:BoundField HeaderText="Para" DataField="TransacaoSigla" />
<asp:BoundField HeaderText="Valor" DataField="ValorImovel" DataFormatString="{0:c}" HtmlEncode="false" />
<asp:TemplateField HeaderText="Endereco">
<ItemTemplate>
<%# Eval("Logradouro") %>, <%# Eval("Numero") %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Data Cadastro" DataField="DataHora" DataFormatString="{0:dd/MM/yyyy}" HtmlEncode="false"/>
<asp:BoundField HeaderText="Data Expira" DataField="DataExpira" DataFormatString="{0:dd/MM/yyyy}" HtmlEncode="false"/>
<asp:TemplateField HeaderText="Ação">
<ItemTemplate>
<asp:CheckBox ID="chkExpiraSeteDias" runat="server" onclick="alert('Foo')" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Without the checkbox, when I put a image and put a link href to the javascript, it's works!, but with checkbox, no!
A: Add onclick attribute to Checkbox markup and include the javascript function that you'd like to call.
<asp:CheckBox ID="chkExpiraTresDias" runat="server" onclick="alert('Foo')" />
A: this should help you
$('input:checkbox[ID$="chkExpiraTresDias"]').change(function() {
alert('Hello world!');
});
A: I fear that you will have to iterate through the Gridview when your "Insert" button is clicked and then do what you have to do. Something like this:
foreach (GridViewRow row in this.grdImoveis2.Rows) {
if (row.RowType == DataControlRowType.DataRow) {
CheckBox chk = row.Cells(0).FindControl("chkExpiraTresDias");
if (chk != null) {
Response.Write(chk.Checked); //Do what you gotta do here if it's checked or not
}
}
}
Good luck.
Hanlet
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: join table and has_many relationships not working I have two items, users and posts, and a join table linking them together. The two items have a has_many relationship with each other (:through the join table). I created the join table after creating the two databases. The problem I am having is that I get errors every time I try and do something with @user.posts or @post.users. It is almost like they are not set up correctly. Somewhere I was reading that if you create an association after creating the model, then you have to use the add_column method. Is that my problem? I wasnt sure on how to implement that method or anything. This is the error I get:
SQLite3::SQLException: no such column: users.post_id: SELECT "users".* FROM "users" WHERE "users"."post_id" = 60 AND "users"."id" = ? LIMIT 1
Looks like from the error I need to add a column but im not sure on how to do that.
here is my latest schema.db:
ActiveRecord::Schema.define(:version => 20110930155455) do
create_table "posts", :force => true do |t|
t.text "content"
t.integer "vote_count"
t.text "author"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "user_id"
end
create_table "users", :force => true do |t|
t.string "user_name"
t.string "password"
t.date "time"
t.integer "posts_id"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "post_id"
end
create_table "votes", :force => true do |t|
t.integer "post_id"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end
end
A: Yes, you need to create a migration for the foreign keys. You need to add post_id to the :users table with type integer. Perform
rails g migration AddPostIdToUsers post_id:integer
to generate your migration. You should create one that looks like
class AddPostIdToUsers < ActiveRecord::Migration
def change
add_column :users, :post_id, :integer
end
end
You might also want to consider setting up a *has_many :through association*, it'll give you more control.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Microsoft Access Database: How to Remove User & Password settings I've got a MS Access database here that I can open in Access 2007 using a modified shortcut like this:
"C:\Program Files\Microsoft Office\Office14\MSACCESS.EXE" "C:\Temp\cat32.mdb" /wrkgrp "C:\Temp\cat32.mdw" /user "admin95" /pwd "somepassword"
I'm trying to import this database into our SQL Server environment, but pointing SQL Server at the Access database I want to import fails because I am logged in as another user. There is, in fact, no such user as admin95.
I could spend a few days writing a program that opens the database and copies everything over, but I'd rather just find a way to remove the owner tags or password requirements.
Notice, I don't think I can just remove the Password! I need to somehow add or change the Owner as well.
A: With a bit of luck:
*
*Check the permissions of every object that you need to access, including the database itself.
*Give full rights to user admin on all objects, or put Admin in the same groups as admin95
*Then finally remove password of user admin. You are done (maybe). If it works, you can now open the db without reference to the
This is all done using the Tools, Security menu.
If that's unsuccessfull, try creating a blank db (without security) and export all objects from your locked mdb to that new mdb.
Hope it works, good luck. More reading here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Regarding Android CTS Error How to kill a running ANDROID CTS instance.Suppose one CTS instance is running on a terminal and if we abruptly close that terminal, that CTS instance will not be closed and when we try to start CTS again in a fresh terminal,we get this error[CTS_ERROR >>> Error: CTS is being used at the moment. No more than one CTS instance is allowed simultaneously] so how to go to CTS Host this time or kill this running instance.
A: You can use $ ps -ef | grep "startcts" then it will print the username, pid and other info for currently running CTS. Now use $ kill -9 <PID> to terminate the CTS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Windows Listen to service Status Changed How Can I make an app that listens to services for Service Status Changed event. (I don't want repeated checking on of all services)
EDIT
I need it to work on Windows XP / 2000
A: In Vista and above you can use NotifyServiceStatusChange API. See some sample code on MSDN.
If you are monitoring more than one service, you will have to call NotifyServiceStatusChange for each service you want to have monitored.
A: You are looking for NotifyServiceStatusChange which requires Vista. On 2000/XP you will need to poll.
A: You could use WMI with something like SELECT * FROM __InstanceModificationEvent WHERE TargetInstance ISA 'Win32_Service' and then checking the State field of the Win32_Service class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: font-face issue in IE8 I've started using font-face for a site. I've included a free font by Fontsquirrel called Chunk Five (http://www.fontsquirrel.com/fonts/ChunkFive) that has support for IE (EOT font).
However when I implement it, some letters look 'squashed' which gives it a very ugly look.
Here's how it looks under Chrome (with text-shadow):
Here's how it looks under IE8:
The e's, m's and 's look awful.
Is this an issue with the font? Or the CSS that I use? Or IE8?
A: May be add shadow with JS?
CSS:
h1, h2{ text-shadow: 2px 2px 2px #ddd;}
Add Jquery:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
Add script file:
<script src="js/jquery.textshadow.js" type="text/javascript"></script>
JS code:
<script type="text/javascript">
// <![CDATA[
jQuery(document).ready(function(){
jQuery("h1, h2").textShadow();
})
// ]]>
</script>
Jquery shadow plugin you can find here http://plugins.jquery.com/project/textshadow
A: I think it has something to do with odd font sizes. Try applying an even font size and the rendering should be correct.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Creating an ASM file that will return the characters located in 8 consecutive registers I have to create an ASM file for the PIC18F452 that does the following:
(a) define the label MapName as the first of 8 consecutive registers containing a null-terminated string of not more than 7 characters. (b) access an 8-bit unsigned integer variable called MapIndex which was declared in a C file. (c) define an ASM function getMapChar which can be called from C using the function prototype char getMapChar(void). The function should return the appropriate character when the value of MapIndex is <= 7 or the value 255 if MapIndex is > 7. (d) make the labels MapName and getMapChar accessible to an external C file.
My code so far is shown below:
; Configuration word : WDT off, power-up timer on, code protect off, RC oscillator
list = p18f452
MapName equ 0x20
MapName1 equ 0x21
MapName2 equ 0x22
MapName3 equ 0x23
MapName4 equ 0x24
MapName5 equ 0x25
MapName6 equ 0x26
MapName7 equ 0x27
CurrentChar equ 0x28
extern MapIndex
org 0x00
goto getMapChar
getMapChar
movlw 0x00
movwf MapName7
GLOBAL getMapChar
GLOBAL MapName
END
I have already done parts (a), (b) and (d) but I am having some problems with writing the code that moves through each of the consecutive registers automatically using the value of MapIndex. Could anyone help me please? It would be much appreciated.
A: You can use one of FSR (file select registers) to address MapName file registers:
lfsr 0, MapName ;Load 12bit file address pointer to FSR0
movf MapIndex, w ;Load MapIndex to WREG ; or movff MapIndex, WREG
addwf FSR0L, f ;Add MapIndex to FSR0 low byte
movf INDF0, w ;Load MapName[MapIndex] to WREG
If all file registers of variable MapName aren't inside 8 bit address space then after adding MapIndex to FSR0L check Carry flag for overflow. If Carry is set increase also the FSR0H file register.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612237",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Variables of form __something__ What is the purpose of python variables __something__
e.g. __name__, __file__
I often see them in real python programs.
Is there a list of these variables?
thank you
A: PEP8 covers this:
In addition, the following special forms using leading or trailing
underscores are recognized (these can generally be combined with any
case convention):
*
*_single_leading_underscore: weak "internal use" indicator. E.g.
"from M
import *" does not import objects whose name starts with an
underscore.
*single_trailing_underscore_: used by convention to avoid
conflicts with
Python keyword, e.g.
Tkinter.Toplevel(master, class_='ClassName')
*__double_leading_underscore: when naming a class attribute,
invokes name
mangling (inside class FooBar, __boo becomes FooBar_boo; see
below).
*__double_leading_and_trailing_underscore__: "magic" objects or
attributes that live in user-controlled namespaces. E.g.
__init__,
__import__ or __file__. Never invent such names; only use them
as documented.
The final bullet point is pertinent.
Is there a list of these variables?
I doubt that there is an official list of all such double leading and trailing underscore names, but I could not say so for sure.
A: Check this chapter of Python manual. Does it satisfy you?
A: They're considered special or magic. The language doesn't prevent you from creating your own, but don't.
Here is a good guide on the magic methods but there are also special attributes, such as __all__, which is normally pronounced "dunder all" or "under under all".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Linq expression builder, add conditional in divide case As part of a larger set of expressions, we have our divide case. It's simple enough
protected override Expression BuildDivideExpression(Expression left, Expression right)
{
return Expression.Divide(left, right);
}
I'd like to change it so that it returns 0 if left is 0, and as is if left != 0.. Something like this:
protected override Expression BuildDivideExpression(Expression left, Expression right)
{
return Expression.Condition(left != 0, Expression.Constant(0), Expression.Divide(left, right))
}
But I can't figure out the conditional bit currently shown as "left != 0"
?
A: I think you mean if right is equal to zero you want the result to be zero. So you want to use Expression.Equal like so
protected override Expression BuildDivideExpression(Expression left, Expression right)
{
return Expression.Condition(Expression.Equal(right, Expression.Constant(0)),
Expression.Constant(0),
Expression.Divide(left, right))
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Plot density of periodic function I've got a vector that represents the times (in seconds past midnight) that a bunch of events happened, and I want to plot the density of those events through the day. Here's one way to do that:
rs <- 60*60*24*c(rbeta(5000, 2, 5), runif(10000, 0, 1))
den <- density(rs, cut=0)
plot(den, ylim=range(0,den$y))
The problem with that is that it gets the endpoint density wrong, because this is a cyclical function. If you plot 3 periods in a row you see the true densities in the middle period:
den <- density(c(rs, rs+60*60*24, rs+2*60*60*24), cut=0)
plot(den, ylim=range(0,den$y))
My question is whether there's some [better] way to get the density of that middle chunk from the original data, without tripling the number of observations as I've done. I'd of course need to supply the length of the period, in case there aren't any observations near the endpoints.
A: I don't think your evidence that the curve should look line a portion of the repeated spline fit is compelling. You should examine the results of hist() on the same object where you specify breaks at hour boundaries. The logspline function allows calculation of density estimates with specified bounds on hte data:
hist( c(c(rs, rs+60*60*24, rs+2*60*60*24), breaks= 24*3 )
require(logspline)
?logspline
fit <- logspline(c(rs), lbound=0, ubound=60*60*24)
plot(fit)
A better fit because it correctly captures the fact that the end-of-the-day density is lower than the first of the day which isn't really correctly captured with that triple day densityplot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: MVC 2 - Cannot retieve checkbox values in MVC Contrib grid I have a checkbox on my MVC Contrib grid;
<%= Html.Grid(Model.TeamMembers).Columns(column =>
{
column.For(model => model.Surname);
column.For(model => model.Forename);
column.For(model => model.DaysLeftThisYear).Named("Days Left This Year");
column.For(model => model.DaysLeftNextYear).Named("Days Left Next Year");
column.For(model => Html.CheckBox("chkbox", model.SelectForConfirmationFlag))
.Named("Select?")
.Sortable(false);
}).Sort((GridSortOptions)ViewData["sort"]) %>
</div>
<p><%= Html.Pager((IPagination)Model.TeamMembers)%></p>
The user can then click on the checkboxes, but when he submits, the new values are NOT picked up in the controller.
The page is contained in a page which has a BeginForm statement;
<% using (Html.BeginForm("Home", "Approver", FormMethod.Post, new { id = "frmHome" }))
{%>
My controller looks like;
[HttpGet]
[Authorize(Roles = "Administrator, ManagerIT, ManagerAccounts, Approver")]
public ActionResult Home(GridSortOptions sort, int? page)
{
SessionObjects.LoggedInUserName = User.Identity.Name;
if (SessionObjects.ApprovalViewModel.TeamMembers.Count() == 0)
SessionObjects.ApprovalViewModel = new ApprovalViewModel();
TempData["ReadOnly"] = true;
if (sort.Column != null)
{
SessionObjects.ApprovalViewModel.TeamMembers = SessionObjects.ApprovalViewModel.TeamMembers.OrderBy(sort.Column, sort.Direction);
}
SessionObjects.ApprovalViewModel.TeamMembers =
SessionObjects.ApprovalViewModel.TeamMembers.AsPagination(page ?? 1, Utility.GetPageLength());
ViewData["sort"] = sort;
return View(SessionObjects.ApprovalViewModel);
}
[HttpPost]
public ActionResult Home(ApprovalViewModel avm)
{
if (avm.TeamMembers.Count() == 0)
{
TempData["ErrorMessage"] = "You have no team members to select";
return RedirectToAction("Home");
}
else if (avm.TeamMembers.Where(x => x.SelectForConfirmationFlag == true).Count() == 0)
{
TempData["ErrorMessage"] = "You must select at least one team member";
return RedirectToAction("Home");
}
else
{
string[] selectedEmployees = avm.TeamMembers
.Where(x => x.SelectForConfirmationFlag == true)
.Select(x => x.EmployeeId.ToString()).ToArray();
var result = RedirectToAction("ConfirmBookings", "Approver",
new { selectedEmployeesParameters = selectedEmployees });
result.AddArraysToRouteValues();
return result;
}
}
A: Are you not supposed to match the name attribute of the checkbox? Your following line does not generate checkbox with name SelectForConfirmationFlag
column.For(model => Html.CheckBox("chkbox", model.SelectForConfirmationFlag))
Could you try following instead?
column.For(model => Html.CheckBoxFor(m => m.SelectForConfirmationFlag))
Or
column.For(model => Html.CheckBox("SelectForConfirmationFlag",model.SelectForConfirmationFlag))
A: I'm not familiar with MVC Contrib grid, but my approach would be to add the team member ids as value of the checkboxes and work with an array of ids in the controller method. Like so:
column.For(model => Html.CheckBox("teammembers", model.SelectForConfirmationFlag, new { value = model.Id }))
.Named("Select?")
.Sortable(false);
Controller method:
[HttpPost]
public ActionResult Home(int[] teammembers)
{
// code to process ids...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why isn't the exception caught by << try >>? I have a Python (Django) unit test FAIL from an exception, but the failing code is in a try / except block written for that exception. A similar block handles the exception when it is directly raised.
This passes:
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Code catches a directly raised ImmediateHttpResponse
try:
raise ImmediateHttpResponse(response=auth_result)
self.fail()
except ImmediateHttpResponse, e:
self.assertTrue(True)
This, immediately following it, fails:
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# FAIL
try:
resp = resource.dispatch_list(request) #<--- Line 172
self.fail()
except ImmediateHttpResponse, e:
self.assertTrue(True)
Here is the trace:
Traceback (most recent call last):
File ".../web_app/tests/api/tastypie_authentication.py", line 172, in test_dispatch_list_diagnostic
resource.dispatch_list(request)
File ".../libraries/django_tastypie/tastypie/resources.py", line 410, in dispatch_list
return self.dispatch('list', request, **kwargs)
File ".../libraries/django_tastypie/tastypie/resources.py", line 434, in dispatch
self.is_authenticated(request)
File ".../libraries/django_tastypie/tastypie/resources.py", line 534, in is_authenticated
raise ImmediateHttpResponse(response=auth_result)
ImmediateHttpResponse
Per the trace, the dispatch_list() call fails because it raises an << ImmediateHttpResponse >> exception. But placing just such an exception in the try block does not create a similar failure.
Why is the try / except block handling the one exception but not the other?
Note that the test code is copied from a library's test code, which does run as expected. (I'm using the library test code to diagnose my own implementation failures.)
A: Did you define your own ImmediateHttpResponse? (I so, do not do that.) It's possible to get the symptom you are describing if tastypie is raising a
tastypie.exceptions.ImmediateHttpResponse while your unit test is testing for
a locally defined ImmediateHttpResponse.
If so, to fix the problem, delete your definition of ImmediateHttpResponse and put something like
from tastypie.exceptions import ImmediateHttpResponse
in your unit test instead.
A: Got it, the problem was that my import of ImmediateHttpException differed from that of the code raising the error.
My import statement was:
from convoluted.directory.structure.tastypie.exceptions import ImmediateHttpResponse
The resource.py code that threw the error used:
from tastypie.exceptions import ImmediateHttpResponse
So it raised an exception != to the one I imported, though their string outputs were the same.
Fixing my import statement resolved the problem.
Thanks for listening!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612255",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Django MakeMessages missing xgettext in Windows Running Django on Windows 7.
I'm currently trying to translate a couple of Django templates using the instructions found in the django book chapter 19. I've added a translation tag to the template, loaded I18N, and modified django settings. Then I run django-admin.py makemessages -l en to create the po files. All folders are created but then django terminates with the following error:
Error: errors happened while running xgettext on init.py
'xgettext' is not recognized as an internal or external command,
operable program or batch file.
Reading up on the problem, I've discovered that django uses the gnu gettext library for unix based systems. To remedy this I installed cygwin which downloaded and installed the gettext package version 0.18.1.0 which I then added to my PATH. Sadly that did not solve anything. Cygwin did not add any xgettext files whatsoever.
My question is now this. Is there an easy way (or a tutorial) to install xgettext and the other functionality django's internationalization will require on Windows 7 without having to download a ton of assorted gnu packages. Django has been excellent so far in minimizing unnecessary hardships and these sudden difficulties are not characteristic of django at all.
A: please see http://code.djangoproject.com/ticket/1157. you do not need cygwin. try these files: http://sourceforge.net/projects/gettext/files/
EDIT:
http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/gettext-tools-0.17.zip
http://ftp.gnome.org/pub/gnome/binaries/win32/dependencies/gettext-runtime-0.17-1.zip
the above links are from this thread: http://groups.google.com/group/django-i18n/browse_thread/thread/577afdaef1392958?pli=1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Catalyst::Controller::FormBuilder view does not render input fields I'm trying to use the example view in CPAN for Catalyst::Controller::FormBuilder, which looks like this:
<!-- root/src/books/edit.tt -->
<head>
<title>[% formbuilder.title %]</title>
[% formbuilder.jshead %]<!-- javascript -->
</head>
<body>
[% formbuilder.start -%]
<div id="form">
[% FOREACH field IN formbuilder.fields -%]
<p>
<label>
<span [% IF field.required %]class="required"[%END%]>[%field.label%]</span>
</label>
[% field.field %]
[% IF field.invalid -%]
<span class="error">
Missing or invalid entry, please try again.
</span>
[% END %]
</p>
[% END %]
<div id="submit">[% formbuilder.submit %]</div>
<div id="reset">[% formbuilder.reset %]</div>
</div>
</div>
[% formbuilder.end -%]
</body>
The problem is I do get the field labels, but not the input fields, on my page: did anybody had this problem, before?
A: I found the issue: there is an error in the docs:
[% field.field %]
should read as
[% field.tag %]
...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: linking facebook share api to a button image i don't want to use the default fb share button so I've created a button that symbolizes fb with nice hover, now i want to link it to the fb share api.is it possible to do that?
A: You can do that using the javascript sdk and the feed dialog. Just assign your image an onclick event and then call the dialog function. Below is the snippet from https://developers.facebook.com/docs/reference/dialogs/feed/
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:fb="https://www.facebook.com/2008/fbml">
<head>
<title>My Feed Dialog Page</title>
</head>
<body>
<div id='fb-root'></div>
<script src='http://connect.facebook.net/en_US/all.js'></script>
<p><a onclick='postToFeed(); return false;'>Post to Feed</a></p>
<p id='msg'></p>
<script>
FB.init({appId: "YOUR_APP_ID", status: true, cookie: true});
function postToFeed() {
// calling the API ...
var obj = {
method: 'feed',
link: 'https://developers.facebook.com/docs/reference/dialogs/',
picture: 'http://fbrell.com/f8.jpg',
name: 'Facebook Dialogs',
caption: 'Reference Documentation',
description: 'Using Dialogs to interact with users.'
};
function callback(response) {
document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
}
FB.ui(obj, callback);
}
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to constrain/filter More Like This results in Solr? In Solr, I am wondering if it's possible to constrain/filter the "More Like This" result set from a standard (dismax) query - e.g., without having to use the specific MoreLikeThis request handler? For example, I have a Solr index which has documents for two countries. When I do my original (dismax) query, I use a field query operator (fq) to filter the results for the country of interest. But the MLT results that get returned are for both countries. I tried using the mlt.fl=country,name to indicate "show me more results that are similar in country and name" but it doesn't seem to obey the country criteria (or at least the name parameter far outweighs the country parameter).
I can't seem to find any Solr documentation that indicates there is an option for this, but I'm hoping one of you Solr experts out there may have some nifty tricks/hacks for this.
Thanks in advance!
A: Solr mlt.fl is supposed to find Related Documents based on these fields. However, it is not obligated to do so like the NOT clause of fq. A workaround could be to exclude the country using fq param. So, your mlt query could become something like
/mlt?q=id:ID&fq=-country:COUNTRY&mlt.boost=true
ID: The document ID for which MLT needs to be calculated. COUNTRY: The country which you want to exclude.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7612279",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.