text stringlengths 8 267k | meta dict |
|---|---|
Q: Navigationbar is shown and but its not placed correctly in iphone When i call this method, the navigationbar is shown and its not placed correctly. Exactly navigation bar placed from 20pixels from top of simulator. How to solve this. I call this method before subclass. but next page navigation bar not placed correctly.
UtilityController *object=[[UtilityController alloc]initWithNibName:@"UtilityController" bundle:nil];
navigationController=[[UINavigationController alloc] initWithRootViewController:object];
[self.view addSubview:navigationController.view];
[object release];
How to solve this method. Thanks in advance.
A: You should set appropriate value of frame property of your navigationController, for exmaple:
navigationController.frame = CGRectMake(0, 0, 320, 460);
Also the best practice is to set UINavigationController as modal view:
[self presentModalViewController:navigationController animated:YES];
New example
UtilityController *object=[[UtilityController alloc]initWithNibName:@"UtilityController" bundle:nil];
navigationController=[[UINavigationController alloc] initWithRootViewController:object];
[self presentModalViewController:navigationController animated:YES];
[object release];
[navigationController release];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: NHibernate and NHibernate Validation Is it possible to validate domain model with Nhibernate validation framework in PreTranctionCommint event? If possible how we can write this event ?
A:
Is it possible to validate domain model with Nhibernate validation
framework... ?
If you really have a domain model then it does not need validation framework. In other words the objects encapsulate behavior and protect their internal invariants without relying on external magic-validation framework. Domain objects never get into 'invalid' state in the first place. If they are long-lived then they should also be 'always persistable'. The validity of your domain objects should not rely on the event that may or may not be fired by data access library. You can also find it helpful to not think about VALIDATION because it is overgeneralized and context dependent but instead think about business object INVARIANTS. You don't need thirdparty framework to properly enforce invariants in your objects. It is really not hard to implement it without coupling your domain classes to validation framework.
But if you rephrase your question to:
Is it possible to validate anemic domain model with Nhibernate validation
framework... ?
Then the answer would be: Yes, go for it, its awesome! But keep in mind that as complexity grows you would want to enforce more complex domain rules involving multiple object fields, separate domain services etc. You will either get more and more coupled to validation framework by writing 'custom validators' or just give up on it and end up with some rules implemented by framework and other spread all over the code base. It might be worth looking at this answer and DDD in general.
A: Excerpt below taken from http://nhforge.org/wikis/validator/nhibernate-validator-1-0-0-documentation.aspx
NHibernate event-based validation
NHibernate Validator has two built-in NHibernate event listeners.
Whenever a PreInsertEvent or PreUpdateEvent occurs, the listeners will
verify all constraints of the entity instance and throw an exception
if any of them are violated. Basically, objects will be checked before
any insert and before any update triggered by NHibernate. This
includes cascading changes! This is the most convenient and easiest
way to activate the validation process. If a constraint is violated,
the event will raise a runtime InvalidStateException which contains an
array of InvalidValues describing each failure.
A: how about this?
using(transaction...)
{
validationA();
validationB();
session.saveOrUpdate();(do some transaction)
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to create namespaces and classes in javascript / jQuery Just like C# or Java to put all my jQuery code in one .js file, something like this:
namespace MySite
{
class HomePage
{
function Init(params) { /*...*/ }
//...
}
class ContactForm
{
function Validate() { /*...*/ }
//...
}
}
So you can call it in this way:
$(function () {
MySite.HomePage.Init({a : "msg"});
});
I have this code, but doesn't work:
$.namespace = function () {
var a = arguments, o = null, i, j, d;
for (i = 0; i < a.length; i = i + 1) {
d = a[i].split(".");
o = window;
for (j = 0; j < d.length; j = j + 1) {
o[d[j]] = o[d[j]] || {};
o = o[d[j]];
}
}
return o;
};
$.namespace('$.mysite');
$.mysite.Home = function () {
function Home(params) {
//...
};
Home.prototype = function () {
Init: function () {
alert("lol");
}
}
};
Is it possible to that in jQuery? (something similar or recommendations / examples to keep my jquery code organized. )
Thanks for your time and answers (sorry for my bad english).
A: Why not just put it inside a js object?
var _o = {};
_o.module1 = {};
_o.module2 = {};
_o.module1.someFunc = function(){//code};
_o.module2.someFunc = function(){//code};
A: var MODULE = (function () {
var my = {},
privateVariable = 1;
function privateMethod() {
// ...
}
my.moduleProperty = 1;
my.moduleMethod = function () {
// ...
};
return my;
}());
If I understood well, you want to add your namespace under jQuery. To do that you need to use technique called sub moduling;
MODULE.sub = (function () {
var my = {};
// ...
return my;
}());
Or, you can use module import:
(function(jQuery){
jQuery.myNamespace = {};
jQuery.myNamespace.myFunc = function(arg){
console.log(arg);
};
}($));
After that you can run it like this:
$.myNamespace.myFunc("somevalue")
And it will write:
LOG: raera
For more techniques and examples, see http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth
A: var nameSpace= {};
nameSpace.nameSpace1= nameSpace.nameSpace1|| (function()
{
}());
A: MySite = {
HomePage : {
Init: function(params) { /*...*/ }
},
ContactForm: {
Validate: function() { /*...*/ }
}
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: user licencing, mobile web php I'm developing a mobile web for android, iphone & blackberry. We should enforce license for users. Let us say this product comes with 3 types of license.
*
*1 user 50USD
*3 user 100USD
*5 user 200USD
*10 user 300 USD and so on...
They say "if customer has purchased application for 3 users then he should be allowed to access the application only in 3 devices, when he tries to access the same in 4th device he should be sent to some error page"
Let me explain further, we are designing a table, order selection app for restaurant, where every table(or waiter) will have a mobile, he/she opens the application and orders for the selected table. In such case a web app can be accessed in any device and customer may buy and install the app on their server and ask every one to access. That means he'll buy the product for one device and uses in many. So through PHP we need to limit the product to only one device. Remember it can be any device he's wish whenever, whatever the device he might use application should be accessed by/on x devices.
How can we do this? Any suggestions are welcomed.
Thanks in advance.
A: (FWIW I'd be very skeptical of buying a product licenced per device rather than on the basis of a named user).
The problem will be differentiating between devices.
While browser finger printing can provide very impressive results these datasets are predominantly filled with desktop browsers - I suspect you would see a lot less variation between mobile browsers (when was the last time you installed a new font on your android / iphone).
A: make a database of allowed devices, and set those devices with a cookie or track the users ip address (not recommended since it changes). You might also want to look into UNIX timestamps for figuring out time operations related to this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Add events for before/after a action of a controller in Magento I have a controller in Magento as below:
#File: ./app/local/FilFact/Test/IndexController
class FilFact_Test_IndexController extends Mage_Core_Controller_Front_Action{
public function indexAction(){
$this->_testConfig();
}
}
I need to add two events for:
before index action
after index action
How could I do that?
A: This is simple as the Mage_Core_Controller_Varien_Action base class provides pre/post dispatch events.
If you open up the Mage_Core_Controller_Varien_Action class you find two methods: preDispatch() and postDispatch()
These method perform a few tasks and most importantly fire off three events.
controller_action_(pre|post)dispatch
controller_action_(pre|post)dispatch_{{routeName}}
controller_action_(pre|post)dispatch_{{fullActionName}}
The fullActionName is the route name, the controller name, and the action name separated by '_' and all lower case. (See Mage_Core_Controller_Varien_Action::getFullActionName for reference)
/app/code/local/FilFact/Test/etc/config.xml
<?xml version="1.0"?>
<config>
<modules>
<FilFact_Test>
<version>1.0.0</version>
<FilFact_Test>
</modules>
<global>
<models>
<FilFact_Test>
<class>FilFact_Test_Model</class>
</FilFact_Test>
</models>
</global>
<frontend>
<routers>
<filfact>
<use>standard</use>
<args>
<module>FilFact_Test</module>
<frontName>filfact</frontName>
</args>
</filfact>
</routers>
<events>
<controller_action_predispatch_filfact_index_index>
<observers>
<FilFact_Test>
<class>FilFact_Test/Observer</class>
<method>indexPreDispatch</method>
</FilFact_Test>
</observers>
</controller_action_predispatch_filfact_index_index>
<controller_action_postdispatch_filfact_index_index>
<observers>
<FilFact_Test>
<class>FilFact_Test/Observer</class>
<method>indexPostDispatch</method>
</FilFact_Test>
</observers>
</controller_action_postdispatch_filfact_index_index>
</events>
</frontend>
</config>
/app/code/local/FilFact/Test/Model/Observer.php
<?php
class FilFact_Test_Model_Observer
{
public function indexPreDispatch(Varien_Event_Observer $observer)
{
// TODO: Your code
}
public function indexPostDispatch(Varien_Event_Observer $observer)
{
// TODO: Your code
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510293",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: How to draw a layout of this type in android? I want to provide a background drawable, similar to the one shown in the figure, to a layout. How can i do it using a drawable xml? Please suggest a suitable approach to go about this.
A: It is not possible to do this with single xml drawable but probably you can club two to create this effect. I would do it this way
*
*Create a drawable of square type with black borders
*Create a clip drawable and clip the bottom of sqaure drawable.
Reference here
http://developer.android.com/guide/topics/resources/drawable-resource.html#Clip
You can use the android:gravity="top" and then programmatically set the level to reveal 90% (or more) of the image
ImageView imageview = (ImageView) findViewById(R.id.image);
ClipDrawable drawable = (ClipDrawable) imageview.getDrawable();
drawable.setLevel(drawable.getLevel() + 9500);
A: I know this is 4+ years after the fact but for anyone else wanting to achieve the same result, there's a very simple way to achieve this by creating a layer-list xml drawable.
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<padding
android:top="5dp"
android:left="5dp"
android:right="5dp" />
<solid
android:color="@android:color/black" />
</shape>
</item>
<item>
<shape>
<solid
android:color="@android:color/white" />
</shape>
</item>
</layer-list>
Save this to your project's drawable folder and reference it like any other drawable (android:src / android:background, or programatically)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: cakephp sha1 password saving in mysql I have forgot password feature in my cakephp application. The function for this will request the email address, find this user, generate a new password, convert it to sha1 and save it to the database, emailing the contents to the user.
Anyway I am having issues, the generated sha1 password is different to the one being saved.
I have called the info to the screen to show what is happening:
TEMP PASSWORD- lHQcVp4 (FROM THE FUNCTION)
Blockquote
SHA1 PASSWORD- 0ee4ae757733f458b9e395a8457c2ef307af99f0 (FROM sha1($user['User']['tmp_password']);
Auth Password PASSWORD- 93df9bd251620d0634235c22f4ab6fe9ad5421f4 (FROM: $this->Auth->password($user['User']['tmp_password']);)
DB Record After Save PASSWORD- 13ef648db45cc62b593c3943646806af06846016 (FROM $this->User->field('password');)
I am saving the data as follows: $this->User->save($user, false)
Why would it come though differently all 3 times? I cannot work it out. Very strange.
Thankyou
A: sha1($user['User']['tmp_password']
This will simply hash the password and output the text
$this->Auth->password($user['User']['tmp_password']);
This hashes the password with the cakephp salt defined in core.php. This is why you see a difference
If you simply set the password value to $user['User']['password'] and call save() on it, Auth might be hashing the password again since it doesn't know you've already hashed it. Have you tried just setting the password to $user['User']['password'] and calling save() on it? Let Auth handle the hashing for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CSS: why line-height disturbs the width? How does the line-height property in CSS works? If i set the line-height equal or less than the font size, it creates the problem with layout width. Please check this jsFiddle to see the problem.
I'm using font-size 14px, and line height 14px. If you change the line-height to 15px or more, the problem will be solved. Shouldn't the line-height only change the height, not disturb the width?
Please see the image below, as you see the #wrap has width of 300px, now because of line height the two div's of width 150px are not fitting into it.
I have checked with firefox and chrome, latest versions.
A: Line height is an inherited property but its inheritance works in a complicated way as compared to other inherited properties.
There is an excellent slideshow to Illustrate how line-height works depending on the units you specify the line height.
http://www.slideshare.net/maxdesign/line-height.
Slide 28 onwards explains your issue.
A: It has nothing to do with line height... not directly atleast. The two boxes will remain 150px wide regardless of whether you specify a line height or not. The overflow: auto causes a vertical scroll bar to appear (for reasons unknown to me) which reduces the available width of your container from 300px to ~280px hence the two colored boxes cannot appear side by side anymore. If you remove overflow: auto the result will appear as expected.
Edit
Revised demo here. To counter the vertical scrollbar, I added 1px padding on the container which seemed to counter the problem. For larger font sizes, use a padding of 2px.
A: In Chrome, if I increase the line height to 18px, the divs will be side by side, but the width doesn't change. Apparently this has something to do with the calculation of the height of #wrap. The browser cannot decide wether to show the scrollbar in #wrap or not. But since #wrap is exactly 300 wide, and thus can hold the two divs side by side only when the scrollbar isn't displayed, you'll have to force to hide it. Change #wrap overflow to hidden, or remove this property altogether.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Display a chart in a pop-up/modal on mouse click (jquery?) without loading chart first? (mvc3/razor) I'm using the FileStreamResult (or FileResult) method to display a chart on a razor view page (from a Controller action) and this works as expected.
However, I'm wondering if it's possible to display the chart ONLY when an html element is clicked.
e.g. Click on an element, display chart in modal pop-up.
I can get a modal to display using Jquery...but ONLY if I have already loaded the chart into a div.
I'd like to have the page load without the chart (for performance reasons), and then only generate/load the chart when the is clicked.
I guess I need an Ajax call of somekind...but I'm a little stuck as to how to proceed and googling didn't return anything useful (just lightbox for photos)
Pseudo Code:
HTML:
<img src='small chart icon.jpg' alt='click me to see chart' id='showchart'/>
<div>
rest of page goes here...
</div>
C#:
public FileStreamResult GetChart(){
//generate any chart
return FileStreamResult(newchartstream, "image/png");
}
JS:
<script>
$(document).ready(function(){
$('#showchart').click(function(){
//make ajax call to generate chart
//show in modal with "close" button
//OR
//open a new page as a modal?
});
});
</script>
EDIT
Clarification:
Controller generates a ViewModel (from an EF4 model) which contains the results of lots of calculations, and some "summary" rows (totals, averages etc)
View displays the results (ViewModel) as tables.
Requirement:
Click on one of the summary rows, opens modal window displaying a chart for that summary row.
Would like to avoid sendind the parameters for the ViewModel and re-generating it from scratch (doing all the calcs again etc) for two reasons
1) The figures in the back-end db may have changed...so the chart doesn't reflect whats being shown in the tables.
2) It takes time to do the calcs!
I'd also like to ONLY generate the chart if the row is clicked, as opposed to loading the chart always and hide() show() with jquery.
I've thought about an ajax call, but unsure about how to return an image, or how to open a new page.
Can't see a way to pass a complex model in the Url.Action() method.
Think caching may be the best option, and have the click method call "old fashioned" javascript for a new window, passing over the parameters to get the object from cache?
A: You have some difference question mixed in one. You should split them each in one question. For your question's title, -loading an image by AJAX- you can use code-snippet below:
HTML:
<div id="chartholder"></div>
<a id="showchart">Show the chart</a> <!-- or any element else you want to fire show event -->
JS:
$(document).ready(function(){
$("#showchart").click(function(){
// Put your controller and action (and id if presented) below:
var file = "/YourControllerToGetChart/GetChart/id"
$("<img />").attr("src", file).load(function () {
$(this) // the loaded image
.css({"some-css-you-want":"some-value"})
.appendTo($("#chartholder")); // fixed syntax
});
});
});
Let me know if you have any questions or need clarifications on any part or you want to know how to css the div id="chartholder" to display it as an modal. Cheers.
A: You have many ways to do that, but here is what I would do.
1/ Create an action which returns a tag with the good src (assuming that your controller's name is ChartsController).
public ActionResult GetImage(int chartId = 0)
{
var image = @"<img id='chart' src='" + Url.Action("GetChart", new {controller = "Charts", chartId = chartId}) + @"'/>";
return this.Content(image);
}
2/ I assume that, in your view, you have a div somewhere which contains your modal's content (like jQuery-ui would do) with an img inside, for the chart.
<div id="modal-div">
<div id="chart-div"></div>
</div>
3/ For every row, you have to create an Ajax link who will call your "GetImage" action and replace "chart-div" with your . You can specify a "OnBegin" Javascript function, this is where you will put your code to launch the modal.
@Ajax.ActionLink("Show me the chart!", "GetImage", "User", new { chartId = @Model.Rows[i]}, new AjaxOptions()
{
HttpMethod="GET",
OnBegin = "showModalWindow",
UpdateTargetId="modal-div",
InsertionMode = InsertionMode.Replace
});
Everytime you will click on an Ajax link, the modal will be launched and the inside will be replaced (in fact, all the content of the modal will be replaced).
Don't forget to include "Scripts/jquery.unobtrusive-ajax.js" and "Scripts/jquery.validate.unobtrusive.js" for the Ajax links to work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Searching multiple attributes for one value I am using this xpath expression
String expr = String.format("//a/b/c[@name1='%s']", name);
I am making an android app that searches a xml document for a name. I want it to search through both attributes name1 and name2 listed in the xml. As the expression is now, it searches name1 but if the name does not appear it force closes my app. If it is there it works as I planned. How can I get it to not only search both attribute values but if the name does not appear make sure the app does not force close?
Thanks
Ok figured the xpath part out, im just having it search all of the values
[@* = '%s']
But can anyone help me with the issue if the name does not appear in the xml? To return a response "the name is not valid"
A: The simplest solution is to surround your search with a try-catch block:
try {
// Do your search here
}
catch (Exception e) {
// Handle the situation where the name was not found here
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Custom username/password validator Is it possible to write a custom username/password validator which will be used in the adfs signin method (on the formssignin.aspx page)?
And if so, are there any examples?
A: This article customizing-the-ad-fs-2-0-sign-in-web-pages shows how to add two factor authentication.
This article modifying-and-securing-the-adfs-2-web-application shows how to create a VS project from the ADFS files on your dev. PC.
ADFS has a Master page and css files as well depending on how far you want to go.
Also, there's some info. here customizing-the-ad-fs-2-0-sign-in-web-pages about other changes you may care to make e.g.
*
*Customizing the Sign-In Pages Using Web.config
*ASP.NET Master Pages Overview
Hopefully, that will give you some direction.
ADFS out the box can only authenticate against AD. If you want a custom authentication mechanism, the classic solution is to create a custom STS e.g. Identity Server
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Transparent PNG in PIL turns out not to be transparent I have been hitting my head against the wall for a while with this, so maybe someone out there can help.
I'm using PIL to open a PNG with transparent background and some random black scribbles, and trying to put it on top of another PNG (with no transparency), then save it to a third file.
It comes out all black at the end, which is irritating, because I didn't tell it to be black.
I've tested this with multiple proposed fixes from other posts. The image opens in RGBA format, and it's still messed up.
Also, this program is supposed to deal with all sorts of file formats, which is why I'm using PIL. Ironic that the first format I tried is all screwy.
Any help would be appreciated. Here's the code:
from PIL import Image
img = Image.open(basefile)
layer = Image.open(layerfile) # this file is the transparent one
print layer.mode # RGBA
img.paste(layer, (xoff, yoff)) # xoff and yoff are 0 in my tests
img.save(outfile)
A: I think what you want to use is the paste mask argument.
see the docs, (scroll down to paste)
from PIL import Image
img = Image.open(basefile)
layer = Image.open(layerfile) # this file is the transparent one
print layer.mode # RGBA
img.paste(layer, (xoff, yoff), mask=layer)
# the transparancy layer will be used as the mask
img.save(outfile)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: cookie values disappear when traversing between content pages in my app. there's a log in mechanism which save a cookie with the info of the user who just logged in
private void CreateCookie(LoginEventArgs args)
{
HttpCookie cookie = new HttpCookie("user");
cookie.Values["name"] = args.User_Name;
cookie.Values["id"] = args.ID;
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
}
on my master page load i perform a check to see if this cookie exists or not :
HttpCookie cookie = Request.Cookies["user"] ;
if( (cookie != null) && (cookie.Value != ""))
{
if (Session["user"] == null)
Login_Passed(this, new LoginEventArgs(cookie.Values["name"].ToString(), int.Parse(cookie.Values["id"])));
}
now if i Log in ( Create A cookie ) , close the browser , and run my app. again the cookie
exists it's values are correct and the user is "automatically" logged in .
if i first redirect to a different content page from the start up content page
the cookies values are also intact ,
the problem is when i redirect back to a different content page a second time,
the master page loads , makes the check
the cookie exists but the values are deleted ...
any ideas on why this happens ?
btw maybe the way i log out could be the reason for this problem :
when i log-out i create a cookie with the same name that expires 1 day ago .
private void Remove_Cookie()
{
HttpCookie cookie = new HttpCookie("user");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
in the case iv'e described i don't log-out formally , i just end my app , so this shouldn't
have any effect .
A: To reiterate and build upon what has already been stated (yes, I know this is a 4 year old question) I have found it best to build a utility to handle this - mostly because I want to check that specific cookie often.
This will not touch the Response but only read from the Request.
public static HttpCookie GetCookie(string cookieName)
{
HttpCookie rqstCookie = HttpContext.Current.Request.Cookies.Get(cookieName);
/*** NOTE: it will not be on the Response!
* this will trigger the error noted in the original question and
* create a new, empty cookie which overrides it
*
HttpCookie respCookie = HttpContext.Current.Response.Cookies.Get(cookieName);
*
*/
if (rqstCookie != null && !String.IsNullOrEmpty(rqstCookie.Value))
{
// is found on the Request
return rqstCookie;
}
else
{
return null;
}
}
rule-of-thumb
Always read from the Request and write to the Response.
Thanks eran! this post was exactly what I needed
A: o'k , the problem was unthinkable
special thanks to Peter Bromberg
http://www.eggheadcafe.com/tutorials/aspnet/198ce250-59da-4388-89e5-fce33d725aa7/aspnet-cookies-faq.aspx
in the section of the Article " The Disappearing Cookie "
the author states that if you have a watch on Response.Cookies["cookie_name"]
the browser creates a new empty cookie that overrides your cookie .
i used such a watch which made my cookie loose it's values ,and when i took it off the cookie kept its values.
the moral is DON't WATCH Response.Cookies[" "]
also i read in some other post that if you check
if( Response.Cookies["cookie_name"] != null )
for example it also gets overridden.
A: try the following:
*
*If you are developing on your local machine, put your app on some free web page, so there will be no 'special treatment' because you're in the local host.
*If you already are on a web-server, and if the re-directions are between tow different domains, you may want to search google for 'same origin policy' or read this: http://en.wikipedia.org/wiki/Same_origin_policy (the document talks about javascript, but its true also for cookies).
A: Use the following approach to get a value from cookies:
public string GetValueFromCookies(HttpCookieCollection cookies)
{
if (cookies == null)
{
throw new ArgumentNullException(nameof(cookies));
}
// check the existence of key in the list first
if (Array.IndexOf(cookies.AllKeys, key) < 0)
{
return null;
}
// because the following line adds a cookie with empty value if it's not there
return cookies[key].Value;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: UML use case diagram problem with relations between actors and use cases i've been created the following diagram for forums system but i'm not sure if the relation between use cases and actors is correct.
so i want to know if my diagram is correct or if i've added too much complexity to my diagram. did i got my use cases relation with the actors correctly? well to better say, is it correct at all?
any help is really appreciated.
A: Not a bad effort for a first attempt, but I'd say it is a bit over complex. When you do analysis, using use cases or some other method, you really do want to keep it simple and avoid going into design mode, which is when you start thinking about relationships between things.
In my opinion, your actors should not be generalizations of one another. A "person who posts" on a forum is not a a more specific type of a "person who reads posts": they are different roles which the same person might take on at different times, not expansions on one another. So I'd advise you to drop those generalizations.
The same goes for the use cases themselves. Normally, use cases relate to one another by way of either the <<extend>> or <<include>> relationship, but generalizations or not normally used. Use cases aren't like classes and don't really have the option of being abstract, so the "manage" use cases need to make sense on their own, and they don't really do that. Your "concrete" use cases, on the other hand, make perfect sense.
In order to group related use cases together, it's a better idea to use separate diagrams and / or gather the use cases into packages called "post management", "site administration", etc. There is nothing which says you have to put all your use cases into a single diagram.
A: I support your method of use case diagrams. I struggled with this very issue a while back. To show each association from one use case to each of the actors was getting messy. By generalizing the actors, it consolidated the associations into a nice, easily readable format. Thus, the information is easier for others to consume.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the syntax for GotoIf with & condition in asterisk server? exten => s,n,GotoIf($["${choice}" = "*"] & $["${isharvesttoday}" = "1"]?question4)
The above line is not worked in my application. Is this syntax is correct?
A: No, it isn't. This should work:
exten => s,n,GotoIf($[$["${choice}" = "*"] & $["${isharvesttoday}" = "1"]]?question4)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why do parameters passed by reference in C++ not require a dereference operator? I'm new to the C++ community, and just have a quick question about how C++ passes variables by reference to functions.
When you want to pass a variable by reference in C++, you add an & to whatever argument you want to pass by reference. How come when you assign a value to a variable that is being passed by reference why do you say variable = value; instead of saying *variable = value?
void add_five_to_variable(int &value) {
// If passing by reference uses pointers,
// then why wouldn't you say *value += 5?
// Or does C++ do some behind the scene stuff here?
value += 5;
}
int main() {
int i = 1;
add_five_to_variable(i);
cout << i << endl; // i = 6
return 0;
}
If C++ is using pointers to do this with behind the scenes magic, why aren't dereferences needed like with pointers? Any insight would be much appreciated.
A: When you write,
int *p = ...;
*p = 3;
That is syntax for assigning 3 to the object referred to by the pointer p. When you write,
int &r = ...;
r = 3;
That is syntax for assigning 3 to the object referred to by the reference r. The syntax and the implementation are different. References are implemented using pointers (except when they're optimized out), but the syntax is different.
So you could say that the dereferencing happens automatically, when needed.
A: C++ uses pointers behind the scenes but hides all that complication from you. Passing by reference also enables you to avoid all the problems asssoicated with invalid pointers.
A: When you pass an object to a function by reference, you manipulate the object directly in the function, without referring to its address like with pointers. Thus, when manipulating this variable, you don't want to dereference it with the *variable syntax. This is good practice to pass objects by reference because:
*
*A reference can't be redefined to point to another object
*It can't be null. you have to pass a valid object of that type to the function
How the compiler achieves the "pass by reference" is not really relevant in your case.
The article in Wikipedia is a good ressource.
A: There are two questions in one, it seems:
*
*one question is about syntax: the difference between pointer and reference
*the other is about mechanics and implementation: the in-memory representation of a reference
Let's address the two separately.
Syntax of references and pointers
A pointer is, conceptually, a "sign" (as road sign) toward an object. It allows 2 kind of actions:
*
*actions on the pointee (or object pointed to)
*actions on the pointer itself
The operator* and operator-> allow you to access the pointee, to differenciate it from your accesses to the pointer itself.
A reference is not a "sign", it's an alias. For the duration of its life, come hell or high water, it will point to the same object, nothing you can do about it. Therefore, since you cannot access the reference itself, there is no point it bothering you with weird syntax * or ->. Ironically, not using weird syntax is called syntactic sugar.
Mechanics of a reference
The C++ Standard is silent on the implementation of references, it merely hints that if the compiler can it is allowed to remove them. For example, in the following case:
int main() {
int a = 0;
int& b = a;
b = 1;
return b;
}
A good compiler will realize that b is just a proxy for a, no room for doubts, and thus simply directly access a and optimize b out.
As you guessed, a likely representation of a reference is (under the hood) a pointer, but do not let it bother you, it does not affect the syntax or semantics. It does mean however that a number of woes of pointers (like access to objects that have been deleted for example) also affect references.
A: The explicit dereference is not required by design - that's for convenience. When you use . on a reference the compiler emits code necessary to access the real object - this will often include dereferencing a pointer, but that's done without requiring an explicit dereference in your code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510336",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Editable list through html, javascript Here is the UI scenario I'm trying to develop:
There is a text box field below which there are two buttons. On clicking the first button , there will be a popup in which the user will have to add a IP address. On pressing submit on the popup , the IP address will be displayed in the text area. The user can keep on adding IP addresses, which will be visible on the text area in different lines.
The user should be able to select a particular IP address from the box and delete it using the second button.
The user should not be able to enter data directly into the text field. Any ideas ?
A: I would suggest you keep clear of using a <textarea> since this involves sniffing selections etc. Instead, use simple container elements (e.g., <li>s in a <ul>/<ol> cf. @David Thomas' comment) to hold the entered IP addresses (one each).
I trust you'll get the idea from this JsFiddle.
HTML
<ul id="addresses"></ul>
<hr />
<a href="#" id="add">Add...</a>
JS (Assuming jQuery. You would need some framework to handle selections too.)
var deleteHandler = function() {
$(this).parent().remove();
}
$("#add").click(function() {
var ip = prompt("Enter IP:");
if (ip) {
var $deleteIp = $("<a />", {"class": "delete"})
.text("X")
.click(deleteHandler);
$("<li />")
.text(ip)
.append($deleteIp)
.appendTo("#addresses");
}
return false;
});
Just a demo — deemed to be a candidate for improvements :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Modal Popup Extender: Fetch data from database then bind it to the label in the modalpopupextender I've a problem with ModalPopupExtender. I have put a label in ModalPopupExtender and trying to bind label with the value from database. When I am debugging, the value is showing on the label's text (ie there is no database error), but it is not displaying when the popup window is shown.
Can any one help me please ????????
Here's my code
Code on html
<asp:Panel ID="PopupPnl" runat="server">
<table style="width:100%;">
<tr>
<td >
<asp:Label ID="Label2" runat="server"
Text="View Description" >
</asp:Label>
</td>
</tr>
<tr>
<td >
<asp:Label ID="label_Descrption" runat="server" >
</asp:Label>
</td>
</tr>
<tr style="background-color:White;">
<td >
<asp:Button ID="btnExit" runat="server" Text="Exit"/>
</td>
</tr>
</table>
</asp:Panel>
<asp:Button ID="btnShowPopup" runat="server"
style="display:none;"/>
<cc1:ModalPopupExtender ID="ModalPopupExtender2" runat="server"
TargetControlID="btnShowPopup"
PopupControlID="PopupPnl"
CancelControlID="btnExit"
BackgroundCssClass="ModalPopupBG" >
</cc1:ModalPopupExtender>
Code on c#
protected void lbn_Template_Click(object sender, EventArgs e)
{
util_Category objUtilCategory = new util_Category();
cl_Category objClCategory = new cl_Category();
if (ddlSubCategory.SelectedItem.Text != "--Select A SubCategory--")
{
objClCategory.CategoryId = Convert.ToInt32(ddlSubCategory.SelectedValue);
Label lbl = (Label)PopupPnl.FindControl("label_Descrption");
label_Descrption.Text = objUtilCategory.GetATemplate(objClCategory);
ModalPopupExtender2.Show();
}
}
A: You need to place the Panel which contains the label_Description inside UpdatePanel.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Handling ascii char in python string i have file having name "SSE-Künden, SSE-Händler.pdf" which having those two unicode char ( ü,ä) when i am printing this file name on python interpreter the unicode values are getting converted into respective ascii value i guess 'SSE-K\x81nden, SSE-H\x84ndler.pdf' but i want to
test dir contains the pdf file of name 'SSE-Künden, SSE-Händler.pdf'
i tried this:
path = 'C:\test'
for a,b,c in os.walk(path):
print c
['SSE-K\x81nden, SSE-H\x84ndler.pdf']
how do i convert this ascii chars to its respective unicode vals and i want to show the original name("SSE-Künden, SSE-Händler.pdf") on interpreter and also writeing into some file as it is.how do i achive this. I am using Python 2.6 and windows OS.
Thanks.
A: Assuming your terminal supports displaying the characters, iterate over the list of files and print them individually (or use Python 3, which displays Unicode in lists):
Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> for p,d,f in os.walk(u'.'):
... for n in f:
... print n
...
SSE-Künden, SSE-Händler.pdf
Also note I used a Unicode string (u'.') for the path. This instructs os.walk to return Unicode strings as opposed to byte strings. When dealing with non-ASCII filenames this is a good idea.
In Python 3 strings are Unicode by default and non-ASCII characters are displayed to the user instead of displayed as escape codes:
Python 3.2.1 (default, Jul 10 2011, 21:51:15) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> for p,d,f in os.walk('.'):
... print(f)
...
['SSE-Künden, SSE-Händler.pdf']
A: for a,b,c in os.walk(path):
for n in c:
print n.decode('utf-8')
A: For writing to a file: http://docs.python.org/howto/unicode.html#reading-and-writing-unicode-data
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can we thread the web-service and insert in in custom table cell? The thing is i have to make Custom cell of UITable, i have to call large webservice with many data which will take longer tym to load it once. So i want to apply threading in it. now my que is. can we at run -time insert value one by one in custom cell , as user will see data comming one by one at run time..?? if yes how we can do that.
A: yes you can ... try this
- (void)viewDidLoad
{
myApp = (myAppDelegate *) [[UIApplication sharedApplication] delegate];
[self performSelectorInBackground:@selector(startParsing) withObject:nil];
[super viewDidLoad];
}
- (void) startParsing
{
[self performSelectorOnMainThread:@selector(startIndicator) withObject:nil waitUntilDone:NO];
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSURL *url = [[NSURL alloc] initWithString:@"http://abc.com"];
NSData *data = [NSData dataWithContentsOfURL:url];
// 2 -- parsing
parser = [[VolMyParser alloc] init];
[parser parseXML:data];
[data release];
//[parser print];
[self performSelectorOnMainThread:@selector(updateTable) withObject:nil waitUntilDone:NO];
[pool release];
}
- (void) startIndicator
{
av.hidesWhenStopped = YES;
[av startAnimating];
}
- (void) updateTable
{
[av stopAnimating];
[myTable reloadData];
}
Hope its gives you an Idea...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I encode the & symbol for batch requests? I have a Facebook batch request that looks like this:
https://graph.facebook.com/?access_token=ACCESS_TOKEN&batch=[{"method": "GET", "relative_url": "search?q=EMAIL@ADDRESS.COM&type=user"}]
Sending this across the wire returns:
{"error"=>0, "error_description"=>"batch parameter must be a JSON array"}
If I remove the &type=user, it works fine (sends back an empty data array). I am absolutely certain that Facebook is not parsing the & character correctly. I read online somewhere that I could try encoding the & symbol to %26, however using that replacement seems to instead do a query for "EMAIL@ADDRESS.COM%26type=user". If you reverse the order of the parameters, you will see what I mean.
Any ideas how I can get the batch request parser on Facebook to recognize the & symbol without filing a bug report that will never be fixed?
EDIT:
I am using URI.encode. Here is the exact code:
queries = email_array.map { |email| { :method => "GET", :relative_url => "search?q=#{email}&type=user" } }
route = "https://graph.facebook.com/?access_token=#{token}&batch=#{URI.encode(queries.to_json)}"
res = HTTParty.post(route)
A: After actually playing around with this some more, I managed to reproduce the same behavior, even with a careful check and double-check that I was following the api specs correctly. This looks like a bug in facebook's batch method -- it doesn't understand ampersands in param values correctly.
A: Don't use a string literal to construct the json. Use to_json, like below. (Also, as an aside, don't use {} notation across more than one line, use do/end).
queries = []
email_array.each do |email|
queries << {:method => 'GET', :relative_url => "search?q=#{email}&type=user"}
end
route = "https://graph.facebook.com/?access_token=#{token}&batch=#{URI.encode(queries.to_json)}"
res = HTTParty.post(route)
Also, you can use Array#map to simply the code, like this:
queries = email_array.map { |email| {:method => 'GET', :relative_url => "search?q=#{email}&type=user"} }
route = "https://graph.facebook.com/?access_token=#{token}&batch=#{URI.encode(queries.to_json)}"
res = HTTParty.post(route)
EDIT: below is my original answer before the question was edited, for reference.
Try properly url encoding the whole parameter:
https://graph.facebook.com/?access_token=ACCESS_TOKEN&batch=[%7B%22method%22:%20%22GET%22,%20%22relative_url%22:%20%22search?q=EMAIL@ADDRESS.COM&type=user%22%7D]
In practice, you'd use URI.encode from the uri library to do this. Example:
irb(main):001:0> require 'uri'
=> true
irb(main):002:0> URI.encode('[{"method": "GET", "relative_url": "search?q=EMAIL@ADDRESS.COM&type=user"}]')
=> "[%7B%22method%22:%20%22GET%22,%20%22relative_url%22:%20%22search?q=EMAIL@ADDRESS.COM&type=user%22%7D]"
Or even better, use to_json to create your json string in the first place. Example:
irb(main):001:0> require 'rubygems'
=> true
irb(main):002:0> require 'json'
=> true
irb(main):003:0> require 'uri'
=> true
irb(main):004:0> URI.encode([{:method => 'GET', :relative_url => 'search?q=EMAIL@ADDRESS.COM&type=user'}].to_json)
=> "[%7B%22method%22:%22GET%22,%22relative_url%22:%22search?q=EMAIL@ADDRESS.COM&type=user%22%7D]"
A: If this helps anyone, when my AdSet batch update failed because there was an "&" in one of the interests name:
{u'id': u'6003531450398', u'name': u'Dolce & Gabbana'}
I learned that the name can be anything, and as long as the id is correct, FB will populate the name itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Help with shell script What does this script do?
if [ -f /../../file1] then
. /../../file1
fi
It checks if file1 exists. What does the then statement do?
A: In bash . is equivalent to source. It reads file1 and runs it in the current bash process.
A: It contains several errors.
/../../file1 doesn't make much sense as a file name. /.. would be the parent of the root directory; normally the root directory is its own parent, so /../../file1 is probably just an odd way to write /file1.
Whitespace is required around both [ and ], and the ] should be followed by either a semicolon or a newline.
With those problems corrected, it does what the other answers say it does.
A: It cheecks if the file exists and, if it does, it sources the file (running the commands from the file in the current process). For example, if the file contains export lines, the environment variables will be set in the current process.
As an example, on ubuntu, the default .bashrc file has the following lines:
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
This instructs bash to run all the commands from ~/.bash_aliases if the file exists.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510358",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to Pause and Resume Downloading Files with ASIHTTP Request in iPhone I m using ASIHTTP Request sample source code for downloading urls.
My question is that how to pause and resume the downloading files.
Please Help.
A: Deprecation Notice
ASIHTTP was deprecated around 2011, if you want network connectivity now, you should look up AFNetworking for ObjC or Alamofire for Swift, or stick to the native support:
For native support, in iOS 7 Apple added the NSURLSession, which can start download tasks (NSURLSessionDownloadTask), and these can be cancelled and restarted, check the method downloadTaskWithResumeData(_:) from NSURLSession, that has a very good explanation.
ASIHTTP is no longer needed, if you gotta are keeping a legacy app running, well, good luck.
Original Answer
Posted on 2011
ASI itself can resume a download from a file using [myASIRequest setAllowResumeForFileDownloads:YES];, check out the How-to-Use for an example.
Edit: Ok, there's no easy way to pause a download (a [myRequest pause] would be ideal). After reading and trying for a while, turns out that cancelling the request and resending it again is the only way.
For example, here's an example class I made:
@interface TestViewController : UIViewController <ASIHTTPRequestDelegate>
{
ASIHTTPRequest *requestImage;
UIImageView *imageViewDownload;
}
@property (nonatomic, retain) IBOutlet UIImageView *imageViewDownload;
- (IBAction)didPressPauseButton:(id)sender;
- (IBAction)didPressResumeButton:(id)sender;
To start (or restart) the download:
- (IBAction)didPressResumeButton:(id)sender
{
if (requestImage)
return;
NSLog(@"Resumed");
// Request
requestImage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://www.myheadhealth.com/_IMAGES/cheese.jpg"]];
// Using a temporary destination path just for show.
// Better pick a suitable path for your download.
NSString *destinationDownloadPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"cheese.jpg"];
NSString *temporaryDownloadPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"cheese.jpg-part"];
requestImage.downloadDestinationPath = destinationDownloadPath;
requestImage.temporaryFileDownloadPath = temporaryDownloadPath;
requestImage.allowResumeForFileDownloads = YES;
requestImage.delegate = self;
[requestImage startAsynchronous];
}
In the exmaple above, I'm loading a random image of cheese I found, and storing a temporary download, and a full download.
Canceling the request will keep the contents of the temporary file intact, in fact, I made an UIImageView, and when pressing "Cancel" I could see a part of the downloaded file. If you want to try it out:
- (void)didPressPauseButton:(id)sender
{
if (requestImage)
{
// An imageView I made to check out the contents of the temporary file.
imageViewDownload.image = [UIImage imageWithContentsOfFile:requestImage.temporaryFileDownloadPath];
[requestImage clearDelegatesAndCancel];
requestImage = nil;
NSLog(@"Canceled");
}
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
imageViewDownload.image = [UIImage imageWithContentsOfFile:request.downloadDestinationPath];
requestImage = nil;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Swedish text Localization on iphone I want to know about localization.The exact requirement is copy/paste text should be changed to swedish text accordingly while entering the text in UITextField.Can any one have source code or example link for this?
I meant the copy/paste tip text appears when editing the UITextfied.How to change this to swdish text?
A: I'm not sure if you can have dynamic text in localization, i guess you should call google translator so it translates the copied text, you'll get a json response for that.
Take a look here for example:
http://www.raywenderlich.com/1448/how-to-translate-text-with-google-translate-and-json-on-the-iphone
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to place a star mark beside a not null textbox in winform like we can do in webform How to place a star mark beside a not null textbox in winform like we can do in webform. And does winform has a value-required validator like in webform ?
A: Use ErrorProvider control instead. It is meant for that kind of situation.
According to MSDN: "ErrorProvider - Provides a user interface for indicating that a control on a form has an error associated with it."
You can learn how to use it here:
http://msdn.microsoft.com/en-us/library/system.windows.forms.errorprovider%28v=VS.90%29.aspx#Y0
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Gibberish in read() buffer? I am new to C, and so I am completely confused by the following behavior. Using pipe() and fork() I am reading the output of the following trivial ruby program:
puts "success"
via a call to the read function in C:
n = read(fd[0], readbuffer, sizeof(readbuffer));
printf("received: %s", readbuffer);
However, printf is printing a bunch of those 'unrecognised character' symbols (like the question mark in a diamond) to the console. Furthermore, doing a comparison like:
if (strcmp(readbuffer, "success") == 0)
{
/* do something */
}
fails. What am I doing wrong?
Edit: Declarations as requested. I have no idea about memsetting, my first day in C.
int fd[2], in;
pid_t pid;
char readbuffer[6];
Edit:
The answer by 'mu is too short' also solves the problem. The consensus seems to be that using memset is overkill. I am a novice C programmer so I will have to believe the commentors' opinions. This is, however, argumentum ad populum and mu is too short may indeed be more in the right. In any case, I recommend a reading of both answers as any 'overkill' is probably still trivially so.
A: As others have pointed out, your buffer isn't big enough to hold the text you're reading, and you don't ensure it's null terminated.
But using memset() to zero the entire buffer before each read is unnecessary; you just need to ensure that there's a null at the end of data you've read (and make your buffer bigger of course).
If you make readbuffer at least 9 characters long, and replace:
n = read(fd[0], readbuffer, sizeof(readbuffer));
..with..
n = read(fd[0], readbuffer, sizeof(readbuffer) - 1);
readbuffer[n] = '\0';
..then that should do it (though you should ideally check that n is >= 0 to make sure the read() succeeded). Specifying one less than the size of the read buffer ensures that readbuffer[n] won't overrun (but if read() failed it could underrun).
Then you'll just have to deal with the linefeed at the end.
This also assumes that the entire string is read in one read call. It's likely in this case, but often when using read its necessary to concatenate multiple reads until you've read enough of the data.
A: As the comments note, you won't have a null terminator on readbuffer so it isn't really a C string. You could do this:
#include <string.h>
/* ... */
memset(readbuffer, 0, sizeof(readbuffer));
n = read(fd[0], readbuffer, sizeof(readbuffer) - 1);
That will give you a proper null terminated string. But, if you actually want a string of length 6, then change the declaration of readbuffer to:
char readbuffer[7];
If you only need your readbuffer once, you could say:
char readbuffer[7] = { 0 };
to initialize it to all zeros. However, if you're doing the read in a loop then you'll want to memset(readbuffer, 0, sizeof(readbuffer)) before each read to make sure you don't end up with any leftover data from the last step.
C won't automatically initialize a local variable, you have to do it yourself.
A: As I understand it, your line:
puts "success"
will output (in C-terms)
success\n\0
which I count as 9 characters.
You declared readbuffer as only 6. The previous answer only upped it to 7.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Assembly Language: difference between ja and jg? I am having trouble understanding the difference between ja and jg for assembly language. I have a section of code:
cmp dh, dl
j-- hit
and am asked which conditional jump to hit (that replaces j-- hit) will be taken with the hex value of DX = 0680.
This would make dl = 06 and dh = 80, so when comparing, 80 > 06. I know that jg fits this as we can directly compare results, but how should I approach solving if ja fits (or in this case, does not fit) this code?
A: The difference between ja and jg is the fact that comparison is unsigned for ja and signed for jg (treating the registers as signed vs unsigned integers).
If the numbers are guaranteed to be positive (i.e. the sign bit is 0) then you should be fine. Otherwise you have to be careful.
You really can't intuit based on the comparison instruction itself if ja is applicable. You have to look at the context and decide if sign will be an issue.
A: *
*If dx is 0x0680, then dh is 0x06 and dl is 0x80.
*0x80 is interpreted as 128 in unsigned mode, and -128 in signed mode.
*Thus, you have to use jg, since 6 > -128, but 6 < 128. jg does signed comparison; ja does unsigned comparison.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Does PHP have an ordered dictionary? Does PHP have an Ordered Dictionary, like that in Python? IE, each key value pair additionally has an ordinal associated with it.
A: That's how PHP arrays work out of the box. Each key/value pair has an ordinal number, so the insertion order is remembered. You can easily test it yourself:
http://ideone.com/sXfeI
A: If I understand the description in the python docs correctly, then yes.
PHP Arrays are actually only ordered maps:
An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.
PHP Array docs
A: PHP arrays work this way by default.
$arr = array('one' => 1, 'two' => 2, 'three' => 3, 'four' => 4);
var_dump($arr); // 1, 2, 3, 4
unset($arr['three']);
var_dump($arr); // 1, 2, 4
$arr['five'] = 5;
var_dump($arr); // 1, 2, 4, 5
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: AJAX:CalendarExtender does not localize Today I'm using the CalendarExtender from the AJAX library with the possibility of localization. Currently everything works fine except when I try to localize it for the Danich (da-DK) language. The calendar looks localized, except the part that says "Today" that remains in English. How do you localize that part too?
PS. And if localization is not possible, can I hide "Today" part of the calendar?
A: Re:
PS. And if localization is not possible, can I hide "Today" part of the calendar?
As we deemed it more work that it was worth to add our own resources, we decided to hide the "Today" bit. This was however easily done by adding the following to our css file:
.ajax__calendar_footer {
display: none;
}
A: By default Ajax Control Toolkit doesn't localized for the Danish. You need to customize toolkit soulution a bit. Download toolkit sources and add Danish resource file into MicrosoftAjax.Extended project (ExtenderBase folder). You may just create a copy of BaseScriptsResources.resx file and change copy file name to "BaseScriptsResources.ds.resx". I believe you easy find which resource value in that file you must change for your language.
After that add that file as a link into ScriptResources folder of the AjaxControlToolkit's project. When you build up solution you will find a new folder with a Danish resource assembly in project's bin folder (da/AjaxControlToolkit.resources.dll). Just copy that folder with a dll to your project's bin folder.
A: We just had the same problem in a legacy project using an old version of AjaxControlToolkit (4.1), after localization to a specific language has been added. And I definitely did not want to compile my own version of AjaxControlToolkit.
Thus, after digging through CalendarExtender's JavaScript source, I noticed that the text is loaded from a resource, and that this resource can be modified. To make a long story short, if you update Sys.Extended.UI.Resources.Calendar_Today (default: Today: {0}) in JavaScript
*
*after the Toolkit's scripts have been loaded but
*before the user opens the Calendar for the first time,
then the resource value is replaced by your value:
<!-- Add this to the bottom of your page -->
<script type="text/javascript">
Sys.Extended.UI.Resources.Calendar_Today = "Σήμερα: {0}";
</script>
Obviously, if your application is multi-lingual, you will have your own translation resource files:
<script type="text/javascript">
Sys.Extended.UI.Resources.Calendar_Today =
'<%= HttpUtility.JavaScriptStringEncode(Resources.MyTexts.Today) %>';
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: JPA 2.0 / Hibernate and "orphanRemoval": Just replacing an entity does not remove the old one I have question regarding JPA 2.0, Hibernate and "orphanRemoval".
First my setup:
*
*Spring 3.0.5.RELEASE
*SprnigData JPA 1.0.1.RELEASE
*Hibernate 3.5.2-Final
*DBMS: PostgreSQL 9.0
I have two rather simple entity classes, "User" and "AvatarImage", A "User" has an "AvatarImage", and so between "User" and "AvatarImage" there is the relationship.
In the class "User", the property looks like this:
// class "User"
@OneToOne(cascade = CascadeType.ALL, fetch=FetchType.LAZY, orphanRemoval = true)
private AvatarImage avatarImage;
So that means, if the "avatarImage" property gets set to null, the reference between "User" and "AvatarImage" is removed and "orphanRemoval" mechanism will delete the "avatarImage" from the database (please correct me if I'm wrong).
So when I update the "avatarImage" for a certain user, I currently have to write this:
user.setAvatarImage( null ); // First set it to null
userRepository.save( user ); // Now "orphanRemoval" will delete the old one
user.setAvatarImage( theNewAvatarImage );
userRepository.save( user );
So setting the "avatarImage" property first to null, saving the "user", and then set the new AvatarImage "theNewAvatarImage", again saving the user.
This is the only way it currently works for me - the "orphanRemoval" will delete the old "avatarImage" on setting it to "null" and then saving the user.
But, I would have thought that this code should also work:
user.setAvatarImage( theNewAvatarImage );
userRepository.save( user );
So I omit setting the "avatarImage" to "null" but just setting "theNewAvatarImage", replacing the old "avatarImage". But this does not work, the old AvatarImage does not get removed from the database upon transaction commit.
Does anyone know, why the second code (just replacing the AvatarImage without setting it to "null" before) does not work?
I really appreciate any help you can offer
Thanks a lot!
A: This is related to Hibernate JIRA tickets HHH-5559 and HHH-6484. By and large, Hibernate, as of today, requires you to set the reference to null and flush the persistence context, before providing a new value to the relationship (see the test case in HHH-6484); it is only in such a case that Hibernate issues a SQL DELETE statement, providing a broken implementation (IMHO) for orphanRemoval.
In short, you'll need to wait for the bugs to be fixed, or write code to nullify references and flush the persistence context, or use a JPA provider that supports orphanRemoval in this manner (EclipseLink 2.3.0 does).
A: As of @OneToMany relationship, this is related to Hibernate JIRA ticket HHH-6709. Please vote for these so it get some attention.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Python: map widgets to database for reading and editing it I am relatively new to database GUI programming, and I want to make a simple app in Python, which allows user to access and edit database. I want to view/edit tables and specific records plus generate some specific reports about stored data. For example, if we have a table with employees name and position, it should allow to edit name and select position from list and immediately change database according to changes. For one employee record it should output name and, again give a selectable list of positions. Also, it should have a dialog to add employees.
So, is there a way to create widgets for data tables and specific records which allows to output and edit data with automatic changes in database? I want to reduce the need for writing methods, which look at changes in view and reflect them at model.
I am using PyQt for writing GUI. Solutions for SQL, or ORMs like SQLAlchemy would both be fine.
A: You can use the Qt Database GUI Layer.
If you want to use SQLAlchemy too, you can take a look at Camelot.
UPDATE
A good introduction to the Qt Database GUI Layer is chapter 15 of the book
"Rapid GUI Programming with Python and Qt".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: List manipulation in XUL I'm trying to figure out an easy way to edit/add/delete items on a list in XUL. My initial thought is to have a separate file to handle all of this but I'm not sure on how to affect the main XUL with another file. So far my list looks like:
<?xml version = "1.0"?>
<!DOCTYPE window>
<window title = "Hello"
xmlns:html="http://www.w3.org/1999/xhtml"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" >
<script>
</script>
<listbox id = "mainList" flex = "1">
<listhead>
<listheader label = "Album Name"/>
<listheader label = "Artist"/>
<listheader label = "Year"/>
<listheader label = "Sales"/>
<listheader label = "Rating"/>
<listheader label = "Genre"/>
<listheader label = "Edit" />
<listheader label = "Delete"/>
</listhead>
<listitem id = "1">
<listcell label = "OK Computer"/>
<listcell label = "Radiohead"/>
<listcell label = "1997"/>
<listcell label = "Platinum"/>
<listcell label = "5/5"/>
<listcell label = "Alternative Rock"/>
<button label = "Edit" oncommand= "editItem()"/>
<button label = "Delete" oncommand = "deleteItem()"/>
</listitem>
<listitem>
<listcell label = "The Moon and Antarctica"/>
<listcell label = "Modest Mouse"/>
<listcell label = "2000"/>
<listcell label = "Gold"/>
<listcell label = "4.5/5"/>
<listcell label = "Alternative Rock"/>
<button label = "Edit"/>
<button label = "Delete"/>
</listitem>
<listitem>
<listcell label = "Pinkerton"/>
<listcell label = "Weezer"/>
<listcell label = "1996"/>
<listcell label = "Gold"/>
<listcell label = "5/5"/>
<listcell label = "Alternative Rock"/>
<button label = "Edit"/>
<button label = "Delete"/>
</listitem>
<listitem>
<listcell label = "Helplessness Blues"/>
<listcell label = "Fleet Foxes"/>
<listcell label = "2011"/>
<listcell label = "Gold"/>
<listcell label = "4/5"/>
<listcell label = "Folk Pop"/>
<button label = "Edit"/>
<button label = "Delete"/>
</listitem>
</listbox>
</window>
Pretty simple but I'm confused about what javascript I need to make the buttons actually work. Ideally I'd want to have an Add button that will open a new window with blank fields for each of the columns, and then add the new row to the list. What would be the best way to accomplish this?
A: You use the regular DOM manipulation functions. When adding items dynamically it is easier if you have a "template" somewhere that you can clone and modify, e.g.:
<listitem id="template" hidden="true">
<listcell class="album"/>
<listcell class="title"/>
<listcell class="year"/>
<listcell class="group"/>
<listcell class="rating"/>
<listcell class="category"/>
<button label="Edit" oncommand="editItem()"/>
<button label="Delete" oncommand="deleteItem()"/>
</listitem>
You can then add a new item like this:
var item = document.getElementById("template").cloneNode(true);
item.removeAttribute("id");
item.removeAttribute("hidden");
item.getElementsByClassName("album")[0].setAttribute("label", albumName);
item.getElementsByClassName("title")[0].setAttribute("label", songName);
...
document.getElementById("mainList").appendChild(item);
Changing text of an existing item is similar. You have to get the new text from somewhere - adding text fields for editing is your responsibility however, the list has no built-in editing capabilities.
Removing items is obviously simpler:
var item = document.getElementById("item1");
item.parentNode.removeChild(item);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do you attribute a sale to PPC if a visitor comes from PPC but then returns to buy through another medium? On an e-commerce site, how do you attribute a sale to PPC if a visitor comes from PPC but then returns to buy through another medium?
Can we use cookies and if so how do we install this? What software could track this kind of conversion scenario?
A: Google analytics (new interface) has a feature called multi channel funnels.
You can see the metrics in that report.
Based on what keywords and sources people in this funnel came to your site with, you would need to assign a weight/value to each stage that lead to the sale.
i.e.
First search: men's running shoes (ppc)
Second search: Nike trainers (ppc)
Third search: Nike Air Max 90 (organic)
If you didn't have the first search query then perhaps they wouldnt have come back to your site for the second and third time. Thus you have to assign a value to the first search term..
The values you need to assign will be bespoke to you, but this is essentially what you should be looking at..
Hope that helps. :-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: error NoMethodError (undefined method `+' for ActiveRecord::Associations::BelongsToAssociation:0xb6c9b45c) I'm using Rails 2.3.11. I have 2 tables customers and posts:
# Table name: customers
# id :integer(4) not null, primary key
# Name ::string(255) default("Anonymous")
...
class Customer < ActiveRecord::Base
has_many :posts
...
# Table name: posts
# id :integer(4) not null, primary key
# customer_id :integer(4)
...
class Post < ActiveRecord::Base
belongs_to :customer
...
In my posts_controller, I wanted to return the XML response for a GET call, with corresponding post and customer details.
@customer = Customer Details
@posting = Corresponding Post
Following line throws the error NoMethodError (undefined method '+' for ActiveRecord::Associations::BelongsToAssociation:0xb6c9b45c):
respond_to do |format|
format.xml { render :xml => (@customer + @posting)}
This looks to be a very trivial issue and I'm missing some basics here. Can some one help me understand this error.
A: Sounds like you need this:
format.xml { render :xml => @posting.to_xml(:include => :customer) }
If you ever want the posts a customer has created you would use:
format.xml { render :xml => @customer.to_xml(:include => :posts) }
Just an FYI.. I would name the singular instance version of your object the same.. So a Post object would be @post :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Business Layer in 3 tier Architecture I went for an interview, and was asked to show up my Business layer architecture. I have some idea about 3 tier architecture but really no idea, to what to write in front of interviewer.
So suppose my project deals with Employees of an organization, then what would i have written there. Will it be any kind of diagrams i should have made or some coding part. I worked in C# framework 3.5. I really don't understand what else to mention in this question, so please let me know if something is required.Thanks.
Edit
I worked in winforms.
I know what Business layer is, but was not sure what to tell the interviewer as business layer has codes and obviously my project was a bit big, so there were huge numbers of codes. So what i should have written there??
A: a 3 tier Architecture is composed by 3 Main Layers
*
*PL Presentation Layer
*BLL Business Logic Layer
*DAL Data Access Layer
each top layer only asks the below layer and never sees anything on top of it.
When They ask you about How will you build your BLL, you can write something like:
namespace Company.BLL
{
// let's create an interface so it's easy to create other BLL's if needed
public interface ICompanyBLL
{
public int Save(Order order, UserPermissions user);
}
public class Orders : ICompanyBLL
{
// Dependency Injection so you can use any kind of BLL
// based in a workflow for example
private Company.DAL db;
public Orders(Company.DAL dalObject)
{
this.db = dalObject;
}
// As this is a Business Layer, here is where you check for user rights
// to perform actions before you access the DAL
public int Save(Order order, UserPermissions user)
{
if(user.HasPermissionSaveOrders)
return db.Orders.Save(order);
else
return -1;
}
}
}
As a live example of a project I'm creating:
PL's are all public exposed services, my DAL handles all access to the Database, I have a Service Layer that handles 2 versions of the service, an old ASMX and the new WCF service, they are exposes through an Interface so it's easy for me to choose on-the-fly what service the user will be using
public class MainController : Controller
{
public IServiceRepository service;
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
...
if (thisUser.currentConnection.ws_version == 6)
// Use old ASMX Web Service
service = new WebServiceRepository6(url, ws_usr, ws_pwd);
else if (thisUser.currentConnection.ws_version == 7)
// Use the brand new WCF Service
service = new WebServiceRepository7(url, ws_usr, ws_pwd);
...
}
}
In the code above, I simply use Dependency Injection to separate the knowladge of the other layer, as at this layer (the Presentation Layer as this is a Controller in a MVC project) it should never care about how to call the Service and that the user uses ServiceA instead of ServiceB... What it needs to know is that calling a IService.ListAllProjects() will give the correct results.
You start dividing proposes and if a problem appears in the service connection, you know that's nothing to do with the Presentation Layer, it's the service Layer (in my case) and it's easy fixed and can be easily deployed a new service.dll instead publishing the entire website again...
I also have a helper that holds all Business Objects that I use across all projects.
I hope it helps.
A: Business logic is defined as any application logic that is concerned with the retrieval, processing, transformation, and management of application data; application of business rules and policies; and ensuring data consistency and validity. To maximize reuse opportunities, business logic components should not contain any behavior or application logic that is specific to a use case or user story. Business logic can be further subdivided into the following two categories:
*
*Business Workflow. After the UI components collect the required data from the user and pass it to the business layer, the application can use this data to perform a business process. Many business processes involve multiple steps that must be performed in the correct order, and may interact with each other through an orchestration. Business workflow define and coordinate long running, multi step business processes, and can be implemented using business process management tools. They work with business process components that instantiate and perform operations on workflow components.
*Business Entity Business Entity entities, or—more generally—business objects, encapsulate the business logic and data necessary to represent real world elements, such as Customers or Orders, within your application. They store data values and expose them through properties; contain and manage business data used by the application; and provide stateful programmatic access to the business data and related functionality. Business entities also validate the data contained within the entity and encapsulate business logic to ensure consistency and to implement business rules and behavior.
A: 3 Tier is as follows,
*
*Your presentation in one layer.
*Your application logic in other layer -- called business layer.
*Your Data Access classes in third layer. -- called Data Layer.
Webforms will be presentation layer
So for employee class doing anything in ASP.Net code behind file can be considered business layer per my understanding as you are applying business rules using if/else and so forth.
Data Access classes in App_Code folder would be Data Layer.
In case of desktop apps form designs would be presentation layer, form code will be business layer and anything related to accessing database would be data layer.
A: Business layer layer that responsible for all business logic. For example
you have Organizarion so organization and collection of employee.
In employee object need to implement some restriction or some rules.
This rules will be implemented in this layer.
A: A 3-tier architecture is a type of software architecture which is composed of three “tiers” or “layers” of logical computing. They are often used in applications as a specific type of client-server system. 3-tier architectures provide many benefits for production and development environments by modularizing the user interface, business logic, and data storage layers.
Business Logic Layer: Business logic is the programming that manages communication between an end user interface and a database. The main components of business logic are business rules and workflows.
A Business Logic Layer (BLL) that serves as an intermediary for data exchange between the presentation layer and the DAL. In a real-world application, the BLL should be implemented as a separate Class Library project in App_Code folder in order to simplify the project structure. below illustrates the architectural relationships among the presentation layer, BLL, and DAL.
The BLL Separates the Presentation Layer from the Data Access Layer and Imposes Business Rules
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: how to use different package for different device in android? Hi i have develop a application in android which run in every device, i use different layout for different size device's but i have use some code programmatically without xml so, it create a problem in different size device.
so i require to change the package acording to the device resolution so, it can posible in android to programmatically detect and change the package class
plz, give some suggestion.
Thanking you.
i have use android2.2 for my application
A: No, it is not possible to programmatically change the application package. For device-specific display sizes you can create size-specific layouts as described in the guide and use getResources().getConfiguration() to programmatically choose specific code paths to execute.
A: Another way:
Create an installer app which checks the device configuration and downloads the device-specific package afterwards from a ftp/network resource.
After installation, delete the installer and the .apk file.
A: "i use different layout for different size device's " means you just use dp/dip sizes or that you have completely different layouts for each screen size?
If you only used dp/dip units, then you can add a scalefactor to your code to get the matching coordinates. If you are using different layouts, it's much more difficult. Depending on how many different layout configurations you have, you could build seperate apk files and upload them parallel. The Market will handle the distribution of the matching files then.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can I disable the refactor preview in Eclipse? When renaming a variable using Eclipse, I always get a popup dialog showing me a preview of the refactoring. Is there some way I can disable this popup dialog? In other words, I want to place the cursor over a variable name, press alt+shift+r, edit the variable name, press enter, and have the renaming take place without ever seeing the preview. Is there some preference or setting for this?
I"m using Eclipse 3.6 (Helios)
UPDATE:
To test this, I did the following. I created a new Java Project and added the following class to the package.
public class TestRename{
private int var;
}
This is the only code in the project and still when I try to rename var I get a preview dialog in which I have to click "OK" to make the change. I'm pretty sure this wasn't the default behavior in Eclipse, but I must have edited the defaults somehow. I just don't know what I did or how to reset the preview behavior of the refactor.
A: I'm also using Helios, a dialog only appears when you are potentially creating a name conflict or refactoring code that has compile errors.
A: There is a preference under "Java" for this called "Rename in editor without dialog". If this is not selected, the rename dialog will show up every time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Can i cp migration files from one ror project to another? I just tried to cp those migration files from my former projects to my present project so that i won't generate the similar db structure again.
but after i tried "rake db:migrate" and edit some controllers it shows that it can not find those models even if it was migrated successfully.
so i rolled back and tried to recreate those files and did copy-paste staff and it finally works.
can anyone explain why to me?
thanks.
A: Instead of just copying over the migration *.rb files, I would suggest that you go through them manually and combine them.
Just copy/pasting everything is a bad idea.
A: Migrations only create tables, not models. To create models, you need to copy files from app/models/ directory too. And copying migrations should work, they're just files with timestamp (it doesn't matter it timestamp is from before project was created, it just has to be unique) which maps to create table/alter table/... commands of your database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to specify a condition in an Entity Framework join? I have a Blogs table related to BlogComments table with a FK.
I need to get, through Linq, all the BlogComments items that match a certain flag
If i do:
db.Blogs.Where(b => b.BlogComments.Where(bc=>bc.Where(bc.Flag1==true));
I get "Cannot implicity convert type IEnumerable to bool"
Which is the best way to solve this problem?
A: Because this expression:
b.BlogComments.Where(...)
returns an IEnumerable (of BlogComments), but you are then passing it into this method:
db.Blogs.Where(...)
which expects a function that returns a bool, not an IEnumerable.
You probably need something like this:
var blogId = 5;
db.BlogComments.Where(bc => bc.BlogId == blogId && bc.Flag1 == true)
If you need to select comments from multiple blogs, then you could try using Contains:
var blogIds = new [] {1,2,3,4,5};
db.BlogComments.Where(bc => blogIds.Contains(bc.BlogId) && bc.Flag1 == true)
If you want to place criteria on the set of blogs, as well as the comments, then you could do this in one query using a join:
var query = from b in db.Blogs
join c in db.BlogComments on c.Blog equals b
where b.SomeField == "some value"
&& c.Flag1 == true
select c;
A: You could write it in LINQ form.
var blogs = from b in db.Blogs
join c in db.BlogComments
on b.BlogId equals c.BlogId
where c.Flag1
select b;
If you have a composite key you can write
on new { A = b.BlogKey1, B = b.BlogKey2 }
equals new { A = c.CommentKey1, B = c.CommentKey2 }
A: If it were me, I would just have another DbSet in your DbContext.
DbSet<BlogComment> BlogComments
and just search through there without going through Blogs.
db.BlogComments.Where(bc => bc.Flag1 == true);
If anyone knows if there's anything wrong in doing so, then I'm all ears :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How does my plugin appear under the WYSIWYG Editor in "Create new article"-Screen I have written a Wordpress Plugin and now I want, that the Plugin appears (HTML Form) in the "Create New Article"-Screen unter the WYSIWYG Editor (after installation and activation). How can this be done. In the Codex and other sources I haven't found anything related to that problem.
BR & Thanks in advance,
mybecks
A: Are you aware of this feature in wordpress add_meta_box()
There is every thing available.you want!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting transparent SVGs to work in both IE and Safari? This seems like an either or to me. I can get them to work in one or the other, but not both (while working fine in Firefox no matter how I do it).
I've been reading a lot on the subject, and unless it's already been fixed by Safari, it seems flat-out external svg is not supported by and does not render correctly in Safari when they have transparency and you want to see other elements underneath. The only solution for that is to put the svg inline in your html and it works fine. Of course to do that it has to be xhtml which isn't supported by less than IE 9.
Please correct me if I'm wrong on either of these counts, but I very much like using SVG and the power it has, yet just today I tested these problems again with IE and Safari, using a single chunk of SVG data, that works inline and externally in firefox, and will not work in Safari when external, and of course does not work inline in xhtml with IE <=8.
I can't see an easy way to hack a solution given the above without making two separate sites made in completely different ways. Obviously the best chance seems to lie with getting external svg files to work with Safari, does anyone know any tricks that I haven't read about? There doesn't seem to be much out there on the subject.
Cheers
A: This demo works on Safari/Chrome/FF/IE9. SVG does not work (embedded or referenced) in earlier versions of IE, so it won't work there.
In short:
*
*Make your document served as XHTML
*Embed SVG directly within it with the proper namespace.
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="content-type"
content="application/xhtml+xml; charset=utf-8" />
<title>Transparent SVG</title>
</head><body>
<svg xmlns="http://www.w3.org/2000/svg">
<!--
this SVG will have a transparent background
and blend over any content below it.
-->
</svg>
</body></html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Which one to use Http Handler or Http Module We want to do something like we have to execute some piece of code in each request to the application. We want to use this same code in multiple applications.
What this code will do is, this will check the incoming request and according to some conditions it will decide whether it has to redirect or not.
So while searching i found that we can use either http handler or http module. But i am not sure about which one has to chose in this case? Please give your suggestions.
A: HttpModule in this case. It sits in the pipeline where you can inspect each and every request.
How To Create an ASP.NET HTTP Module Using Visual C# .NET
http://support.microsoft.com/kb/307996
HttpHandler is altogether different thing. If you implement HttpHandler for existing file types such as .aspx etc, you will have implement what is already implemented by ASP.NET runtime which is beyond the scope of your requirement.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: When is a call to "synchronize()" not necessary in C++ AMP? Background: For a C++ AMP overview, see Daniel Moth's recent BUILD talk.
Going through the initial walk-throughs here, here, here, and here.
Only in that last reference do they make a call to array_view.synchronize().
In these simple examples, is a call to synchronize() not needed? When is it safe to exclude? Can we trust parallel_for_each to behave "synchronously" without it (w/r/t the proceeding code)?
A: my_array_view_instance.synchronize is not required for the simple examples I showed because the destructor calls synchronize. Having said that, I am not following best practice (sorry), which is to explicitly call synchronize. The reason is that if any exceptions are thrown at that point, you would not observe them if you left them up to the destructor, so please call synchronize explicitly.
Cheers
Daniel
A: Just noticed the second question in your post about parallel_for_each being synchronous vs asyncrhonous (sorry, I am used to 1 question per thread ;-)
"Can we trust parallel_for_each to behave "synchronously" without it (w/r/t the proceeding code)?"
The answer to that is on my post about parallel_for_each:
http://www.danielmoth.com/Blog/parallelforeach-From-Amph-Part-1.aspx
..and also in the BUILD recording you pointed to from 29:20-33:00
http://channel9.msdn.com/Events/BUILD/BUILD2011/TOOL-802T
In a nutshell, no you cannot trust it to be synchronous, it is asyncrhonous. The (implicit or explicit) synchronization point is any code that tries to access the data that is expected to be copied back from the GPU as a result of your parallel loop.
Cheers
Daniel
A: Use synchronize() when you want to access the data without going through the array_view interface. If all of your access to the data uses array_view operators and functions, you don't need to use synchronize(). As Daniel mentioned, the destructor of an array_view forces a synchronize as well, and it's better to call synchronize() in that case so you can get any exceptions that might be thrown.
The synchronize function forces an update to the buffer within the calling context -- that is if you write data on the GPU and then call synchronize in CPU code, at that point the updated values are copied to CPU memory.
This seems obvious from the name, but I mention it because other array_view operations can cause a 'synchronize' as well. C++ AMP array_view tries it best to make copying between the CPU and GPU memory implict -- any operation which reads data through the array view interface will cause a copy as well.
std::vector<int> v(10);
array_view<int, 1> av(10, v);
parallel_for_each(av.grid, [=](index<1> i) restrict(direct3d) {
av[i] = 7;
}
// at this point, data isn't copied back
std::wcout << v[0]; // should print 0
// using the array_view to access data will force a copy
std::wcout << av[0]; // should print 7
// at this point data is copied back
std::wcout << v[0]; // should print 7
A: I'm betting that it's never safe to exclude because in a multi-threaded (concurrent or parallel) it's never safe to assume anything. There are certain guarantees which certain constructs give you but, you have to super careful and meticulous not to break these guarantees by introducing something which you think is fine to do but when in reality there's a lot of complexity underpinning the whole thing.
Haven't spent any time with C++-AMP yet but I'm inclined to try it out.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Dead sessions in apache mina We have a apache mina based GPRS gateway(server). Sometimes, usually when the connection is terminated from client side brutally i.e, power cable unplugged or any other unusual shutdown or some problem with network, it is not removed or closed at server side. It remain there, in idle state, for I don,t know how long( may be forever).
At times we face issues while shutting the server down, MINA take too much time and at times we have to kill it eventually. We suspect that this issue is related to dead connection problem.
Actually, this dead connection make sense. Since the connection is closed brutally and mina don't have a way to check it (that's how tcp session works).
We as a workaround, devised a solution that we will close session if it remain idle (both read and write) for let say 30 min(or any configurable time). Which we do not like for 2 reasons:
1- It doesn't look nice.
2- Plus we have a rule that client make a persistent connection with the server. So, it's a bit difficult to set an 'idle timeout' as we can't just close any session which has been idle for x min/hrs as it can be a valid connection.
So, is there any nicer and more safer (in our case) way to detect and clean these dead connection in MINA?
A: In both cases long not active connection and lost connection - having no activity in channel should result in timeout after configured time in every layer of OSI model.
E.g. you firewall/router/server may timeout inactive connection entry in 10 minutes, then you application layer connection should also do that after 10 minutes - waiting more makes no sense.
To prevent silent connections from timeout keep-alive protocol should be introduced.
It may be ping (not exactly ICMP) or other form of periodic no-operation communication.
When peer is alive it should respond and thus refresh timeout countdown on all network layers. After failed attempt caused by timeout or layer signaling broken connection you can assume that your application layer connection is also broken.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Rails: redirect_to with :error, but flash[:error] empty I'm trying to do a redirect while setting the flash[:error] value. (Rails 3.0.10)
In my view I have
<p id="error"><%= flash[:error] %></p>
<p id="notice"><%= flash[:notice] %></p>
If I do a redirect_to show_path, :notice => "ok" it works fine, but if I do redirect_to show_path, :error => "error" it doesn't show up.
what could I be missing?
A: As stated in the Rails API only :notice and :alert are by default applied as a flash hash value. If you need to set the :error value, you can do it like this:
redirect_to show_path, flash: { error: "Insufficient rights!" }
A: If you are having problem to keep the flash after redirecting to another path, then use this.
flash.keep
in your method, before redirecting.
A: To truly follow the PRG pattern, I wonder if this project works well
https://github.com/tommeier/rails-prg
I can't stand apps not following PRG as a user.....I have been 6 pages after a POST and hit the back button to get back to 10 pages ago get blocked by "do you want to repost this crap"....no, of course not. I just want to get back to a page I had seen before.
non-PRG apps are very very annoying to users.
A: controller.rb
flash[:sucess] = "Your sucess message"
redirect_to action: :index
layout.html
<% if flash[:sucess] %>
<div class="alert alert-solid-success alert-bold" role="alert">
<div class="alert-text"><%= sanitize(flash[:sucess]) %></div>
</div>
<% end %>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "127"
} |
Q: how to manually add simulators in blackberry eclipse? Is there any way to add a simulator manually in my eclipse? In android SDK,we have options for selecting various emulators.Likewise,is there any way so that I can choose any one from the various simulators available?
A: Yeah, it can do it. Download simulators from RIM's Software Download for Device Simulators page and you can see how to add them from the support forum thread: how to add another simulator to eclipse
A: As Ajmal said when you install a simulator it will be added to your simulator list in Eclipse. Select a simulator from "Device" dropdown menu within run configurations as shown in screenshot. The sim package number will correspond to a simulator you installed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: When should we change a String to a Stringbuilder? In an application a String is a often used data type. What we know, is that the mutation of a String uses lots of memory. So what we can do is to use a StringBuilder/StringBuffer.
But at what point should we change to StringBuilder?
And what should we do, when we have to split it or to remplace characters in there?
eg:
//original:
String[] split = string.split("?");
//better? :
String[] split = stringBuilder.toString().split("?);
or
//original:
String replacedString = string.replace("l","st");
//better? :
String replacedString = stringBuilder.toString().replace("l","st");
//or
StringBuilder replacedStringBuilder = new StringBuilder(stringBuilder.toString().replace("l","st);
A: In your examples, there are no benefits in using a StringBuilder, since you use the toString method to create an immutable String out of your StringBuilder.
You should only copy the contents of a StringBuilder into a String after you are done appending it (or modifying it in some other way).
The problem with Java's StringBuilder is that it lacks some methods you get when using a plain string (check this thread, for example: How to implement StringBuilder.replace(String, String)).
What we know, is that a String uses lots of memory.
Actually, to be precise, a String uses less memory than a StringBuilder with equivalent contents. A StringBuilder class has some additional constant overhead, and usually has a preallocated buffer to store more data than needed at any given moment (to reduce allocations). The issue with Strings is that they are immutable, which means Java needs to create a new instance whenever you need to change its contents.
To conclude, StringBuilder is not designed for the operations you mentioned (split and replace), and it won't yield much better performance in any case. A split method cannot benefit from StringBuilder's mutability, since it creates an array of immutable strings as its output anyway. A replace method still needs to iterate through the entire string, and do a lot of copying if replaced string is not the same size as the searched one.
If you need to do a lot of appending, then go for a StringBuilder. Since it uses a "mutable" array of characters under the hood, adding data to the end will be especially efficient.
This article compares the performance of several StringBuilder and String methods (although I would take the Concatenation part with reserve, because it doesn't mention dynamic string appending at all and concentrates on a single Join operation only).
A:
What we know, is that the mutation of a String uses lots of memory.
That is incorrect. Strings cannot be mutated. They are immutable.
What you are actually talking about is building a String from other strings. That can use a lot more memory than is necessary, but it depends how you build the string.
So what we can do is to use a StringBuilder/StringBuffer.
Using a StringBuilder will help in some circumstances:
String res = "";
for (String s : ...) {
res = res + s;
}
(If the loop iterates many times then optimizing the above to use a StringBuilder could be worthwhile.)
But in other circumstances it is a waste of time:
String res = s1 + s2 + s3 + s4 + s5;
(It is a waste of time to optimize the above to use a StringBuilder because the Java compiler will automatically translate the expression into code that creates and uses a StringBuilder.)
You should only ever use a StringBuffer instead of a StringBuilder when the string needs to be accessed and/or updated by more than one thread; i.e. when it needs to be thread-safe.
But at what point should we change to StringBuilder?
The simple answer is to only do it when the profiler tells you that you have a performance problem in your string handling / processing.
Generally speaking, StringBuilders are used for building strings rather as the primary representation of the strings.
And what should we do, when we have to split it or to replace characters in there?
Then you have to review your decision to use a StringBuilder / StringBuffer as your primary representation at that point. And if it is still warranted you have to figure out how to do the operation using the API you have chosen. (This may entail converting to a String, performing the operation and then creating a new StringBuilder from the result.)
A: If you frequently modify the string, go with StringBuilder. Otherwise, if it's immutable anyway, go with String.
To answer your question on how to replace characters, check this out: http://download.oracle.com/javase/tutorial/java/data/buffers.html. StringBuilder operations is what you want.
Here's another good write-up on StringBuilder: http://www.yoda.arachsys.com/csharp/stringbuilder.html
A: If you need to lot of alter operations on your String, then you can go for StringBuilder. Go for StringBuffer if you are in multithreaded application.
A: Both a String and a StringBuilder use about the same amount of memory. Why do you think it is “much”?
If you have measured (for example with jmap -histo:live) that the classes [C and java.lang.String take up most of the memory in the heap, only then should you think further in this direction.
Maybe there are multiple strings with the same value. Then, since Strings are immutable, you could intern the duplicate strings. Don't use String.intern for it, since it has bad performance characteristics, but Google Guava's Interner.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can I chain two rails Queries together elegantly? I have the following model object:
#<Insight id: 155, endorse_id: 15, supporter_id: 15, created_at: "2011-09-22 02:27:50", updated_at: "2011-09-22 02:27:50">
Where Endorse has_many insights and Supporter has many insights.
I can query the db in the following way:
Endorse.find(15).insights.count
Insight.find_all_by_supporter_id(15).count
How can I elegantly chain both of these queries together where I can search for all Insights created by Endorse 15, and Supporter 15?
A: Rails2:
insight_count = Insight.count(:conditions => {:supporter_id => 15, endorse_id => 15})
insights = Insight.all(:conditions => {:supporter_id => 15, endorse_id => 15})
Rails3:
insight_count = Insight.where(:supporter_id => 15, endorse_id => 15).count
insights = Insight.where(:supporter_id => 15, endorse_id => 15).all
A: Try this
For Rails 3.0.x and probably 3.1
Endorse.find(15).insights.find_all_by_supporter_id(15).count
For Rails 2.3.x
Endorse.find(15).insights.find_all_by_supporter_id(15).length
A: I'm not sure you would want to chain them together since each one is a different query. If there were relationships between them, then it would make sense to me. For example, if Endorse contained Insights which contained Supporters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: QR Reader in android I want to integrate QR Reader in my android app without integrating third party tool and also need auto scan feature .I reviewed few tutorials using zxing libraries but scanning is not done in them.It generally captures image to sdcard and then access it and which doesnt give result every time....
Please help experts .
A: If you want to Integrate QR reader which is not a third party tool, then i suggest download the Zxing code which is an open source.
*
*Call the activity which initiates the scan, from your app activity.
*Regarding saving to the sd card, Zxing doesn't do that, it analyzes the image in focus and tried to find the match until the activity is cancelled or a match is found.
*Have a look at ZXing QR reader app before you can integrate it in yours.
I have integrated the ZXing QR reader successfully and it works without a problem. Requires some effort though. Good luck.
A: Take a look at the Zxing Barcode Scanner app, which does QR Code decoding with auto scanning.
I'm sure of it, because i used it last week :)
BarcodeScanner.apk
Greetings Ralf
A: Integrate ZXing's Barcode Scanner app with your app without having to install the app separately.
Step-By-Step Guide
A: A great alternative is Google's barcode scanner available in the Google Play services through the namespace com.google.android.gms.vision.barcode. It's fast and robust (it does all the parsing locally) and it's all made with just a few classes, giving you full control of the source code. And of course it supports all the standard barcode formats.
A good place to get started is Android QR Code Reader Made Easy. This will get you up and running in no time and you can easily build further upon the code provided or equally easily implement it in your existing project!
Give it a try, I bet you'll love it!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Paypal IPN Problem I am developing a site where users can buy features using paypal. If user's paypal email is different from the email stored in our site how can i get notified about the user's payment via IPN?
A: You tagged your question with C#, so I'm assuming you're developing an ASP.NET site. And in the absence of more specific information, I'm going to assume you're using the default SqlMembershipProvider for your site.
So, to identify your user, you should probably use the ProviderUserKey property of the MembershipUser object. Use the following code to get the ProviderUserKey for your currently logged-in user:
MembershipUser currentUser = Membership.GetUser();
string userId = currentUser.ProviderUserKey.ToString();
Once you have a String containing the ProviderUserKey, you can pass it to PayPal using the custom HTML variable in your form:
<input type="hidden" name="custom" value="<%=userId%>"/>
When PayPal send the IPN message, it will send back the value that you set for the custom HTML variable. You can get the value from Response.Form and get the corresponding user:
object userId = Request.Form["custom"];
MembershipUser user = Membership.GetUser(userId);
Hope this helps!
A: You need to use the email of the user (the one which he/she used for your website) as an identifier.
When the user pays you, your website needs to send this email to Paypal as a "custom" field, and Paypal will send it back to you, among other IPN notification parameters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: software developed in vb.net hanging and it is giving exceptions software developed in vb.net(communicating with serialport) hanging and it is giving these rexceptions
1.The device does not recognize the command
2.Unhandled exception has occurred in your application. If you click continue, the application will ignore this error and attempt to continue. if you click Quit, the application will close immediatly. The device does not recognize the command..
A: I assume your question is incomplete. Please provide your code and the serialport library you use.
If you use .NET 2.0 (and above) System.IO.Ports.SerialPort, the exception is clearer and it's more device independent as long as you are communicating over serial port. If you don't, then the exception isn't clear and can be too broad or too specific for specific devices.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: onCompletion of MediaPlayer on Android device, and resizing video I am developing an application which plays videos from a playlist. In case there is no video on the device the app dowloads it from a site and moves to the next video in the list.
It works fine on the emulator, but on the real device there is an error when the mediaplayer method "onCompletion" is called:
09-22 11:50:54.553: ERROR/AndroidRuntime(4529): FATAL EXCEPTION: main
09-22 11:50:54.553: ERROR/AndroidRuntime(4529): java.lang.NullPointerException
09-22 11:50:54.553: ERROR/AndroidRuntime(4529): at android.widget.VideoView$3.onCompletion(VideoView.java:347)
09-22 11:50:54.553: ERROR/AndroidRuntime(4529): at android.media.MediaPlayer$EventHandler.handleMessage(MediaPlayer.java:1304)
09-22 11:50:54.553: ERROR/AndroidRuntime(4529): at android.os.Handler.dispatchMessage(Handler.java:99)
09-22 11:50:54.553: ERROR/AndroidRuntime(4529): at android.os.Looper.loop(Looper.java:123)
09-22 11:50:54.553: ERROR/AndroidRuntime(4529): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-22 11:50:54.553: ERROR/AndroidRuntime(4529): at java.lang.reflect.Method.invokeNative(Native Method)
09-22 11:50:54.553: ERROR/AndroidRuntime(4529): at java.lang.reflect.Method.invoke(Method.java:521)
09-22 11:50:54.553: ERROR/AndroidRuntime(4529): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-22 11:50:54.553: ERROR/AndroidRuntime(4529): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-22 11:50:54.553: ERROR/AndroidRuntime(4529): at dalvik.system.NativeStart.main(Native Method)
So the app runs and plays the 1st video, then crashes.
PS the device is dreambook w7
Can anyone help please?
here is the code:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
setContentView(R.layout.main);
FLcurrentVideo = 0;
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 0, this);
boolean isGPS = locationManager.isProviderEnabled (LocationManager.GPS_PROVIDER);
if (isGPS == false) startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
//
//Downloading Play List here
//
File clip=new File(Environment.getExternalStorageDirectory(),
playList[FLcurrentVideo].substring(2, playList[FLcurrentVideo].length()-1)+".mp4");
if (FLReady[FLcurrentVideo]==1) {
video=(VideoView)findViewById(R.id.video);
video.setVideoPath(clip.getAbsolutePath());
video.requestFocus();
video.start();
}
else {
if (FLReady[FLcurrentVideo] == 0) {
new CheckOutVideos(false).execute(FLcurrentVideo);
}
}
video.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer player) {
if (FLstoppedVideo==1) {
FLstoppedVideo=2;
}
else if (FLstoppedVideo==2) {
FLstoppedVideo = 0;
File clip=new File(Environment.getExternalStorageDirectory(),
playList[stoppedVideoMarker].substring(2, playList[stoppedVideoMarker].length()-1)+".mp4");
video=(VideoView)findViewById(R.id.video);
video.setVideoPath(clip.getAbsolutePath());
video.requestFocus();
video.start();
video.seekTo(stoppedVideoTime);
video.resume();
}
else if (FLstoppedVideo==0) {
isGPSplaying = false;
int FL = 1;
while (FL == 1) {
if (FLcurrentVideo<count-1) FLcurrentVideo++;
else FLcurrentVideo = 0;
File clip=new File(Environment.getExternalStorageDirectory(),
playList[FLcurrentVideo].substring(2, playList[FLcurrentVideo].length()-1)+".mp4");
if (FLReady[FLcurrentVideo]==1) {
FL=0;
video=(VideoView)findViewById(R.id.video);
video.setVideoPath(clip.getAbsolutePath());
video.requestFocus();
video.start();
}
else {
FL = 1;
if (FLReady[FLcurrentVideo] == 0) {
new CheckOutVideos(false).execute(FLcurrentVideo);
}
}
}
}
}
});
End the same problem: resizing video works fine on the emulator, but on the real device video size didn't changes, but text and image views displays at the "right" position, above video, wich didn't resized. Here is main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:layout_width="fill_parent">
<VideoView
android:id="@+id/video"
android:layout_width="600dip" android:layout_height="match_parent">
</VideoView>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_width="180dip">
<TextView
android:id="@+id/clock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="time"
>
</TextView>
<TextView
android:id="@+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="time"
>
</TextView>
<ImageView
android:id="@+id/image1"
android:layout_height="match_parent" android:layout_width="match_parent">
</ImageView>
</LinearLayout>
Thank you in advance.
SentineL
A: If this helps someone:
It seems, there is a some kind of bug on android 2.2 for VideoView class. The only way i foud to do something - is to do nothing. I throw away VideoView and done all what I nedded useing MediaPlayer class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to receive Google ChannelPresence in an ActionBean? I am trying to receive the disconnect google ChannelPresence in a Stripes ActionBean. I am currently using DynamicMappingFilter to dynamically map my ActionBean URLs. The disconnect presence was working perfectly when I was using a servlet that was mapped to "/_ah/channel/disconnected/".
The custom mapping is working with my other ActionBean that uses UrlBinding("/testing/"). However, the ChannelPresence does not seem to be sent to my ActionBean that handles a ChannelPresence disconnect :
@UrlBinding("/_ah/channel/disconnected/")
public class LogoutActionBean implements ActionBean {
private ActionBeanContext context;
public void setContext(ActionBeanContext abc) {
context = abc;
}
public ActionBeanContext getContext() {
return context;
}
@DefaultHandler
public Resolution logout() {
UserStore userStore = UserStore.getInstance();
ChannelService channelService = ChannelServiceFactory.getChannelService();
ChannelPresence presence = null;
String clientID = null;
try {
presence = channelService.parsePresence(context.getRequest());
} catch (IOException e) {
}
if (presence != null) {
clientID = presence.clientId();
userStore.removeUser(clientID);
}
UserStoreUtility.updateAllUserList();
return new ForwardResolution("UserList.jsp");
}
}
This is my web.xml:
<web-app version="2.5" 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_2_5.xsd">
<filter>
<display-name>Stripes Filter</display-name>
<filter-name>StripesFilter</filter-name>
<filter-class>net.sourceforge.stripes.controller.StripesFilter</filter-class>
<init-param>
<param-name>ActionResolver.Packages</param-name>
<param-value>net.sourceforge.stripes.examples, com.channel</param-value>
</init-param>
</filter>
<filter>
<description>Dynamically maps URLs to ActionBeans.</description>
<display-name>Stripes Dynamic Mapping Filter</display-name>
<filter-name>DynamicMappingFilter</filter-name>
<filter-class>
net.sourceforge.stripes.controller.DynamicMappingFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>DynamicMappingFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: .NET 1.1 Captcha Implementation Compiler Error I'm quite new to ASP.NET. A client's server is running .NET 1.1 and I am trying to implement the simple captcha outlined here: http://www.codekicks.com/2008/04/implement-simple-captcha-in-cnet.html
I have the following code in captcha/BuildCaptcha.aspx:
<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Color" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<script language="C#" runat="server">
Bitmap objBMP = new Bitmap(60, 20);
Graphics objGraphics = Graphics.FromImage(objBMP);
objGraphics.Clear(Color.Wheat);
objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
//' Configure font to use for text
Font objFont = new Font("Arial", 8, FontStyle.Italic);
string randomStr = "";
char[] myArray = new char[5];
int x;
//That is to create the random # and add it to our string
Random autoRand = new Random();
for (x = 0; x < 5; x++)
{
myArray[x] = System.Convert.ToChar(autoRand.Next(65,90));
randomStr += (myArray[x].ToString());
}
//This is to add the string to session, to be compared later
Session.Add("RandomStr", randomStr);
//' Write out the text
objGraphics.DrawString(randomStr, objFont, Brushes.Red, 3, 3);
//' Set the content type and return the image
Response.ContentType = "image/GIF";
objBMP.Save(Response.OutputStream, ImageFormat.Gif);
objFont.Dispose();
objGraphics.Dispose();
objBMP.Dispose();
</script>
I am receiving the following error upon visiting captcha/BuildCaptcha.aspx:
Compiler Error Message: CS1519: Invalid token '(' in class, struct, or interface member declaration
Source Error:
Line 7: Bitmap objBMP = new Bitmap(60, 20);
Line 8: Graphics objGraphics = Graphics.FromImage(objBMP);
Line 9: objGraphics.Clear(Color.Wheat);
Line 10: objGraphics.TextRenderingHint = TextRenderingHint.AntiAlias;
Line 11: //' Configure font to use for text
Source File: \\...\captcha\BuildCaptcha.aspx Line: 9
Your help is appreciated.
Best,
Mark
A: You should put this codes into a method, OnLoad for example:
<%@ Page Language="C#" %>
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Drawing" %>
<%@ Import Namespace="System.Drawing.Color" %>
<%@ Import Namespace="System.Drawing.Imaging" %>
<script language="C#" runat="server">
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
Bitmap objBMP = new Bitmap(60, 20);
Graphics objGraphics = Graphics.FromImage(objBMP);
objGraphics.Clear(Color.Wheat);
objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
//' Configure font to use for text
Font objFont = new Font("Arial", 8, FontStyle.Italic);
string randomStr = "";
char[] myArray = new char[5];
int x;
//That is to create the random # and add it to our string
Random autoRand = new Random();
for (x = 0; x < 5; x++)
{
myArray[x] = System.Convert.ToChar(autoRand.Next(65, 90));
randomStr += (myArray[x].ToString());
}
//This is to add the string to session, to be compared later
Session.Add("RandomStr", randomStr);
//' Write out the text
objGraphics.DrawString(randomStr, objFont, Brushes.Red, 3, 3);
//' Set the content type and return the image
Response.ContentType = "image/GIF";
objBMP.Save(Response.OutputStream, ImageFormat.Gif);
objFont.Dispose();
objGraphics.Dispose();
objBMP.Dispose();
}
</script>
A: Try this one instead from CodeProject. It works very well
CAPTCHA Image
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding BarButtonItem To NavigationBar I Added a NavigationBar Through IB and I Tried to Add a BarButtonItem Programatically.....But it Doesn't Work.
- (void)viewDidLoad {
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit"style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)];
[self.navigationItem setLeftBarButtonItem:self.addButton];
[super viewDidLoad];
}
A: Try to do this :
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(backButtonTapped:)];
A: In your case try this:
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit"style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)];
[self.navigationItem setLeftBarButtonItem:addButton];
I guess this might work.
A: What you are doing is right, but so far, you've only added the addButton to a UINavigationItem as the leftBarButtonItem. To add it to a navigationBar, you need to then push the navigationItem onto it, similar to how you add a new UIViewController to a UINavigationController. Assuming you name your UINavigationBar navBar:
UINavigationItem *navigationItem = [[UINavigationItem alloc] init];
self.addButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit"style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)];
[navigationItem setLeftBarButtonItem:self.addButton];
[self.navBar pushNavigationItem:navigationItem animated:NO];
[navigationItem release];
Hope that helps!
A: UIBarButtonItem *addButton = [[UIBarButtonItem alloc] init];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Edit"style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)];
self.navigationItem.leftBarButtonItem = addButton;
self.navigationItem.leftBarButtonItem.enabled = YES;
A: For some views the leftBarButtonItem doesnt work and you need to use the backBarButtonItem. Try this:
- (void)viewDidLoad {
[self.navigationItem setBackBarButtonItem:[[[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)] autorelease];
// Or, if that doesnt work for some reason use:
// [self.navigationItem setLeftBarButtonItem:[[[UIBarButtonItem alloc] initWithTitle:@"Edit" style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)] autorelease];
[super viewDidLoad];
}
Also, your creating a variable within the scope of viewDidLoad called addButton, but then you are trying to set the property self.addButton as the leftBarButtonItem.
Either remove the self. from the self.addButton in:
[self.navigationItem setLeftBarButtonItem:self.addButton];
or initialize the property instead of creating a new item with the same name:
self.addButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit"style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)];
// instead of:
// UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithTitle:@"Edit"style:UIBarButtonItemStyleBordered target:self action:@selector(EditTable:)];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I fix high MultiTail CPU consumption in Perl? I have written a script with Perl that basically multitails files (using the Perl library File::MultiTail): after tailing each lines it does many other things but that's another story, so I just paste a resume based on the piece of code that's causing problems:
#!/usr/bin/perl
use File::MultiTail;
$path="my/path";
$files="*.log";
sub first{
$True=0;
my $file=MultiTail->new(OutputPrefix => 'f',
Files => ["$path"],
RemoveDuplicate => $True,
ScanForFiles => "0");
while(defined(my $line=$file->read)) {
print"$line\n";
$file->update_attribute(Files => ["$path"]);
}
}
&first();
The script works well: it tails every single line from several files each time a new log line arise, but my problem is that this script uses 100% CPU, and I was wondering how I could make it not be checking the files at every single second, I can do so with a delay like sleep 10; and it really liberates the CPU, but I need to see the lines in real time and I don't know how to solve it.
A: It seems that File::MultiTail is an old piece of code ( 1998 ): maybe it isn't doing file checks in an efficient way, or it doesn't scale well with growing number of files.
Doing as many I/O checks as possible in that while loop, looks as a waste of CPU time.
Maybe you can spare CPU cycles on I/O using a more recent module like File::Tail, because The module tries very hard NOT to "busy-wait".
I was thinking about something like this:
#!/usr/bin/env perl
use 5.012;
use strict;
use File::Tail;
my @logs = glob '/var/log/*.log';
my @tails = ();
foreach ( @logs ) {
push @tails, File::Tail->new( $_ );
}
foreach ( @tails ) {
while ( defined ( my $line = $_->read ) ) {
say $line;
}
}
In order to know if this more CPU friendly than File::MultiTail, you have to check CPU time ( real, user, sys ).
A: I think this answer is what you are looking for. See usage of select with File::Tail from CPAN.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to test the inner classes by using EasyMock I am new to the EasyMock. I need to test my class using the EasyMock, but here the problem is my class has inner class and this inner class is instatiated in the outer class's method and calling the method of inner class by passing some parameters. I am not sure how to test this class.
Below is some sample code.
Any help or suggetions are highly appreciated.
public class ServiceClass implements ServiceInterface {
public void updateUSer(USer) {
//some logic over here.
sendEmailNotice(subject, vTemplate);
}
private sendEmailNotice(subject, vTemplate) {
MimeMessagePrepator eNotice = new PrepareEmailNotice(subject, vTemplate);
MailSender.send( eNotice );
}
public class PrepareEmailNotice implements MimeMessagePrepator {
// some local variables.
public PrepareEmailNotice(subject, vTemplate) {
subject = subject;
vTemplate = vTemplate;
}
public void prepare( MimeMessage message) {
MimeMessageHealper helper = new MimeMessageHealper(message, true);
// setting the mail properties like subject, to address, etc..
}
}
A: There are some things that you cannot mock with Easymock as calls to static methods and calls to constructors. You might change your code to be able to test it with Easymock because in the method sendEmailNotice there is a call that you may like to mock but you can't. A mock for the MailSender.send() call would be appropriate. We could do that creating a class that contains the call to the MailSender that could be mocked.
public class MailWrapper {
public MailWrapper () {
}
public void send ( MimeMessagePrepator eNotice) {
MailSender.send(eNotice);
}
}
You could use an instance of this class to be used in your ServiceClass.
public class ServiceClass implements ServiceInterface {
//Added as a member
private MailWrapper mw;
public ServiceClass () {
this.mw = new MailWrapper();
}
//Constructor added for test purposes
public ServiceClass (MailWrapper mw) {
this.mw = mw;
}
public void updateUSer(USer) {
//some logic over here.
sendEmailNotice(subject, vTemplate);
}
private sendEmailNotice(subject, vTemplate) {
MimeMessagePrepator eNotice = new PrepareEmailNotice(subject, vTemplate);
mw.send( prepator );
}
...
}
The test of the ServiceClass class would be like this:
public class ServiceClassTest {
@Test
public void testUpdateUser() {
String subject = "Expected subject";
String vTemplate = "Expected vTemplate";
MimeMessagePrepator eNotice = new PrepareEmailNotice(subject,vTemplate);
MailWrapper mwMock = createMock (MailWrapper.class);
//expecting the void call to the MailWrapper
mwMock.send(eNotice);
//other expectations...
replay(mwMock);
ServiceClass sc = new ServiceClass(mwMock);
sc.updateUser(new User());
verify(mwMock);
//some asserts
}
}
In the message you were asking about the inner class, but I think that the test of the inner class is contained in the test of the outer class, and you would
not need to test it apart. In case PrepareEmailNotice has complex code and should be mocked, you could do changes, adding a MimeMessagePrepator member that
could be passed as a parameter in the constructor like the MailWrapper. But I think that in case it has complex and have-to-be-mocked code, maybe it would not be an inner class.
Also, you could use Powermock, that allows you to mock static calls and constructor calls, in case you don't mind to change your test framework.
Hope it helps.
Regards.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CSS inherit style I have a style set for many divs that looks similar. The only difference is that each div has different padding and margin setup. Something like this:
<div class="mainStyle" id="cc">CC</div>
<div class="mainStyle" id="bb">BB</div>
<div class="mainStyle" id="aa">AA/div>
And have:
.mainStyle {
float: right;
width: 60px;
text-align : center;
font: 95% Arial;
-moz-border-radius: 5px;
border-radius: 5px;
background : #69abd0;
}
And for each id have only:
#aa {
margin: 0px 2px 0px 2px;
padding: 2px 0 5px 0;
}
#bb {
margin: 10px 2px 10px 2px;
padding: 2px 0 5px 0;
}
#cc{
margin: 10px 2px 10px 2px;
padding: 20px 0 50px 0;
}
I know this is the wrong syntax but I don't know how else to ask the question...
I don't want to have a long style definition for each element id because they are %90 the same except the padding and margin. I want to somehow combine the style of the class and the element.
How do I do this?
A: I don't understand your question. You can perfectly combine an ID with a class the way you did. Are you looking for a way to reuse these id's? You can just convert them to classes and in html use this:
<div class="mainStyle aa">AA/div>
There really is nothing wrong with your code.
A: There is nothing wrong with that syntax, but you can make it less repetetive. An id is more specific than a class, so you can just override settings from the class style:
.mainStyle {
float: right;
width: 60px;
text-align : center;
font: 95% Arial;
-moz-border-radius: 5px;
border-radius: 5px;
background : #69abd0;
margin: 10px 2px;
padding: 2px 0 5px 0;
}
#aa {
margin: 0 2px;
}
#bb {
}
#cc{
padding: 20px 0 50px 0;
}
If you don't want the class on the element, you can use the , operator to use multiple selectors for a style. Style rules are applied in the order they are written, so the later rules with the same specificity will override previous rules:
#aa,#bb,#cc {
float: right;
width: 60px;
text-align : center;
font: 95% Arial;
-moz-border-radius: 5px;
border-radius: 5px;
background : #69abd0;
margin: 10px 2px;
padding: 2px 0 5px 0;
}
#aa {
margin: 0 2px;
}
#bb {
}
#cc{
padding: 20px 0 50px 0;
}
(The empty #bb rule is only included to show that I haven't forgotten it. As it's empty it is of course not needed.)
A: I'm not sure I'm totally understanding your question. You "can" target html IDs in CSS using the class, like .mainstyle#aa, but that's completely overkill. There really isn't too much to simplify:
.mainStyle {
float: right;
width: 60px;
margin: 10px 2px 10px 2px;
padding: 2px 0 5px 0;
text-align : center;
font: 95% Arial;
-moz-border-radius: 5px;
border-radius: 5px;
background : #69abd0; }
#aa { margin: 0px 2px 0px 2px; }
#cc { padding: 20px 0 50px 0; }
It's also better practice to do something like:
<div class="main">
<div id="cc">CC</div>
<div id="bb">BB</div>
<div id="aa">AA</div>
</div>
and
/* Use the child selector... */
.main > div { /* apply .mainStyle here */ }
#aa...
A: What you've written will accomplish what you're asking. You do have a syntax error in your code, the tag for the final AA element is missing the left <. Also, just remember that order is important when it comes to CSS styles. The styles for the id's needs to come after .mainStyle and any other styles that may overwrite your margin or padding. You can overcome this necessity by using the !important modifier on your styles.
A: Like this.. This is the cascade part of cascading style sheets don't do the same thing twice just write it onces and the over ride it later on down the line if you need to. The CSS settings set after will over ride the one set early. Also you should research specificity concerning css.
CSS
.mainStyle {
float: right;
width: 60px;
text-align : center;
font: 95% Arial;
-moz-border-radius: 5px;
border-radius: 5px;
background : #69abd0;
margin: 10px 2px 10px 2px;
padding: 2px 0 5px 0;
}
#aa {
margin: 0px 2px 0px 2px;
}
#cc{
padding: 20px 0 50px 0;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Task monitor and manager in C++ I'm looking to build a task monitor/manager using the Win32 API. It will be started (preferably as a windows service) with a command line argument specifying how many instances of a new process it should start.
task_man.exe 40
Will start 40 instances of the process
task.exe
Now, whenever a task.exe exits (correctly or not), I will have to start a new one to replace it.
My rough idea is this:
Start the tasks from task_man, get their PIDs, and then have a loop that checks whether the PIDs are all active processes. For every invalid PID, start a new process and replace the old PID with the new one.
Is there a better design I can use, or a better workflow? Is there a standard method for doing this? I don't want to reinvent the wheel... Also, which APIs should I look into?
I'm also looking for a design that is easy to change afterwards - i.e. if I run
task_man.exe 30
afterwards, a new task_man shouldn't start running, but rather it should change the number of tasks in the previous instance. (I know it will start running, what I'm saying it should modify the original and then exit)
I'm not looking for code (as in I'm not looking for the full implementation, not that I mind looking over samples), rather what APIs I can use, or suggestions on the overall design I came up with.
A: The easiest way to tell if a process has exited is to wait on its handle. You can do that in a few ways:
*
*Build an array of all the process handles, and use WaitForMultipleObjects (bWaitAll being FALSE) to wait on all of them. Then, when your code continues, you'll have to figure out which process ended, create a new one, update the array and wait again.
*Run 40 threads, each creating one process and infinitely waiting on its one handle (using WaitForSingleObject). Then, when that task ends, that thread will be responsible to create a new one and wait on it.
*If you don't want to create 40 threads, just have one that will wait for short periods of times over each of the process handles (using WFSO), and check the return value. Your program will response slower this way, but it would be easier to recognize the process that has ended, and you won't be creating many threads.
A: If you want to replace pooling with wait operations, you can use WaitForSignalObject/WaitForMultipleObjects for created processes. Process handle becomes signaled when the process exits. Unlike pooling, wait operations don't consume CPU. Waiting thread is inactive unless one of objects is signaled.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is the path of my module in Drupal 7? This is my first time with Drupal 7, i wrote a test module that echo "test" , and in the menu the path is "test".
When i'm trying to access localhost/drupal/test OR localhost/drupal/admin/test it can't find it, and i see 404 or admin page.
What is the problem here?
this is the code, and its doesnt work
<?php
/* $Id$ */
/**
* @file
* Very simple DRUPAL module
*/
/**
* Implementation of hook_help().
*/
function hello_world_help($section) {
switch ($section) {
case 'admin/help#hello_world':
$output = '<p>Hello world help...</p>';
return $output;
case 'admin/modules#description':
return 'Hello world module description...';
}
}
/**
* Implementation of hook_menu().
*/
function hello_world_menu($may_cache) {
$items = array();
if ($may_cache) {
}
else {
$items[] = array(
'path' => 'hello', // drupal path example.com/?q=hello
'title' => 'Hello world page...', // page title
'callback' => 'hello_world_page', // callback function name
'access' => TRUE, // every user can look at generated page
'type' => MENU_CALLBACK // define type of menu item as callback
);
}
return $items;
}
/**
* Function which generate page (this generate any content - you need only your own code...)
*/
function hello_world_page() {
return '<p>Hello world!</p>';
}
?>
A: Use drupal_get_path() to get the path of your module or theme. If the name of your module is 'mymodule', then you'd simply invoke the below piece of code to get the path.
drupal_get_path('module', 'mymodule');
EDIT
Reading your question again makes me realise that your'e asking for the URL to your module. Could you please post the code you've got in your module's hook_menu()?
A: If I am getting you correctly,
*
*you wrote a hook_menu() where you created a menu path test(say $item['test']) and wrote a page callback function.
*In the page callback function, you say echo test.
If this is the scenario, you just need to clear your cache. Drupal needs to register the menu item. After writing any menu hook implementation, you should clear your cached data and then try again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java method to assign object field values with Reflection I was wondering whether it would be possible to have something like the following in Java:
public class MyClass {
private String name;
private Integer age;
private Date dateOfBirth;
// constructors, getters, setters
public void setField(String aFieldName, Object aValue) {
Field aField = getClass().getDeclaredField(aFieldName);
// use: aField.set(...) with proper type handling
}
}
I am really stuck in the setField method and any idea would be very helpful.
Thanks!
EDIT: The reason for this is that I would like to have a method in another class like the following
public static MyClass setAll(List<String> fieldNames, List<Object> fieldValues) {
MyClass anObject = new MyClass();
// iterate fieldNames and fieldValues and set for each fieldName
// the corresponding field value
return anObject;
}
A: Sure:
aField.set(this, aValue);
To do type checking first:
if (!aField.getType().isInstance(aValue))
throw new IllegalArgumentException();
but since calling set with a value of the wrong type will generate an IllegalArgumentException anyway, that sort of check isn't very useful.
A: Though I'm at a loss as to why you would want to do it like that (since you already have getters and setters), try this:
Field aField = getClass().getDeclaredField(aFieldName);
aField.set(this, aValue);
For more info, see this.
A: I'd like to suggest a map instead of List<T>.
for(Map.Entry<String,Object> entry:map.entrySet())
{
Field aField = anObject.getClass().getDeclaredField(entry.getKey());
if(entry.getValue().getClass().equals(aField.getType()))
aField.set(anObject,entry.getValue());
}
return anObject;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Android default JSON example Android has default JSON support with import org.json. Is there any simple example of serializing and deserializing this way? Are there any advanced options for serializing/deserializing like references or inheritance?
Thanks
A: Try the first google hit.
What do you mean with serializing/deserializing like references or inheritance?
JSON is not a class serialization format like the build-in Java serialization. It's a pure and simple data exchange format, check the format definition.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Problem when connecting my device to PC? I can't connect my device Samsung Galaxy SII to my pc. I'm using Windwos XP 32-bit Operating System. I've also installed Samsung Kies. And, in eclipse i've also change the run configurations to Manual also. Why it's not connected. Anyone help me to connect that please? Advance Thanks.
A: get the device "Hardware Ids" from the device manager and add them to the android_winusb.inf file in "...\android-sdk_r11-windows\android-sdk-windows\extras\google\usb_driver" like
; HTC Desire HD
%SingleAdbInterface% = USB_Install, USB\VID_0BB4&PID_0CA2&MI_01
%CompositeAdbInterface% = USB_Install, USB\VID_0BB4&PID_0CA2&REV_0226&MI_01
these are the values for htc desire hd,
UPDATE: the values for the galaxy sII are
; Samsung Galaxy S II
%SingleAdbInterface% = USB_Install, USB\VID_04E8&PID_685E&MI_03
%CompositeAdbInterface% = USB_Install, USB\VID_04E8&PID_685E&REV_0400&MI_03
A: Yes exactly now as you want to start with android application development on your real device samsung galaxy SII, just go through this checkout steps:
*
*settings->Applications->Unknown sources
*Settings->Applications->Development->USB debugging
These 2 steps are necessary before starting development with real device.
A: Un-check the USB debugging mode (from Settings - Development; if it's checked), and try to reconnect. Also, check that the Settings - Connect to PC is not set as default to "Charge Only", make sure to connect it as "Mass Storage" / "Disk Drive" initially.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: htaccess confilcting rules for two different files Here are the conflicting rules
Options +FollowSymLinks
RewriteEngine on
# For www.domain.com it should go to my-index.php page
#
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC]
RewriteRule ^(.*)$ my-index.php [NC,L]
# For Accessing Division Page http://user1.domain.com/news/news-details.php
RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com [NC]
RewriteCond %{HTTP_HOST) !^www\.
RewriteRule ^news/news-details.php$ my-news.php?user=%1 [QSA,NC,L]
# For Page URL http://www.domain.com/news/news-details.php
#
RewriteCond %{REQUEST_URI} ^/news/news\-details\.php [NC]
RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC]
RewriteRule ^(.*)$ my-news.php [NC,QSA,L]
# For Accessing Users Page
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com$
RewriteRule ^$ /users.php?user=%1 [L]
The call for the news page and the index page both goes to the index page. i dont know why?
A: *
*The order of rules is important -- right now both of those mentioned URLs will be served by the first rule which will rewrite them to my-index.php.
*Your first rule (for my-index.php) is too broad -- even if you place it in correct order it will still rewrite it to the my-index.php page -- as you matching everything using .* pattern.
Considering the above try these rules:
Options +FollowSymLinks
RewriteEngine On
# For Page URL http://www.domain.com/news/news-details.php
RewriteCond %{HTTP_HOST} ^www\.domain\.com$ [NC]
RewriteRule ^news/news-details\.php$ /my-news.php [NC,QSA,L]
# For Accessing Division Page http://user1.domain.com/news/news-details.php
RewriteCond %{HTTP_HOST} ^(.+)\.domain\.com [NC]
RewriteCond %{HTTP_HOST) !^www\.
RewriteRule ^news/news-details\.php$ /my-news.php?user=%1 [QSA,NC,L]
# For Accessing Users Page
RewriteCond %{HTTP_HOST} !^www\.domain\.com$ [NC]
RewriteCond %{HTTP_HOST} ^(.*)\.domain\.com$
RewriteRule ^$ /users.php?user=%1 [L]
# For www.domain.com it should go to my-index.php page
# (but only if requested resource is not real file)
RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /my-index.php [L]
What I did:
*
*rearranged rules: moved my-index.php one to the bottom;
*added a condition to not to rewrite requests to existing files (otherwise my-news.php will be rewritten as well).
These rules may still require some tweaking -- I do not know what kind of website logic you have there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why doesn't my rails controller stop execution after I returned false in a private method? When I run ajax POST delete on my follows controller, for a record that has already been deleted, rails raises error "undefined method `destroy' for nil:NilClass". But why does it still say that when I tried to render the response in a find_follow method preceding the destory call? Shouldn't the execution stop inside find_follow?
class FollowsController < ApplicationController
def find_follow
begin
@follow = current_artist.follows.find(params[:id])
raise "Record Not Found" if @follow.nil?
rescue => e
respond_to do |format|
format.html { redirect_to(artist_follows_path(current_artist),:notice => "#{e}") }
format.js { render :text => "#{e}", :status => :not_found}
format.json {render :json => "#{e}", :status => 400}
end
return false
end
end
def destroy
find_follow
if (@follow.destroy)
# respond_to html, js, json...
end
end
end
A: Your find_follow returns nil which is fine but as you are calling destroy method you need to write return in destroy method only
Try
def destroy
return find_follow
You can also use before_filter something like following
class FollowsController < ApplicationController
before_filter :find_follow, :only=>[:destroy]
def find_follow
@follow = current_artist.follows.find_by_id(params[:id])
if @follow.nil?
redirect_to(artist_follows_path(current_artist),:notice => "#{e}")
else
return true
end
end
def destroy
if (@follow.destroy)
# respond_to html, js, json...
end
end
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Eclipse show warnings in my first android project I am using Eclipse indigo, android sdk 8 (android api 2.2). When i create a new android project using
Name:Bucky
Package: com.theboston.android.bucky
eclipse shows a yellow triangle on the Project. The yellow triangle eventually becomes red
A simple java project ansuljava works well.
A: You can use the eclipse problem view to explore any issues with your projects.
Go to Window->Show View->Other->Problems
you can also use Window->Show View->Markers, but this one is more cluttered with less problematic stuff.
A: Project > Clean > Clean Project
This will force Eclipse to regenerate some of the code and rebuild everything. Wait a few seconds, then the red flag(s) should go away.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510480",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I substitute a left join in SQL Can anyone tell me how can I write the equivalent of a left join without really using left joins.
Select * from a left join b on a.name = b.name.
A: Although left outer joins are the recommended way of writing sql as compared to an alternative but still we can achieve left outer join by using union for the resultset. If we have two table Table1 and Table 2 then we can achieve this by the following -
select
A.Id,
A.Col1,
A.Col2,
A.Col3,
B.Id Col4,
B.Col1 Col5,
B.Col2 Col6,
B.Col3 Col7,
B.Col4 Col8
from Table1 A, Table2 B
where A.Id = B.Id
union all
select
A.Id,
A.Col1,
A.Col2,
A.Col3,
null as Col4,
null as Col5,
null as Col6,
null as Col7,
null as Col8
from Table1 A
where not exists(select 1 from Table2 B where B.Id = A.Id)
This will help achieve the same result but because of the use of Union there could be some performance problems in case the tables are large.
A: Bear in mind that SQL’s outer join is a kind of relational union which is expressly designed to project null values. If you want to avoid using the null value (a good thing, in my opinion), you should avoid using outer joins. Note that modern relational languages have dispensed with the concept of null and outer join entirely.
This outer join:
SELECT DISTINCT T1.id, T1.value, T2.other_value
FROM T1
LEFT OUTER JOIN T2
ON T1.id = T2.id;
…is semantically equivalent to this SQL code:
SELECT T1.id, T1.value, T2.other_value
FROM T1
INNER JOIN T2
ON T1.id = T2.id
UNION
SELECT T1.id, T1.value, NULL
FROM T1
WHERE NOT EXISTS (
SELECT *
FROM T2
WHERE T1.id = T2.id
);
The second query may look long winded but that’s only because of the way SQL has been designed/evolved. The above is merely a natural join, a union and a semijoin. However, SQL has no semijoin operator, requires you to specify column lists in the SELECT clause and to write JOIN clauses if your product hasn’t implemented Standard SQL’s NATURAL JOIN syntax, which results in a lot of code to express something quite simple.
Therefore, you could write code such as the second query above but using an actual default value rather than the null value.
A: Oracle disguised left join:
SELECT * FROM A, B
WHERE a.name = b.name(+)
Generic :
SELECT a.*, case c.existence WHEN 1 then c.name ELSE NULL END
FROM A
INNER JOIN ( SELECT name name, 1 existence FROM B
UNION ALL
SELECT a.name name, 0 existence FROM A
WHERE a.name NOT IN ( SELECT name FROM B )
) C
ON c.name = a.name
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: where exactly do we need exception handling for web-services on iPhone I am a new iPhone developer and totally new to web-services as well. I had used http://www.sudzc.com/ to develop my obj-c code for my wsdl. I need to know that where exactly i need to handle exceptions in this code? Or the code generated by sudz itself takes care of the exception handling itself?
A: Generally the proxy classes from the WSDL has selector methods which gets called,when you do some operation/method call. So you just need to check it out what method (from service level) you are going to call and implement the selector method in your class.
A: Look at the example code generated for your web service. They give you the generic layout for the error handlers. Should look something like this:
// Handle the response from webserviceConnection.
*
*(void) webserviceConnectionHandler: (BOOL) value {
// Do something with the BOOL result
NSLog(@"webserviceConnection returned the value: %@", [NSNumber numberWithBool:value]);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ModelClientValidationRule conflict I have installed vs 2011 developer preview side by side with vs 2010. Now when i run my asp.net mvc 3 project in vs 2010 I am getting the following error in my project where i am using ModelClientValidationRule.
The type System.Web.Mvc.ModelClientValidationRule exists in both
c:\Program Files\Microsoft ASP.NET\ASP.NET MVC
3\Assemblies\System.Web.Mvc.dll and c:\Program Files\Microsoft
ASP.NET\ASP.NET Web Pages\v2.0\Assemblies\System.Web.WebPages.dll
Is this related to vs 2011 conlict with vs 2010 or something else
A: The accepted answer was "useful" but after installing MVC4 beta today, a few of my MVC 3 projects would not compile. (ModelClientValidationRule conflict) The fix was:
Edit:
ProjectName.csproj
Change
<Reference Include="System.Web.WebPages"/>
To
<Reference Include="System.Web.WebPages, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL "/>
A: please see the below release notes :
http://www.asp.net/learn/whitepapers/mvc4-release-notes
Installing ASP.NET MVC 4 Developer Preview breaks ASP.NET MVC 3 RTM
applications.
ASP.NET MVC 3 applications that were created with the RTM release (not
with the ASP.NET MVC 3 Tools Update release) require the following
changes in order to work side-by-side with ASP.NET MVC 4 Developer
Preview. Building the project without making these updates results in
compilation errors.
http://www.asp.net/learn/whitepapers/mvc4-release-notes#_Toc303253815
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "44"
} |
Q: How to remove all nontext nodes from the beginning of the contents of a div? How can I remove the NonText Nodes(BR,empty <p> tags, nbsp) from the html of a div but only those which occur before the first text node appears. Just like stripping leading white space from a normal string of characters, but here to remove leading whitespace from the HTML string.
I have tried using Regular Expressions, but often problems occur in this approach. I would like to do it using NodeType and JQuery. If anyone has any example, please share.
Thanks!
UPDATE:
Take the following DIV:-
<div id="foo">
<div>
<div>
<p>
</p>
<p>
</p>
<br/>
<p>
this is a test</p>
<p>
</p>
<br />
<br>
<p>
this is a fast test
</p>
</div>
</div>
</div>
When passing "foo" to the whitespace removal function, it should become like following:-
<div id="foo">
<div>
<div>
<p>
this is a test</p>
<p>
</p>
<br />
<br>
<p>
this is a fast test
</p>
</div>
</div>
</div>
A: Something like this should do it:
var $contents = $('#foo').contents();
var stopFiltering = false;
$contents.filter(function() {
var isEmpty = $.trim($(this).text()) == '' ||
this.tagName == "BR";
var shouldFilter = !stopFiltering && isEmpty;
stopFiltering = stopFiltering || !isEmpty;
return shouldFilter;
}).remove();
This is an adaptation of the filter function. Each element (including text nodes) is tested for "emptiness" (isEmpty). After the first non-empty node is seen shouldFiltering is set to false, and this way the filtering condition expresses your requirements: select empty nodes and elements before the first non-empty one.
See it in action.
Update: Recursive solution is here. It simply packages the above into a function TrimElements and recurses into all children of the target element before processing the target element itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I create an event in a trigger? Is it possible to create a new event from inside a trigger?
It's not something I'd particularly recomment, but I'm just wondering if it can be done.
I would like to fire a insert in response to an update, but have the insert be done delayed.
Right now I insert a value into a temp table and have a predefined event sweep that table every x minutes.
However this seems wasteful because most of the time there's nothing to do.
If I cannot create the event, can I at least enable/disable it on the fly?
A: You cannot create an event from a stored procedure or trigger.
>If I cannot create the event, can I at least enable/disable it on the fly?
ALTER EVENT event1 ENABLE;
ALTER EVENT event1 DISABLE;
CREATE EVENT Syntax
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: update values dynamically ? So I have to write a program that will take formulas from the user and calculate them.
Age, Height, fights, (age+height)*fights <- user defined
10, 5, 10, 150 <- I calculate this
1, 2, 1, 3 <- I calculate this
But now let say I change the values around and I want the formula column to update dynamically is there anyway to go about doing that ? I am storing by each row into an array list which is array list of array list. Any advice or guidance would be really helpful thank you :)
A: You might want to look at using one of a number of expression calculation engines instead of ArrayLists. You can see Expr4J or BIRT for possible solutions.
A: You might want to write an event listener for those arrays. Documentation can be found here
http://download.oracle.com/javase/tutorial/uiswing/events/listdatalistener.html
An easier solution is to write a simple method that computes the formula and call it from each portion of the program that triggers a change in the list values (but this solution can clutter the code). If this is a homework or really small project you can go with this approach otherwise I would suggest writing a listener.
A: We can revise this to make a simple engine
public interface Function<T> {
T operate(Map<String,T> values);
}
public class Calculation<T> {
private Map<String,T> values;
private Function<T> function;
public Calculation(Map<String,T> values, Function<T> function) {
this.values = new HashMap<String,T>(values);
this.function = function;
}
public T calculate() {
return function.operate(Collections.unmodifiableMap(values));
}
// assume setters and getters are in place to manipulate the backing map and the functor object
}
With this in place, we can define various functions and calculations
public static void main(String[] args) {
Function<Integer> original = new Function<Integer>() {
public Integer operate(Map<String,Integer> values) {
// these will throw exceptions if they don't exist, which is desired
// granted it's NullPointerException instead of IllegalStateException, but close enough for this example
int age = values.get("age").intValue();
int height = values.get("height").intValue();
int fights = values.get("fights").intValue();
return (age+height)*fights;
}
};
Map<String,Integer> map = new Map<String,Integer>();
map.put("age",10);
map.put("height",100);
map.put("fights",25);
Calculation<Integer> calc = new Calculation<Integer>(map,original);
// later someone can replace either the values in the backing map
// or replace the function altogether to get a new function
}
The problem comes when you try to make it not only user defined, but user entered. As in, a user could define the function as being one of a set of functions you have pre-entered. In this case, you'll need to have a parser that turns something like this:
value + (other + (something * that)) / wazook
into this:
EquationBuilder<Integer> eb = new EquationBuilder<Integer>();
eb.append(map.get("value"));
eb.append(OPERATOR.PLUS);
// etc
return eb.evaluate();
But that may be beyond the scope of your assignment. Or maybe it's not.
Hopefully this is a little closer to your requirements than my previous example.
A: To be honest I'll use more OO manner, please take a look:
public class Parameter {
private String id;
private Number value;
public Parameter(String id, Number value) {
this.id = id;
this.value = value;
}
public String getId() {
return id;
}
public Number getValue() {
return value;
}
@Override
public int hashCode() {
return id.hashCode();
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Parameter) {
Parameter parameter = (Parameter) obj;
return id.equals(parameter.getId());
}
return super.equals(obj);
}
}
public class Equation {
private String formula;
private Set<Parameter> parameters;
public Equation(String formula, Parameter ... parameters) {
this.formula = formula;
this.parameters = new HashSet<Parameter>();
for(Parameter parameter : parameters) {
this.parameters.add(parameter);
}
validatePresenceOfAllParameters();
}
private void validatePresenceOfAllParameters() {
// here you parse formula and check if all parameters are present
}
public Number doTheMagic() {
Number result = null;
// here you do the all magic related to equation and its parameters
return result;
}
// public void setParameter(Parameter parameter) {
// parameters.add(parameter);
// validatePresenceOfAllParameters();
// }
}
I would also make Parameter and Equation object immutable, if there is a necessity of change I'll make another equation object but if this is the requirement you could write method in Equation for adding/setting Parameter's. Set will handle them properly if they will have same id's.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Process does not show in android I have an application that I wrote which is the following package "com.pack" . When i launch the app, I dont see the "com.pack" in the list of processes being shown in the device in DDMS. How is that possible does anybody know why ? Here is the code and the xml manifest file.
package com.pack;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.PorterDuff.Mode;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.internal.telephony.CallManager;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.Call;
import com.android.internal.telephony.PhoneFactory;
public class AutoVT extends Activity {
public static final int MAKE_CALL = 1;
public static final int END_CALL = 2;
public static final int PHONE_STATE_CHANGED = 101;
//CallManager mCM;
Button callButton ;
ActivityInfo info =null;
ComponentName component ;
String callperiod_text;
String waitperiod_text;
String number;
public int callPeriod=0;
public int waitPeriod = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i("AutoVT","starting AutoVT");
//registerForPhoneStates();
super.onCreate( savedInstanceState );
setContentView( R.layout.main );
callButton = (Button)findViewById(R.id.callButton);
callButton.getBackground().setColorFilter(0xFFFF0000,Mode.MULTIPLY);
callButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
callperiod_text = ( ( ( EditText )findViewById( R.id.call_period )).getText()).toString();
waitperiod_text = ( ( ( EditText )findViewById( R.id.wait_period )).getText() ).toString();
number = ( ( ( EditText )findViewById( R.id.PhoneNumber )).getText() ).toString();
if( !callperiod_text.equals("")&& !waitperiod_text.equals("") && ! number.equals("")) {
callPeriod = (Integer.valueOf( callperiod_text ))*1000;
waitPeriod = (Integer.valueOf( waitperiod_text ))*1000;
phoneHandler.sendEmptyMessage(MAKE_CALL);
}
}
});
}
private Handler phoneHandler = new Handler() {
public void handleMessage(Message msg) {
Log.i("AutoVT received some message:", msg.toString());
switch(msg.what) {
case PHONE_STATE_CHANGED: {
Log.i("AutoVT","Phone State Changed");
Log.i("AutoVT", mCM.getActiveFgCallState() );
if( mCM.getActiveFgCallState() == Call.State.ACTIVE ) {
Log.i("AutoVT","Call ACTIVE");
final Timer timer = new Timer();
Log.i("AutoVT","Active timer started");
timer.scheduleAtFixedRate( new TimerTask() {
int count = 0;
public void run() {
if( count++ >=1) {
timer.cancel();
runOnUiThread(new Runnable() {
@Override
public void run() {
phoneHandler.sendEmptyMessage(END_CALL);
}
});
}
}
}, 0, callPeriod );
} else if( mCM.getActiveFgCallState() == Call.State.DISCONNECTED ) {
Log.i("AutoVT","Call DISCONNECTED");
final Timer timer =new Timer();
Log.i("AutoVT","Waiting timer started");
timer.scheduleAtFixedRate( new TimerTask() {
int count = 0;
public void run() {
if( count++ >=1) {
timer.cancel();
runOnUiThread(new Runnable() {
@Override
public void run() {
phoneHandler.sendEmptyMessage(MAKE_CALL);
}
});
}
}
}, 0, waitPeriod );
}
break;
}
case MAKE_CALL : {
Log.i("AutoVT","In the case MAKE_CALL");
Intent callIntent = new Intent(Intent.ACTION_CALL_PRIVILEGED,Uri.fromParts("tel", number,null));
callIntent.putExtra("videocall", true);
callIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_NEW_TASK);
getApplicationContext().startActivity(callIntent);
break;
}
case END_CALL :{
Log.i("AutoVT","In the case END_CALL");
Intent callEndIntent = new Intent();
callEndIntent.setAction("com.android.phone.END");
sendBroadcast(callEndIntent);
break;
}
}
}
};
}
XML manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pack"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AutoVT"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
A: *
*go to your android-sdk/tools directory.
*go in adb shell if you are in linux ./adb shell work for you.
*fire command dumpsys activity
and if you want to it from eclipdse then,
DDMS -> Devices -> select your device or Emulator -> look at that window you have find
your current running process's package name.
Thanks.
A: it is not process its logcate goto Windows >> Show View >> Other >> click on logcate and run your project so it will display
i think you need this
and also use
System.out.println();
for message generation in logcate
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mongo db sorting on both parent and child collection fields Ok I have two Collections, Parent and Child.
A parent collection can have multiple Child documents.
Now I'd like to be able to to sort ChildCollection documents by it's own fields as well as the fields of it's parent. Is this possible? Yes, I could put it in one big Collection but it will be a lot of redundancies. This would be for millions of records so the more that can be done on the server the better.
ParentCollection
_id : "parentid1"
field1 : "val1"
field2 : "val2"
fieldx.......
ChildCollection
_id : "childid1"
_parentid: "parentid1"
field1 : "val3"
field2 : "val4"
fieldx.........
A: To sort child collection on parent collection fields you should put parent fields on which you want sort into the each child. There is no another way to do this. And you will need update these fields in all child's when you update parent document. Mongodb love denormalization, so don't care to this. Also to increase speed of parent fields update you can make child updates async.
A: There is a work around.
By using $sort I was able to sort the child collection. I returned the same code to a Java List and implemented sorting of parent collection there using Collections.sort(List<T>); and VOILA!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: algorithm complexity question of f>>g & f>g f>g means that f>=g (f dominates g) and g does not dominate f.
f>>g means that cf>g (eventually) for any c>0
What's the difference?
A: An example:
f = 2n
g = n
You can see that f > g but f not >> g because you can choose c == 0.1 and then cf will never be > g.
However:
f = n^2
g = 2n
You can see that at first g>f but eventually f>g for large enough n and no matter how small you make c, eventually cf will become larger than g. Therefore f>>g.
A: > can be read greater than where
>> can be read as much greater than
Difference is in approximations for instance
if a>>b then a+b is approximetly same as a , where you can not say if only a>b holds.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Drag and drop a hyperlink from one website (web page) to another I would like to add drag and drop functionality not just within a web page. The user would drag a hyperlink from a given web page and drop it into an area of another page. This page would then process the hyperlink on the server side.
A: Yo can get dropped item like that
$(document).bind('drop', function (e) {
var url = $(e.originalEvent.dataTransfer.getData('text/html')).filter('img').attr('src');
if (url) {
jQuery('<img/>', {
src: url,
alt: "resim"
}).appendTo('#imgSection');
}
return false;
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ISDATE equivalent of DB2 I have a table which contains date in character format . I want to check the format of date . Please let me know how i can do this in DB2. I know there is a function ISDATE but its not working in DB2. I am on AS400 using db2 as date base .. Please help me out
A: Actually, it looks like DB2 for the AS/400 may not have the ISDATE() function (I can't find anything in the V6R1 reference - or, interestingly, the LUW reference either). So your problem appears to be that the function does not exist.
The root of the problem, of course, is that attempting to translate an invalid date causes the statement to halt. In light of that, this statement should give you a date if the formatting was possible, and null if it was not. Please note that if you've mixed USA and EUR formats/ordering, you might not be able to correctly recover the data (if your separators are different, which I think they are by default, you'll probably be okay).
WITH date_format(strDate, format) as (
SELECT strDate,
CASE
WHEN strDate LIKE('____-__-__') THEN 'ISO'
WHEN strDate LIKE('__.__.____') THEN 'EUR'
WHEN strDate LIKE('__/__/____') THEN 'USA'
ELSE NULL END
FROM dataTable
)
SELECT
strDate,
format,
CASE
WHEN format IS NOT NULL THEN DATE(strDate)
ELSE NULL
END AS realDate
FROM date_format
This turns a dataTable looking like this:
String Dates
=============
2011-09-22
22.09.2011
09/22/2011
a111x90x00 -- And who knows what this is...
Into this:
Results:
strDate format realDate
============================
2011-09-22 ISO 2011-09-22
22.09.2011 EUR 2011-09-22
09/22/2011 USA 2011-09-22
a111x90x00 - -
This example is of course using the default formats which auto-translate. If you have something else, you'll have to manually translate it (instead of returning the format, you can substring it into ISO then cast it).
A: I am not clear on what "check the format of date" intends, nor do I know what any existing ISDATE() effects, but what is implied by the name seems clear enough. Consider:
Extremely lightly tested on v5r3 [i.e. only to ensure both that a few bad date character string example values and some garbage text input actually returned NULL and that each of the various standard date formats with valid values returned a date value], that the following should effect the evaluation of the input varying character string up to 10 characters as a value that can be cast to DATE; that when the input value can not be cast to date, then the result is NULL. Of course that means an initially NULL value is not directly distinguishable from the result produced for an invalid date string.
If some desired indicator, such as TRUE or FALSE is desired as the result instead, then the use of the User Defined Function (UDF) could be coded in a CASE expression; e.g.: CASE WHEN ISDATE(myVCcol) IS NULL THEN 'FALSE' ELSE 'TRUE' END
DROP FUNCTION ISDATE
;
CREATE FUNCTION ISDATE
( InpDateStr VARCHAR( 10 )
) RETURNS DATE
LANGUAGE SQL
DETERMINISTIC
RETURNS NULL ON NULL INPUT
SET OPTION DBGVIEW = *SOURCE , DATFMT = *ISO
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION RETURN NULL ;
RETURN DATE( InpDateStr ) ;
END
;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Django database API (model layer) without installing django? I'm starting a new Python project where I'd love to have Django-like control over my database using models and SQLite, but I don't need all of Django. Also I don't want users to have to install any dependencies before using my product.
Are there any smaller projects out there that deliver Django-like database models, or is it possible to extract only the model functionality from Django and include it in my project folder so the user doesn't have to worry about it?
A: It's not currently possible to just install Django's ORM without the rest of it. You can install the whole lot and just use the ORM, though.
Alternatively you might like to look into one of the standalone Python db wrappers/ORMs. The big one is SQLAlchemy, and there's also the smaller SQLObject.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to handle "open with" without ApplicationDidFinishLaunchingWithOptions I have implemented "documents types" and when I open PDF in safari, I can "open with" my own application. However, I cannot get the newly imported URL, since the application is already launched and was just put in the background (Not being launched from scratch). Only "ApplicationDidBecomeActive" will be called, but without the right file url for me to process.
Anyone knows how to get the file url?
A: When your application is going to open URL then application:openURL:sourceApplication:annotation: method in application delegate is called - you must to handle opening in that method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to read/write "binary" files form Hadoop/HDFS using RUBY gem ganapati I am using the Ganapati Ruby gem to read/write files from a Hadoop HDFS cluster as pointed out in this question - How to write and read files in/from Hadoop HDFS using Ruby?
But this works properly only for text files. How to make it work for binary files (images, pdf, doc, xls, etc)?
I have already edited the client.rb file in the gem code to use the 'b' flag as required by Ruby for binary files in Kernel.open(). The original gem was not using this flag.
But this still does not help.
Thanks for your suggestions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: StackOverflow exception in Java while iterating through a hash set I am trying to select some objects called elements kept in a hashset. I am iterating over the hashset called elements with foreach like
for( Element e: elements).
These selected elements are handled in an ArrayList<Element> el.
Actually, I haven't any problems a while ago. The method passed from unit tests. Then, suddenly I started to get stackoverflow exception for the method. I debugged. I saw something strange going on there.
I am filling an arraylist and iteration of the elements is finished. Finally, the method must return the arraylist. However, it starts to re-iterate the hashset with setting arraylist empty. I did not understand why this happens. I have been programming for 2 years and this is the first time that I saw this strange thing.
Here is the code if you want to have a look at:
public ArrayList<Element> addNextLeftElements(Element firstEl, HashSet<Element> elements, ArrayList<Element> el) {
for (Element nextEl : elements) {
if (!nextEl.equals(firstEl)) {
if (nextEl.overlaps(firstEl, ac.absPrecision)) {
el.add(nextEl);
} else {
for (double dis = 16.0; dis <= 18.1; dis += 0.1) {
if (nextEl.transOverlap(firstEl, dis, ac.absPrecision)) {
if (!el.contains(firstEl)) {
el.add(firstEl);
}
}
for (int displus = 9; displus <= 11; displus++) {
if (nextEl.transOverlap(firstEl, dis, ac.absPrecision)) {
if (!el.contains(firstEl)) {
el.add(firstEl);
}
}
}
}
}
}
}
return(el);
}
Thanks in advance
A: This function as it is, is fine.
StackOverFlow exceptions in java are almost always triggered by an infinite loop, so look if one of the functions you call re-calls addNextLeftElements. run the function like this, and simply look at the stack so you know what functions are causing the overflow.
public ArrayList<Element> addNextLeftElements(Element firstEl, HashSet<Element> elements, ArrayList<Element> el) {
try{
for (Element nextEl : elements) {
if (!nextEl.equals(firstEl)) {
if (nextEl.overlaps(firstEl, ac.absPrecision)) {
el.add(nextEl);
} else {
for (double dis = 16.0; dis <= 18.1; dis += 0.1) {
if (nextEl.transOverlap(firstEl, dis, ac.absPrecision)) {
if (!el.contains(firstEl)) {
el.add(firstEl);
}
}
for (int displus = 9; displus <= 11; displus++) {
if (nextEl.transOverlap(firstEl, dis, ac.absPrecision)) {
if (!el.contains(firstEl)) {
el.add(firstEl);
}
}
}
}
}
}
}
return(el);
}catch (Exception e){
e.printStackTrace();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: share Linkedin API I am working on LinkedIn share API, but I'm facing some problems.
My code:
public function shareAPI()
{
$datatopost ="<?xml version=1.0 encoding=UTF-8?><share><comment>hi</comment><content><title>Survey: Social networks top hiring tool - San Francisco Business Times</title><submitted-url>http://google.com</submitted-url><submitted-image-url></submitted-image-url></content>
<visibility><code>anyone</code></visibility></share>";
$this->_oauth_token_secret=$_SESSION[_oauth_token_secret];
$this->_oauth->fetch(BASE_API_URL.'/v1/people/~/shares',$datatopost,OAUTH_HTTP_METHOD_PUT);
}
When this function is called, it doesn't send the message to the wall.
Please help.
A: Could you be more specific? What is the problem?
One suggestion would be to just use this code:
<iframe src="//www.facebook.com/plugins/like.php?href&send=false&layout=box_count&width=80&show_faces=false&action=like&colorscheme=light&font&height=90" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:80px; height:90px;" allowTransparency="true"></iframe>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the purpose of a listener class in a large project I'm confused about what listener classes do. For example, in this project there is a listener class referenced as so:
<listener>
<listener-class>com.sun.javaee.blueprints.petstore.model.CatalogFacade</listener-class>
</listener>
Is it as the name implies, just listening for actions to do?
A: Listener Classes get notified on selected events, such as starting up the application or creating a new Session.
Listener Classes :
These are simple Java classes which implement one of the two following
interfaces :
*
*javax.servlet.ServletContextListener
*javax.servlet.http.HttpSessionListener
If you want your class to listen for application startup and shutdown
events then implement ServletContextListener interface. If you want
your class to listen for session creation and invalidation events then
implement HttpSessionListener interface.
Source
A: I'd suggest reviewing the chapter on "Application Lifecycle Events" from the Servlet specification.
Depending on which version you're using, here are the corresponding chapters and links to the docs:
*
*Servlet 3.0 : Chapter 11
*Servlet 2.5 : Chapter 10
*Servlet 2.4 : Chapter 10
Listeners are used to be notified of events to web applications, including state changes in the ServletContext, HttpSession, and ServletRequest objects. By implementing predefined listener interfaces (javax.servlet.ServletContextListener, javax.servlet.http.HttpSessionListener, javax.servlet.ServletRequestListener, etc.), the servlet container will notify you of certain events that are happening in your application. They have a lot of potential uses, such as performing one-time application setup and shutdown tasks, intercepting requests to perform logging, tracking HTTP session use, etc.
A: Yes exactly they are listening for some action todo, for example if its contextloaderlistener then it will listen to context loading event and there are many stuff that we can do at such event so these are made for that
A: More generally, a listener is the observer/subscriber side in the observer pattern. The server/framework side provides you with a means to be notified of some event and therefore give you a chance to do your actions.
And it not necessarily must be "a large project". Listeners come handy even in the smaller ones :).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Insert update and delete checkbox datas in mysql database How to Insert update and delete checkbox datas in mysql database table.I need mysql query for all operations . I have only one database table for that operations. Thanks in advance
<input type="checkbox" name="sports" value="Cricket" /> Cricket
<input type="checkbox" name="sports" value="Football" />Football
<input type="checkbox" name="sports" value="Chess" />Chess
Database Structure
ID ,NAME, AGE ,SPORTS(checkbox need to save)
A: You should change your table schema, it's not even in the 1NF, the way you have it. You should create a minimum of two tables to handle this, but I would suggest three tables, considering the fact that sports will repeat.
These would be your tables...
users
id | name | age
sports
id | sport
user_sports
user_id | sport_id
These would be the queries...
When you generate the checkboxes, you would select from the sports table, and as value you would put the id of the sport, not the name.
insert Notice for insert, you are going to use mysql_insert_id to get the id of the user, which will be used on the relationship table.
INSERT INTO users(name, age) VALUES('John', 22);
INSERT INTO user_sports(user_id, sport_id) VALUES(mysql_insert_id(), 123);
select if your checkboxes will contain the id of the sport as value
SELECT u.id user_id, u.name, u.age, s.sport
FROM users u
INNER JOIN user_sports us
ON u.id = us.user_id
AND us.sport_id = 123
INNER JOIN sports s
ON us.sport_id = s.id
select if you have the name of the sport
SELECT u.id user_id, u.name, u.age, s.sport
FROM users u
INNER JOIN user_sports us
ON u.id = us.user_id
INNER JOIN sports s
ON us.sport_id = s.id
AND s.sport = 'Football'
delete
DELETE u, us
FROM users AS u
INNER JOIN user_sports AS us
ON u.id = us.user_id
INNER JOIN sports AS s
ON us.sport_id = s.id
AND s.sport = 'Basketball'
A: Like Shef said, you need those 3 tables user, sport, user_sport
user
+----+----------------+-----+
| id | name | age |
+----+----------------+-----+
| 1 | Freddy Mercury | 65 |
| 2 | Ian Gillan | 66 |
| . | . | . |
+----+----------------+-----+
sport
+----+----------+
| id | sport |
+----+----------+
| 1 | Cricket |
| 2 | Football |
| 3 | Chess |
+----+----------+
user_sport
+---------+----------+
| user_id | sport_id |
+---------+----------+
| . | . |
+---------+----------+
Generate the checkboxes with this php:
$sql = '/* Current User Sports */
SELECT
sp.id AS "sport_id"
, sp.name As "sport"
, us.user_id AS "checked"
FROM sport AS sp
LEFT JOIN user_sport AS us ON (
sp.id = us.sport_id
AND user_id = '.$user_id.'
)
;';
$result = query($sql);
foreach ($result as $row) {
?>
<label>
<input type="checkbox" name="sports[<?php echo ($row['sport_id']) ?>]" checked="checked" />
<?php echo ($row['sport']) ?>
</label>
<?php
}
That will give you this HTML:
<input type="checkbox" name="sports[1]" checked="checked" />Cricket
<input type="checkbox" name="sports[2]" checked="checked" />Football
<input type="checkbox" name="sports[3]" checked="checked" />Chess
The update part
First query (Delete the values for the current $user_id):
DELETE FROM user_sport WHERE user_id = $user_id;
Second query (Insert the new values for the current $user_id):
$sql = 'INSERT INTO user_sport
(user_id, sport_id)
VALUES
(';
$tmp = array();
foreach ($sports as $sport_id => $void) {
$tmp[] = "($user_id, $sport_id)"
}
$sql .= implode("\n, ", $tmp).'
)
;';
This can work for insert/update/delete
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Redirect to subdirectory without losing the rooting to index.php I have the following .htacess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /subdir
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [R,L]
</IfModule>
It does what it should do - put index.php in front of every request.
What I would like to do is to redirect any request to root into the subfolder /de WITHOUT losing the above rooting. Whenever someone comes to the site he should be forwarded to the de folder. I was able to build the rooting to de:
RewriteCond %{HTTP_REFERER} !^http://www.mydomain.com/ [NC]
RewriteRule ^$ index.php/de [R,L]
But I am not able to combine the two. I would appreciate some tips.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510544",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: html form name= php variable I have a form (basically a test) that the users has to fill in. The question nr I get from the MySQL table but I can not get the question number carried over to the answer.php file.
form
$sql1="SELECT * FROM ex_question WHERE test_name = '$tid' ORDER BY RAND() LIMIT 5";
$result1=mysql_query($sql1);
while($row1 = mysql_fetch_array($result1))
{
$test_name=$row1['test_name'];
$q_nr=$row1['q_nr'];
$q_type=$row1['q_type'];
$question=$row1['question'];
$option1=$row1['option1'];
$option2=$row1['option2'];
echo "<form method='post' action='answer.php'>";
echo "<P><strong>$q_nr $question</strong><BR>";
echo "<input type='radio' name='$q_nr' value='option1'>$option1<BR>";
echo "<input type='radio' name='$q_nr' value='option2'>$option2<BR>";
echo "<BR>";
echo "<BR>";
echo "</p>";
}
echo "<input type='submit' value='Send Form'>";
echo "</form>";
?>
answer.php
<?php
$q_nr = $_GET['q_nr'] ;
echo $q_nr;
?>
A: First your form submission method is POST and your are retrieving in GET,
Secondly its not going to work dude, you are creating many forms in loop, It is a logic realted problem, put your FORM out of the loop and make the elelent an array like q_nr[] -------
A: If FORM METHOD equals POST you get the params in $_POST superglobal variable:
$q_nr = $_POST['q_nr'] ;
A: I assume you want to get all questions and display them on the one page and then submit all answers to answer.php? In that case you could:
$sql1="SELECT * FROM ex_question WHERE test_name = '$tid' ORDER BY RAND() LIMIT 5";
$result1=mysql_query($sql1);
echo "<form method='post' action='answer.php'>";
while($row1 = mysql_fetch_array($result1))
{
$test_name=$row1['test_name'];
$q_nr=$row1['q_nr'];
$q_type=$row1['q_type'];
$question=$row1['question'];
$option1=$row1['option1'];
$option2=$row1['option2'];
echo "<P><strong>$q_nr $question</strong><BR>";
echo "<input type='radio' name='question[$q_nr]' value='$option1'>$option1<BR>";
echo "<input type='radio' name='question[$q_nr]' value='$option2'>$option2<BR>";
echo "<BR>";
echo "<BR>";
echo "</p>";
}
echo "<input type='submit' value='Send Form'>";
echo "</form>";
And on answer.php:
//Key is $q_nr and $answer is selected $option
foreach($_POST['question'] as $key => $answer) {
echo $key;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ERROR: could not find gem engineyard-serverside locally or in a repository I am new to Engine Yard.
I just clone an app from the github , its already live at engine yard server.
Now when i try to push latest changes using ey deploy --ref production command it do gave me the error.
ERROR: could not find gem engineyard-serverside locally or in a repository
/usr/local/ey_resin/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:777:in `report_activate_error': RubyGem version error: engineyard-serverside(1.4.1 not = 1.4.10) (Gem::LoadError)
from /usr/local/ey_resin/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:211:in `activate'
from /usr/local/ey_resin/ruby/lib/ruby/site_ruby/1.8/rubygems.rb:1056:in `gem'
from /usr/local/ey_resin/ruby/bin/engineyard-serverside:18
Failed deployment recorded in AppCloud
Deploy failed
Is there any one who can figure out the problem.
A: What version of the engineyard gem do you have on your local machine? It could be an issue with a specific version of that gem that was recently patched; upgrade to engineyard version 1.3.30 on your local machine and try again. That should hopefully alleviate the problem. Otherwise you can submit a ticket to Engine Yard's support staff at support.engineyard.com.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Customizing the show page in ActiveAdmin The default show page in ActiveAdmin is a table with one attribute per row. For my backend, this would be fine, except that I want to hide fields such as id, created_at, updated_at.
Is is possible to do that in a way similar to the index page, i.e. by explicitly listing the desired attributes, while letting AtiveAdmin handle the layout?
The only example shown in the docs suggests that to customize the show page you have to completely take over and write a partial or an arbre construct.
Thanks!
A: I think you're looking for attributes_table:
show do
attributes_table :name, :content
end
See https://github.com/gregbell/active_admin/blob/master/lib/active_admin/views/pages/show.rb if you're curious.
(I completely removed my prior answer because it was basically useless!)
A: show do
attributes_table do
row :profilepic do
image_tag admin_user.profilepic.url, class: 'my_image_size'
end
row :name
row :email
row :adrs
row :phone
row :role
row :salary
row :parent_id
row :joindate
end
end
A: This will show an example of an object Package with a has_many relationship (FAQS)
show do |package|
attributes_table do
row :slug
...
row :hotel
panel "FAQS" do
table_for package.faqs do
column :question
column :answer
end
end
end
end
It will be rendered like this:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: .Net Remoting : Windows Time change cause inoconsistcy state [I am C++ developer now working on C# & .net concept , So question may be very basic ]
I have a Server and Client based on .Net Remoting. Problem is that when i change windows time , Session between client and server goes for a toss. I asked expert who delivered this code , According to him "In .NET Remoting, remote object lifetimes are based on lease
time. If the lease expires, the object is marked for GC" So when i change time lease expire and object is collected by GC.
Client and server both are running on same system.
Can some body suggest me what is going wrong and how to correct this issue.
Thanks
A: I don't know if this is a solution, but give it a try.
I think if you monitor for Windows time change you can close and restart your remoting connection.
I've found this link, hope is't useful.
A: Thanks all for your answers. I found the root cause . Its a ingenious way where a thread from client time calls server at regular interval.
So this way Server knows that client is alive and keep lease time properly. Once time is changed. Ingenious way of calling server at regular interval goes for a toss. and on server side object is disposed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Adobe Air, Actionscript 3: Programmatically set the horizontalscrollpolicy in a scroller to off I am wrapping a VGroup in a Scroller (by setting the scroller.viewport = vgroup), but I want to only be able to scroll vertically. In flex, a scroller component can set the "horizontalscrollpolicy" to "off", but programmatically in Actionscript 3, it does not seem to expose this attribute. How can I do this in Actionscript 3?
A: horizontalScrollPolicy is a style not a property. You can set it like this:
scroller.setStyle('horizontalScrollPolicy', ScrollPolicy.OFF);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510553",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What happens to keystrokes when windows switch focus You know when you are sitting at your computer typing away, sometimes the window focus changes, a pop-up appears or a program starts and you lose focus on the window where you were typing.
Usually what happens is that whatever you are typing at the moment of the focus change gets lost. But where does it go?
A: When a window has focus and you type, that window receives keypress messages. When another window steals focus, the latter window starts receiving those messages instead. If that new window rejects or ignores those messages, that's when the keystrokes "disappear".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510558",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to dismiss a pop up window? private void newGame() {
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final PopupWindow pw = new PopupWindow(inflater.inflate(
R.layout.settings, null, true), 300, 600, true);
pw.showAtLocation(this.findViewById(R.id.settings), Gravity.RIGHT, 0, 0);
pw.setTouchInterceptor(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// your code when touched on the event
return false;
}
});
}
I have posted my code here.I am getting the pop up window.but i dont know how to add events to that pop up window and make it invisible after clicking it.
A: Call the method dismiss in the method onTouch
public boolean onTouch(View v, MotionEvent event) {
// your code when touched on the event
// you can add events here when the pop up window is touched
pw.dismiss();
return true;
}
A: Is it some kind of custom Alert View, meaning some kind of text, textinput, ... and one or more buttons ("OK", "Cancel")?
Then you could use the following code:
protected Dialog onCreateDialog(int id) {
Dialog dialog = new Dialog(this);
switch (id) {
case DIALOG_HELP_ID:
// This example shows how to add a custom layout to an AlertDialog
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(
R.layout.helpdialog_main, null);
return new AlertDialog.Builder(Main.this)
.setView(textEntryView)
.setPositiveButton(R.string.stringHelptextButtonOK,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
// Popup is closed automatically, nothing
// needs to be done here
}
}).create();
default:
dialog = null;
}
return dialog;
}
A: public class Pop extends Activity {
PopupWindow pw;
/** Called when the activity is first created. */
Button ok;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ok = (Button) findViewById(R.id.but);
ok.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
LayoutInflater inflater = (LayoutInflater)Pop.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
pw = new PopupWindow(inflater.inflate(R.layout.popup,null, false),400,400,true);
pw.showAtLocation(findViewById(R.id.mainn), Gravity.BOTTOM, 0,0);
}
});
}
public void onbuttonClick(View v) {
Intent openstartingpoint2=new Intent("com.lee.pop.CLA");
startActivity(openstartingpoint2);
pw.dismiss();
return ;
}
}
A: how to handle the Popup window and alert - just follow this code -
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;`enter code here`
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Alart_Pop_Handel {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
Set<String> wind = driver.getWindowHandles();
System.out.println("total window size -> " +wind.size());
// blank fire fox will open
Iterator<String> it = wind.iterator();
System.out.println(it.next()); // show the window id
driver.get("http://in.rediff.com/");
wind = driver.getWindowHandles(); // call one more time to get window
it = wind.iterator();
System.out.println(" total window size -> " +wind.size());
// show 2 window and id
// handel pop up
// create string
String main= it.next();
String pop= it.next();
System.out.println(main); // take a print for both window id
System.out.println(pop);
driver.switchTo().window(pop); // control change to pop up
driver.close(); // close pop up
driver.switchTo().window(main); // get back to main window
System.out.println("************ main window id*****************");
System.out.println(main); // make sure the main window id will see
//click signin
driver.findElement(By.xpath(".//*[@id='signin_info']/a[1]")).click();
driver.findElement(By.xpath("//input[@type='submit']")).click();
// handel alert
Alert al=driver.switchTo().alert();
System.out.println(al.getText());
al.accept();
driver.switchTo().defaultContent();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Tracking down memory leak in a plugin, using _crtBreakAlloc, _CRTDBG_MAP_ALLOC We have several after effects plugins that we have good evidence are leaking memory. To investigate this, I am playing around with Memory Leak Detection and Isolation in the vcc compiler/runtime. I enabled leak detection with:
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
And I get a nice dump of leaks. However, I don't get file names and line numbers. My best guess is that this is because I'm building a dll, which is consumed by the after effects exe, and the #define needs to be made in the executable, not my plugin (this doesn't entirely fit with my mental model of what this define and includes actually do, but it's the best I can come up with).
So the other option is setting breakpoints for specific memory allocation numbers. However, the leaking allocations aren't a set of consistant allocation numbers, so I'm having limitted success with that.
So, any ideas here? Either how to better use this tool, or other ways to investigate this? Thanks!
A: You do have to recompile those DLLs with the same #defines - they turn calls to malloc() into calls to malloc_dbg() and this enables filenames and line numbers in the dump. That's all the "leak detection" does - each allocation is passed the filename and line number and they are stored and later dumped. No calls to malloc_dbg() - no filenames and no line numbers.
Also leak dumps (all related functions) are per-runtime - the dump is done for the heap of the current module runtime, not necessarily for all modules. Since you might have several C++ runtimes in your process (each DLL can be linked against its own runtime) it might happen that the dump is simply not done for the runtime you expect.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510566",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: In ASP.Net how can you update a database after sending a HttpResponse I am new to ASP.Net coding and have written a simple website.
The client sends a POST to my website. The post data is used to perform an update to my database, and save an image on the website. The Response to the client is very simple and could be sent before the database is updated or the image is saved.
My website is currently set up using the Page_Load method
protected void Page_Load(object sender, EventArgs e)
{
UploadData uploadData = new UploadData(Request);
if (uploadData.isValid)
{
UploadDataToDB(uploadData);
SaveImage();
}
}
How can I go about sending the Response to the client immediately, and updating the database and saving the image after I have sent the response?
A: Use ajax to start async saving using page method which calls a web service or other backend logic. do the db update and image save in backend. if it fails with ajax you have the onError method to notify the user on UI but UI will never be blocked with this approach.
A: If you run your code in a separate thread (either use a Task or create your own threaded queue of work, depending on how much load this is going to see), you can start the work and allow Page_Load to return.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510584",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hibernate - Entity referencing itself through a join table with an additional column I have an annotated Entity called Part. It consists of an "id" and a few other variables. I have another table called "bomdefinitions". This table has three columns (qty, parent, target) (I understand target is a stupid name but I can't change it as the database already exists). The idea is a Part can be made up of many other parts, and can also be used in many other parts, and the table "bomdefinitions" says what parent has what "target"s associated with it and how many are used by it.
The problem is, if I comment out one of the OneToMany relationships in Part.java and leave the other, it works fine, but if I have them both in my code, trying to access either of them results in an infinite loop of Hibernate queries.
I can find examples of mapping an entity to itself, examples of mapping an entity using a join table with extra columns, and examples of various ways to do the annotations, but nothing doing all of that within a single application, and the individual examples I can find don't seem to be helping here.
Anyone with more experience in Hibernate have any ideas as to what I am doing wrong?
Edit (this code causes the infinite loop):
getHibernateTemplate().get(Part.class, id).getParentBomDefinitions();
And here is the query in the Output -
It starts with:
Hibernate: select part0_.id as id0_3_, childbomde1_.target as target0_5_, childbomde1_.parent as parent5_, childbomde1_.target as target5_, childbomde1_.parent as parent4_0_, childbomde1_.target as target4_0_, childbomde1_.qty as qty4_0_, part2_.id as id0_1_ from parts part0_ left outer join bomdefinitions childbomde1_ on part0_.id=childbomde1_.target left outer join parts part2_ on childbomde1_.parent=part2_.id
Hibernate: select parentbomd0_.parent as parent0_2_, parentbomd0_.parent as parent2_, parentbomd0_.target as target2_, parentbomd0_.parent as parent4_1_, parentbomd0_.target as target4_1_, parentbomd0_.qty as qty4_1_, part1_.id as id0_0_ from bomdefinitions parentbomd0_ left outer join parts part1_ on parentbomd0_.target=part1_.id where parentbomd0_.parent=?
Then these 2 queries repeat indefinitely:
Hibernate: select parentbomd0_.parent as parent0_2_, parentbomd0_.parent as parent2_, parentbomd0_.target as target2_, parentbomd0_.parent as parent4_1_, parentbomd0_.target as target4_1_, parentbomd0_.qty as qty4_1_, part1_.id as id0_0_ from bomdefinitions parentbomd0_ left outer join parts part1_ on parentbomd0_.target=part1_.id where parentbomd0_.parent=?
Hibernate: select childbomde0_.target as target0_2_, childbomde0_.parent as parent2_, childbomde0_.target as target2_, childbomde0_.parent as parent4_1_, childbomde0_.target as target4_1_, childbomde0_.qty as qty4_1_, part1_.id as id0_0_ from bomdefinitions childbomde0_ left outer join parts part1_ on childbomde0_.parent=part1_.id where childbomde0_.target=?
BomDefinition.java (pretty much taken out of "Java Persistence with Hibernate")
@Entity
@Table(name = "bomdefinitions")
public class BomDefinition {
@Embeddable
public static class Id implements Serializable {
@Column(name = "target")
private String targetId;
@Column(name = "parent")
private String parentId;
public Id() {}
public Id(String targetId, String parentId) {
this.targetId = targetId;
this.parentId = parentId;
}
public boolean equals(Object o) {
if (o != null && o instanceof Id) {
Id that = (Id) o;
return this.targetId.equals(that.targetId) && this.parentId.equals(that.parentId);
} else {
return false;
}
}
public int hashCode() {
return targetId.hashCode() + parentId.hashCode();
}
}
@EmbeddedId
private Id id = new Id();
@Column(name = "qty")
private String quantity;
@ManyToOne
@JoinColumn(name = "parent",
insertable = false,
updatable = false)
private Part parent;
@ManyToOne
@JoinColumn(name = "target",
insertable = false,
updatable = false)
private Part child;
public BomDefinition() {}
public BomDefinition(String quantity, Part parent, Part child) {
this.quantity = quantity;
this.parent = parent;
this.child = child;
this.id.parentId = parent.getId();
this.id.targetId = child.getId();
}
// Getters and Setters
}
Part.java:
@Entity
@Table(name="parts", uniqueConstraints = {@UniqueConstraint(columnNames = {"id"})})
public class Part implements Serializable {
protected final Logger log = Logger.getLogger(getClass());
private String id;
// *** other variables ***
public Part() {}
public Part(String id, /* other variables */) {
this.id = id;
// *** other variables ***
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
private Set parentBomDefinitions = new HashSet(0);
private Set childBomDefinitions = new HashSet(0);
@OneToMany(mappedBy = "parent",
targetEntity = BomDefinition.class,
cascade = {CascadeType.PERSIST, CascadeType.MERGE},
fetch = FetchType.EAGER)
public Set getParentBomDefinitions() {
return parentBomDefinitions;
}
public void setParentBomDefinitions(Set<BomDefinition> parentBomDefinitions) {
this.parentBomDefinitions = parentBomDefinitions;
}
@OneToMany(mappedBy = "child", // target?
targetEntity = BomDefinition.class,
cascade = {CascadeType.PERSIST, CascadeType.MERGE},
fetch = FetchType.EAGER)
public Set getChildBomDefinitions() {
return childBomDefinitions;
}
public void setChildBomDefinitions(Set childBomDefinitions) {
this.childBomDefinitions = childBomDefinitions;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Xcode 4.1 editor text color problem While I editing code, the editor window suddenly become unreadable. I attached a screenshot (Left window has the problem). It happens 2 or 3 times a week. I'm using Xcode 4.1 on Lion and color theme is Midnight.
It happens also when I using Basic theme. When I use Basic theme text color changed to white.
What's the problem?
A: That used to happen when I made a syntax error in the code, after I fixed it the problem went away. But this time it became permanent for some reason, and it really bothers me. I suggest you to check for warnings/ syntax errors but I also would like to hear a real solution for the problem.
Edit: Following solutions on this page helped: xcode code sense color/completion not working
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510586",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Entity Framework or SQL In our company we have a lot of old Delphi applications and we want to rewrite them to .Net applications. These applications are very complex, because they stared with them 15 years ago and are still expanding them.
I'm the only (real) .Net developer in the team.
Now the head of the department wants to use the Entity Framework because he read something about it.
But I don't have experience with EF, but I have created my own framework, based on SQL statements.
I don't see how EF can be easier and stronger than SQL statements.
Can somebody convince me why we should move to Entity Framework? Taking into account that the team knows SQL, but are not real .Net developers.
Thanks
A: If you're in the lucky position to be able to start from scratch, on a green pasture - by all means, invest that time you need to get to know Entity Framework!
It's a great ORM - and a great productivity helper. EF can help you make the 80% case - grabbing an object, manipulating it, and storing it back into the database - just sooooo much easier!
using(MyDatabaseContext ctx = new MyDatabaseContext())
{
Customer c1 = ctx.Customers.Find(4711);
c1.Name = "Acme Inc.";
// set other properties, if needed......
ctx.SaveChanges();
}
Is using your SQL based framework just as easy as this?? Can't be that hard to learn for Delphi developers! Delphi and the .NET framework are actually quite similar (duh! the same guy created them, basically.....) and coming to .NET from Delphi is very easy and very natural (I did this step couple years ago) - much easier than for an old-school VB6 developer, actually....
Go read up on Entity Framework - start with the Absolute Beginner's Guide to Entity Framework! EF takes care of just soo much silly and boring "glue code" that you don't have to write yourself anymore.......
Also: using EF doesn't mean you cannot use SQL anymore - for certain tasks, like bulk operations, SQL is still by far the best choice. If you need, at least with EF in .NET 4, you can even plug in stored procedures in places where performance or other concerns require it. Works like a charm!
Find lots of info on Entity Framework (white papers, samples, videos) at the MSDN Entity Framework Developer Center
A: Even if you have made your generic dal whic allows you to call stored procs and get tables, scalars, readers and so on I doubt that classes will be as tested and mature as the db context object of EF.
Dont forget you can use EF to call your sql stored procs or get data with sql and you do not need to model all entities at day 1.
I would rely on db context class just to write modern .net code and forget about direct managing SqlConnection and SqlCommand by hand the Ado.Net way.
A: The head of your department seems a'ok. Invest in learning the Entity Framework, its robust, tested, functional, flexible, and best of all, you can still use your framework too. Though, I advise just using only EF. Especially if you are to pave the way for future .NET devs in the company, use EF. Its well documented, so you can jump right in less than a single day worth of coding. Furthermore, if these applications are being expanded upon todate as you say, EF will pave the way (very easily too) for things like MySQL and other connector support (after all that is one of its strengths). EF will gain you so much in the short and long term. You also get the support of the tools for EF, which is a huge ++. I used my own ADO.NET stuff for a long time, then moved to DLinq, and now EF and I will never look back (for the most part). MSFT is still making improvements to EF too (being 4.1 was just released in April), so I would have to say its a great choice. Its the core for our data layer in our new flagship product too, supporting MySQL, SQL 2005, 2008, Azure, and 2008 R2 pretty much out of the box. +++
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510591",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: is there a way to tell if a web app was started from home screen icon? iOS/android? The app in question is a magazine that behaves like many of the iPad magazine apps, but it is a web page. I have a spinner that runs for the duration of the initial query setup, with a healthy additional two seconds.
this works fine when starting the web app from a web page, but after saving to the home screen, where is is cached properly, it takes almost twice as long before it becomes responsive, yet the spinner lasts the usual time.
is there a way to tell if the app is opened from the home screen icon so I can add some extra 'pad time' to the spinner, keeping the user from jabbing at the screen and cursing may name in frustration, and possibly deleting the app?
A sample of the app in question can be seen here: http://straathof.acadnet.ca/stacks/test1/
try to time the spinner/response for movement from the web page and save it to the home screen and reopen it to see the delay in behaviour...
any help is always appreciated.
A: This may work, as well as a timer to add more messages while people are waiting. detecting UIWebView with Javascript
The modified code to turn off the spinner is here, as derived from the link above. The spinner is constructed with spin.js...
this may need modification after ios5 as the delay due to slow javascript may be solved.
$(window).load(function(){
if (window.navigator.standalone == true) {
//not in safari
var timer = 10000; // longer timer for homepage icon
} else {
var timer = 2500; // shorter time for safari
}
setTimeout ( function () {
spinner.stop();
$('#spinner').addClass('hidder').css('z-index','-10');
updateOrientation;
},timer);
});
A: You can append you url address a querystring ?is_cached=true on run time from JS, then once the user will add the app to the homescreen (or his favorites) it will be saved with the querystring :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Child objects not binding to model in wcf web api Him
I'm using the WCF Web API for creating a restful services. I've a method with following signature
[WebInvoke(UriTemplate="AddJob")]
public string AddJob(Job job)
{
//...
}
The Job object has a child object RecurDay. the posted values from the form are not binding to the RecurDay properties, in fact the RecurDay object itself is not getting created.
NOTE: The form fields are named same as the class properties. Ex. Id, JobName, RecurDay.Id, RecurDay.Day etc. The Id, JobName are mapped correctly but the Address.Id and RecurDay.Day are not getting mapped.
A: I think you'll have to create a JSON object from your form data on the client and send this to your API - otherwise it won't get de-serialized.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: [iOS]How to get the Calendar Event, one Recurrence as one event? I get calendar event as the following code:
NSDate *startDate1 = [NSDate date];
NSDate *endDate1 = [NSDate distantFuture];
NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:startDate1 endDate:endDate1 calendars:calendarArray];
NSArray *events = [eventStore eventsMatchingPredicate:predicate];
But if I add a recurrence event, if the frequency is every week, the 'events' will has 209 objects; if a event frequency is every 2 week, 'events' will have 105 objects.
I compute the time, it is 4 years of time also.
How can I get the event, one recurrence event only has one object?
//I'm testing using event.eventIdentifier...
A: Repeated events has a read-only property 'isDetached'.
Also, you can find the details about recurrence rules, etc. in:
WWDC 2010 videos, Session 136 Calendar Integration with Event Kit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7510602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.