text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Free the memory of a std::vector C++ I have a vector as below.
std::vector<std::string> exportNameList;
I am adding elements to this by using push_back method. But I am getting a debug assertion as "
"Windows has triggered a breakpoint in AxCent.exe.This may be due to a corruption of the heap, which indicates a bug in AxCent.exe or any of the DLLs it has loaded.
This happens when it calls the destructor of the class. When I refer to the call stack I was directed to the following code block in the vector class.
~vector()
{ // destroy the object
_Tidy();
}
What I noticed is there is an error when deleting the vector. Am I correct? How do I fix this? I have referred to many examples, but did not manage to work this out yet. I am quite new to C++.
Thanks a lot.
A: You are presumably corrupting the memory used by the vector somewhere else.
A: The bug you encounter may not be directly related to your vector.
If the memory (heap) is corrupted before the destructor of your vector is called, then the heap manager may only detect the corruption at this time (freeing the structure dynamically allocated by the vector or the dynamically allocated strings inside).
In my opinion, the best way to handle these kinds of bugs on the Windows platform is to activate the Full Page Heap for your program.
You can do this in 2 ways :
*
*either using gflags contained in the 'Debugging Tools for Windows'. Run it as administrator, go to the 'Image File' tab, enter the name of your EXE in the Image field (AxCent.exe), press TAB and check 'Enable page heap' and press 'Apply'
*or use Application Verifier. Select your executable through the File/App application menu make sur the check 'Basics/Heap' is checked and click save.
This setting will be applied whenever this application is launched.
Then run your application under a debugger (WindDbg or Visual Studio). If the memory is corrupted before your vector deletion, the debugger should break at this point.
When you are finished tracking the bug, don't forget to turn Full Page Heap off.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595793",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to get or set the Database character encoding when using PHP ODBC Functions? If I use odbc functions to connect to a database in PHP, How can I get or set the database character encoding? is there a function in PHP that I can use to do that?
An example of the odbc functions used in php script
<?php
//Connecting To The Database and getting $conn Variable
$conn = odbc_connect("database","username","password");
//Connection Check
if (!$conn)
{
echo "Database Connection Error: " . $conn;
}
$sqlResults = "SELECT EmpID AS EmployeeID, EmpName AS EmployeeName FROM Emp ORDER BY EmpName ASC";
$rsResults = odbc_exec($conn,$sqlResults);
if (!$rsResults)
{
echo "No Data Avialable";
}
else
{
while ( odbc_fetch_row($rsResults) )
{
$EmployeeID = odbc_result($rsResults,"EmployeeID");
$EmployeeName = odbc_result($rsResults,"EmployeeName");
//Printing the output
echo '<p>'. $EmpolyeeID . ' , ' . $EmployeeName . '</p>';
}
}
//Closing The Database
odbc_close($conn);
?>
A: You can find information on this here at Rob Allens dev notes page
rob allens dev notes
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can't import javax.servlet.annotation.WebServlet I have started to write app that can run on Google App Engine.
But when I wanted to use my code from Netbeans to Eclipse I had an errors on:
import javax.servlet.annotation.WebServlet;
and
@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})
the errors are:
The import javax.servlet.annotation cannot be resolved
WebServlet cannot be resolved to a type
I tried to import the servlet-api.jar to Eclipse but still the same, also tried to build and clean the project. I don't use Tomcat on my Eclipse only have it on my Netbeans. How can I solve the problem?
A:
I tried to import the servlet-api.jar to eclipse but still the same also tried to build and clean the project. I don't use tomcat on my eclipse only have it on my net-beans. How can I solve the problem.
Do not put the servlet-api.jar in your project. This is only asking for trouble. You need to check in the Project Facets section of your project's properties if the Dynamic Web Module facet is set to version 3.0. You also need to ensure that your /WEB-INF/web.xml (if any) is been declared conform Servlet 3.0 spec. I.e. the <web-app> root declaration must match the following:
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
In order to be able to import javax.servlet stuff, you need to integrate a fullworthy servletcontainer like Tomcat in Eclipse and then reference it in Targeted Runtimes of the project's properties. You can do the same for Google App Engine.
Once again, do not copy container-specific libraries into webapp project as others suggest. It would make your webapp unexecutabele on production containers of a different make/version. You'll get classpath-related errors/exceptions in all colors.
See also:
*
*How do I import the javax.servlet API in my Eclipse project?
Unrelated to the concrete question: GAE does not support Servlet 3.0. Its underlying Jetty 7.x container supports max Servlet 2.5 only.
A: Go to
window->Preference->server->runtime environment
then choose your tomcat server.
If the error is still there, then
right click project->properties>Targeted Runtimes
then check the server
A: Simply add the below to your maven project pom.xml flie:
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
A: I had the same issue, it turns that I had my project configured as many of you stated above, yet the problem persisted, so I went deeper and came across that I was using Apache Tomcat 6 as my Runtime Server, so the fix was simple, I just upgraded the project to use Apache Tomcat 7 and that's all, finally the IDE recognized javax.servlet.annotation.WebServlet annotation.
A: import javax.servlet.annotation.*;
(no one has written this, but need to import this as WebInitparam is not recognized by the other packages)
A: Copy servlet-api.jar from your tomcat server lib folder.
Paste it to WEB-INF > lib folder
Error was solved!!!
A: Check that the version number of your servlet-api.jar is at least 3.0. There is a version number inside the jar in the META-INF/manifest.mf file:
Implementation-Version: 3.0.1
If it's less than 3.0 download the 3.0.1 from Maven Central: http://search.maven.org/#artifactdetails|javax.servlet|javax.servlet-api|3.0.1|jar
Former servlet specifications (2.5, 2.4 etc.) do not support annotations.
A: If you're using Maven and don't want to link Tomcat in the Targeted Runtimes in Eclipse, you can simply add the dependency with scope provided in your pom.xml:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
A: Add library 'Server Runtime' to your java build path, and it shall resolve the issue.
A: If you are using IBM RAD, then ensure the to remove any j2ee.jar in your projects build path -> libraries tab, and then click on "add external jar" and select the j2ee.jar that is shipped with RAD.
A: I had the same issue using Spring, solved by adding Tomcat Server Runtime to build path.
A: You need to add your servlet-api.jar to the build path of your project. Have a look here for how to do that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
}
|
Q: Coded UI Testing of Silverlight in Sharepoint 2010 I am creating a Coded UI test for our system which runs on Sharepoint 2010. Part of the test sequence is creating a site; Sharepoint's UI for creating sites runs on Silverlight. Therefore, I need to create a Coded UI test for a Silverlight component which is part of out-of-the-box Sharepoint rather then part of our application. When I try to record a test, I get the following message:
No Silverlight controls where detected. Verify that the application under test is built using Silverlight assemblies with a version of 4.0 or greater and that a reference to the Microsoft.VisualStudio.TestTools.UITest.Extension.SilverlightUIAutomationHelper.dll assembly has been added to the project. For more information, see http://go.microsoft.com/fwlink/?LinkId=204562
I have two questions:
1) How can I find out the Silverlight version which Sharepoint components are built against? If they are built against Silverlight version 3.5 or earlier - I suppose the problem is unresolvable?
2) Assuming the previous question is answered - how can I make Sharepoint's Silverlight components reference the SilverlightUIAutomationHelper.dll library? That seems problematic at best to me...
Silverlight version installed on the test machine is 4; Visual Studio Feature Pack 2 is installed.
Thanks.
A: You can't make SharePoint's Silverlight components reference the automation helper library unless you have the source code and can recompile them. So the answer to your first question doesn't really matter.
A: You could modify Sharepoint XAPs to simply add Microsoft.VisualStudio.TestTools.UITest.Extension.SilverlightUIAutomationHelper.dll in there. You don't really need the code itself to reference it, it just has to part of the package. The XAP file is just a zip file so you should be able to modify this.
You will have to find where Sharepoint is getting the XAPs from and change the source (obviously you don't want to do this in prod boxes and there's even a license restriction for the Automation dll that prevents you from do it). You could also write a Fiddler AutoResponder to modify the XAP file and add the dll before it gets to the browser. For an example of this have a look at this AutoResponder:
https://bitbucket.org/mamadero/hackingsilverlightdemo/src/2fecb7b59dec/FiddlerAutoResponder
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595804",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: asp.net data binding in literal Lets say we have the following in the default.aspx file
<asp:Literal runat="server" Text="<%= TestMethod() %>" />
What needs to be defined in the default.aspx.cs file to make this work?
I tried to add a method called TestMethod to the _Default class which simply returned the string Test, but it didn't seem to work.
Can anyone help?
Thanks,
AJ
A: Apart from the method being marked public...
i think you could also remove the asp:Literal altogether
example
your code
<p><asp:Literal runat="server" Text="<%= TestMethod() %>" /></p>
could be
<p><%= TestMethod() %></p>
However if you are intent on using the Literal then please rather set it on page load.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.literal.aspx
Regards.
A: I think you can get the same result by doing this
In your .aspx file
<asp:Literal runat="server" ID="ltr1" />
And in your aspx.cs file
ltr1.text = TestMethod();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Downloading files in background with Python I have got a working web application in Python that downloads a file into the web server upon a user's request. This works fine for small file downloads but when the user requests a larger file, the connection times out. So, I think I need to process the download in the background but I'm not sure what tool is most suitable for this. Celery seems to be right but I don't really want it to be queued(the download must start immediately). What would you suggest?
A: Timout duration is up to you, you could just make it longer.
Anyway there are plenty of flash or AJAX uploaders out there, nothing you can do only server side AFAIK
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595809",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: AppEngine datastore design advice required I am building a distributed accounting system.
In terms of the DB structure and requirements, it's probably easiest to describe the app as a Twitter-like app, but with a hierarchical DB structure of 14 tables.
A company that uses the app may have 1 and more users, all sharing the company information.
Currently, each entity represents a record type, i.e. customers, invoices etc.
All entities have a parent which is the user of the app. (for HRD query consistency reasons)
Each query to the DB consists of 14 AppEngine queries. One for each table.
The query involves property filtering.
A new requirement is that a query of a user may require different property values based on each of the other users.
This means that we need (14 x the number of company-users) AppEngine queries. This seems far too much.
Kindless Ancestor queries that can filter by properties would be really nice, alas, no can do :)
My options are:
*
*Set entity kind to User. No parent. This means that all record types are mixed. (The filtered fields exist in all record types).
This is not pretty. But would you consider that?
*Have a fixed entity kind and query by filter only. The result is the equivalent of the Kindless Ancestor queries. However, I fear that it will be slow in a multi user use.
Some numbers:
We plan for 10,000 companies, average of 5 users per company and 1 to 5 million records per record type. (x 14 for total)
Thank you for your patience so far.. :)
A: Honestly I found it challenging to follow your description, so this may be off base. Seeing your existing code might help. But I get that you want an efficient alternative to propertied kindless ancestor queries, so let's start there.
Consider de-normalizing your data model to include a meta-entity just for querying:
class User(db.Model):
pass
class OwnedObject(db.Expando):
object_key = db.StringProperty()
class Customer(db.Model):
name = db.StringProperty()
created_on = db.DateProperty()
class Invoice(db.Model):
amount = db.IntegerProperty()
created_on = db.DateProperty()
# on write
customer = Customer()
customer.name = name
customer.created_on = date.today()
customer.put()
user = User(key_name=users.get_current_user().user_id())
owned_object = OwnedObject(parent=user)
owned_object.object_key = customer.key()
owned_object.created_on = customer.created_on
owned_object.put()
# on read
query = OwnedObject.all()
query.ancestor(user)
query.filter('created_on =', date.today())
entities = db.get([x.object_key for x in query])
So here you're doing more work on write and less on read.
Each real entity is coupled with an OwnedObject entity that descends from the appropriate ancestor and points to the real entity's key. OwnedObject is an expando, so you'll eager-assign any properties that you want to query on (in this example, created_on).
On read, you can query for any properties that you've copied to the expando meta-entity, and you can pull back all of a user's objects with a fixed overhead of one query and one batch get.
Edit: You can accomplish something similar without the meta-entity by using PolyModel.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Sending data from windows service to WCF - MaxArrayLength Error I've had a problem sending data from a local service to a web service for a while now, and I've tried many articles, but they all dont seem to help...
When I run the app I get the following error:
"The maximum array length quota (16384) has been exceeded while reading XML data. This quota may be increased by changing the MaxArrayLength property on the XmlDictionaryReaderQuotas object used when creating the XML reader."
Here is my web.config for the wcf service
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IOnlineSyncService" maxReceivedMessageSize="50000000" maxBufferPoolSize="50000000" messageEncoding="Mtom">
<readerQuotas maxDepth="500000000" maxStringContentLength="500000000" maxArrayLength="500000000" maxBytesPerRead="500000000" maxNameTableCharCount="500000000" />
<security mode="None"/>
</binding>
</basicHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>
</system.serviceModel>
<system.web>
<compilation debug="true"/>
</system.web>
</configuration>
My App.config on my Windows Service is as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.diagnostics>
<sources>
<source name="DefaultSource" switchName="DefaultSwitch">
<listeners>
<add name="FileLog"/>
</listeners>
</source>
</sources>
<switches>
<add name="DefaultSwitch" value="Information" />
</switches>
<sharedListeners>
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter"/>
</sharedListeners>
</system.diagnostics>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IOnlineSyncService" closeTimeout="00:05:00" openTimeout="00:05:00" receiveTimeout="00:10:00" sendTimeout="00:05:00" allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard" maxBufferSize="50000000" maxBufferPoolSize="50000000" maxReceivedMessageSize="50000000" messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered" useDefaultWebProxy="true">
<readerQuotas maxDepth="32" maxStringContentLength="50000000" maxArrayLength="50000000" maxBytesPerRead="50000000" maxNameTableCharCount="50000000" />
<security mode="None">
<transport clientCredentialType="None" proxyCredentialType="None" realm="" />
<message clientCredentialType="UserName" algorithmSuite="Default" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:65093/OnlineSyncService.svc" binding="basicHttpBinding" bindingConfiguration="BasicHttpBinding_IOnlineSyncService" contract="MyApp.OnlineSyncService.IOnlineSyncService" name="BasicHttpBinding_IOnlineSyncService" />
</client>
</system.serviceModel>
</configuration>
I call it from a windows app (MySyncService.Upload_Cust_Data(fileContents, BranchID, MyFile.Name))
filecontents is defined as a Byte()
I'm defining the MaxArrayLength property on both files, but it still gives me the same error.
I am up in arms with this one :(
A: have you tried remove the binding name in the wcf service, and set it to blank?
So the binding overrides the default binding.
Since you don't specify an endpoint I assume that the wcf service use default binding config.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Wordpress Custom Registration Form I have a client that needs a custom registration form.
*
*I need to make a custom design on this page
*I need to add custom fields like First Name, Company, Phone, etc.
Someone can help me with this?
A: A better place to ask WordPress questions is probably on WordPress Answers. Anyhoo, if you want to solve this without plugins, you need three things:
*
*A custom WordPress theme
*A Page Template
*A WordPress Page that uses the Page Template
When you have these three parts in place, you can do the following in your Page Template:
<?php
/*
Template Name: Registration
*/
global $current_user;
wp_get_current_user();
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$company = $_POST['company'];
if (($firstname != '') && ($lastname != '') && ($company != '')) {
// TODO: Do more rigorous validation on the submitted data
// TODO: Generate a better login (or ask the user for it)
$login = $firstname . $lastname;
// TODO: Generate a better password (or ask the user for it)
$password = '123';
// TODO: Ask the user for an e-mail address
$email = 'test@example.com';
// Create the WordPress User object with the basic required information
$user_id = wp_create_user($login, $password, $email);
if (!$user_id || is_wp_error($user_id)) {
// TODO: Display an error message and don't proceed.
}
$userinfo = array(
'ID' => $user_id,
'first_name' => $firstname,
'last_name' => $lastname,
);
// Update the WordPress User object with first and last name.
wp_update_user($userinfo);
// Add the company as user metadata
update_usermeta($user_id, 'company', $company);
}
if (is_user_logged_in()) : ?>
<p>You're already logged in and have no need to create a user profile.</p>
<?php else : while (have_posts()) : the_post(); ?>
<div id="page-<?php the_ID(); ?>">
<h2><?php the_title(); ?></h2>
<div class="content">
<?php the_content() ?>
</div>
<form action="<?php echo $_SERVER['REQUEST_URI'] ?>" method="post">
<div class="firstname">
<label for="firstname">First name:</label>
<input name="firstname"
id="firstname"
value="<?php echo esc_attr($firstname) ?>">
</div>
<div class="lastname">
<label for="lastname">Last name:</label>
<input name="lastname"
id="lastname"
value="<?php echo esc_attr($lastname) ?>">
</div>
<div class="company">
<label for="company">Company:</label>
<input name="company"
id="company"
value="<?php echo esc_attr($company) ?>">
</div>
</form>
</div>
<?php endwhile; endif; ?>
Now, when you want to retrieve the stuff you've stored, you need to know whether the information is within the User object itself or in metadata. To retrieve the first and last name (of a logged-in user):
global $current_user;
$firstname = $current_user->first_name;
$lastname = $current_user->last_name;
To retrieve the company name (of a logged-in user):
global $current_user;
$company = get_usermeta($current_user->id, 'company');
That's the basic gist of it. There's still a lot of stuff missing here, like validation, error message output, the handling of errors occurring within the WordPress API, etc. There's also some important TODO's that you have to take care of before the code will even work. The code should probably also be split into several files, but I hope this is enough to get you started.
A: An advantage of using a custom registration form is that modifying the code according to the user's needs becomes easy. For a custom submit form you can make use of existing hooks in Wordpress like template_redirect and then map that hook to some function which will do the post-processing of the form, like validation and submitting data to the site's database. You can refer to an in-depth article here.
<div class="employee">
<input type="hidden" name="show_msg">
<form name="customer_details" method="POST" required="required" class="input-hidden">
Your Name: <input type="text" id="name" name="customer_name">
Your Email: <input type="text" id="email" name="customer_email">
Company: <input type="text" id="company" name="company">
Sex: <input type="radio" name="customer_sex" value="male">Male <input type="radio" name="customer_sex" value="female">Female
<textarea id="post" name="experience" placeholder="Write something.." style="height:400px;width:100%"></textarea>
<input type="submit" value="Submit">
<!--?php wp_nonce_field( 'wpshout-frontend-post','form-submit' ); ?-->
</form></div>
PHP function
function wpshout_frontend_post() {
wpshout_save_post_if_submitted();
}
add_action('template_redirect','wpshout_frontend_post', 2);
A: A custom WordPress registration form has two major advantages over the standard form.
The first is the integration with the overall look and feel of the website theme. Standard forms often don’t work well with custom themes and there is always a chance that the custom CSS files do not render well with the form. A custom form, on the other hand, can be easily set up to work with custom CSS.
The second and more popular reason of using a custom registration form is the option of custom fields that are not included on the standard form. A small custom registration form speeds up the process and collects all the necessary data from a neat interface.
function wordpress_custom_registration_form( $first_name, $last_name, $username, $password, $email) {
global $username, $password, $email, $first_name, $last_name;
echo '
<form action="' . $_SERVER['REQUEST_URI'] . '" method="post">
First Name :
<input type="text" name="fname" value="' . ( isset( $_POST['fname']) ? $first_name : null ) . '">
Last Name:
<input type="text" name="lname" value="' . ( isset( $_POST['lname']) ? $last_name : null ) . '">
Username <strong>*</strong>
<input type="text" name="username" value="' . ( isset( $_POST['username'] ) ? $username : null ) . '">
Password <strong>*</strong>
<input type="password" name="password" value="' . ( isset( $_POST['password'] ) ? $password : null ) . '">
Email: <strong>*</strong>
<input type="text" name="email" value="' . ( isset( $_POST['email']) ? $email : null ) . '">
<input type="submit" name="submit" value="Register"/>
</form>
';
}
This form can be inserted anywhere by using the shortcode [wp_registration_form]. Here is the code snippet for setting up the shortcode:
function wp_custom_shortcode_registration() {
ob_start();
wordpress_custom_registration_form_function();
return ob_get_clean();
}
I hope that by now you have a fair idea of creating a WordPress custom Registration form.Still any confusion kindly check Build Custom WordPress Registration Forms
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595821",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How to denied all requests except some in Magento The question is not enough clear, so I will explain more.
My client has a requirement in mobile1 about the users all SHOULD not visit all request2
For example:
The users SHOULD: only visit some in below list:
*
*mydomain.com/catalog/product/view
*mydomain.com/cusotmer/account/any_action
*mydomain.com/onepage/checkout/any_action
So, I am having a solution is at the method: Mage_Core_Controller_Varien_Action::preDispatch()
I will get the request variable to check what is moulde, controller, action. If it is valid in list, if not I will redirect to an accessed denied page.
I know that is bad, so I am looking for other solutions.
1: We've already designed a theme for mobile, just want to give for user some pages are necessary.
2: I mean to the router format: module/ controller/ action.
UPDATE:
Thanks all guys so much. Now, I understand what I need to do. I don't know how to close my question. So please help me if you can. I don't want to be a member who never accept the answer.
A: This is not good question which could be easy to answer, but very happy for help from @azakolyukin and @elgabbu
So, I think @azakolyukin's comment is correct answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to count in a join statement I have got table post: int post_id, varchar title, text content
And table comment:int comment_id, int post_id, varchar content where post_id is a foreign key references table post.
How do i get the post_id and sum of comments of each post order by comments count. Thank you.
A: If you want posts that have no comments:
SELECT
post.post_id,
--post.title,
--post.content,
COUNT(comment.post_id) AS comment_count
FROM post
LEFT JOIN comment ON post.post_id = comment.post_id
GROUP BY post.post_id
ORDER BY comment_count DESC
(This query uses the MySQLs GROUP BY with hidden columns extension).
If you don't want posts that have no comments you can use a simpler query:
SELECT post_id, COUNT(*) AS comment_count
FROM comment
GROUP BY post_id
ORDER BY comment_count DESC
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595824",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: SQL Server table result to array in SQL Server 2005 Hi and thanks in advance.
First off, I do not mean I want to convert an array into a table. I can do that. Easy :)
I would like to do the opposite.
I have a row with n rows related to it in another table. I wish to output the row and then within a single column of that row, let's say Children, its linked rows in an array (or a string that I can interpret as an array with front-end code).
Like this:
ID TITLE DESCRIPTION CHILDREN
--------------------------------------------------------
36 Blah Blah Blah ['Bob','Gary','Reginald']
20 Pah Pah Pah ['Emily','Dave']
You see?
I know, this is probably not the best way to do it. But, it's for a specific use that would be too long to explain here.
Thanks again.
A: You can actually do this all in one CTE select query, without using any functions. Here's how:
First, consider this parent/child table structure:
CREATE TABLE P (ID INT PRIMARY KEY, Description VARCHAR(20));
CREATE TABLE C (ID INT PRIMARY KEY, PID INT,
Description VARCHAR(20),
CONSTRAINT fk FOREIGN KEY (PID) REFERENCES P(ID));
(I've use P and C to save on typing!)
And lets add some test data, matching that of the question asker:
INSERT INTO P VALUES (36, 'Blah Blah');
INSERT INTO P VALUES (20, 'Pah Pah');
INSERT INTO C VALUES (1, 36, 'Bob');
INSERT INTO C VALUES (2, 36, 'Gary');
INSERT INTO C VALUES (3, 36, 'Reginald');
INSERT INTO C VALUES (4, 20, 'Emily');
INSERT INTO C VALUES (5, 20, 'Dave');
Then finally, the CTE expression:
WITH
FirstItems (PID, FirstCID) AS (
SELECT C.PID, MIN(C.ID)
FROM C
GROUP BY C.PID
),
SubItemList (PID, CID, ItemNum) AS (
SELECT C.PID, C.ID, 1
FROM C JOIN FirstItems FI ON (C.ID = FI.FirstCID)
UNION ALL
SELECT C.PID, C.ID, IL.ItemNum + 1
FROM C JOIN SubItemList IL ON C.PID = IL.PID AND C.ID > CID
),
ItemList (PID, CID, ItemNum) AS (
SELECT PID, CID, MAX(ItemNum)
FROM SubItemList
GROUP BY PID, CID
),
SubArrayList (PID, CID, Array, ItemNum) AS (
SELECT IL.PID, IL.CID, CAST(C.Description AS VARCHAR(MAX)), IL.ItemNum
FROM ItemList IL JOIN C ON IL.CID = C.ID
WHERE IL.ItemNum = 1
UNION ALL
SELECT IL.PID, IL.CID, AL.Array + ',' + CAST(C.Description AS VARCHAR(MAX)), IL.ItemNum
FROM ItemList IL
JOIN SubArrayList AL ON (IL.PID = AL.PID AND IL.ItemNum = AL.ItemNum + 1)
JOIN C ON (IL.CID = C.ID)
),
MaxItems (PID, MaxItem) AS (
SELECT PID, MAX(ItemNum)
FROM SubItemList
GROUP BY PID
),
ArrayList (PID, List) AS (
SELECT SAL.PID, SAL.Array
FROM SubArrayList SAL
JOIN MaxItems MI ON (SAL.PID = MI.PID AND SAL.ItemNum = MI.MaxItem)
)
SELECT P.ID, P.Description, AL.List
FROM ArrayList AL JOIN P ON P.ID = AL.PID
ORDER BY P.ID
Result:
ID Description List
-- -------------- --------
20 Pah Pah Emily,Dave
36 Blah Blah Bob,Gary,Reginald
To explain what's going on here, I'll describe each part of the CTE and what it does.
FirstItems looks at all the children, and finds the lowest ID in each parent group to use as the anchor for the next recursive SELECT:
FirstItems (PID, FirstCID) AS (
SELECT C.PID, MIN(C.ID)
FROM C
GROUP BY C.PID
)
SubItemList is a recursive SELECT that picks up the lowest child from the previous query, and allocates an incrementing item number to each child starting from 1:
SubItemList (PID, CID, ItemNum) AS (
SELECT C.PID, C.ID, 1
FROM C JOIN FirstItems FI ON (C.ID = FI.FirstCID)
UNION ALL
SELECT C.PID, C.ID, IL.ItemNum + 1
FROM C JOIN SubItemList IL ON C.PID = IL.PID AND C.ID > CID
)
The trouble is it dups up and repeats a lot of the items, so ItemList filters it to just pick the max from each group:
ItemList (PID, CID, ItemNum) AS (
SELECT PID, CID, MAX(ItemNum)
FROM SubItemList
GROUP BY PID, CID
)
Now we have an ID list of parents with each of there children numbered from 1 to x:
PID CID ItemNum
----------- ----------- -----------
36 1 1
36 2 2
36 3 3
20 4 1
20 5 2
SubArrayList takes the children rows, recursively joins to the numbers list and starts appending all the descriptions to each other, starting with a single description:
SubArrayList (PID, CID, Array, ItemNum) AS (
SELECT IL.PID, IL.CID, CAST(C.Description AS VARCHAR(MAX)), IL.ItemNum
FROM ItemList IL JOIN C ON IL.CID = C.ID
WHERE IL.ItemNum = 1
UNION ALL
SELECT IL.PID, IL.CID, AL.Array + ',' + CAST(C.Description AS VARCHAR(MAX)), IL.ItemNum
FROM ItemList IL
JOIN SubArrayList AL ON (IL.PID = AL.PID AND IL.ItemNum = AL.ItemNum + 1)
JOIN C ON (IL.CID = C.ID)
)
The result is now:
PID CID Array ItemNum
----------- ----------- ----------------- -----------
36 1 Bob 1
20 4 Emily 1
20 5 Emily,Dave 2
36 2 Bob,Gary 2
36 3 Bob,Gary,Reginald 3
So all we need to do is to get rid of all the partly concatenated rows.
MaxItems simply grabs a list of parents and their highest item numbers, which makes the following query a bit simpler:
MaxItems (PID, MaxItem) AS (
SELECT PID, MAX(ItemNum)
FROM SubItemList
GROUP BY PID
)
ArrayList performs the final cull of the partly concatenated rows using the max item number aquired from the previous query:
ArrayList (PID, List) AS (
SELECT SAL.PID, SAL.Array
FROM SubArrayList SAL
JOIN MaxItems MI ON (SAL.PID = MI.PID AND SAL.ItemNum = MI.MaxItem)
)
And finally, all that remains is to query the result:
SELECT P.ID, P.Description, AL.List
FROM ArrayList AL JOIN P ON P.ID = AL.PID
ORDER BY P.ID
A: There are multiple ways to do it; the article below presents various solutions for this type of operation:
http://www.simple-talk.com/sql/t-sql-programming/concatenating-row-values-in-transact-sql/
A: You need a function that when passed the foreign key that links the child table to the parent, queries the child table to build a cursor and then loops through it concatenating the required values. Function then returns that string. Function is then called as the fourth column of your query. Can't help you with the syntax etc as I don't use SQL-Server
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How does cache mechanism of Orbeon 3.9 PE feature works I implemented the following code in all my static instances. I was expecting the browser to hold these readonly instances in client side cache but its fetching those readonly instance from server for each request.
Please confirm my understanding on xxforms:readonly="true" xxforms:cache="true". If it’s wrong kindly explain the same.
<xforms:instance id="drop-downs" xxforms:readonly="true" xxforms:cache="true">
<form>
<yes-no>
<options>Yes</options>
<options>No</options>
</yes-no>
<true-false>
<options>False</options>
<options>True</options>
</true-false>
</form>
</xforms:instance>
A: *
*xxforms:readonly="true" isn't related to caching: it is a way for you to tell Orbeon Forms that you won't be modifying data in that instance, which allows Orbeon Forms to use a more compact representation for that data, thus using less memory.
*xxforms:cache="true" is useful when you are retrieving the XML from a URL, not when the XML in inline in your form. In that case you can tell Orbeon that the XML at this URL is constant, and can be cached by Orbeon. This way you save yourself the cost of reading that URL every time the form is loaded.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot fix the cell width in a HTML table I would have thought that the CSS below would work;
table#ScheduledLeaveCalendar
{
table-layout:fixed;
}
/* Calendar that shows annual leave */
#ScheduledLeaveCalendar
{
border-collapse:collapse;
}
#ScheduledLeaveCalendar td, #ScheduledLeaveCalendar th
{
font-size:0.8em;
border:1px solid #2906A6; /* dark blue */
padding:3px 3px 2px 3px;
width:30px;
}
#ScheduledLeaveCalendar th
{
font-size:0.9em;
text-align:center;
padding-top:5px;
padding-bottom:4px;
background-color:#6640EE; /* blue */
color:#ffffff;
}
The html will make sense to MVC developers;
<table id="ScheduledLeaveCalendar">
<%: Html.DisplayFor(x => x.cvm.Header1)%>
<%: Html.DisplayFor(x => x.cvm.Header2)%>
<%: Html.DisplayFor(x => x.cvm.Header3)%>
<%: Html.DisplayFor(x => x.cvm.Lines)%>
</table>
However for some reason it does not. It seems to ignore the fixed property - I am using IE8.
There are no issues with test wrapping or scrollbars with this problem.
This is the rendered HTML, edited to remove repetitive code;
<table id="ScheduledLeaveCalendar">
<tr>
<th colspan="2"></th>
<th colspan="6">Apr 2011</th>
<th colspan="6">Apr 2011</th>
<th colspan="6">Apr 2011</th>
<th colspan="6">Apr 2011</th>
<th colspan="6">May 2011</th>
<th colspan="6">May 2011</th>
<th colspan="6">May 2011</th>
<th colspan="6">May 2011</th>
<th colspan="6">May/Jun 2011</th>
</tr>
<tr id="CalendarHeader2Row">
<th>
F
</th>
<th>
</th>
<th>
M
</th>
<th>
T
</th>
<th>
W
</th>
<th>
T
</th>
<th>
F
</th>
<th>
</tr>
<tr id="CalendarHeader3Row>
<th>
1
</th>
<th>
</th>
<th>
4
</th>
<th>
5
</th>
<th>
6
</th>
<th>
7
</th>
<th>
8
</th>
</tr>
<tr id="CalendarLines">
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight DefaultColour"></td>
<td class="StandardCellHeight BankHolidayColour"></td
</tr>
</table>
This is what is being rendered, the cells have different widths;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595829",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get Facebook UserID Using Facebook's new Open Graph technologies launched just recently at their F8 Conference, how do I retrieve the facebook user id when a facebook user hits my open graph object? Is this even possible at all?
As per this video:
http://developers.facebook.com/blog/post/564/
I've created the object
I've also initialized the object and action on facebook:
object --> video
action --> recommend
If you go to the above .htm file and go view source, you will see the meta tags that I am using. I am referring to my pazooza:video object type, the one I created on facebook.
But the point of this is that when a facebook user hits the .htm page to view the video, then I want to record that users hit in the database.
Does fb send a signed_request or user id via the querystring or do I subscribe to the .htm file somehow and my server gets a response from facebook? I'm a lil confused any help would be appreciated.
I'm using ASP.Net MVC (Facebook C# SDK).
A: Never mind I found the answer, well part of it.
My architectural approach to the problem was wrong. I've spoken to one of the developers on the facebook c# sdk and some of the samples he gave made me realise how the open graph works. Or "facebooks" version of it anyway.
The MVC design pattern reigns supreme in this case. By having actions mimic the actions in your facebook open graph implementation you can now publish real-time events into the graph and have them available to new and existing users.
See this post: http://facebooksdk.codeplex.com/discussions/274238
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595833",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: InterfaceOrientation issues when popping a ViewController off the stack I have the beginnings of my app working pretty well but I have one small issue that I can't figure out how to fix.
It's a view based app and I have a NavigationController in my appDelegate file which is pushing various ViewControllers as required. Going in the "forwards direction" everything works well, seems perfect actually, but the problem I have is when VC's are popped off the stack. This is the code I'm using to show the VC and then just using the back button to go back.
UINavigationController *iaxNC = [[UINavigationController alloc] init];
LogInViewController *logInVC = [[LogInViewController alloc] init];
[iaxNC pushViewController:logInVC animated:NO];
[logInVC release];
[_window addSubview:iaxNC.view];
[_window makeKeyAndVisible];
That loads my login view and then the code checks to see if there are any users before it loads the SetUp screen (if there are none) as follows:
setUpVC = [[SetUpViewController alloc] init];
setUpVC.firstUse = self.firstUse;
[self.navigationController pushViewController:setUpVC animated:YES];
[setUpVC release];
The problem happens when I hit the back button from the SetUp view to go back to the LogIn view.
I have a portrait and a landscape view for most of the VC's and these VC's are subclasses of Michael Tyson's TPMultiLayoutViewController. The portrait view is hooked up as *portraitView and also as *view, the landscape view is hooked up as *landscapeView.
The problem is this:
If I push a VC into view and change the orientation of the device before I hit the back button then when I do hit "Back" the previous VC is displayed in its original format (i.e. NOT rotated to the current orientation) it also appears that the lower left corner of the view is in the lower left of the screen. It then "sticks" like that until I rotate the device again and then all is good and functions as expected.
So the thing is I'm working through the contents of the TPMultiView subclass but I don't pretend to understand all of it yet (and therein probably lies my REAL problem) but as a stopgap solution is there a way to force the view of the "pusher" VC to appear in it's previous orientation (albeit briefly - and THEN allow it to rotate once it has been displayed) when the "pushee's" VC is popped?
Does that make sense?
SOLVED IT! The problem was I had included my own viewWillAppear method in LogInVC but I hadn't called [super viewWillAppear] so the effect of the superclass was never really going to work, was it! Thanks for the input. I can recommend the TPMultiView drop in subclass BTW works very nicely.
A: You should first verify your implementation of shouldAutoRotateToInterfaceOrientation: is correct for all your view controllers.
Then make sure the views of your view controller's have an appropriate autoresizingMask set. If you have created the view controllers and their views in Interface Builder you should set the resizing mask there.
Otherwise in your -loadView or -viewDidLoad methods you should have this line:
self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth |
UIViewAutoresizingFlexibleHeight;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Symfony - module template not loading withing layout specified in view.yml file I inherited these symfony source files from a site previously hosted on a linux box, and developed by someone else.
I'm developing on a Windows XP machine and am trying to make this site work on localhost.
I've made sure that in /apps/frontend/config/view.yml the setting below are there. (And this is a default setting for all site pages.)
has_layout: on
layout: layout
And that the selected layout is available and correct in /apps/frontend/templates/layout.php
Yet, whenever I try to load a page, in page source, I can see that it only loads the module template code, without anything around it.
A: There could be multiple issues:
*
*An error is thrown in your layout.php Have you enabled all warnings/errors and checked your log files?
*It renders the wrong layout somehow This could happen when you have view setups for different environments. If you add <?php decorate_with('layout'); ?> to one of your views (like indexSuccess.php, does it work? Is there no override for the project view.yml in the module? Or is the template overriden with a <?php decorate_with(FALSE); ?> statement?
But my first guess is the top one: enable all logging and view your log.
A: Guess what, it was a syntax error in a config/settings.yml file.
I've put 'true' instead of 'on' and 'false' instead of 'off'. I'm not sure if it was a because the file contained both 'on' and 'true', or if it can only tolerate one or the other depending on version of symfony.
5 days of banging head into keyboard over a stupid file format that has no debug.
I will not use yaml files willingly again.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595839",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: TypeError (can't convert nil into Integer) paperclip I am using paperclip while creating new object for saving in database i am facing
can't convert nil into Integer paperclip error
This is what i have written in my function.
def create
@asset = Asset.new(params[:snap]) #here i am facing the above error.
@asset.user_id = current_user.id
@asset.save
redirect_to "/"
end
This is what i am getting while posting form
{:original=>#<File:/tmp/stream20110929-1212-17asdf-0,6708,0>, .... }
Any suggestions for solving this?
A: I fixed this error by applying the following patch.
https://github.com/thoughtbot/paperclip/commit/1bcfc14388d0651c5fc70ab9ca3511144c698903
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595841",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to show Multiple Pins on mkmapview I want to show multiple pin annotations on a mapview.
I am getting multiple hotel location lat long from server and i have store them in NSMutableArray, now I want to show these lat long value on my mapview.
A: Every thing you need is here: MKMApView and here MKAnnotations
Some a nice example code: WeatherMap
A: You need to create a model object that conforms to the MKAnnotation protocol. At the very least, it should implement the coordinate method (which returns a CLLocationCoordinate2D struct for your latitude and longitude). If you want to display a callout for the map pin, you'll also need to implement the title method.
You should create one of these objects for each lat,lon pair, and store these in your array. Then call the addAnnotations: on your mapView with the array of objects
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595842",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to show sqlite datas in a textview? My name is NipinVarma,I would want to know about some errors in my iphone application.I am doing a bible application for a client,i almost complete the functionality s of the application,like authentication ,UI etc etc.sqlite is used for the database of the bible,i want to display the bible sql database in a textview.But i already done this with a tableview controller,every verses and genisis are displayed in tableview according to my needs through array count.My need is to display this in a textview when we open that page for reading bible.here i put my code that gives me the correct input in tableview.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
BibleIphoneAppDelegate *appDelegate = (BibleIphoneAppDelegate *)[[UIApplication sharedApplication] delegate];
return appDelegate.biblearray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.detailTextLabel.numberOfLines = 0;
cell.detailTextLabel.font = [UIFont fontWithName:@"Arial Rounded MT Bold" size:12.0];
// Set up the cell
tbl.separatorColor = [UIColor clearColor];
BibleIphoneAppDelegate *appDelegate = (BibleIphoneAppDelegate *)[[UIApplication sharedApplication] delegate];
bible *jesus = (bible *)[appDelegate.biblearray objectAtIndex:indexPath.row];
[cell setText:jesus.chapterNo];
cell.detailTextLabel.text = jesus.verseNumber;
cell.font = [UIFont systemFontOfSize:9.0];
return cell;
Please help me to do this.
Thanks in advance.
A: Use didSelectRowAtIndexPath of UITableViewDelegate:
-(void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath {
NSInteger row = [indexPath row];
[self pushChildViewControllerForRow:row animated:YES];
}
Then in pushChildViewControllerForRow you can do something like:
-(void)pushChildViewControllerForRow:(NSUInteger)row animated:(BOOL)flag {
if (chapterViewController==nil) {
self.chapterViewController = [[ChapterViewController alloc] initWithNibName:@"ChapterViewController" bundle:nil];
[navigationController pushViewController:chapterViewController animated:flag];
// and here you will need to populate chapterViewController with data extracted from your sqlite database
}
ChapterViewController might be similar to:
@interface ChapterViewController : UIViewController <UITextViewDelegate> {
IBOutlet UITextView *textView;
}
@property (nonatomic, retain) UITextView *textView;
-(void)backButtonPressed:(id)sender;
@end
Hope you got an idea.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595844",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Center positioning for my popup dialog box I have used a dialog box in my application which is causing trouble with it's alignment as my page has grown in content.
Till my page was short and had less content , it used to popup up nicely at the center of my page . But , now my page has grown vertically , and once I click on my popup , I want it to be positioned at the center of my screen instead of scrolling everytime to the center of the page.
#bdy_content is the parent/root div in my page.
target element is actually a span as given below :
<span adname="testtraffickerbannertext" adtag="Click here!" title="showAdTag">
<a class="banner" href="javascript:void(0);" title="showAdTag">Ad Tag</a>
</span>
Hereis my centerPopup() function :
function centerPopup(e){
var target = e.target.title;
//request data for centering
var windowWidth = document.documentElement.clientWidth;
var windowHeight = $('#bdy_content').height();
if(windowHeight < 600){
windowHeight = 600;
}
var popupHeight = $("#" + target).height();
var popupWidth = $("#" + target).width();
//centering
$("#"+ target).css({
"position": "absolute",
"top": windowHeight/2-popupHeight/2,
//Instead, we go with where the click was
// "top" : e.pageY - 20,
"left": windowWidth/2-popupWidth/2
});
//only need force for IE6
$("#previewCurtain").css({
"height": windowHeight
});
window.scrollTo(0,windowHeight/2-popupHeight/2);
}
Also , I can't change my existing popup plugin as I have reused it this throughout my site and it will be a big overhead .
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Speed of HttpWebRequest/HttpWebResponse Is there any quicker alternative to the code below to get a http response into a string?
string req = "http://someaddress.com";
Stopwatch timer = new Stopwatch();
timer.Start();
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream dataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
reader.ReadToEnd();
}
}
timer.Stop();
Console.WriteLine(timer.Elapsed);
The response is pretty big - around 2MB and is in XML format. Affter this codes completes, the timer is equal to ~50 seconds. When I paste the same url into the browser window it takes about 35 seconds for it to display the xml document.
A: (You should have a using statement for the response, by the way... and I agree with asbjornu's comment. You should update your question with more details.)
You should use something like Wireshark to look at what the requests and responses look like in each case. For example, is the browser specifying that it supports compressed responses, and WebRequest not? If it's over a slow connection, that could well be the important part.
Another thing to test is whether the string decoding is taking significant time in the .NET code... if you simply read the data from the stream into a byte array (possibly just throwing it away as you read it) is that significantly faster? For example:
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
// Just read the data and throw it away
byte[] buffer = new byte[16 * 1024];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
// Ignore the actual data
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Exceptions handling guidelines for C++ I understand benefits of using exceptions handling in C++ and I'm aware that it may be tricky. One of rule says, that every function may throw. Ok, but there are situations, where we want to make sure, that function does not throw. I'm looking for any well-known practices or guidelines for handling such situations. Examples:
try
{
// do something
}
catch (std::runtime_error& error)
{
save_log (error);
emit_dbus_signal (error);
}
I don't care if save_log() or emit_dbus_signal() will fail, I only want to make sure, that I tried to call them.
ThreadPool thread_pool;
SocketsPool socket_pool;
MainLoop main_loop;
try
{
thread_pool.init ();
socket_pool.init ();
main_loop.run ();
}
catch (std::runtime_error& error)
{
save_log (error);
emit_dbus_signal (error);
}
thread_pool.finalize ();
socket_pool.finalize ();
I only want to make sure, that I tried to finalize thread_pool and socket_pool. Any error during finalization process should be handled inside finalize() methods.
I can remember, which functions does not throw, but it will work only for small programs. Should I add suffix like _nothrow to such "non throwing" functions' names and handle this while writing code? Exceptions specification is deprecated since C++11 so I want to avoid it. What about noexcept? I still not sure if I understand this new feature. Is it what I'm looking for?
There's no excpetions checking at compile time in C++11 right?
Or maybe I'm completely wring? :)
A: I think you need to understand RAII as a starting point.
Once you're using RAII correctly, you'll find that most of the case where you thought you needed to manually finalize objects have magically disappeared: And, so in a lot of cases, that means you can dispense with the try/catch/finalize approach entirely.
As others have said, you're still going to want your save_log/emit_dbus_signal calls in a catch statement somewhere...
In the above case, ThreadPool's constructor would call init(), and the destructor would call finalize().
A: You should certainly document which functions are guaranteed not to throw, don't just "remember"!
A common example is that swap functions should be no-throw. In that case, there's no reason to put nothrow in the name, it's fairly fundamental that many uses of swap need to be nothrow. You could likewise make a rule for your project that log functions never throw. But this still needs to be documented. Ideally, every function should document what it throws and why, but failing that every function should certainly document what level of exception guarantee it offers, and "nothrow" is the strongest level.
If I had throwing and non-throwing versions of the same functionality, then personally I'd put nothrow in the name to distinguish them. Other than that, see what the code looks like. It's possible you'll find yourself writing a piece of code in which you call seven functions in a row, all of which have to be nothrow for the code to be correct. It would probably be helpful to future readers not to have to go and check the declaration of each of those functions to make sure it really doesn't throw, although IDEs help with that. They certainly don't want to have to read 7 doc files if that's avoidable. In that case, I suppose it might be helpful to have Hungarian-style warts in the function names, but that kind of thing can rapidly get out of hand and make the code harder to read, not easier.
Also, if you use a naming convention then operator overloads become rather difficult - you can't distinguish between a throwing and non-throwing operator+ by name.
Empty exceptions specifications are OK, and C++11 noexcept is probably better. Aside from their meaning to the compiler, they help with documentation. It's non-empty exception specifications that are troublesome.
I agree with what everyone is saying about finalize: that's what destructors are for.
A: This depends on what you actually intend on doing. When you say that you do not care whether save_log or emit_dbus_signal fails, you are not saying what don't care means. That is, if save_log fails, do you want to still try and emit_dbus_signal? If so, you can:
catch ( std::runtime_error& error ) {
try { save_log( error ); } catch (...) {}
try { emit_dbus_signal( error ); } catcn ( ... ) {}
}
If you do not care about emit_dbus_signal not being called if save_log fails, another approach would be enclosing the whole try/catch inside a second try/catch:
try {
try {
// current code
} catch ( std::runtime_error const & error ) {
// current handling
}
} catch (...) {} // ensure that no other exception escapes either the try or the catch blocks
thread_pool.finalize();
socket_pool.finalize();
There are actually other approaches, like using a RAII to ensure that threadpool.finalize() is called regardless of how the function completes in the lines of ScopeGuard.
A: For the finalization functions, you should consider using wrapper classes with the RAII principle instead, that is, rewrite your code using:
try {
initialized_thread_pool pool = thread_pool.init();
} catch (std::runtime_error& error) { handle(error); }
and do the finalization in the destructor of initialized_thread_pool.
Once you get that principle right, exception specifications don't seem that much of an issue anymore.
A: Read up on RAII
http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization
If your function throws, any stack variables in that function will still have their destructors called. That means you can simply call finalize() inside the ~ThreadPool() and ~SocketPool() destructors.
If you can't modify the ThreadPool or SocketPool classes, you can write your own wrapper classes that call finalize on destruction, e.g.
class ScopedThreadPool
{
public:
ScopedThreadPool(ThreadPool &threadPool) : m_threadPool(threadPool) {}
~ScopedThreadPool() { m_threadPool.finalize(); }
private:
ThreadPool &m_threadPool;
};
And then use it like this...
ThreadPool threadPool;
ScopedThreadPool scopedThreadPool(threadPool);
When the function exits (either via return or throw) then the ScopedThreadPool destructor will call finalize() for you.
A: Add throw() to the end of a function declaration. The compiler (gcc at least) will then complain if the function throws exceptions.
void function() throw();
This is standard C++ that says this function doesn't throw any exceptions. Previously you could say which exceptions it threw, but I think C++11 removed that feature. Only the empty clause, as above, remains.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595869",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How do I check if the user is the new user or not in Facebook? <?php
$facebook = new Facebook(array("appId"=>'xxxxxx', "secret"=> 'xxxxxxxx'));
$user = $facebook->getUser();
if (!$user) {
$loginUrl = $facebook->getLoginUrl(array(
'redirect_uri'=>'apps.facebook.com/abc/'));
header("Location:$loginUrl");
}
?>
How do I check if the user is the new user or not? Earlier, Facebook used to provide installed = 1 in the URL. Now, how do I check if the user is the new user or not?
A: An API call to /me/?fields=installed will tell you if the current user has installed your app - if you need to know if the user has never used the app before, you should probably keep this state in your own app
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: RMI Client and Server programms I implemented a client and server programms using RMI. I wrote this both server and client classes in same project. But now I want to run this client and server programms separately (as two projects). So how can I do this?
A: Split your application into three artifacts/projects/JARs:
*
*client - code that calls the server via RMI API. Depends on api
*server - implement the API on the server side. Obviously client is not dependent on this artifact
*api - both client and server depend on API: client uses, server implements.
This approach allows you to develop both client and server independently. Also changing the api can't easily be missed since it is a separate project.
A: You should have main method in each class you want to run. After creating main methods and compiling files, simply run each file, using your IDE or command "java". You don't need two projects to do this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595874",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Making unopened boxes un-clickable until larger opened box is closed I am currently playing about with jQuery Isotope. I love it but it is way above my very very basic jQuery knowledge. So far with help from other people I am slowly getting to my end goal. My question today is to see whether it is possible to make the small boxes un-clickable until the big opened box is closed - please refer http://jsfiddle.net/djsbaker/gPuD9/
My ideal was to have each smaller box opening at the very top and pushing all the smaller ones down. This doesn't look like it is possible as after a user clicks on several boxes the larger box drops down on the second line. A way round this would be to not make the smaller boxes un-clickable once the larger one was opened...at least I hope.
Thanks in advance.
DB
A: Try something like this:
$(".element").click(function () {
if ($(".element.large").not(this).length === 0) {
$(this).toggleClass("large");
}
}
This says if there is an element which has the "large" class already on it (not including the element that was clicked) then do nothing. Otherwise toggle the currently clicked elements "large" class.
Your css would then have styling for the "large" class to make the element larger.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How would one make a unit converter in objective c? I was wondering how, in objective c, one would go about making a unit converter, in particular one specific point: would you need a new block of code for each unit to be converted to every other unit. e.g.
meters - feet
meters - centimeters
meters - inches
etc then have a new code to convert feet to each of the units, then one for inches to each, another for centimetres to each unit etc, or is there some easier way?
Thanks
A: You could use a table with all the conversion factor and write a method which takes the conversion factor and the value which is meant to be converted. Therefore you need only one "block" of code.
A: There's indeed an easier way, keep your units and conversion rules in a file or database. In most cases you need more or less simple arithmetic to convert the units. There is the program "units" in Unix or Linux, you could study the source and the unittab or units.tab.
A: In general all units conversions are of the same form:
valueInUnit1 = A * valueInUnit2 + B
B often even being zero (meters to feets, inches to meters, etc) -- and being non-zero only for a some cases (like converting temperature from Kelvins to Celcius)
What you only need is to keep a list of the values of A and B for each pair of units to convert one unit to another.
Note that you can even keep only main values (from metric system units to other units for example) and deduce the others, as from the formula above you can obviously conclude the reverse
valueInUnit2 = (valueInUnit1 - B) / A = (1/A) * valueInUnit1 + (-B/A)
So once you have the list of values A and B for every pair of units you want to convert from and to, you will only have one method to convert them all.
You can store the list of values A and B whereever you want, in a dedicated PLIST file, in a sqlite3 database, in CoreData, ... (for your case using a PLIST file will probably be much more easier. e.g. a NSDictionary whose keys are the name of the origin unit, and values are themselves NSDictionaries whose keys are destination units and values are the A and B pairs... -- that's just a suggestion, not the only solution)
A: Do like United Nations or European Union do for translations: convert from any to reference then from reference to any other.
For physical units, a convenient reference is the international system of units.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How should comment authentication work? Open discussion? Or Registered Users only? I'm building my CMS and am up to the comment authentication part of it. I am wondering what type of commenting I will allow. To give you an insight into my target audience, I will be targeting a range of people specific in their field/topic.
My posts will largely be based on development, with some lolcats pics here and there. I would expect some quality discussion from the online community, much like the greatly received articles of Glenn Fiedler, known for his Game Networking articles, which have an extremely large discussion behind them.
Now I don't expect such a large audience as that, but I still want to have the support for it.
I'm asking this question to the community. What authentication methods should I use to allow for an open discussion, but with protection from spamming, and only allow high quality content?
To give you an example, I'm wondering if to prevent spam, I could allow for login (either from my website specific user system, or OpenID). This would prevent spambots, however manual trolls could still login using their Google account and troll with that.
I could however allow for open commenting, but using CAPTCHA to prevent spam bots, reducing the need for logging in, but still allowing manual trolls.
Any suggestions?
A: There is always a chance that people will manually troll and there is no protection against that. I would advice to use openID because most developers have it and that is your audience. About the Captcha, just wait and see if you get spammed. If you don't get spammed, don't install captcha. If you do get spammed, just install it.
A: Like Bob said you are always going to get spammers I would use registration and login but if you are worried about them having to login all the time just set a cookie for a long period of time like a year or so. But during the registration process make them use a captcha image and then also make them activate their account. Or you could track by ip address and block them that way. There are many different ways to control spam by many ways around it too so its your call. I have a captcha setup that works really well and is not tough to read http://www.php-help.ro
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: XSLT transform function failing due to special characters I have an XSLT function which is selecting data from a C# data table. If the column name of the table happens to contain special characters such as brackets then it’s causing the XSLT to fail as it I guess it thinks it’s calling a new function. If I put single quotes around the column name then XSLT selects the string within the single quotes and not the data contained in that column of the table.
E.g
<Data>
<xsl:value-of select=”MyColumnName(WithBrackets)”/>
<Data>
Can anyone help
Thanks
A: The select expression needs to contain a valid XPath expression. XPath expressions select data from XML documents, not from "C# data tables" (whatever they might be). To help you with your enquiry, we need to know what your XML document looks like.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595906",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Application crashes on simulator 5.0 before reaching main.m
Possible Duplicate:
iOS App crashing before entering main() with Xcode 4.2 & iOS 5
I am working on an app that works fine on simulator 4.3 but when I try it on simulator 5.0 it crashes before even reaching the main method. I get no informations, only gdb is available but the few I can ask him leads me nowhere.
Here's the stack-trace from gdb:
#0 0x00000000 in ?? ()
#1 0x95392ef3 in mig_get_reply_port ()
#2 0x9538c70c in mach_ports_lookup ()
#3 0x02845124 in _xpc_domain_init_local ()
#4 0x02842eb1 in _libxpc_initializer ()
#5 0x8fe7c15b in __dyld__ZN16ImageLoaderMachO18doModInitFunctionsERKN11ImageLoader11LinkContextE ()
#6 0x8fe7bcc0 in __dyld__ZN16ImageLoaderMachO16doInitializationERKN11ImageLoader11LinkContextE ()
#7 0x8fe79220 in __dyld__ZN11ImageLoader23recursiveInitializationERKNS_11LinkContextEjRNS_21InitializerTimingListE ()
#8 0x8fe791b6 in __dyld__ZN11ImageLoader23recursiveInitializationERKNS_11LinkContextEjRNS_21InitializerTimingListE ()
#9 0x8fe791b6 in __dyld__ZN11ImageLoader23recursiveInitializationERKNS_11LinkContextEjRNS_21InitializerTimingListE ()
#10 0x8fe791b6 in __dyld__ZN11ImageLoader23recursiveInitializationERKNS_11LinkContextEjRNS_21InitializerTimingListE ()
#11 0x8fe791b6 in __dyld__ZN11ImageLoader23recursiveInitializationERKNS_11LinkContextEjRNS_21InitializerTimingListE ()
#12 0x8fe7a1c0 in __dyld__ZN11ImageLoader15runInitializersERKNS_11LinkContextERNS_21InitializerTimingListE ()
#13 0x8fe6e656 in __dyld__ZN4dyld24initializeMainExecutableEv ()
#14 0x8fe72ef2 in __dyld__ZN4dyld5_mainEPK12macho_headermiPPKcS5_S5_ ()
#15 0x8fe6c2ef in __dyld__ZN13dyldbootstrap5startEPK12macho_headeriPPKclS2_ ()
#16 0x8fe6c063 in __dyld__dyld_start ()
Is it understandable for someone? Or how can I find more readable informations about that crash?
P.S. I'm working under XCode 4.2 Build 4D177b
A: Removing -weak_library /usr/lib/libSystem.B.dylib from your OTHER_LDFLAGS in Build Settings worked for me.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: JSTL Format Number in million I have a number like, 48371000000 i need to display it like 48371.
Using JSTL, I tried like
<fmt:formatNumber var="salesFormat" type="currency" currencyCode="USD" value="48371000000"/>
Output: $48,371,000,000.00
Do I need to use any pattern?
Please Help, Thank in advance...
A: Ok, I get an alternative like,
Firstly I am getting the value by dividing it by 1000000.
Thanks guys.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how can I mix objective-c objects (i.e UITextView) with pure c++ UI like DooleJump leadboard How can I mix objective-c objects (i.e UITextView) with pure c++ UI like DooleJump leadboard, which is scrollable and the text in it is from system`font. Can somebody help me ..thanks...
A: I can't see the relation between DooleJump leadboard being scrollable and using system fonts, and the use of C++.
Anyway, to answer the question, if you need to mix Objective-C and C++, use Objective-C++ (and rename all your files from ".m" to ".mm")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595914",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Post ajax requests parameters are sometimes sent in the wrong format to rails My problem is so weird:
*
*I have this form:
<form id="my-form" method="post" action="/password_reset/update/<%= @user.perishable_token %>" charset="utf-8" autocomplete="off">
<input type="password" name="user[password]" class="required" minlength="6" />
<input type="password" name="user[password_confirmation]" class="required" equalto="#password-field" minlength="6" />
<input type="hidden" name="page" value="set" />
<input type="submit" value="Submit"/>
</form>
*The client send an ajax request to my rails server (using jquery 1.6.1, jQuery Validation Plugin 1.8.1, jQuery Form Plugin 2.67)
$("#my-form").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
});
*The server side receives the request and here is the probleme. Sometimes:
*
*Instead of get parameters with the expected format as below
Parameters: {"user"=>{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "page"=>"set", "id"=>"bFC7bkz6tzOF4i2KXZ"}
*... I get:
Parameters: {"_json"=>"user%5Bpassword%5D=password&user%5Bpassword_confirmation%5D=password&page=set", "id"=>"perishable_token"}
I tested the form in lots of cases (with different browsers/OS) and it's impossible to me to reproduce this problem. I can just see it in my production rails log.
So my questions are:
*
*Why this problem can happen ?
*How can I reproduce this bug ?
Thank you very much for your help.
A: Try set datatype, that you want:
$(form).ajaxSubmit({dataType=>"desirable format"});
format may be "xml", "script" or "json"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to use asp variable in JavaScript? I have stored text box value in JavaScript variable
var strline1side1 = document.frmartwork.side1textbox1.value;
and then saved that value in JavaScript cookie
document.cookie="lineside1="+strline1side1+";path=/;";
now I want to save this cookie in asp variable.
I tried this:
<%=ASPVariable%> = document.frmartwork.side1textbox1.value;
but its not working
How can I do this?
A: You could store the value in a formfield e.g. hidden field and then access its contents by checking the Request.Forms collection
...
myCookieValue = Request.Forms("side1textbox1")
...
A: you can use Set-Cookie Header rather than javascript
The Set-Cookie response header uses the following format:
Set-Cookie: <name>=<value>[; <name>=<value>]...
[; expires=<date>][; domain=<domain_name>]
[; path=<some_path>][; secure][; httponly]
A: ASP runs on the server, JavaScript on the client. So you obviously cannot write to ASP variables from JavaScript.
You need to perform an AJAX call if you want to change something on the server.
A: Fascinating array of answers here is my 2 pennies worth
<%
Dim aspVar
aspVar = Request.Cookies("lineside1");
%>
Of course you understand this code will not see the cookie until the page in which is resides is requested after the client side code has set the cookie.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jquery rotating image banner first image issue I have created an rotating image banner module for an in house CMS. I did not write all the jquery for this and that's why I'm a little confused.
Basically the problem is the first image displayed in the banner after a page reload does not fade out like the rest of the images do. I understand that this probably because it is the default image loaded and is not part of the loop that's causing the image banner to rotate. The banner can be seen here: http://www.easyspacedesign.com/craig/dentalwise/
Notice how the first image after a reload sort just jumps to the next image but then all he images afterwards smoothly fade in and out.
How do I grab that first image after a reload and make it fadeout like rest?
here is the code:
<script type="text/javascript">
<!--
var doLooop = true;
$(document).ready(function(){
setInterval("loop()",5000);
});
function loop(){
if(!doLooop){ return; }
var $total = parseInt($("input[name=total_slides]").val());
var $id = parseInt($("a._active").attr("rel"));
var $new = $id+1;
if($new>$total){$new=1;}
changeSlide($new);
}
function changeSlide($id){
// Prepare selectors
var $total = $("input[name=total_slides]").val();
var $txtSlt = "#_slideText_"+$id;
var $imgSlt = "#_slideImg_"+$id;
var $active = $("a._active").attr("id");
var $new_img_href = "#animation_selectors a:nth-child("+$id+") img";
var $new_active = "#animation_selectors a:nth-child("+$id+")";
// Hide active images and text
$(".slideImg").css("display","none");
$(".slideTxt").css("display","none");
// Display selected images and text
$($txtSlt).fadeIn(1200);
$($imgSlt).fadeIn(1200);
$($txtSlt).delay(2500).fadeOut(1200);
$($imgSlt).delay(2500).fadeOut(1200);
// Update active anchor image
$("a._active img").attr("src","<?php echo ROOT; ?>Images/StyleImages/off.png");
$("a._active").removeClass("_active");
$($new_img_href).attr("src","<?php echo ROOT; ?>Images/StyleImages/on.png");
$($new_active).addClass("_active");
}
$(function(){
$("#animation_selectors a").click(function(e){
e.preventDefault();
var $id = $(this).attr("rel");
doLooop = false;
changeSlide($id);
});
});
-->
</script>
<div id="animation">
<div id="animation_slides">
<?php
$img_sql = "SELECT strImageUrl FROM tbl_mod_Animation ORDER BY intAnimationID";
if($img = $db->get_results($img_sql)){ $i=1;
foreach($img as $img){
if($i!=1){ $display = " style=\"display:none;\""; } else { $display = ""; }
echo "<div id=\"_slideImg_$i\" class=\"slideImg\" $display><img src=\"".ROOT."Images/Uploads/Slides/".$img->strImageUrl."\" alt=\"\" /></div>";
$i++;
}
}
?>
</div>
<div id="animation_text">
<?php
$text_sql = "SELECT strText FROM tbl_mod_Animation ORDER BY intAnimationID";
if($text = $db->get_results($text_sql)){ $i=1;
foreach($text as $text){
if($i!=1){ $display = " style=\"display:none;\""; } else { $display = ""; }
echo "<div id=\"_slideText_$i\" class=\"slideTxt\" $display>".$text->strText."</div>";
$i++;
}
}
?>
</div>
<div id="animation_selectors">
<?php
for($x=1;$x<$i;$x++){
if($x==1){
?><a id="slide_opt<?php echo $x; ?>" href="#" rel="<?php echo $x; ?>" class="_active"><img class="slideOpt" src="<?php echo ROOT; ?>Images/StyleImages/on.png" alt="" /></a><?php
} else {
?><a id="slide_opt<?php echo $x; ?>" href="#" rel="<?php echo $x; ?>"><img class="slideOpt" src="<?php echo ROOT; ?>Images/StyleImages/off.png" alt="" /></a><?php
}
}
echo "<input type=\"hidden\" name=\"total_slides\" value=\"".($i-1)."\" />";
?>
</div>
</div><!--end of animation-->
<?php
?>
A: changeSlide() sets up each slide to fade in and then fade out in 2.5 seconds. loop() calls changeSlide() every 5 seconds and passes the id of the next slide to be shown. The problem is that the first slide isn't set up the same way on page reload. It's probably just statically written on the page with the _active class.
You'd be better off, instead of setting a delay to fade each slide out after 2.5 seconds, to pass in both the previous and next slide to the changeSlide function and then fade out the previous and fade in the next.
function loop() {
...
changeSlide($id, $new);
}
and then in changeSlide:
function changeSlide($prev, $next) {
...
var $prevTxtSlt = "#_slideText_" + $prev;
var $prevImgSlt = "#_slideImg_" + $prev;
var $nextTxtSlt = "#_slideText_" + $prev;
var $nextImgSlt = "#_slideImg_" + $prev;
...
$($prevTxtSlt).fadeOut(1200);
$($prevImgSlt).fadeOut(1200);
$($nextTxtSlt).fadeIn(1200);
$($nextImgSlt).fadeIn(1200);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: zend_form decorator on whole form not each individual element Custom HTML Output on Zend Form Checkbox setLabel Property
In adition to this question.
I want to apply this to all my form_elements without adding it to each individual form_element
class my_form extends Zend_Form
{
public function init()
{
$this->setAction('')
->setMethod('post');
//shouldn't I be able to set the decorator here?
$firstname= new Zend_Form_Element_Text('firstname');
$firstname->setLabel('firstname')
->setRequired(true)
->getDecorator('label')
->setOptions(array('requiredSuffix'=> ' <span class="required">*</span> ', 'escape'=> false))
//here it works but I don't want it on every element.
;
$lastname= new Zend_Form_Element_Text('lastname');
$lastname->setLabel('firstname')
->setRequired(true)
->getDecorator('label')
->setOptions(array('requiredSuffix'=> ' <span class="required">*</span> ', 'escape'=> false))
//here it works but I don't want it on every element.
;
$this->addElements(array($lastname, $firstname));
}
A: You could make yourself a class that extends the Zend_Form and overload the createElement method :
class My_Base_Form extends Zend_Form
{
public function createElement($type, $name, $options = null)
{
$element = parent::createElement($type, $name, $options);
$element->setOptions(
array('requiredSuffix'=> ' <span class="required">*</span> ')
);
$label = $element->getDecorator('Label');
if (!empty($label)) {
$label->setOption('escape', false);
}
return $element;
}
}
and then you extends that form :
class My_Form extends My_Base_Form
{
public function init()
{
...
// $firstname= new Zend_Form_Element_Text('firstname'); old version
// taking advantage of the createElement
$firstname = $this->createElement('text', 'firstname');
...
}
}
You could use that method for a lot of other things. In the past I've used it to define the default decorators on all my form elements.
A: You can call setElementDecorators() after addElements() to set decorators for all the elements in the form. See more information in the related Zend Framework documentation.
Hope that helps,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595922",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Which design pattern should I use to write an ASP.net page that persists to a DB? Is there a design pattern I can use in asp.net pages that will help me program pages more effieciently? In particular its when I have to save something to a database and then set up some page controls etc...
A: Microsoft would tell you to go with ASP.NET MVC3 and Entity Framework 4+.
However, this is kind of a generic question, and the real answer for you depends on a lot of different stuff, including what your app needs to do, how complex it is, blah blah blah.
With mentions of "web pages" and "saving to databases", first thing that comes to mind is an ORM (that's the Entity Framework) working with an MVC frameworked web application.
A: ASP.NET Page shouldn't be used to realise DB centric tasks. You should introduce Data Access Layer and then
You should consider:
Repository Pattern
A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes. Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.
ActiveRecord Pattern
Active record is an approach to accessing data in a database. A database table or view is wrapped into a class. Thus, an object instance is tied to a single row in the table. After creation of an object, a new row is added to the table upon save. Any object loaded gets its information from the database. When an object is updated the corresponding row in the table is also updated. The wrapper class implements accessor methods or properties for each column in the table or view.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: checkbox checked or unchecked function Check_Clickd_li(objRef) {
var btn1 = $find("<%= RadButton1.ClientID %>");
var btn2 = $find("<%= RadButton2.ClientID %>");
if (objRef.checked = true) {
btn1.set_enabled(true);
btn2.set_enabled(true);
alert("Enable");
}
else if (objRef.checked = false) {
btn1.set_enabled(false);
btn2.set_enabled(false);
alert("Disable");
}
}
What is the problem in this code? It always says "Enable".
A: You're doing an assignment. Use == for a comparison, or just:
if (objRef.checked) {
// ...
}
A: You need to use == for comparison (or just test if(objRef.checked)).
Right now you set the value to true...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Windows Explorer plugin DLL in 32 and 64 bits I am currently working on a DLL for Windows Explorer, which provides various features like information and thumbnails for certain types of files. So far it works fine on Windows x64, and I am now working on the 32/64 bits issue and on the registration process (this process is made by a small standalone program written in C#).
My understanding is:
*
*a 64 bits DLL will not work with a 32 bits application and vice versa
*thus the 64 bits DLL will not work for the Open file dialog box of a 32 bits application
*I need to register separately the 32 and 64 bits versions
My questions are:
*
*are my assumptions correct so far? In particular I am wondering if the browse dialog box opened by an application necessarily has the same bitness as the application (or is the dialog box managed by some Windows 64 process anyway?)
*supposing I have a 32 bits and a 64 bits versions of my DLL, how do I register them from a 64 bits program? ("Ok Windows I'm a 64 bits process, but I'm registering this for 32 bits applications, got it?")
Some pages I have read on the topic:
Windows 64-bit registry v.s. 32-bit registry
http://msdn.microsoft.com/en-us/library/aa384232%28v=VS.85%29.aspx
A: Your understanding is correct. You need to supply a 32 bit version for users on 32 bit Windows as well as for common dialogs for 32 bit processes under WOW64.
How to deploy depends on your installation tool. When I have done this I created separate MSIs for the two versions, from the same source, and used a bootstrapper setup.exe that installed them both. Recommended practice is to set the registry settings from the MSI. Then you let registry redirection do it's magic under WOW64.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I prevent users from downloading MP3s directly I'm building a web-radio like service, in which the user authenticates to the services, gets a cookie and a Flash-based app plays mp3s from the server. The server only delivers if the client is allowed for that particular mp3.
If a user opens a HTTP logger (like FireBug), he can see the files being downloaded by flash. If he opens the mp3 URL directly via the address bar, he can easily download the MP3, although the URLs are not guessable by the user.
I'm looking for a safe system to prevent the user from downloading the MP3 directly to his system. I have examined last.fm, as they use a similar setup, and somehow they prevent it.
A: In the end, you're not going to be able to stop someone who's determined. However, you can at least make it difficult.
There are several options involving referrer checks, authentication, and fun stuff like that. But probably the most successful anti-downloading check I've seen was one that works like this:
The user indicates that he wants to stream a file; the app makes an authenticated, encrypted request indicating his desired action. The result is a one-use-only and time-limited URL that is recognized by whatever application or CDN is hosting the file. After the URL is used once (i.e. by the flash app) it then expires and can never be used again. If the streaming does not start within a given amount of time (several seconds), the URL likewise expires. Obviously the URL given does not directly correspond to the file name, but is instead authenticated, decoded, and translated server-side.
It's still not impossible to work around, but it's fairly difficult.
A: You might use RTMP instead of HTTP to deliver audio data. RTMP is meant to be used for streaming audio, video and misc data. It streams just data rather than a file. It's not 100% safe, because if something gets to client (browser, flash player, whatever), user can save it, but it's still better than giving a file via HTTP.
You will need a server that supports RTMP though, e.g., Flash Media Server (FMS), Wowza or Red5.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to get Registration ID from C2DM Servers? I am very new to Android. I developed my project in android. Now I would like to add notification for my application. So I planned to use C2DM. I register to C2DM and i have received a mail. but i not yet receive registration ID from gmail. How can i receive from gmail registration. What i wil do? Any body pls help me. Thanks in advance.
A: You have misunderstood the Registration ID. It will not be emailed to you. The Registration ID represents One App on One Device, so each user of your app will have a separate Registration ID. The get it, you need to request one, and it is sent to you as a C2DM message.
This tutorial explains how the process works, and how to get the registration ID
http://www.vogella.de/articles/AndroidCloudToDeviceMessaging/article.html#example_manifest
Once you have the Registration ID, you need to store it on YOUR server, next to the user's record. Then, when your server sends a message to the user, it sends the Registration ID to the C2DM servers, along with a message. The Registration ID acts as a destination descriptor.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: write the content of the mac os terminal to a file in java I am new to mac os. I have used the following code in java to get the system details. It opens a terminal to display the result of that command. I need to get those details in a file. How can I get it.
String[] command = {"/usr/bin/open", "/Applications/Utilities/System Profiler.app"};
Process proc = Runtime.getRuntime().exec(command);
int resultCode = proc.waitFor();
if (resultCode != 0) {
throw new Exception("failed to open system profiler");
}
A: By opening an application to the user, you can not deal with any results. You need to use the commandline-version of the "System Profiler", which prints it's results back to the shell.
You can then deal with the result in Java, by using the following code:
String[] command = {"/usr/sbin/system_profiler"}
String sendback = "";
Process proc = Runtime.getRuntime().exec(command);
InputStream istr = proc.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
String str;
while ((str = br.readLine()) != null) {
sendback = sendback + str;
}
int resultCode = proc.waitFor();
br.close();
if (resultCode != 0) {
throw new Exception("failed to open system profiler");
}
Within Java, you can deal with the result in any way (write it to a file or whatever).
But if you really want to simply write it into a file (and not use it in Java), you can do it, by changing your command and redirecting the output into the target-file on your shell:
/usr/sbin/system_profiler >/path/to/yourfile.txt
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I make my Android ContentObserver for detect changed contact detail (added, updated or deleted)? I can catch the event when contact is modified. But I want to catch that modified contact details like CONTACT_ID, name, etc... Please can you help me to do that. my code is follow.
public class TestContentObserver extends Activity {
int contactCount = 0;
final String[] projection = new String[] { RawContacts.CONTACT_ID, RawContacts.DELETED };
Cursor curval;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
curval = getContentResolver().query(RawContacts.CONTENT_URI, projection, null, null, null);
contactCount = curval.getCount();
curval.registerContentObserver(new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfChange) {
getChangedContactDetails();
}
@Override
public boolean deliverSelfNotifications() {
return true;
}
});
}
public void getChangedContactDetails(){
// how can I catch the affected contact details
}
}
A: Have a look at: http://developer.android.com/resources/articles/contacts.html, section "Lookup URI"
when registering your ContentObserver you can just register an URI that points directly to the contact you are interested in. then your observer will only get notified when your interesting contact is modified.
Uri lookupUri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
getContentResolver().registerContentObserver(lookupUri, false, new ContentObserver(){});
Lookup key key is unique for each record
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595938",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to upload multipart Image data in json request Android? I have to upload image data in multipart post using json request so can anyone help me out here.
Here is my json string request to send server (I am able to create JSON request in string but how to send that code is required)
{
"Request": {
"data": {
"Key": "keydata",
"info": {},
"param": {
"title": "Testingpostmultipartimageupload",
"photo": **"IMAGE BYTE DATA"**,
"photoFilename": "Test.png"
}
},
"info": {}
}
}
So how can I post this data along with image byte data in JSON to webservice...
Thanks in advance.
A: I found my solution based on this post: http://prativas.wordpress.com/2014/03/03/uploading-image-from-android-app-to-server-programmatically/:
And combined this with a multipart for the json data:
// the json values:
multiPartEntityBuilder.addPart("fieldname", new StringBody("value",ContentType.APPLICATION_JSON));
//the file:
File file = new File(filename);
FileBody fileBody = new FileBody(file);
multiPartEntityBuilder.addPart("FIle_Fieldname_depending_on_the_api", fileBody);
This uploads the file to a rest api (django restframework)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ruby check if a thread is "free" I want to have an array of threads[] such that if a thread is "free" or not working on any program then it will be assigned a new task.
Is there anyway to check if a thread in ruby is "free". Currently I used
if (threads[thread_id].nil? || !threads[thread_id].status)
# yes thread is free
But doesn't seem to be correct way, some thread still override working other.
A: threads.each.map {|t| t.alive?}.none?
returns true if all threads are dead
if you have something like this:
threads << Thread.new do
# do dome work ...
end
and you want to check if all threads are not alive (i.e. dead) you can always use this:
threads.each.map {|t| t.alive?}.none?
We are taking one by one thread from array and checking if it's alive. map method is creating array with true/false values (alive/dead). Finally none? method of enumerable should return true if all members are false (i.e. all threads are dead)
A: See the answer of Deadlock in ThreadPool for a working threadpool implementation.
With a thread pool, you can do something like this:
pool = ThreadPool.new(10) # up to 10 threads
email_addresses.each do |addr|
pool.process {send_mail_to addr}
end
ThreadPool#process will block if there are no free threads to complete the work, and continue when one is free.
There are also gems implementing a thread pool, like: http://rubygems.org/gems/work_queue
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What does each sc-win32-status code indicate? In my IIS log I see many instances of sc-bytes=0.
The time-taken for these entries are generally higher than average.
I can see various values of sc-win32-status like 64, 22, 121, 1236 etc.
Most of them have sc-status 200. Few have sc-win32-status 400.
Now I want to analyse each situation to figure out what happened in IIS.
But this MSDN site gave only the error name and not a detail about when they can occur.
I found a good article here which gave a good scenario description for sc-win32-status = 64 and sc-status = 200 with high time-taken.
I wanted a similar explanation for all sc-win32-status.
Is there any site which gives details about scenario for sc-win32-status codes?
Else can anybody explain when do we get following values for sc-win32-status:
64, 22, 121, 1236.
A: The IIS Server status codes that you find in the logs are informational and are intended to provide what went wrong in certain requests/responses not why. So when you see an error code like 1326 that simply means that the username and password are not correct etc.
If you want to dig deeper and see why something happens in the background, tools like Debug Diagnostic Tool and Debugging Tools for Windows can help you out to perform analysis.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: SELECT Column1 FROM tablename in Django Okay I know this is really stupid.But how to i write SELECT Column1 FROM tablename
I know i can use Court.objects.all()[0] to get just one row.But how do I get one column only(the whole column values).Am I missing something?
Also in Court.objects.all()[0] isn't it first retrieved and then spliced.So isn't it kinda inefficient.
A: Court.objects.values_list('column_name', flat=True)
And if you write Court.objects.all()[0] only one row is retireved.
A: Court.objects.only('column_name')
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595945",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: :hover not fired for element when parent has CSS3 perspective In the following example I created on jsfiddle try to hover on gray boxes. You can see each "Box" inside the first container gets ":hover" but for the second one items located on "the right half of the container" don't get :hover!
(move your mouse over gray boxes)
(Open this in Chrome or Safari because other browsers don't support CSS3 perspective)
Look at here: http://jsfiddle.net/jyBES/10/
This is very strange to me.
Can anybody explain why? Is there any possible workaround for this?
A: float: left;
in the parent div seems to do the job.
http://jsfiddle.net/lollero/jyBES/11/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Can I create a pthread inside a pthread, which is already created by the main? Will I run into an error if I create a pthread_create inside a pthread, which is created by the main function. If, I can then what all things I should take care of???
Important....:I am doing a socket programming, where I have opened 5 threads each on separate ports which are listening on ports, when ever I receive a message, I want to create a thread which takes the message and writes into a file using pwrite. So, I have a few questions, please can you help me???
If not then what is another solution of creating a thread inside a thread..??
Or will it give me a segmentation fault???
or will I run into some race conditions....
A: pthread_create creates a new thread. Independently of where it is
called. And creating a new thread for a connection when listening on a
port is pretty much standard procedure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Intermittent JDBC error two-task conversion routine I am intermittently getting the following jdbc error with my oracle db (in remote linux machine)
java.sql.SQLException: ORA-03120: two-task conversion routine: integer overflow
The query that mostly breaks(not the only one!) looks like this, note that I am using Groovy Sql
String insertScript =
"""
INSERT INTO data_table (invoke_id , trans_type , trans_from ,
trans_to , serv_type ,msg_type , man_id , recip_id ,
trx_id , part_id , msg_orig_time , create_time ,
action_code , num_ranges , use_trx_id, due_date,owner,route,lsa,
cl_id,hl_id,requ_type,lnp_type,use_invoke_id)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
"""
def params = [invokeId,transType,transFrom,transTo,servType,msgType,man,recip,portId,owner,
now,now,"W",1,trxId,dueDate,owner," ", "LSA","CCH"," ","Basic","lspp",invokeId]
sql.execute insertScript, params
What I do not understand is why my queries work some time and not other times. Generally it will happen during the first run and only rarely appear in subsequent runs.
[UPDATE] I am getting this error sometimes on application startup also, when spring tries to load its context. I am using spring and dbcp for the connection pooling.
Caused by: org.apache.commons.dbcp.SQLNestedException: Error preloading the connection pool
at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1238)
at org.apache.commons.dbcp.BasicDataSource.getConnection(BasicDataSource.java:880)
at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:113)
at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:79)
... 46 more
Caused by: java.sql.SQLException: ORA-03120: two-task conversion routine: integer overflow
at oracle.jdbc.driver.SQLStateMapping.newSQLException(SQLStateMapping.java:70)
at oracle.jdbc.driver.DatabaseError.newSQLException(DatabaseError.java:131)
at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:204)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:455)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:406)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:399)
at oracle.jdbc.driver.T4CTTIoauthenticate.receiveOauth(T4CTTIoauthenticate.java:799)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:368)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:508)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:203)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:33)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:510)
at org.apache.commons.dbcp.DriverConnectionFactory.createConnection(DriverConnectionFactory.java:38)
at org.apache.commons.dbcp.PoolableConnectionFactory.makeObject(PoolableConnectionFactory.java:294)
at org.apache.commons.pool.impl.GenericObjectPool.addObject(GenericObjectPool.java:1059)
at org.apache.commons.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1235)
... 49 more
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Django form field label translations I have a baseform with over 20 fields. Then I have about 15 other forms inheriting from that form, passing in a parameter called fields which the baseform uses to delete all other fields. Best explain via example:
class BaseForm(forms.Form):
reportid = forms.HiddenInput()
fromdate = forms.DateField(label=_("From"), widget=widgets.AdminDateWidget())
todate = forms.DateField(label=_("To"), widget=widgets.AdminDateWidget())
sort_by = forms.ChoiceField(label=_("Sort by"), choices=[])
.......
def __init__(self, *args, **kwargs):
fields = kwargs.pop('fields')
#Pseudo:
***del self.fields[field] for field not in fields***
class SubForm(forms.Form):
def __init__(self, *args, **kwargs):
fields = ['reportid', 'todate']
super(SubForm, self).__init__(fields=fields, *args, **kwargs)
The resulting form would then look like this:
class SubForm(forms.Form):
reportid = forms.HiddenInput()
todate = forms.DateField(label=_("To"), widget=widgets.AdminDateWidget())
My problem is that when the BaseForm is initialized for the first time, the labels are bound to the fields with the active language, and when another user logs in with another language setting (or the current user changes languages) the field labels don't update.
I've come to a solution using a dict like this:
labels = {
'todate': lambda: _("To"),
'fromdate': lambda: _("From"),
.....
}
and then when initializing the baseform looping through all fields and setting
self.fields[field].widget.label = labels[field]()
Do I have any nicer (read: more pythonic) way of achieving this?
A: Django provides _lazy variants of the translation functions (for example ugettext_lazy) so you can ark strings for translations at the access time (as opposed to when the translation function is called).
It's documented in details at https://docs.djangoproject.com/en/1.7/topics/i18n/translation/#lazy-translation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Grid rows custom formatting How can I apply custom fomratting to some ExtJS grid rows? To be more concrete, I need to change font color of some rows.
EDIT:
Model contains state field. I want to change for color of every row, where state = 1, for exemple.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: OmniAuth: redirect to page which requires authentication instead of the one which user came from There are some pages in my app which require authentication with linked in. I use before filter to redirect user to /auth/linked_in if s/he is not already authenticated. I want that after authentication user should be redirected to page which required authentication instead of page from which user came from.
Before filter looks like:
def require_linked_in!
unless current_user and current_user.linked_in_authenticated?
redirect_to "/auth/#{Authentication::LINKED_IN}"
end
end
In my omniauth callback I do some stuff, like logging in or associating provider data with user account and if everything was ok, redirect_to request.env['omniauth.origin'] || root_url, but this redirects back the user to page from which he clicked the link to page requiring linked_in authentication and not the target page.
How can I redirect the user to page which triggered authentication instead of page which user came from?
PS: User can only sign up using the registration form for the app, but can later on connect there linked and facebook profile and also use them instead of normal email/password login form. If it makes any difference.
A: I guess you need to store the url in your session and redirect after the omniauth callback.
def require_linked_in!
session[:return_to] = request.url
unless current_user and current_user.linked_in_authenticated?
redirect_to "/auth/#{Authentication::LINKED_IN}"
end
end
In your callback-action you can use:
redirect_to session[:return_to] || root_url
Hope it helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Simple C pointer issue It's been a long (long...) time since I've done any C programming and I'm stuck on what should be a really simple issue. I have a simple function that's calling another function that is allocating some memory on the heap, populating it with a structure and returning a pointer back. Everything looks great, except when the pointer is returned to the calling function, it's address is corrupted.
Here's the relevant code:
Called function:
struct server_type *init_gwserver(Cfg* cfg)
{
struct server_type *res = NULL;
// Lots of irrelevant code removed here - doesn't reference res.
res = gw_malloc(sizeof(struct server_type));
gw_assert(res != NULL);
res->server_start = gwserver_start; // Pointer to a function
res->server_stop = gwserver_stop; // Pointer to another function
return res;
}
Calling function:
struct server_type *do_init_server(Cfg *cfg)
{
struct server_type *res = NULL;
res = (struct server_type *)init_gwserver(cfg);
if (res) {
return res;
}
}
OK, here's the weirdness. When "res" is returned to the calling function, the address the pointer is pointing to changes, and becomes an invalid memory reference. Here's a quick run through with GDB. Comments (//...) are mine...
Breakpoint 1, init_gwserver (cfg=0x100214e30) at init_gwserver.c:339
339 res->server_stop = gwserver_stop;
(gdb) print /x res
$18 = 0x100215b10
// Pointer above looks fine and seems to be a valid address
(gdb) p *res
$14 = {
type = 0x100215460,
sql_enter = 0x100003820 <gwserver_start>,
sql_leave = 0x100005ae0 <gwserver_stop>,
}
// Contents of the pointer are looking great
(gdb) next
340 return res;
(gdb) print /x res
$19 = 0x100215b10
// Pointer is unchanged - should return this value just fine.
(gdb) next
do_init_server (cfg=0x100214e30) at init_server.c:52
52 if (res) {
(gdb) print /x res
$20 = 0x215b10
// WOW - what the hell happened to the address pointed to by res? It lost the leading 100.
(gdb) p *res
Cannot access memory at address 0x215b10
// Yep, it's definitely now an invalid pointer. Crash time...`
This is probably something really, really simple, but I can't put my finger on it. Anyone got suggestions?
Thanks!
Toby.
A: This cast looks suspicious: (struct server_type *)init_gwserver(cfg).
If the cast is necessary to make the code compile then it indicates that there is not a correct prototype visible for init_gwserver at the call site.
If there is no prototype visible, the compiler will make the assumption that the function returns an int. When the return value is retrieved as something that it is not, depending on the implementation, its value may be corrupted and when converted back to a pointer information may have been irretrievably lost.
The cast should not be necessary and if removing it causes a compile error it indicates that you need to add (or #include) a correct prototype for init_gwserver before the point where you attempt to call it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: SharedObject for Arrays of Object. Can't get correct data when restart flash I have an array that stored some Object with its data, and I try to store it in my computer.
If I try to load for the data after I've save the data, I could get a correct data.
Exp: [Object Player]
But if I restart the flash, the data seems to be gone.
What is the problem?
private var sharedObject:SharedObject = SharedObject.getLocal("aquarium", "/");
public function save(n:String):void
{
/* player list will only handle the list of all the Players
* each player data will handle by Player class itself.
*/
registerClassAlias("Player", Player)
player = new Player()
player.newPlayer(n, LATEST_VERSION)
playerArray.push(player)
//saving as shared object
sharedObject.data.aquariumData = playerArray
sharedObject.flush()
load()
}
public function load():void
{
if (sharedObject.size > 0)
{
trace("loading player info")
playerArray = sharedObject.data.aquariumData
trace(playerArray)
}
else
{
trace("there's no record")
}
}
A: Can you please provide the code how you obtain the shared object ?
Do you use var sharedObject:SharedObject = SharedObject.getLocal("sharedObject"); or something like this ?
Apart from that when calling registerClassAlias("Player", Player) before serialization keep in mind that it must be called before extraction of the data also, so the de-serialization will work correctly and returns array of Player objects not array of Object objects.
And ofc closing the sharedObject is very nice practice after flushing :)
P.S. Your code works as far as i've tested it replacing your Player class with other custom class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: calling a child page component from parent page component in wicket I have a problem which I tried to explained in the Image.I hope that will help all to understand what I need.
My Base Page is like this (menuNavPanel is the tree panel):
<div class="colContainer">
<div class="leftColumn" >
<div wicket:id="menuNavPanel"></div>
</div>
<div class="rightColumn">
<wicket:child/>
</div>
</div>
And Ny BIA Page which is a child of Base Page is like this:
<wicket:extend>
<div wicket:id="bodyPanel"></div>
</wicket:extend>
in my Tree Panel, when I click on a node the code is this:
@Override
protected void onNodeLinkClicked(AjaxRequestTarget target, TreeNode node) {
super.onNodeLinkClicked(target, node);
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node;
Unit unitObject =(Unit) treeNode.getUserObject();
// I want to call bodyPanel fo child page passing the unitObject param
}
Now, How can I call bodyPanel fo child page passing the unitObject param from the tree panel of the parent page?
Am I been able to express my problem? Hoping to get some help :)
A: Instead of doing the override method, upgrade to Wicket 1.5 and utilize the new event bus to communicate between your components. You can create a custom, type-safe, event that is specific to your component's use case: for example "ItemAddedToShoppingCart" or "GlobalThermoNuclearWarStarted".
The linked article in the 1.5 migration guide provides enough information on how to set up things.
A: I'm not sure I understand que question correctly. Your BasePage defines a left column with the TreePanel and lets subclasses expand themselves inside the right column div. You usually put a BodyPanel inside BasePages's subclasses. And now you want to invoke a BodyPanel's method on some event on the TreePanel.
You could do it with an overridable method on BasePage, which would be called in TreePanel through getPage(). Your child pages would override that method, and its implementation would call the BodyPanel they're holding.
public class BasePage ... {
// Hook
public void treePanelSelected(Object someObject) { }
...
}
public class ChildPage extends BasePage ... {
BodyPanel bodyPanel;
@Override
public void treePanelSelected(Object someObject) {
bodyPanel.selectionChanged/(someObject);
}
...
}
public class TreePanel ... {
...
@Override
protected void onNodeLinkClicked(AjaxRequestTarget target, TreeNode node) {
super.onNodeLinkClicked(target, node);
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node;
Unit unitObject =(Unit) treeNode.getUserObject();
((BasePage)getPage()).treePanelSelected(unitObject);
}
}
From my ignorance on your specific needs and details of implementation, I don't see why is subclassing the BasePage necessary. You could add the BodyPanel right there in the BasePage and control it from the same class.
A: Thanks all, After reviewing all the nice options I finally opted out for the event bus way defined by martijn. What I did is I have created an event payload and connected the panels for the talking. I also needed to pass the selected Id / entity to the receiving panel.
Is there a way to set a compound property model of the receiving panel according to the model of the tree element so that I don't need to do the model manually ?
I did like this for the time being:
public class TreeNodeClickUpdate {
private final AjaxRequestTarget target;
private final long selectedId;
/**
* Constructor
*
* @param target
* @param selectedId
*/
public TreeNodeClickUpdate(AjaxRequestTarget target, long selectedId)
{
this.target = target;
this.selectedId = selectedId;
}
/** @return ajax request target */
public AjaxRequestTarget getTarget()
{
return target;
}
public long getSelectedId() {
return selectedId;
}
}
On the sender side I've done like this:
send(getPage(), Broadcast.BREADTH,
new TreeNodeClickUpdate(target, unitObject.getId()));
And on the receiving end I got it like this:
@Override
public void onEvent(IEvent<?> event) {
super.onEvent(event);
if (event.getPayload() instanceof TreeNodeClickUpdate)
{
TreeNodeClickUpdate update = (TreeNodeClickUpdate)event.getPayload();
setSelectedId(update.getSelectedId()); //sets to id field of panel
update.getTarget().add(this);
}
}
and for just as an example in my receiving panel, to get the value I have created a label like this:
label = new Label("label",new PropertyModel<BiaHomePanel>(this,"selectedId"));
Later, in reality I want to get information from the entity and show in form. Is there a nice way to pass models in a better way or I should pass as a parameter in event payload.
A: There are two ways to do this. One is cleaner, but requires more code. The other is quick and dirty.
Method 1: (Good)
Since your parent page is being extended, you can provide an abstract method in the parent like
protected abstract WebMarkupContainer getBodyPanel();
that is implemented in your child page and returns the appropriate panel. Then, you can call that method from the panel in your parent page. This is similar to the overrideable method suggested by the other user.
Method 2: (Bad)
The Wicket Component Hierarchy is shared between the parent and child pages. So, if you make sure that your bodyPanel has a unique wicketId and is added directly to the root of the page, you can probably just call
get("bodyPanelId");
and it will return the proper panel.
A: When I was facing the problem, I thought of two ways to solve this (pre 1.5):
a) implement a variation of the observer pattern to notify other component of events like outlined here: Realising complex cross-component ajax actions in wicket - The observer way
b) using wicket visitors to traverse the component tree doing the same.
I decided to go for variant a) but this introduces coupling from your component to your page-implementation which leads to problems when testing panels on their own. So maybe b) might be the better idea but since my application is running quite smoothly with a) implemented and the next big step will be switching over to 1.5 and the event bus, I haven't yet tried b).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Node.js service chokes and dies once a day Everyday this week I've been beginning my workday with restarting our node service.
And everytime it has simply exited with the following message:
node.js:134
throw e; // process.nextTick error, or 'error' event on first tick
^
Error: ETIMEDOUT, Connection timed out
at Socket._readImpl (net.js:163:14)
at Socket._onReadable (net.js:633:22)
at IOWatcher.onReadable [as callback] (net.js:177:10)
I'm having trouble discerning exactly wich part of my code is responsible for that error, and exactly why that error is so severe that it makes node exit.
Anyways I've done some searching around and figured that this might just be an uncaught error event.
I've added a few on('error') listeners to every server instance with a bit of customized log message to make sure it's caught, but to no avail, I still got to work today with the regular error message..
(And is there really such a thing as as 'error' events that must be caught?)
A simple connection timeout shouldn't really crash the whole service.
The service's main purpose is to keep an open tcp connection to a number of connecting clients and to be able to push out
commands (It's much like a private botnet for an embedded product). So in effect 95% of the time we're just idling our tcp sockets and sending out keep-alive packets.
So it's a requirement that clients can loose connection at any moment without interrupting
the service for other connected clients.
We're using latest stable branch node v0.4.13-pre and running on an ubuntu server.
A: Do you have a callback function associated with the "Error" event for that object?
http://nodejs.org/docs/v0.4.12/api/net.html#event_error_
For all your objects, make sure you have a proper callback for their respective "error" events so they can exit gracefully instead of crashing your program.
A: Add something like this to your code:
process.on('uncaughtException', function (err) {
console.log('Caught Uncaught exception: ' + err);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595978",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: COLLADA: Inverse bind pose in the wrong space? I'm working on writing my own COLLADA importer. I've gotten pretty far, loading meshes and materials and such. But I've hit a snag on animation, specifically: joint rotations.
The formula I'm using for skinning my meshes is straight-forward:
weighted;
for (i = 0; i < joint_influences; i++)
{
weighted +=
joint[joint_index[i]]->parent->local_matrix *
joint[joint_index[i]]->local_matrix *
skin->inverse_bind_pose[joint_index[i]] *
position *
skin->weight[j];
}
position = weighted;
And as far as the literature is concerned, this is the correct formula. Now, COLLADA specifies two types of rotations for the joints: local and global. You have to concatenate the rotations together to get the local transformation for the joint.
What the COLLADA documentation does not differentiate between is the joint's local rotation and the joint's global rotation. But in most of the models I've seen, rotations can have an id of either rotate (global) or jointOrient (local).
When I disregard the global rotations and only use the local ones, I get the bind pose for the model. But when I add the global rotations to the joint's local transformation, strange things start to happen.
This is without using global rotations:
And this is with global rotations:
In both screenshots I'm drawing the skeleton using lines, but in the first it's invisible because the joints are inside the mesh. In the second screenshot the vertices are all over the place!
For comparison, this is what the second screenshot should look like:
It's hard to see, but you can see that the joints are in the correct position in the second screenshot.
But now the weird thing. If I disregard the inverse bind pose as specified by COLLADA and instead take the inverse of the joint's parent local transform times the joint's local transform, I get the following:
In this screenshot I'm drawing a line from each vertex to the joints that have influence. The fact that I get the bind pose is not so strange, because the formula now becomes:
world_matrix * inverse_world_matrix * position * weight
But it leads me to suspect that COLLADA's inverse bind pose is in the wrong space.
So my question is: in what space does COLLADA specifies its inverse bind pose? And how can I transform the inverse bind pose to the space I need?
A: I started by comparing my values to the ones I read from Assimp (an open source model loader). Stepping through the code I looked at where they built their bind matrices and their inverse bind matrices.
Eventually I ended up in SceneAnimator::GetBoneMatrices, which contains the following:
// Bone matrices transform from mesh coordinates in bind pose to mesh coordinates in skinned pose
// Therefore the formula is offsetMatrix * currentGlobalTransform * inverseCurrentMeshTransform
for( size_t a = 0; a < mesh->mNumBones; ++a)
{
const aiBone* bone = mesh->mBones[a];
const aiMatrix4x4& currentGlobalTransform
= GetGlobalTransform( mBoneNodesByName[ bone->mName.data ]);
mTransforms[a] = globalInverseMeshTransform * currentGlobalTransform * bone->mOffsetMatrix;
}
globalInverseMeshTransform is always identity, because the mesh doesn't transform anything. currentGlobalTransform is the bind matrix, the joint's parent's local matrices concatenated with the joint's local matrix. And mOffsetMatrix is the inverse bind matrix, which comes directly from the skin.
I checked the values of these matrices to my own (oh yes I compared them in a watch window) and they were exactly the same, off by maybe 0.0001% but that's insignificant. So why does Assimp's version work and mine doesn't even though the formula is the same?
Here's what I got:
When Assimp finally uploads the matrices to the skinning shader, they do the following:
helper->piEffect->SetMatrixTransposeArray( "gBoneMatrix", (D3DXMATRIX*)matrices, 60);
Waaaaait a second. They upload them transposed? It couldn't be that easy. No way.
Yup.
Something else I was doing wrong: I was converting the coordinates the right system (centimeters to meters) before applying the skinning matrices. That results in completely distorted models, because the matrices are designed for the original coordinate system.
FUTURE GOOGLERS
*
*Read all the node transforms (rotate, translation, scale, etc.) in the order you receive them.
*Concatenate them to a joint's local matrix.
*Take the joint's parent and multiply it with the local matrix.
*Store that as the bind matrix.
*Read the skin information.
*Store the joint's inverse bind pose matrix.
*Store the joint weights for each vertex.
*Multiply the bind matrix with the inverse bind pose matrix and transpose it, call it the skinning matrix.
*Multiply the skinning matrix with the position times the joint weight and add it to the weighted position.
*Use the weighted position to render.
Done!
A: BTW, if you transpose the matrices upon loading them rather than transposing the matrix at the end (which can be problematic when animating) you want to perform your multiplication differently (the method you use above appears to be for using skinning in DirectX when using OpenGL friendly matrices - ergo the transpose.)
In DirectX I transpose matrices when they are loaded from the file and then I use (in the example below I am simply applying the bind pose for the sake of simplicity):
XMMATRIX l_oWorldMatrix = XMMatrixMultiply( l_oBindPose, in_oParentWorldMatrix );
XMMATRIX l_oMatrixPallette = XMMatrixMultiply( l_oInverseBindPose, l_oWorldMatrix );
XMMATRIX l_oFinalMatrix = XMMatrixMultiply( l_oBindShapeMatrix, l_oMatrixPallette );
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Dojo loading unnecessary files (shape.js & path.js) I am using customized Dojo library. When I load my client application, Dojo load the below two files after loading the "dojox/gfx/svg.js" file.
1. dojox/gfx/shape.js
2. dojox/gfx/path.js
Even though I have included these two files in to my Dojo Custom build, still these two files are always loading in to my client application.
I know the file "dojox/gfx/svg.js" will be load at run time based on the browser type, but why shape.js and path.js files are loading always at run time ?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How do I test the Facebook "Like" button on localhost? It is possible to test "Like" button on localhost?
A: Not really; facebook has to crawl your site to pull in the title, description, and thumbnail. It can't get to your site if it's on localhost.
A: Dave's answer is correct, however, I just discovered a workaround: You can make your local machine accessible by using http://localtunnel.me . You'll need to (temporarily) change some URLs used in your app code / html so links point to the temporary domain, but at least facebook can reach your machine.
A: It is possible to perform limited testing on the facebook like button on localhost. It renders properly on my machine. The trick is using a live, non-localhost URL on the data-href attribute (I used Google in the sample below):
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/pt_BR/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like" data-href="http://www.google.com" data-width="450" data-layout="button_count" data-show-faces="false" data-send="false"></div>
A: If you're developing the likebutton for www.xyz.com, just add in your hosts file:
127.0.0.1 www.xyz.com
Hooray, no more 500s.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "38"
}
|
Q: How to click an object with Panel.ZIndex low than another in wpf? In wpf, i have to click on an image with Panel.ZIndex="1", but this image is "under" another image with a Panel.ZIndex="2". The event MouseDown fail. How to do that?
Thanks in advance,
M.
<Grid >
<Image Name="Image_1"
Panel.ZIndex="1" />
<Image Name="Image_2"
Panel.ZIndex="2" />
</Grid>
A: Try using IsHitTestVisible
<Grid >
<Image Name="Image_1"
Panel.ZIndex="1" />
<Image Name="Image_2" IsHitTestVisible="false"
Panel.ZIndex="2" />
</Grid>
A: You can have a transparent image on top of all others, and have the click-event on that.
A: The only way is to handle click on the Image_2 and programmatically click on Image_1. You can't break the layout.
Or, of cource, change ZIndex property.
A: I wonder why isn't mouse event working? WPF has tunneling model for events, so you must have the ability to catch a mouse event on any element if another doesn't block it using e.Handled = true...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Is it possible to customize size of listview item for simple_list_item1 Is it possible to change the list item's height and text size for the listview that used as simple_list_item1? Any help is really appreciated and thanks in advance...
A: You can't change the List Item's height and test size if you are using simple_list_item1.
You should use ListView custom adapter and create XML layout for your List Item.
see this..
http://sujitdroid.blogspot.com/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Catching the abort in a WebMethod when calling XHR.abort() Summary: I would like to be able to catch the XHR.abort() in a WebMethod to stop executing server-side code as soon as possible.
I have a webmethod, similar as follows:
[WebMethod]
public static string GetHello()
{
System.Threading.Thread.Sleep(5000);
return "{\"result\":\"Hello!\"}";
}
On the page I call this method with the following javascript (jQuery) code:
var lastXHR = null;
function doCall() {
if (lastXHR != null)
lastXHR.abort();
lastXHR = $.ajax({
url: "default.aspx/GetHello",
data: "{}",
contentType: "application/json; charset=utf-8",
type: 'POST',
error: function (jqXHR, textStatus, errorThrown) {
if (textStatus.statusText == "abort") {
// I know this was aborted here
// Code omitted for simplicity
}
},
success: function (data, textStatus, jqXHR) {
var d = $.parseJSON(data.d);
alert(d.result);
},
complete: function (xhr, status) {
lastXHR = null;
}
});
}
I am able to handle the abort() quite easily with this code on the client, but I would like the web server to stop executing GetHello() when the XHR is aborted.
The reason I need to do this is because on the server side in my project I am calling a search on a database, which can potentially take many seconds to complete, and calling SqlCommand.Cancel() would be very beneficial to my IT team ;-)
UPDATE: I'm going to try calling a secondary WebMethod whose sole purpose is to indicate that the previous call from the same client is to be cancelled. Will post this as an answer if it works.
Other ways to do this would be much-appreciated though!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7595993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Slugify an Acronym List with XSLT Have a requirement to create slugs from XML content.
I was navigating to create Slugs from Titles and found the below ones listed.
*
*Creating Slugs from Titles?
*Java code/library for generating slugs (for use in pretty URLs)
*and similar others.
I was looking for perfect solution for an XSL solution, which provides better slugifies like a PHP solution: http://blog.tersmitten.nl/slugify and also takes care of duplicates in the file system.
Input XML
<table>
<tr>
<td>2D</td>
<td>Two Dimension</td>
</tr>
<tr>
<td>A/C</td>
<td>Account</td>
</tr>
<tr>
<td>A/C</td>
<td>Air Condition</td>
</tr>
<tr>
<td>L&T</td>
<td>Larsen & Toubro</td>
</tr>
<tr>
<td>M + [ # ]</td>
<td>Modified Algo</td>
</tr>
</table>
Expected Output
file: 2d.txt
------------
2D
Two Dimension
file: a-c.txt
-------------
A/C
Account
file: a-c-2.txt
---------------
A/C
Air Condition
file: l-t.txt
-------------
L&T
Larsen & Turbo
file: m.txt (NOT m-.txt)
-------------
M + [ # ]
Modified Algo
Tried XSL
<?xml version="1.0"?>
<xsl:stylesheet extension-element-prefixes="redirect" version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:redirect="http://xml.apache.org/xalan/redirect">
<xsl:output method="text" version="1.0" />
<xsl:template match="/">
<xsl:for-each select="table/tr">
<!-- The logic for variable value requires attention!! -->
<xsl:variable name="acronym" select="translate(td[1], 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')" />
<xsl:variable name="tmpFilename" select="concat('C:/Temp/', $acronym, '.txt')" />
<xsl:variable name="filename">
<xsl:choose>
<xsl:when test="document($tmpFilename)">
<!-- Require logic to handle duplicate file existence. -->
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$filename" />
</xsl:otherwise>
</xsl:choose>
</xsl:variable>
<redirect:write select="$filename">
<xsl:value-of select="td[1]" />
<xsl:text> </xsl:text>
<xsl:value-of select="td[2]" />
</redirect:write>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
Note: The file name should include only the OS supported characters. The rest should be converted to '-'. Also, there shouldn't be leading and trailing '-' characters (e.g. the last output file as mentioned above).
A: If you're looking for a Java based solution, I have an online generator which you can use. If you look in the Javascript, you'll find the POST request that you need to make - just don't hammer it please ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596002",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: To parse an xml having attributes <content type="xhtml">
<apxh:div>
<apxh:p>xyz</apxh:p>
<apxh:p>xyz</apxh:p>
<apxh:p>xyz</apxh:p>
<apxh:p>xyz</apxh:p>
<apxh:p>xyz</apxh:p>
</apxh:div>
</content>
I am able to get the "xhtml" present in type by,
item.getChild(url,CONTENT).setStartElementListener(new StartElementListener() {
@Override
public void start(Attributes attributes) {
str=attributes.getValue("type");
}
});
item.getChild(url,CONTENT).setEndElementListener(new EndElementListener() {
@Override
public void end() {
currentMessage.setType(str);
}
});
Now how can i get the "apxh:div" as it is separated by ":"?
Thank you.
A: I think you need to parse it for SOAP parsing.
The tag patterns of ur Xml shows that, try out using Soap parsing
surely help you...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Search Bar Controller - Crash When Searching for Results I am implementing a search bar controller to search a table view. The below method code which performs the search is crashing with the error "-[__NSArrayM rangeOfString:options:]: unrecognized selector sent to instance 0x65558e0'
The locationInfo array is an array containing 26 arrays, each of which contains a number of objects made up of strings.
Can anyone suggest why the code is crashing ?
Thank you.
- (void)handleSearchForTerm:(NSString *)searchTerm
{
[self setSavedSearchTerm:searchTerm];
if ([self searchResults] == nil)
{
NSMutableArray *array = [[NSMutableArray alloc] init];
[self setSearchResults:array];
[array release], array = nil;
}
[[self searchResults] removeAllObjects];
if ([[self savedSearchTerm] length] != 0)
{
for (NSString *currentString in [self locationInfo])
{
if ([currentString rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound)
{
[[self searchResults] addObject:currentString];
}
}
}
}
A: As you stated in question that "locationInfo" is array containing 26 arrays,
so,
currentString in [self locationInfo] will return an array only so try to write something like below :
for (NSArray *currentArray in [self locationInfo])
{
for (NSString *currentString in currentArray)
{
if ([currentString rangeOfString:searchTerm options:NSCaseInsensitiveSearch].location != NSNotFound)
{
[[self searchResults] addObject:currentString];
}
}
}
or something like this
A: Based on the error you're getting, it seems [self locationInfo] returns an array (NSArray) and not a string (NSString) as you're expecting.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Batik's animation and heavy cpu load we are using Apache Batik in a project for displaying SVG graphics in a Swing application. When we use the animation tag of SVG, it results in heavy cpu load.
I know there are methods to limit the fps or cpu utilization, but why is Batik taking so much cpu power?
Since release 1.7, it seems that the project is dead. Are there any forks of this project or will it be continued?
Thanks in advance.
A: Animations, in particular with vector graphics, just tend to take a lot of CPU. Unless they fully exploit your graphics card acceleration, e.g. by using OpenGL.
As far as I know, Batik so far does all the rendering itself, and cannot offload to your GPU much, so it will use a lot of CPU. (Which on the up side means it will work fine on a server that doesn't have a GPU, allow scripted transcoding, and give guaranteed results.)
Yes, the project seems to lack motivated contributors these days, unfortunately. Just like many other Apache commons projects. But at least it is in a very usable state. But why don't you jump on the project and help out? They have a lot of open bug reports they could use a hand with.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Clean way to cancel object creation I'm wondering how to stop/cancel the creation of an object, risen by new(). Maybe if some preconditions fail and the object isn't needed.
*
*Check before new?
*Check within constructor, returning null or something special, don't know how to handle ...
*Check after new was successful and object is alive. Call a member function myObj->Init(). And destroy object if this fails?
A:
Check before new?
If your preconditions can be verified outside of the object's own inner scope and if they semantically belong in the calling scope, then sure... this is great!
Check within constructor, returning null or something special, don't know how to handle ...
Check within the constructor, and throw an exception. Handle it like you handle any other exception. Best approach.
Check after new was successful and object is alive. Call a member function myObj->Init(). And destroy object if this fails?
Abandoning RAII in this manner is a backwards step.
A: Throw an exception for the object's constructor. Note that the object's destructor will not be called, unlike operator delete, which will be called automatically to reclaim the allocated memory.
A: None of the above.
If the object cannot be constructed because of unmet conditions, the constructor should throw an exception with the throw statement.
A: Maybe it's better to make lightweight constructor which always succeeds, and Initialize function that makes heavy work and throws exception on error.
Edit. After some critical feedback, I found why my suggestion doesn't meet RAII requirements:
"Resources are acquired during initialization, when there is no chance of them being used before they are available".
I don't change my original post, it may be helpful to have this as typical design error sample.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596012",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Sms Application Android develop I need to develop an android application which when receive a message reply automatically
to the sender of the message(without pressing any button) with a predefined text like(thank you for contacting we will contact you soon).
Any links,suggestions most welcome.
If anybody explain in brief what should i do then it will help me a lot.
I already read visit http://mobiforge.com/developing/story/sms-messaging-android link. It help me but eclipse say The type SmsManager is deprecated. so what another type should be use?
A: That's true that SmsManager in android.telephony.gsm package was deprecated. This class has been replaced by SmsManager class from android.telephony package. I resolve this problem by change imported package android.telephony.gsm to android.telephony for SmsManager class.
You can read the documentation. This is SmsManager documentation from android.telephony.gsm package and this is SmsManager documentation from android.telephony package.
A: Yes android.telephony.SmsManager is depreciated . You should use android.telephony.gsm.SmsManager to send SMS and to send SMS automatically you have to use BroadcaseReceiver for incoming SMS.
A: Try this:
*
*First listen for incoming sms.
*Send sms.
Parts 1 and 2 are well tested with Android 2.3.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to cut the picture into equal parts? I have images on my android app. How cut this picture into 9 or 12 equal parts and add these parts an array?
A: This will work:
ArrayList<Bitmap> bs= new ArrayList<Bitmap>();
Bitmap b= BitmapFactory.decodeResource(getResources(),R.drawable.photo1);
divideImages(b);
private void divideImages(Bitmap b) {
// TODO Auto-generated method stub
final int width = b.getWidth();
final int height =b.getHeight();
final int pixelByCol = width / 2;
final int pixelByRow = height / 2;
//List<Bitmap> bs = new ArrayList<Bitmap>();
for(int i=0;i<2;i++){
System.out.println("row no. "+i);
for(int j=0;j<2;j++){
System.out.println("Column no."+j);
int startx=pixelByCol*j;
int starty=pixelByRow*i;
Bitmap b1=Bitmap.createBitmap(b,startx,starty,pixelByCol,pixelByRow );
bs.add(b1);
b1=null;
}
}
b = null;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Perl Tk: confusion with updating a text window I have a small Perl Tk app with a text window that I want to be updated in a non buffered way like I have with my log files but I can't get it to work due to my poor understanding of everything to do with Perl.
The app reads an xml index, parses it then loads each id found in the xml as a url to cache the page. These can number from 1700 to 19,000 depending on which $pubId is entered and takes a couple of hours.
I have the following code for the Submit button and the text window:
my $submit_image = $pict->Photo(-file => $submit);
my $submit_button = $mw->Button(
-image => $submit_image,
-text => "Submit",
-background => "#cccccc",
-command => sub {
if ($pubId eq '') {
$|;
Log_message ("\n$DATE - $TIME - WARNING: Please complete all fields\t");
tk_message ("Please enter a valid Publication ID");
}
else {
request_url(); #Open the xml url and read it in
}
$text->insert(
# put something to the _end_ of the text
# which is in the widget
'end',
sprintf(" $txtmesg\n")
);
# Set window to the end of the text
# I want to see the newest events immediately
$text->see('end');
}) ->place( -x => 60, -y =>195);
which works if the button is pressed with an empty or invalid $pubId (request_url does a further check to see if the html body contains the word 404 and errors out a message to the window).
But if everything is ok and request_url() runs, then the whole Tk window freezes and I can't use my exit button and have to close it via the command prompt.
I know I should be doing this differently but so far every site I have looked at is too complicated for me and I just get baffled. I'm looking for some noddy instructions to enable me to work through this.
Thanks.
EDIT: I have now tried to use MainLoop(); and the DoOneEvent(): within my sub but I am still seeing the same gui freeze and no window updates.
I will continue to research and experiment.
-command => \&long_job)
MainLoop();
sub long_job {
if ($pubId eq '') {
$|;
Log_message ("\n$DATE - $TIME - WARNING: Please complete all fields\t");
tk_message ("Please enter a valid Publication ID");
}
else {
DoOneEvent();
request_url(); #Open the xml url and read it in
}
}
A: Not sure if this will help others with a similar problem, but just in case it does:
MainLoop();
is what "starts" the tk process. Good practice would be to set up all your widgets, callbacks and anything you want to show up on screen first, then call the MainLoop(). Processing should occur after the MainLoop() is called. In the above, you will probably need to call
$myLabel->update;
inside the loop on whatever it is you are using to display your output. In my case I was using a Label to output progress messages in a loop that made calls using system(). Using ->update solved it perfectly (while DoOneEvent() did not).
Hope that helps somebody out there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Initialising Arrays and Objects: using brackets or 'new'? When initialising Arrays and Objects in JavaScript, is there any difference between these two statements:
var a = [];
var a = new Array();
or between these two statements:
var b = {};
var b = new Object();
If there is a difference, which is to be preferred?
A: there aren't any significant differences. You could use both, but if you use javascript for web client side scripting, it's better to use the shorter syntax, because the shorter the javascript code, the faster it will get downloaded and executed.
A: Brackets. Point.
They are shorter, they don't have hidden issues, and they are easier to pre-fill ( var a = [1,2,3,{"use":"brackets"},"because they are cool!"]; ).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Access Ticker stream is there anyway I can access Ticker in my app? If so how can I do it? A quick example would be amazing.
Btw, my app is for iOS
A: There isn't currently an api endpoint for accessing the ticker. I'm guessing/hoping one will be released eventually
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Visual Studio 2010 creates folder in current working directory on launch Every time I launch Visual Studio 2010, it creates a directory called "Visual Studio 2010" in the current working directory at the time I launched it. It just started doing this at the same time that it forgot all of my toolbar settings and so on.
I've clearly got an incorrect setting somewhere, but I can't find it.
Under Tools\Options\Projects and Solutions\General I have:
Projects location:
D:\ian
User project templates location:
M:\Visual Studio 2010\Templates\ProjectTemplates
User item templates location:
M:\Visual Studio 2010\Templates\ItemTemplates
How do I stop this spurious .\Visual Studio 2010 directory being created and tell it to use the proper one on M:\ instead?
Edit: Since I've started a bounty on this, please be reasonable and don't post a suggestion that doesn't answer the question. For example, don't say 'Have you tried reinstalling?' or 'Have you tried deleting all your settings?' Thank you for your understanding.
A: Damn, too annoying. You don't know which plugin/addon or something do this...
So we can't find it too* Ok. thanks god, stackoverflow is here... Here is the solution;
Press Win + R
Type "regedit"
Go to this folder by treeview; "[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0]"
Edit everything which are like this; "Documents\Visual Studio 2010\"
Last step; In registry editor, press Ctrl + F
Search the string "Documents\Visual Studio 2010\". And change them too if anything appears...
I suggest an advanced registry editor for this.
Good luck & best regards...
UPDATE:
And if you still have the problem; open VS2010, go to "tools" > click "extension manager" > try to disable all plugins(I mean all of them). And play with VS again, create a new project etc. If there will be created a new folder( named like "Visual Studio 2010" ) in the "documents" then we will sure this comes from the ide:visual studio 2010( not add-ons ). Also, if you are using a "subversion control software" or "sdk service" try to disable them too... ( with disabling services in OS management )
A: This is the final answer that worked for me.
It turns out that Visual Studio 2010 regularly and automatically exports your settings file. (You would probably expect it to save your settings on exit, but not export them unless you explicitly ask it to.) I think it does this every time you quit, but it seems to create the directory into which it will export as soon as it is launched. This is the problem I was seeing.
This is how I resolved it:
Tools > Options > Environment > Import and Export Settings
The field Automatically save my settings to this file: was just Visual Studio 2010\Current Settings.vssettings. This is a relative path, so the folder Visual Studio 2010 was being created in the current working directory. I changed it to an absolute path M:\Visual Studio 2010\Current Settings.vssettings and this solved the problem.
A: This is another different way, so I'm adding a new answer here.
I don't want to edit my previous answer too much( It's started to looks ugly )...
Just go that link, download/copy the script, carefully save and edit for your needs;
https://github.com/jerker-back/VSUtilities/blob/master/custom_vspaths.js
and run it under admin.user.rights( or disable windows uac )...
A: Is it possible that you have a macro in your EnvirommentEvents that is causing this? Go to menu Tools -> Macros -> Macros IDE. Look in each of the macros trees in the Project Explorer for EnvironmentEvents to see if any of those macros is the culprit.
A: None of the solutions here worked for me. I don't think we've seen the golden bullet yet.
I had been writing to the same settings folder for years and all of a sudden that was no good for visual studio anymore. The folder was a networked folder. One day, every time I fired up a solution it would start making me yet another Visual Studio 2010 folder in the same directory as the .sln file.
I tried (and re-tried) specifying where settings are saved. I also went through and did some registry changes. In the end, what seemed to fix it was to re-config the IDE to use a local path, and then re-config it again to use the network path. I did this for all the paths you can set in Tools...Options...Environment...Import and Export Settings as well as Tools...Options...Environment...Projects and Solutions...General. And now I'm back to the setup I've been using for the last few years. It has stopped creating new folders every time I open a solution. For now, anyway.
A: The brute-force solution:
*
*Run regedit and rename the folder [HKEY_CURRENT_USER\Software\Microsoft\VisualStudio] to something like "VisualStudio_BAK".
*Run devenc.exe /resetsettings to reset all settings to default.
If you don't know what you are doing, don't try this...! ;-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: vector class throwing an error after publishing the FLA for generating .ipa from flash cs5 I am creating a flash game for iPhone using Flash CS5, Everything runs smoothly when creating swf via Ctrl+Enter. But when i am attaching .p12 and provisioning profile files and publish the FLA for generating .ipa there is an error thrown by the compiler that is:
"Incorrect number of arguments, Expected no more than 0"
private static function closestVertexOnOBB(p:Vector, r:RectangleParticle):Vector
{
var d:Vector = p.minus(r.samp);
var q:Vector= new Vector(r.samp.x, r.samp.y);
for (var i:int = 0; i < 2; i++)
{
var dist:Number = d.dot(r.axes[i]);
if (dist >= 0) dist = r.extents[i];
else if (dist < 0) dist = -r.extents[i];
q.plusEquals(r.axes[i].mult(dist));
}
return q;
}
can anyone help please??
A: The Vector class is actually a native flash class since Flash Player 10 (API docs) and is therefore a class-name so should avoid for our custom classes. we should have different class name rather than the inbuilt flash keywords and class names.:)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Copy the contents of an ImageField to a new file path in Django I have a Django model object that has a few normal attributes, and it has a ImageField for the logo. I want to write a method that'll copy this object to a new object. It's easy enough to instanciate the new object, then loop over all the attributes and copy from the old to new (e.g. new_object.name = old_object.name). However if I do that with the logo field (i.e. new_object.logo = old_object.logo), both new_object and old_object point to the same file on the harddisk. If you edit the old file, the logo for the new object will change.
What's the best way to have a full/deep copy of the ImageField? I want it to have a different file name and to point to a different file on the disk, but it should have exactly the same content.
A: Why not create a function that is fun on the save signal which copies the image file to whereever you want, then creates a new object with a new image field?
models.py
class ObjectOne(models.Model):
logo = models.ImageField(...)
class ObjectTwo(models.Model):
logo = models.ImageField(...)
from django.db.models.signals import post_save
from signals import my_signal
post_save.connect(my_signal, dispatch_uid="001")
signals.py
from models. import ObjectOne, ObjectTwo
def my_signal(sender, instance, *args, **kwargs):
if sender is ObjectOne:
new_obj = ObjectTwo()
new_obj.logo.save("custom/path/new_filename.jpg",File(open(instance.image.url,"w"))
new_obj.save()
I haven't tested the image copying code but this is the general idea. There is more here:
Programmatically saving image to Django ImageField
Django: add image in an ImageField from image url
how to manually assign imagefield in Django
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to get value before last forward slash using Jquery I ha got these types of hrefs
http://localhost:8080/en/reservations/tours-and-safaris-booking-enquiry-form/dubai/index.aspx
http://localhost:8080/en/reservations/tours-and-safaris-booking-enquiry-form/muscat/index.aspx
Now I need to write a function which will take this as input and will return "tours-and-safaris-booking-enquiry-form".
Please suggest!!
A: You can do a rudimentary split (to an array) and get the second-to-the-last element.
var _array = url.split('/'),
_foo = _array[_array.length-2];
You have to watch out for URLs formatted this way:
http://your.domain.com/path/to/something/
... that is, those with trailing forward slashes, as those will create an empty array element at the end (which can throw off your parsing). You may want to sanitize your array first by removing empty elements before retrieving the particular string you really want (using something like this solution).
A: If your string will always be of that exact form (i.e. always have the same number of / characters before the part you want) then you can do this:
var partYouWant = yourString.split("/")[5];
split does what it says, and splits the string, using the specified string as a delimiter (in this case, it uses the / character as the delimiter). That returns an array, and the part you want is at index 5.
Note that jQuery will not help you in the slightest here. It's plain old JavaScript that you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Video within a JQuery Slider I am just starting development on a JQuery Slider that will start with a video, and when the video is done the slider will begin. I'd like for the site to be able to work on both IE9 and lower, and the iPhone, which I assume will require an HTML5 option and a Flash option. I would like the slider to look like this:
http://popstache.com/
with a minimal UI, just the arrows and circles on the bottom allowing for slide selection.
I have been playing with Slidedeck at http://www.slidedeck.com/, and I know that videos can be embedded in it. My main concern right now is the video. I've heard about people using Flowplayer, but I'd rather not pay the $95 to remove the branding, and I do not believe that will work on the iPhone. Any suggestions? Thank you.
A: MediaFront's OSM Player is completely free.
So is jPlayer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Exposing and then using OnTextChange Event handler Related Question: Adding custom OnTextChange event handler on custom TextBox
In the related question I asked how I could expose OnTextChange in my custom textbox control and we resolved it by:
public event EventHandler TextChanged
{
add { customTextBox.TextChanged += value; }
remove { customTextBox.TextChanged -= value; }
}
I am trying use TextChanged event like this when the control is implemented:
<uc:CustomTextBox ID="customTextBox"
runat="server"
OnTextChanged="CustomTextBox_OnTextChanged">
</uc:CustomTextBox>
This never seems to hit the following when running:
protected void CustomTextBox_OnTextChanged(System.EventArgs e)
{
// Do something here
}
Or hit:
protected void CustomTextBox_OnTextChanged(object sender, EventArgs e)
{
// Do something here
}
What am I doing wrong, what am I missing out and is this the best way or common practice way to do everything I am trying to do here?
A: You need to set AutoPostBack=True property of TextBox.
If you are designing a web user control then simply define public property to set True/False value of CustomTextBox in user control's code-behind:
public bool AutoPostBack
{
get
{
return CustomTextBox.AutoPostBack;
}
set
{
CustomTextbox.AutoPostBack = value;
}
}
If you are developing a custom web control then you can to override the AutoPostBack property for the customization. If you don't want to customize AutoPostBack property then don't override it.
In case you override AutoPostBack property, please invoke the super class's default implementation.
public override bool AutoPostBack
{
get
{
return base.AutoPostBack;
}
set
{
base.AutoPostBack = value;
}
}
A: In order for OnTextChanged to fire, you need to specify AutoPostBack="true" on the TextBox.
In the ASPX markup:
<uc:CustomTextBox ID="customTextBox" runat="server" OnTextChanged="CustomTextBox_OnTextChanged" AutoPostBack="true"></uc:CustomTextBox>
In the code-behind of the CustomTextBox user control:
public bool AutoPostBack
{
get
{
//the textbox in the user control
return customTextBox.AutoPostBack;
}
set
{
customTextBox.AutoPostBack = value;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596050",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: generically parsing String to date I'm communication with a web service and it the json response has dates in it. the problem is those dates are in different formats. is there a generic way to parse these strings?
A: You should probably have an ordered list of formats to try (ideally using Joda Time as a far better API than the built-in one) and try each in turn until one works. It's not ideal in terms of performance (all the exceptions for failure) but it'll work and should be reasonably clear.
Of course, if you can get in touch with the web service provider and suggest that they return a standard format instead, that would be cleaner...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596052",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: developing Android on Eclipse which eclipse version I should Download to start developing on Android ?
From This Site :http://www.eclipse.org/downloads/
Thanks
A: Eclipse Classic 3.7.1. Anyway, it's already said on Android Developer page anyway: http://developer.android.com/sdk/installing.html
The "Eclipse Classic" version is recommended
Next time please do some little searching before asking, thank you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Apache POI extracting value as it looks in Excel I have Excel file and some contents, coming from external source(database, file, whatever).
I've encountered problems with numeric cells in Excel -getNumericValue returns double value for any cell, no matter how value is formatted in it.
External source returns string representations of numbers, i.e. it may return "301" and "301.0" and these are different values, and i don't know which type may be in which case.
But if i have "301" in Excel file, getNumericValue method will always return "301.0", so if i need to compare values from external source and from excel, "301" in excel will be different from "301" from external source, as they will have different string representations.
Long story short, can you show me the working way to get string representation of cell value as it looks in Excel? I have only HSSF* classes available for using.
A: You want the DataFormatter class. The handles formatting the contents of a cell based on the formatting rules applied to it. It should give you basically what Excel displays
A: basing from another thread
you can probably set the cell's type to string first before getting its values
cell.setCellType(Cell.CELL_TYPE_STRING);
I've tried this approach when getting a number with more than 15 decimal places and it works like a charm.
A: Dont compare String, compare double instead:
String excelDouble=301.0;
String external="301";
Double externalDouble=Double.parseDouble(external);
externalDouble.equals(excelDouble); //return true
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: WkHtmlToXSharp How to add Headers and Footers? I'm building an HTML to PDF converter with the WkHtmlToXSharp (QT webkit) library, and was wondering if someone knows how to add headers and footers to the document? I've seen a few questions about this library here, but couldn't find anything about the headers and footers.
In the wkhtmltopdf manual (http://madalgo.au.dk/~jakobt/wkhtmltoxdoc/wkhtmltopdf-0.9.9-doc.html) there are documentation about headers and footers, but I couldn't find anything in the .NET wrapper library (WkHtmlToXSharp), it is probably not implemented?
Thanks for any help or suggestions!
A: Here are some snippets of how I do it:
public class HeaderFooterSettings
{
public string HtmlUrl { get; set; }
public string Right { get; set; }
public string Spacing { get; set; }
}
public class PdfObjectSettings
{
private WebSettings _webSettings = new WebSettings();
private LoadSettings _loadSettings = new LoadSettings();
private HeaderFooterSettings _headerSettings = new HeaderFooterSettings();
private HeaderFooterSettings _footerSettings = new HeaderFooterSettings();
public string Page { get; set; }
public string Cover { get; set; }
public bool ProduceForms { get; set; }
public bool PagesCount { get; set; }
public HeaderFooterSettings Header { get { return _headerSettings; } }
public HeaderFooterSettings Footer { get { return _footerSettings; } }
public WebSettings Web { get { return _webSettings; } }
public LoadSettings Load { get { return _loadSettings; } }
// TODO: Add remaining settings..
//see the following page for settings format http://www.cs.au.dk/~jakobt/libwkhtmltox_0.10.0_doc/pagesettings.html
}
Here is the main logic of setting the header and footer URL:
var objectSettings = new PdfObjectSettings();
objectSettings.Header.HtmlUrl = headerHtmlUrl;
objectSettings.Header.Spacing = ConfigurationManager.AppSettings["ContentSpacing"];
objectSettings.Footer.HtmlUrl = footerHtmlUrl;
I hope this helps.
Rafi
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Pass a parameter to the ApplicationBarIconButton.Click *Hi everyone,
I'm new in WP7 dev. (i'm used to work on android) and there is a basic thing i don't know how to do.
I create programmatically a list of ApplicationBarIconButton with this:
for (int i=0; i<menus.Count(); i++)
{
ApplicationBarIconButton button = new ApplicationBarIconButton();
button.IconUri = new Uri(menus.ElementAt(i).Element("ImageUrl").Value.Trim(),UriKind.Relative);
button.Text = menus.ElementAt(i).Element("Title").Value.Trim();
button.Click += new EventHandler(button_clicked);
ApplicationBar.Buttons.Add(button);
}
and I want that the button_clicked method could retrieve the i value of the button.
How is it possible?
Thanks
A: I was beaten to it by @Enigmativity but his answer may still be incorrect. In my experience I've found that you need to clone the iterating i variable, otherwise on the click event, i will be the last value. If his doesn't work try this (again using a lamba function)
for (int i=0; i<menus.Count(); i++){
ApplicationBarIconButton button = new ...
...
var cloned = i;
button.Click += (sender, e) => {
sometTextBlock.Text = String.Format("App Button {0} pressed.", cloned);
};
}
Cheers,
Al.
A: You could do this:
for (int i=0; i<menus.Count(); i++)
{
ApplicationBarIconButton button = new ApplicationBarIconButton();
button.IconUri = new Uri(menus.ElementAt(i).Element("ImageUrl").Value.Trim(),UriKind.Relative);
button.Text = menus.ElementAt(i).Element("Title").Value.Trim();
var i2 = i; //Thanks to `ajmccall` - I forgot this.
button.Click += (s, e) =>
{
// the variable `i2` is accessible now.
};
ApplicationBar.Buttons.Add(button);
}
Rather than calling a method to handle click you can use a lambda and still get access to i (via local copy i2). You could then call any method passing i2 as a parameter if you need to.
A: An integrated way of achieving this is through the use of commanding in MVVM frameworks.
Granted with Application bar buttons / menu items it is a bit more tricky but far more flexible than to manipulate the UI Elements on the page.
Look in to MVVM light (http://mvvmlight.codeplex.com) or further with the likes of Calburn.Micro (http://caliburnmicro.codeplex.com/)
For application bar data binding you will need to google further (lost the link at the mo)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why isn't this C program for calculating the area of a triangle working for all inputs? The following is the source code of a program which calculates the area of a triangle when the sides are given.
#include<stdio.h>
#include<conio.h>
#include<math.h>
void main()
{
int a,b,c;
float s,area;
clrscr();
printf("Enter the lengths of the sides of the triangle:\n");
scanf("%d%d%d",&a,&b,&c);
s=(a+b+c)/2;
area=sqrt(s*(s-a)*(s-b)*(s-c));
printf("Area=%f",area);
getch();
}
I used the Turbo C++ compiler Version 3.0 to compile the program. When I give the sides as 10, 10 and 10, I get the area as 43.301270 which is correct. But when I plug the values as 1,1 and 1, the program gives the area as 0.000000 which is obviously wrong. Further, when I plug in the values as 3,3 and 3 I get the area as 2.000000 which is wrong.
Does anyone know the reason for the program's erratic behavior? How can it be corrected? I have uploaded the program as a Zip file.
Thanks in advance.
A: You are using integer arithmetic for the calculation of s and suffering from truncation. Change your program like this to use floating point arithmetic.
s=(a+b+c)/2f;
A: Given that each of a, b, and c is an int; then a+b+c is an int.
2 is also an int.
(a + b + c) / 2 is integer division.
Try (a + b + c) / 2.0.
And prefer to use doubles for floating point values.
A:
s=((float)a+b+c)/2.0f;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Select from one table where not in another I'm trying to find the rows that are in one table but not another, both tables are in different databases and also have different column names on the column that I'm using to match.
I've got a query, code below, and I think it probably works but it's way too slow:
SELECT `pm`.`id`
FROM `R2R`.`partmaster` `pm`
WHERE NOT EXISTS (
SELECT *
FROM `wpsapi4`.`product_details` `pd`
WHERE `pm`.`id` = `pd`.`part_num`
)
So the query is trying to do as follows:
Select all the ids from the R2R.partmaster database that are not in the wpsapi4.product_details database. The columns I'm matching are partmaster.id & product_details.part_num
A: To expand on Johan's answer, if the part_num column in the sub-select can contain null values then the query will break.
To correct this, add a null check...
SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN
(SELECT pd.part_num FROM wpsapi4.product_details pd
where pd.part_num is not null)
*
*Sorry but I couldn't add a comment as I don't have the rep!
A: You can LEFT JOIN the two tables. If there is no corresponding row in the second table, the values will be NULL.
SELECT id FROM partmaster LEFT JOIN product_details ON (...) WHERE product_details.part_num IS NULL
A: So there's loads of posts on the web that show how to do this, I've found 3 ways, same as pointed out by Johan & Sjoerd. I couldn't get any of these queries to work, well obviously they work fine it's my database that's not working correctly and those queries all ran slow.
So I worked out another way that someone else may find useful:
The basic jist of it is to create a temporary table and fill it with all the information, then remove all the rows that ARE in the other table.
So I did these 3 queries, and it ran quickly (in a couple moments).
CREATE TEMPORARY TABLE
`database1`.`newRows`
SELECT
`t1`.`id` AS `columnID`
FROM
`database2`.`table` AS `t1`
.
CREATE INDEX `columnID` ON `database1`.`newRows`(`columnID`)
.
DELETE FROM `database1`.`newRows`
WHERE
EXISTS(
SELECT `columnID` FROM `database1`.`product_details` WHERE `columnID`=`database1`.`newRows`.`columnID`
)
A: Expanding on Sjoerd's anti-join, you can also use the easy to understand SELECT WHERE X NOT IN (SELECT) pattern.
SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN (SELECT pd.part_num FROM wpsapi4.product_details pd)
Note that you only need to use ` backticks on reserved words, names with spaces and such, not with normal column names.
On MySQL 5+ this kind of query runs pretty fast.
On MySQL 3/4 it's slow.
Make sure you have indexes on the fields in question
You need to have an index on pm.id, pd.part_num.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596073",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "76"
}
|
Q: How to check if iPhone supports CDMA or GSM Is there any way to identify if iPhone supports CDMA or GSM network. Any Apple API in Objective-C which can provide this information.
A: You might examine model id with the function (credits):
#include <sys/types.h>
#include <sys/sysctl.h>
NSString* machine () {
size_t size;
// Set 'oldp' parameter to NULL to get the size of the data
// returned so we can allocate appropriate amount of space
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
// Allocate the space to store name
char *name = malloc(size);
// Get the platform name
sysctlbyname("hw.machine", name, &size, NULL, 0);
// Place name into a string
NSString *machineid = [NSString stringWithUTF8String:name];
// Done with this
free(name);
return machineid;
}
Function will return string like @"iPhone3,3" which stands for iPhone 4 (CDMA/Verizon). It might be difficult to gather full table of various model numbers. Some of the models descriptions could be found here. You'll have to expand table of models as new models will appear.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Ruby Hash.has_key? returning false for the first key on Windows I'm having a weird issue with Ruby hashes on windows. I'm loading the following YAML file and parsing it as a hash:
tasks:
- clone_skeleton, <skeleton_path>
- summit_capify, <skeleton_path>
I'm using YAML.load() to load the file into a hash. If I print out hash.keys tasks is listed as a key but if I do hash.has_key?("tasks") I get back false. However if I change the yaml to this
directory_structure:
tasks:
- clone_skeleton, <skeleton_path>
- summit_capify, <skeleton_path>
hash.has_key?("tasks") returns true but hash.has_key?("directory_structure") returns false. I haven't tested in Linux but I don't seem to be having this problem on OS X, just Windows. I'm using Ruby 1.9.2 and have tested in Cygwin and using the standard command prompt.
I don't know if this is a ruby bug, a problem with my YAML or something else. Any ideas?
UPDATE: Looks like this is fixed in Ruby 1.9.3
A: Is it possible the keys are Symbols and not Strings? Trying has_key?(:tasks).
A: Whenever you're debugging, don't do puts hash.keys, but do puts hash.keys.inspect - the latter indicates exactly what's going on.
Or you may want to do puts hash.inspect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ruby string representation i have in database a string like \303\255 which represents í .
How can i convert that 8 chars representation in í ?
I could replace them all, but isn't there any other way ?
A: It's not really 8 characters in the string, it's 2 bytes. I'm not sure where you want \303\255 to show up as í but if you put
# encoding: utf-8
in the top of your .rb-file Ruby will use UTF-8.
If you are using Ruby on Rails you can try to add the following two lines to config/environment.rb
Encoding.default_external = Encoding::UTF_8
Encoding.default_internal = Encoding::UTF_8
A: Assuming the problem really is as you describe, and not just a misunderstanding.
I battled with this. It's not pretty. This parses the string and uses pack to pack down the relevant bytes.
"foo \\303\\255 bar".gsub(/(\\\d{3})+/) do |match|
match[1..-1].split("\\").map{ |octet| octet.to_i(8) }.pack("c*")
end.force_encoding("UTF-8")
The much shorter version uses eval, but it's always worth trying to avoid eval if you can, since it has huge security risks if used incorrectly. Given that we're validating the format of what we're eval'ing here, I'll go ahead and say it's probably safe to do this:
"foo \\303\\255 bar".gsub(/(\\\d{3})+/) { |m| eval('"' + m + '"') }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to upgrade a Facebook app on iOS to OAuth 2.0 and HTTPS I have just received an email from Facebook:
Reminder: Upgrade Your App to OAuth 2.0 and HTTPS by October 1st
Some of my app use Facebook API on iOS. Please help me because I don't know what I have to do. If I use the last SDK for iOS, what do I have to do more? Do I have to change the app settings in Facebook?
Thank you very much in advance!
A: I believe if you are using the Facebook iOS SDK you are already good to go.
http://www.insidefacebook.com/2010/08/12/facebook-adds-graph-api-oauth-2-0-integration-to-ios-sdk/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to disable dojox.grid.DataGrid How can I disable dojox.grid.DataGrid. By disable I mean the whole widget should be disabled and not just some aspect of it (sorting,cell selection etc)
A: You may try with a dojox.widget.Standby as explained here: Loading indicator with dojo XHR requests .
I have never used it on a dojox.grid.DataGrid but it should work...
A: I think you mean a READ-ONLY grid;
In creation of the grid:
var dataGrid = new dojox.grid.DataGrid({
id: 'xxx',
store: myStore, structure:myLayout,
canSort:false, //disable sorting //Then do the same thing for every attributes options and disable them all
}, dojo.byId("myDivName"));
You might have to override some default behavior such as:
onHeaderEvent: function (e) {
//make it do nothing
},
and check on other events from http://livedocs.dojotoolkit.org/dojox/grid/DataGrid
just clear everything out.
And in your css, you might have to do such thing like:
.dojoxGridRowSelected
{
background-color:none;
border:none;.....
}
.dojoxGridCellFocus
{
border:none;
}
Just find the class names from your domNodes
A: Use attribute "canSort : false" to hide or disable sort button in Dojo DataGrid code
var newGrid = new DataGrid({
id : 'newGrid',
canSort:false,
store : this.resultStore,
structure : this.resultGridLayout,
autoHeight:true
});
Regards,
Satish M Hiremath
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Dynamically import a package from a directory I am making a server that listens on a socket. Whenever a new request comes in, the server spawns a new instance of handle_request. Each instance of handle_request.py imports the relevant handler from request_handlers.
server.py
handle_request.py
request_handlers
|_handler_beta
|_handler_1
|_handler_2
While handlerX is a module, request_handlers is not a package. The modules are self-contained and reloaded on each request. The modules may be added, modified or dropped while the program is running.
Question: What is the way to import a module from an arbitrary directory?
Doing my homework, I saw that most questions deal with packages, even one is titled "python: import a module from a folder". Hence I believe this question is distinct. The architecture has been simplified; and yes, I am considering pre-forking with reload on file modification.
A: Create __init__.py in the directory. That makes it a package. If you're scanning the directory for .py files, you'll probably then want to skip __init__.py.
Then, you can import them with __import__('request_handlers.' + module, fromlist=['']) (the fromlist is important, otherwise you'll get request_handlers rather than the appropriate module).
One way of doing it without an __init__.py would be to put the request_handlers directory in sys.path, but that then makes name clashes with other modules possible. Another way would be with execfile. You can research that more if you want to. I'd do it (and have done it before) the package/__import__ way.
A: As Chris said: add an __init__.py to your folder. You can use the __import__() function if you do not know the names beforehand or if you do not want to have their names fixed in your code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: htaccess of virtual subdomain with subfolders currently i have achieved
www.username.domain.com to redirect to domain.com/folder1/folder2/index.php?id=username
with my current .htacceess
RewriteCond %{HTTP_HOST} !^www\.domain\.com$
RewriteCond %{HTTP_HOST} ^www\.(.*)\.domain\.com$
RewriteRule ^$ http://domain.com/general/user/index.php?id=%1 [P,L]
i want to achieve this
www.username.domain.com/pagename/ to redirect to domain.com/folder1/folder2/next.php?id=username
www.username.domain.com/pagename/variable to redirect to domain.com/folder1/folder2/next.php?id=username$val=variable
Please help
A: Use this rule (place after yours):
RewriteCond %{HTTP_HOST} !^www\.domain\.com$
RewriteCond %{HTTP_HOST} ^www\.(.*)\.domain\.com$
RewriteRule ^pagename/([^/]*)$ http://domain.com/folder1/folder2/next.php?id=%1&val=$1 [P,L]
This will work for both www.username.domain.com/pagename/ and www.username.domain.com/pagename/variable (for 1st URL value of val= will be empty string).
P.S.
I assume $ character is a typo in your 2nd destination URL (domain.com/folder1/folder2/next.php?id=username$val=variable) and it should be & instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Saving images from web I am new to IOS development. I am developing an app in which i am viewing some images in my app that are stored on a server. The thing is that, i want an image from the server to store in my photo gallery. anyone know the procedure?
Thanks for every help;
A: You will have implement web services to access images from server, so that it can be downloaded to your iPhone App.
A: Look up the documentation for the UIImageWriteToSavedPhotosAlbum function. It will save a UIImage to the camera roll.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting list element's Attribute I have two list.
List1 contain objects and each object has node1 property.
List2 contain lists of node which are the properties of objects stored in list1.
I want to create separate list which contain list of objects whose node present in list2. I want to create this list without using for loop because my object list is large so code takes long time to run if I use for loop.
How can I achieve this in python?
A: Sounds like it's time to redesign your program. Replace list 2 with a defaultdict(None) mapping the objects in list 1 to their node properties. Call it node so you can get the node of an object x with node[x]. You can get the list of all nodes (unordered) with node.values() in O(m) time where m is the number of objects that have an associated node.
(Alternatively, store a node attribute in the objects with None indicating no node and get the nodes with [x.node for x in list1 if x.node is not None]; this takes O(n) time but may be faster than a for loop.)
A: In my opinion there is no other way than by using a for loop:
final_list = []
for obj in list1:
if obj.node1 in list2:
final_list.append(obj)
EDIT:
As for the comments, using a set is faster for lookup elements (thanks eumiro):
set2 = set(list2)
...
if obj.node1 in set2:
Additionally you can write the code in one line (thanks rocksportrocker):
final_list = [obj for obj in list1 if obj not in set2]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SQL Insert? insert data from one to another Firstly please understand that SQL is not one of my strong areas at the moment and i am a little unsure why i cannot get the query to-do this, it seems possible.
we are running a mysql server v5.1
i have a filenotes table that i need to insert a single record into for a list of clients we have.
so i did this.
insert into filenote(clientid, notetype, datetime, notedetails)
VALUES (clienttable.clientid, 'info','2011-09-29 09:00:00', 'example note')
select clienttable.clientid from clienttable
where clienttable.clientid in (1,2,3,4,5,6,7,8,9)
however i keep getting errors from SQL relating to the select statement, there is no indication in the error to what the problem is though, it just states.
"you have an error in your SQL syntax near select clienttable.clientid
from clienttable where clienttable.clientid in ("
whilst i know there is a problem there i cannot see what that problem would be. please be aware that the field names do not match in the tables.
this is the example i followed.
INSERT INTO Store_Information (store_name, Sales, Date)
SELECT store_name, Sales, Date
FROM Sales_Information
WHERE Year(Date) = 1998
A: insert into filenote(clientid, notetype, datetime, notedetails)
select clienttable.clientid, 'info','2011-09-29 09:00:00', 'example note' from clienttable
where clienttable.clientid between 1 and 9
A: You're mixing up two different styles of INSERT.
To use the same method as your example, you'd need to do:
INSERT INTO filenote(clientid, notetype, datetime, notedetails)
SELECT clientid, 'info','2011-09-29 09:00:00', 'example note'
FROM clienttable
WHERE clienttable.clientid in (1,2,3,4,5,6,7,8,9)
or use BETWEEN:
INSERT INTO filenote(clientid, notetype, datetime, notedetails)
SELECT clientid, 'info','2011-09-29 09:00:00', 'example note'
FROM clienttable
WHERE clienttable.clientid BETWEEN 1 AND 9
A: INSERT INTO filenote(clientid, notetype, datetime, notedetails)
SELECT clienttable.clientid, 'info','2011-09-29 09:00:00', 'example note'
FROM clienttable
WHERE clienttable.clientid in (1,2,3,4,5,6,7,8,9);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Jquery persistent sortable objects in Drupal? I'm working on a project in drupal that allows me to have visual bookmark screenshots (think zootool.com). I have each screenshot in a grid that is using jQuery to be sortable. This all works correctly and I can sort all the images into whatever order I wish. The only problem is that I can't save the locations/order that I've just changed them to.
I have used the 'weight' module to assign a default value to each screenshot and this is output using Views sorted by this 'weight'. Therefore I need to have a mechanism to update/save the weight order of all the nodes when I move them with jQuery.
Currently I have the jQuery code that outputs an alert box with the new order:
//Draggable boxes
$(function() {
$( ".sortable-nodes" ).sortable({
placeholder: "ui-state-highlight",
opacity: 0.7,
update: function(event, ui) {
var result = $(this).sortable('toArray');
alert(result);
}
});
});
My question is this: Does Drupal already have a page I can use to update the nodes through jQuery.post or do I have to make my own one that will save the nodes? Also, is this the right way to go or is there a better way to update/save the node positions once the sortable box has been moved?
Many Thanks!
A: Ok, I thought I'd follow up my question with the solution I've found. It may help others. It's based heavily on the answer that googletorp gave to the very similar question posted here: Drupal 6/jQuery Ajax update a field.
Step 1.0 Create a new module.
I created a simple updatemynode.info file and updatemynode.module file.
1.1 updatemynode/updatemynode.module contains two functions.
function updatepos_menu() {
$items = array();
$items['update_positions'] = array(
'page callback' => 'update_node_position',
'type' => MENU_CALLBACK,
'access callback' => TRUE,
'access arguments' => array('access content'),
);
return $items;
}
This is the first function in the module that creates a URL www.mywebsite.com/update_positions which calls the php function 'update_node_position'. (see below)
1.2 updatemynode/updatemynode.module second function is:
function update_node_position() {
// Create an array from the passed string
$neworder = explode(",", $_POST['theorder']);
// For each array entry, redo their node weight (which Views sorts on)
foreach ($neworder as $key => $value){
$node = node_load($value);
$node->node_weight = ($key+1);
node_save($node);
}
}
For brevity and simplicity I have removed any error checking to it just completes a function and that's it. Basically, it does the following: A. Search for the $_POST['theorder'] variable (which contains a string of NID's in my app), use php 'explode' to convert the string to an array and assign to $neworder. B. For each entry of new array, use the value (NID) to load that Node. C. I'm using the 'Weight' module to create ordering. The $node->node_weight = ($key+1); line assigns the position in the array 1,2,3,4,etc.. to the node wight. (Thus creating an order). D. Save the node and repeat for each entry in array.
2.0 I have a main_javascript.js file that is attached to all of my drupal pages. This javascript file contains the following code:
$(function() {
$( ".sortable-nodes" ).sortable({
placeholder: "ui-state-highlight",
opacity: 0.7,
update: function(event, ui) {
// Create result variable that contains array order.
var result = $(this).sortable('toArray');
// Run AJAX function with RESULT data to update_positions page
$.ajax({
type: "POST",
url: "/update_positions",
// Pass the RESULT array
data: { theorder : [result]},
});
}
});
This is the crux of the jQuery and it does a few bits:
2.1 The object (which is a DIV in my case) labelled .sortable-nodes is made sortable using the jQuery 'sortable' method. When I click and drag the DIV it will do this:
2.2 Use the CSS class 'ui-state-highlight' in between each sortable DIV.
2.3 Reduce the opacity to 70%.
2.4 Once the position has been changed then it will run the 'update' event.
2.5 The 'update' event will create a variable called 'result' that contains a string of all the sortable object node id's . (eg. 113,114,115,116,117,etc... )
2.6 The .ajax method is run and is told to send a POST request to the /update_positions URL (created earlier in the updatemynode/updatemynode.module file) and pass the $_POST variable called 'theorder' which contains the string 'result'. Once the string 'result' is passed to the URL then the module function update_node_position() uses this string and does its magic as explained above.
3.0 My results on the page are ordered by the node weight using views. So, when the page is reloaded the order should stay the same as how you ordered it (because the node_weight has been updated) using the AJAX call.
Hope that maybe helps someone. Any questions/comments welcome!
A: Drupal doesn't already have this sort of functionality, unless you'd count using the Services module over jsonp which would take longer to setup than implementing the functionality yourself would.
In my opinion there isn't any better way to do this, any contributed module you could find to do it would likely be very bloated with lots of functionality you don't need. It's so easy to perform a post to a custom menu item that I'd recommend just doing that. You'll also have full control over the code then and can optimise it as you wish.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596120",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Mysql Query does not work as expected i'm having problems with a MySql query:
I have 2 tables as this:
Ips:
ID
timestamp
user_id
ip
dns
Blacklisted users:
timestamp
user_id
mod_id moderator
What I want to do is to get the number of user blacklisted with ips related to an specific user. My query right now seems like that:
SELECT count( bl.user_id ) AS c, ips_user.ip
FROM user_ips AS ips
INNER JOIN user_ips AS ips_user ON ips.ip = ips_user.ip
INNER JOIN user_blacklist AS bl ON ips_user.user_id = bl.user_id
WHERE ips.user_id = 239925
GROUP BY bl.user_id
But this query results in the number ip associated with the user id blacklisted, and does not search for others users with the same ip.
Thanks in advance for the answers.
A: You need to match your group by clause with the fields selected.
Normally you'd copy all non-aggregated fields in the select part in the group by clause.
Is this what you want?
SELECT
count( bl.user_id ) AS c
, ips_user.ip
FROM user_ips AS ips
INNER JOIN user_ips AS ips_user ON ips.ip = ips_user.ip
INNER JOIN user_blacklist AS bl ON ips_user.user_id = bl.user_id
WHERE ips.user_id = 239925
GROUP BY ips.user_ip <<-- should match field in the select clause
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: jquery ajaxStart/ajaxStop not working i have very simple code that i making partial postback by jquery and i use ajaxStart/ajaxStop for doing some work. but it is not working. i just could not understand why it is not working.
here is my code
$("#imgHolder").ajaxStart(function () {
$('div#content').block({
message: '<table><tr><td><img src="../images/ajax-loader.gif" border="0"/></td><td><h3>Processing...</h3></td></tr><table>',
css: { border: '1px solid #a00' }
});
$('#imgHolder').empty();
$("#btnPrint").hide();
});
$("#imgHolder").ajaxStop(function () {
$("#btnPrint").show();
$('div#content').unblock();
});
$(document).ready(function () {
$.ajax({
type: "POST",
url: "UPSLabelFormUK.aspx/ProcessInfo",
data: JSON.stringify(DTO),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d[0].Message == "SUCCESS") {
//alert(data.d[0].TrackNumber);
///alert(data.d[0].LabelImagePath);
var _images = [data.d[0].LabelImagePath];
$.each(_images, function (e) {
$(new Image()).load(function () {
$('#imgHolder').html("<img src='" + data.d[0].LabelImagePath + "' width='310' height='402' border=0/>");
}).attr('src', this);
});
}
} ,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
});
i just dont not understand why my above ajaxstart/ajaxstop did not work. please help me to understand why was wrong in my code.
but my ajaxstart/ajaxstop started working when i change the code a bit like
$(document).ajaxStart(function () {
$('div#content').block({
message: '<table><tr><td><img src="../images/ajax-loader.gif" border="0"/></td><td><h3>Processing...</h3></td></tr><table>',
css: { border: '1px solid #a00' }
});
$('#imgHolder').empty();
$("#btnPrint").hide();
});
$(document).ajaxStop(function () {
$("#btnPrint").show();
$('div#content').unblock();
});
the only change is $(document).ajaxStop(function () { instaed of
$("#imgHolder").ajaxStart(function () {
so please explain why my above ajaxStart/ajaxStop code did not work. thanks
A:
As of jQuery 1.8, the .ajaxStop() method should only be attached to document.
from jquery api web page of "ajaxStop". You can check it here.
A:
Given the fact that ajaxStart is only called if there are no other
ajax requests in progress, it makes is useless if you want to use it
as an AJAX loader indicator.
have u tried with ( tell me is it working or not)
jQuery(document).ajaxStart(function(){
alert("it begins");
})
A: Try this:
$("#loading").bind({
ajaxStart: function() { $(this).show(); },
ajaxStop: function() { $(this).hide(); }
});
Essentially binding your loadingAnimationElement to the globally fired ajaxStart and ajaxStop events. Only shows up when you intend it to.
When jQuery is not performing any Ajax requests and a new request is initiated, it fires an ajaxStart event. If other requests begin before this first one ends, those new requests do not cause a new ajaxStart event. The ajaxStop event is triggered when the last pending Ajax request is completed and jQuery is no longer performing any network activity.
A: Try this sample code:-
var $loading = $('#div_Loader').hide();
$(document).ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
setTimeout(function () {
$loading.hide();
}, 1000);
});
A: This combination works fine. Thanks to user @brroshan
JS of Master page
<script language="JavaScript" type="text/javascript">
$(document).ajaxStart(function () {
$("#loading").show();
});
$(function () {
// Some other code
// The end of this code block
$("#loading").hide();
$("#loading").bind({
ajaxStart: function () { $(this).show(); },
ajaxStop: function () { $(this).hide(); }
});
});
</script>
html of Master page
<div id="loading" class="display: none;">
<h2>Loading...</h2>
</div>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jpa result-set-mapping throw NPE I can't map query result to POJO.
JPA executes query ok (it trace in logs) but in mapping process throws a NPE.
What is wrong?
NPE:
java.lang.NullPointerException
at org.eclipse.persistence.queries.EntityResult.getValueFromRecord(EntityResult.java:147)
at org.eclipse.persistence.queries.ResultSetMappingQuery.buildObjectsFromRecords(ResultSetMappingQuery.java:165)
at org.eclipse.persistence.queries.ResultSetMappingQuery.executeDatabaseQuery(ResultSetMappingQuery.java:215)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:675)
at org.eclipse.persistence.queries.DatabaseQuery.executeInUnitOfWork(DatabaseQuery.java:589)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2857)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1225)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1207)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1181)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:453)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getResultList(EJBQueryImpl.java:681)
at com.silyan.meyem.view.visor.tienda.TiendaResources.delusuario(TiendaResources.java:284)
execution code:
List<TiendaTO> tiendas = entityManager.createNamedQuery("TiendaResources.tiendas_del_usuario", TiendaTO.class).setParameter(1, user.getId()).getResultList();
metadata:
<named-native-query name="TiendaResources.tiendas_del_usuario" result-set-mapping="TiendaTOMapping">
<query>
select
tienda.id as id,
tienda.nombre as nombre,
tienda.idporcliente as idporcliente,
tienda.cliente_id as clienteid,
ST_X(direccion.geolocalizacion) as x,
ST_Y(direccion.geolocalizacion) as y
from
user_tienda,
tienda,
direccion
where
user_tienda.user_id = ? and
tienda.id = user_tienda.tienda_id and
direccion.id = tienda.direccion_id
</query>
</named-native-query>
<sql-result-set-mapping name="TiendaTOMapping">
<entity-result entity-class="com.silyan.meyem.view.visor.tienda.TiendaTO" >
<field-result name="id" column="id"/>
<field-result name="idPorCliente" column="idporcliente"/>
<field-result name="nombre" column="nombre"/>
<field-result name="x" column="x"/>
<field-result name="y" column="y"/>
</entity-result>
</sql-result-set-mapping>
Plataform:
Glassfish 3.0.1 - eclipselink 2.0.1.v20100213-r6600
Thanks!
A: Is com.silyan.meyem.view.visor.tienda.TiendaTO mapped class? If not, then you are facing this problem: https://bugs.eclipse.org/bugs/show_bug.cgi?id=288957
But on the other hand "entity-result entity-class", it kind of makes sense that entity is expected, of course some implementations can support also other classes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7596134",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.