text stringlengths 8 267k | meta dict |
|---|---|
Q: regex giving error less than 2 okay so I set up this regex to take exponential and give me back doubles but it crashes if I give it less than two
String sc = "2 e 3+ 1";
Pattern pattern = Pattern.compile("\\s+");
Matcher matcher = pattern.matcher(sc);
boolean check = matcher.find();
sc = matcher.replaceAll("");
String sc1;
Pattern p = Pattern.compile("[0-9]+[.]?[0-9]*[eE][-+]?[0-9]+");
Matcher m = p.matcher(sc);
m.find();
int starting = m.start(); //where first match starts
int ending = m.end();//where it ends
String scientificDouble = sc.substring(starting, ending);
String replacement = "" + Double.parseDouble(scientificDouble);
sc1 = sc.replace(scientificDouble, replacement); //first time
//this block must go in a loop until getting to the end, i.e. as long as m.find() returns true
m.find();
starting = m.start(); //where next match starts
ending = m.end();//where it ends
scientificDouble = sc.substring(starting, ending);
replacement = "" + Double.parseDouble(scientificDouble);
sc1 = sc1.replace(scientificDouble, replacement);//all other times,
if I give it sc = "2e3 + 1 " it crashes saying
Exception in thread "main" java.lang.IllegalStateException: No match available
at java.util.regex.Matcher.start(Matcher.java:325)
at StringMan.main(StringMan.java:32)
A: Your regex doesn't fit the spaces in your string. I tried to fix your regex, try this:
Pattern p = Pattern.compile("[0-9]+(\\.[0-9]+)?[eE][\\-\\+]?[0-9]*");
String sc = "2e3+1"; // Whitespaces cleared
A:
still crashed :Exception in thread "main" java.lang.IllegalStateException: No match available ...
That's because you are ignoring the result of the m.find(...) calls. If m.find returns false, then the pattern match failed and methods like Matcher.start Matcher.end and Matcher.group will throw IllegalStateException if called.
This will all be explained in the Javadoc for Matcher and its methods. I strongly recommend that you take the time to read it.
A: To add to @Stephen C's answer, find() will not magically loop the block of code for you. Since you want to execute the same block of code as long as find() returns true, you should use a while loop:
String source = "2e3+1, 2.1e+5, 2.8E-2";
Pattern pattern = Pattern.compile("[0-9]+(\\.[0-9]+)?[eE][\\-\\+]?[0-9]*");
Matcher matcher = pattern.matcher(source);
while (matcher.find()) {
String match = matcher.group();
double d = Double.parseDouble(match);
System.out.println(d);
}
(using regex correctly suggested by @Martijn Courteaux's answer)
This particular example prints all parsed double to System.out - you can do what you need with them.
Please upvote the cited answers if this is helpful.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7543991",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Make Visual Studio 2010 display more lines in code editor With a 14" LCD monitor (1366x768), my VS2010 can only display 21 lines in code editor. There are too many tool bars occupied upper and bottom part (see below screenshot). When writing codes, it's OK to use fullscreen mode. However, when reading codes, I need some of the toolbar like the bookmark bar, open file tab. Is there any suggestion to increase the viewing area?
A: Create a single custom toolbar with just the commands you really use in it. Remove the other toolbars. Close tool windows docked at the bottom.
There is an addon that can even remove the menu bar – you'll need to learn keyboard shortcuts (this is a good idea anyway: moving a hand to/from the mouse is much slower).
A: *
*Increase secreen resolution
*Use a different font such as Terminal or Consolas. I guess you must be already using Consolas, try Terminal.
*Decrease the font size.
A: Turn monitor by 90 degree, so it is higher not wider.
Besides that - get a decent monitor. 14" is barely legal acording to some european laws for office use. Programmers tyically get a lot bigger.
A: Customize your toolbars and get rid of the buttons you don't use. You'll probably be able to fit everything on one row after that.
For example, I don't think I have used the toolbar buttons for cut/copy/paste, using the keyboard instead, so those were the first buttons I removed.
On the right side of each toolbar, there is a button with an arrow, click on that and you should see "customize this toolbar" in the drop-down menu.
A: Well, if you are having an older notebook, you might not able to change your display, increase your screen resolution or turn the monitor by 90 degrees, like the others suggested. Here are my suggestions for when this is the case:
*
*Place your toolbars left or right instead at the top or bottom
*close output window
*use fullscreen mode and learn keyboard shortcuts for bookmarks and file menu functions, so you can work without the specfic toolbars
A: I use Full Screen mode (ALT+SHIFT+ENTER to toggle) when doing the actual editing, with only the solution explorer open on the right hand side.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7543992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: OOP Design Question Got this interview question which i'm wondering about:
A software company designed an app that manages employees and, among other functions, calculates Salary.
The current structure which fits the customer's requirements is:
abstract Class Employee;
Class Manager extends Employee;
Class Engineer extends Employee;
The customer would now like to add the ability to support different types of salary calculations for employees who work on an hourly wage, monthly salary. Both Engineer and Manager can be either.
The customer also notified the software company that they will add a number of other types of salaries in the future.
The Question - How would you design this? Does if fall in any design pattern solution?
Thanks!
A: Apply the strategy pattern:
http://en.wikipedia.org/wiki/Strategy_pattern
Make "Salary_Calculation" a strategy associated to Employee. "Salary_Calculation" should be an interface or an abstract base class, and each salary calculation model is a subclass of that.
A: Add a SalaryCalculator interface and instantiate a SalaryCalculator object during the Employee object's construction using the salary type. The SalaryCalculaotr object will take care of salary calculations for each salary type.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544016",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to initialize pages in jquery mobile? pageinit not firing What's the right way to initialize objects on a jquery mobile page? The events docs say to use "pageInit()" with no examples of that function, but give examples of binding to the "pageinit" method (note case difference). However, I don't see the event firing at all in this simple test page:
<html>
<body>
<script type="text/javascript" charset="utf-8" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8" src="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.js"></script>
<div data-role="page" id="myPage">
test
</div>
<script>
$("#myPage").live('pageinit',function() {
alert("This never happens");
});
</script>
</body>
</html>
What am I missing? I should add that if you change pageinit to another event like pagecreate this code works.
---- UPDATE ----
This bug is marked as "closed" in the JQM issue tracker. Apparently opinions differ about whether this is working properly or not.
A: Turns out this is a bug in 1.0b3 that is fixed in the current head. So if you want a fix now, you gotta grab the latest from git. Or wait for the next release.
A: It started working when I embedded script within page div:
<body>
<div id="indexPage" data-role="page">
<script type="text/javascript">
$("#indexPage").live('pageinit', function() {
// do something here...
});
</script>
</div>
</body>
Used jQuery Mobile 1.0RC1
A: .live() is deprecated, suggestion is to use .on() in jQuery 1.7+ :
<script type="text/javascript">
$(document).on('pageinit', '#indexPage', function(){
// code
});
</script>
Check the online doc for more information about .on(): http://api.jquery.com/on/
A: jQuery(document).live('pageinit',function(event){
centerHeaderDiv();
updateOrientation();
settingsMenu.init();
menu();
hideMenuPopupOnBodyClick();
})
This is working now. Now all page transitions and all JQM AJAX functionality would work along with your defined javascript functions! Enjoy!
A: pageinit will not fire in case it is on secondary pages ( NOT MAIN page ) if it is written in common <script> tag...
I have such a problem - on secondary pages that are not loaded with 'rel="external"', the code in the common <script> tag is never executed...
really this code is always executed...
<body>
<div id="indexPage" data-role="page">
<script type="text/javascript">
$("#indexPage").live('pageinit', function() {
// do something here...
});
</script>
</div>
</body>
althrough if you made "tabbed interface", using of "pageshow" is better
A: I had to put the script in the HTML page section which to me is a bug. It is loaded normally in a browser (not via AJAX) and all on a single page including javascript. We're not supposed to have to use document ready.
A: The easiest way I found to deal with this was to use JQM + Steal. It works like a charm as long as you put:
<script type='text/javascript' src='../steal/steal.js?mypage'></script>
Inside of the data-role='page' div.
Then use AJAX to connect anything that can use the same mypage.js and use an external link (by using the rel="external" tag) to anything that requires a different steal page.
A: @Wojciech Bańcer
From the jQuery docs:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
A: Try this:
$('div.page').live('pageinit', function(e) {
console.log("Event Fired");
});
A: $(document).on("pageinit", "#myPage", function(event) {
alert("This page was just enhanced by jQuery Mobile!");
});
A: The events don't fire on the initial page, only on pages you load via Ajax. In the above case you can just:
<script>
$(document).ready(function() {
alert("This happens");
});
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "41"
} |
Q: PHP-Function ereg_replace() is deprecated class autoActiveLink {
function makeActiveLink($originalString){
$newString = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a href=\"\\0\" target=\"_blank\">\\0</a>", $originalString);
return $newString;
}
}
What should I replace the function ereg_replace with? I tried preg_replace, but the error still persists.
A: preg_replace()
http://php.net/manual/en/function.preg-replace.php
It is not reasonable that the error still exists after you replaced it to preg_replace
But the pattern syntax is different, youll have to convert it
A: Try
class autoActiveLink {
function makeActiveLink($originalString){
$newString = preg_replace('#([A-Za-z]+://[^<>\s]+[A-Za-z0-9/])#','<a href="$1" target="_blank">$1</a>', $originalString);
return $newString;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to prevent specific images from being cached by browser with NGINX I have an avatar upload page in my site. But when the user successfully uploaded the avatar the browser keeps showing the old one. How to prevent avatar image from being cached by browser?
A: Haven't tried it myself but this might work:
if ($request_uri ~* "^/image/location.png$") {
add_header Pragma "no-cache";
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Lesson 16 - Gas Mileage - Multiple Classes Project ~~~Update: Solved! Thanks everyone!~~~
I'm working on a project from the Blue Pelican Java book, lesson 16 project Gas Mileage. It asks to create two classes, one is Automobile which holds the methods I will work with. The other class, Tester, is the main class. Every time I run the Tester class, it returns a value of -Infinity. I can't figure out why, other than that I've singled out the problem is in the Automobile class at line 14 in the takeTrip method. When I leave that method out of the Tester class, it returns the correct values.
This is the Automobile class:
public class Automobile
{
public Automobile(double m) // Accepts value m to the double mpg. Also declares
{
double mpg = m;
double gallons;
}
public void fillUp(double f) // Adds fuel to the tank
{
gallons += f;
}
public void takeTrip(double t) // Takes away fuel from the tank depending upon how many miles are driven
{
gallons -= t / mpg; // Not sure how to do this line. For some reason, when I reference mpg, the output of Tester is "-infinity". Shouldn't it do gallons = gallons - (miles driven / mpg)?
}
public double reportFuel() // Returns value of how much fuel is left in tank
{
double r = gallons;
return r;
}
public double mpg;
public double gallons;
}
And this is the Tester class:
public class Tester
{
public static void main(String args[])
{
Automobile myBmw = new Automobile(24); // Passes constructor argument of 24 mpg
myBmw.fillUp(20); // Adds 20 gallons to fillUp method
myBmw.takeTrip(100); // Takes away the fuel used for 100 miles using the takeTrip method
double fuel_left = myBmw.reportFuel(); // Initializes fuel_left to the method reportFuel
System.out.println(fuel_left);
}
}
Any help is appreciated, thanks!
-AJ
A: You constructor doesn't need the 'double' identifier. Here you are creating a new variable also called mpg, which is forgotten after the constructor completes. Instead use this:
public Automobile(double m) // Accepts value m to the double mpg. Also declares
{
mpg = m;
}
A: This is the problem:
public Automobile(double m) // Accepts value m to the double mpg. Also declares
{
double mpg = m;
double gallons;
}
This is declaring a local variable called mpg, rather than changing the value of the instance variable for the object. (The instance variables are declared at the bottom of the class.) It's then declaring another local variable called gallons which isn't assigned any value. At the end of the constructor, the instance variables gallons and mpg will both be zero - which means you'll be dividing by zero in the takeTrip method - so you're subtracting "infinity gallons" from the fuel tank, leading to your final result. Your constructor should look like this instead:
public Automobile(double m)
{
this.mpg = m;
}
or just:
public Automobile(double m)
{
mpg = m;
}
If you're still unsure about local variables and instance variables after this, see if there's anything earlier in the book which might help you. (By lesson 16 I'd expect it to have been covered...)
A: In your Automobile c'tor, you're currently creating a local variable called mpg, instead of changing the class member. All there should be in that function is mpg = m; (the second line does nothing).
Currently, mpg (the member) is automatically initialized to 0, and then t/mpg is infinity, and when you take that away from some finite number, you get -infinity.
By the way, in reportFuel(), you could just as well just write return gallons;, without declaring r.
A: Why are again declaring your attributes inside your constructor where as you have already declared them in your class. Actually the attributes you are declaring inside the constructor will not persist after the execution of the method ends (in this case the constructor). So though you are trying to initialize the attributes of your class you are actually not doing this.
So in your constructor try this
mpg=m
gallons=0
I think the other methods are fine. Another thing try to keep those attributes (mpg and gallons) private. Though the program will run without any error still you are violating the main thing of oop - encapsulation. cheers :)
A: public class Automobile {
private double mpg = 0; //need to handle the division by 0 if you
//initialize it to 0
private double gallons = 0;
public Automobile(double m, double g)
{
mpg = m;
gallons = g;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can't get the handle of a Cwnd Class in MFC Windowless Activex? I have asked two questions earlier about this and for each post there was some solutions i tried them, but the problem still exist.
My first question was : why a windowless Activex does not return the Handle. the suggestion was "change the creation setting an make windowless activate off, i have tried it but still m_hWnd property has returned zero as GetSafeHwnd() method has did.
the second one was the same question this one focused on COleControl class and it's ancestor CWnd. the solution was as this "Create invisible window somewhere in your control initialization code. Handle the messages sent to this window, and call controls methods directly". so i did that but the created class still returns zero handle.
here is my new invisible class source:
// moWind.cpp : implementation file
//
#include "stdafx.h"
#include "PINActive.h"
#include "moWind.h"
#include "include\xfspin.h"
#include <math.h>
// moWind
IMPLEMENT_DYNAMIC(moWind, CWnd)
moWind::moWind(){}
moWind::~moWind(){}
//=============================================================
LRESULT moWind::OnExecuteEvent (WPARAM wParam, LPARAM lParam)
{
WFSRESULT *pResult = (WFSRESULT *)lParam;
CString EK=_T("");
CString str;
int reskey=0;
if (pResult->u.dwEventID=WFS_EXEE_PIN_KEY)
{
LPWFSPINKEY pressedkey;
pressedkey=(LPWFSPINKEY)pResult->lpBuffer;
reskey = log10((double)pressedkey->ulDigit) / log10((double)2);
EK.Format("%d",reskey);
xfsOnKeyEvent->OnKeyRecieved(reskey);
}
else
{
str.Format("ExecuteEvent: ID = %d\r\n", pResult->u.dwEventID);
}
MessageBox("a Execute message Recieved");
return 0;
}
BEGIN_MESSAGE_MAP(moWind, CWnd)
ON_MESSAGE(WFS_EXECUTE_EVENT,OnExecuteEvent)
END_MESSAGE_MAP()
and this is .h file of the class:
// moWind.h
class IXFSEvents
{
protected:
IXFSEvents(){};
virtual ~IXFSEvents(){};
public:
virtual void OnKeyRecieved(int key)=0;
};
class moWind : public CWnd
{
DECLARE_DYNAMIC(moWind)
public:
moWind();
virtual ~moWind();
void Register(IXFSEvents* obj)
{
xfsOnKeyEvent= obj;
}
protected:
IXFSEvents* xfsOnKeyEvent;
LRESULT OnExecuteEvent (WPARAM wParam, LPARAM lParam);
DECLARE_MESSAGE_MAP()
};
and at the end here this the way I've used this class in my Activex:
in the myActivex.h file:
include "moWind.h"
class CmyActivexCtrl : public COleControl, public IXFSEvents
{
...
Class definition
...
protected:
moWind tmpWind;
.
.
};
finally in the creation method of myActivex i have initialized the component callback method an wanted to get it's Handle as this:
CmyActivexCtrl::CmyActivexCtrl()
{
InitializeIIDs(&IID_DmyActivex, &IID_DmyActivexEvents);
tmpWind.Register(this);
myOtherComponent.WindowsHandle=tmpWind.GetSafeHwnd(); //here my Cwnd derived class returns zero
//my other component gets the handle and call an API with it to register
//the given handle and force the API to send the messages to that handle.
}
A: As you mentioned you need a window handle to be able to receive user messages through it, you always have an option of creating a helper window, such as message only window, see Using CreateWindowEx to Make a Message-Only Window.
For your windowless control it is okay to not have any window handle at all, so you cannot really rely on handle availability unless you own a window yourself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android stacked views The view that I would like to have would be shown in the figure.
A: For that you can take FrameLayout.
For example - 1:
<FrameLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:src="@drawable/icon"
android:scaleType="fitCenter"
android:layout_height="fill_parent"
android:layout_width="fill_parent"/>
<TextView
android:text="Learn-Android.com"
android:textSize="24sp"
android:textColor="#000000"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
android:gravity="center"/>
</FrameLayout>
Update:
For Example - 2: Superb example and Trick, found here: http://www.curious-creature.org/2009/03/01/android-layout-tricks-3-optimize-part-1/
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center"
android:src="@drawable/golden_gate" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dip"
android:layout_gravity="center_horizontal|bottom"
android:padding="12dip"
android:background="#AA000000"
android:textColor="#ffffffff"
android:text="Golden Gate" />
</FrameLayout>
A: Putting the 2 custom views inside a relative layout will give what you've shown in the image.
Yes the customview2 will be transparent in the areas where you don't draw anything. To avoid that you will need to set a background to that view.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: 3tier Architecture for DatagridView I have a DatagridView and i want to populate it with the contents of a database. I know it can be done through DataAdapter, dataset and Fill/Update commands and all. But what I want to know is, how to write it in a 3tier architecture. I mean, what will be the commands in the Presentation layer, Business layer and Data layer. I am new born baby for 3tier architecturre. And not able to get it right.Thanks.
A: After googling it for a while and implementing some of my techniques, I came upto this:
UILayer:
private void FillData(object sender, EventArgs e)
{
BusinessObject bo = new BusinessObject();
Datatable dt = new Datatable();
dt = bo.getTable();
datagridview.DataSource = dt;
}
BusinessLayer:
public DataTable getTable()
{
DataLayer dl = new DataLayer();
DataTable dt = new DataTable();
dt = dl.getTable();
if(dt == null || dt.HasErrors == true)
{
MessageBox.Show("Datable has Errors or is Null");
return
}
return dt;
}
DataLayer:
public DataTable getTable()
{
SqlConnection con = new SqlConnection(connectionString);
string myCommand = "Select empId, empDesignation from Employees";
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(myCommand, con);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Hope it helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Key-value observing on UIButton's State UIButton has a state property, which appears to be KVO compliant by all accounts and there is no documentation to indicate otherwise. However, when I added an observer to a UIButton's state property, the observer callback was never invoked. How come?
A: If you look at the documentation of UIControl, the state property is marked: synthesized from other flags.
I guess this is why changes to this property are not KVO compliant.
However, you can simply register and observer for the values you need - highlighted, selected, enabled. These properties are KVO compliant and you will get the observer callback when they change.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Creating menus for JApplet I am making a simple game where numbers fall from top to bottom
and I have to type the number. (number is erased as I type the number)
This is coordinated with a Zen.java which is a JApplet file.
I am trying to make a menu for this game with a typical menu bar.
So far, I've tried this..
public class MenuApplet extends JApplet{
public void init(){
JMenuBar menubar = new JMenuBar();
JMenu menuOption = new JMenu("Option");
JMenuItem NewGame = new JMenuItem("New Game");
menuOption.add(NewGame);
JMenuItem exitGame = new JMenuItem("Exit Game");
menuOption.add(exitGame);
JMenu menuLevel = new JMenu("Level");
JMenuItem levelOne = new JMenuItem("Level One");
JMenuItem levelTwo = new JMenuItem("Level Two");
JMenuItem levelThree = new JMenuItem("Level Three");
}
}
Right before my main method. However, the menu bar doesn't even show up.
I would appreciate a couple of advices.
A:
/* <applet code='MenuApplet' width=200 height=100></applet> */
import javax.swing.*;
public class MenuApplet extends JApplet{
public void init(){
JMenuBar menubar = new JMenuBar();
JMenu menuOption = new JMenu("Option");
JMenuItem NewGame = new JMenuItem("New Game");
menuOption.add(NewGame);
JMenuItem exitGame = new JMenuItem("Exit Game");
menuOption.add(exitGame);
JMenu menuLevel = new JMenu("Level");
JMenuItem levelOne = new JMenuItem("Level One");
JMenuItem levelTwo = new JMenuItem("Level Two");
JMenuItem levelThree = new JMenuItem("Level Three");
// the menu items, menus and menu bar all need
// to be ADDED to something!
menubar.add(menuOption);
menuOption.add(NewGame);
menuOption.add(exitGame);
menubar.add(menuLevel);
menuLevel.add(levelOne);
menuLevel.add(levelTwo);
menuLevel.add(levelThree);
setJMenuBar(menubar);
}
}
A: You have to add JMenu into JMenuBar and finally use setJMenuBar to set menubar object.
menubar.add(menuOption);
menubar.add(exitGame);
setJMenuBar(menubar);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Map multiple entities to EF4 abstract base class or interface? I have multiple tables in a db that are identical in terms of column structure.
I'd like to have this modelled in EF4 so that they all inherit from a single abstract base class, so I can write common methods etc.
I've tried an abstract base class, but this means that I need to add a property to each entity that is NOT in the base class. It also appears I lose my collections, as each one is now a collection of the base type?
I can add partial classes and inherit each from a common interface?
e.g.
Table 1 Table 2 Table 3
Id Id Id
Month1 Month1 Month1
Month2 Month2 Month2
Month3 Month3 Month3
Quarter2 Quarter2 Quarter2
Quarter3 Quarter3 Quarter3
Quarter4 Quarter4 Quarter4
How can I have a base class or interface called "table" so that I can write all my methods against that and not against each individual table?
A: If you are force to keep separate tables, and you just want to be able to write
common methods, you can use an Interface and Extension methods like below:
public interface ITableBase{
int Id{ get; set; }
// other properties
void Method1();
int Method2();
string Method3(int some_arguments);
}
public partial class Table1 : ITableBase{
// implement ITableBase and other properties and methods
}
public partial class Table2 : ITableBase{
// implement ITableBase and other properties and methods
}
public partial class Table2 : ITableBase{
// implement ITableBase and other properties and methods
}
static public class ITableBaseExtensions{
static public string GetIdAsString(this ITableBase table){
return table.Id.ToString();
}
static public int UsingMethod2(this ITableBase table){
var i = table.Method2();
return i * 5 + 9 - 14 / 3 % 7 /* etc... */;
}
static public void AddingNewMethodToTables(this ITableBase table, string some_string,
int some_int, YourType any_other_parameter /* etc... */ ){
// implement the method you want add to all Table classes
}
//
// You can add any method you want to add to table classes, here, as an Extension method
//
}
And in consumers, you can call all methods defined in ITableBaseExtensions class for all tables:
public class MyConsumer{
public void MyMethod(){
Table1 t1 = new Table1();
Table1 t2 = new Table2();
Table1 t3 = new Table3();
t1.UsingMethod2(); // will be called from ITableBaseExtensions
t1.Method2(); // will be called from ITableBase - must implemented in Table1 class
t2.Method3(some_argument); // will be called from ITableBase - must implemented in Table2 class
t2.GetIdAsString(); // will be called from ITableBaseExtensions
// etc.
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can i detect new items in rss feed I am making an app that will load stories from rss feed and store them locally in Documents folder, so they would be available offline. My question is: How can i detect new items so i could update the existing stories list.
A: You would need to re-query the feeds. Either add a "Refresh" button which loads new data, or you can have a timer execute a reloading method every few minutes or whatever you require.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544045",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why am i getting a 403 forbidden when using a img tag? When trying to use
<img src="../Ginger.jpeg" />
I am getting a 403 error.
Here is the page which is requesting:
http://laponderosakennels.com/beagles/memories/ginger/index.html
What is going on here am I just tired?
A: if you look at http://laponderosakennels.com/beagles/memories/Ginger.jpeg it throws a 403 error.. there is a permission issue for the same.
The problem is probably cos you are referring to the wrong file.. i took the liberty of looking at your folder structure and you are referring to ginger.jpeg which has a permission issue and there is a file ginger.jpg that works fine.
Also make sure you refer to the file correctly.. i.e ginger.jpg
A: This can also be caused by using hotlinking protection. So if hotlinking protection is used, make sure that the URL for your website is added to the white list. Also keep in mind that www.yourdomain.com and yourdomain.com are considered two different URLs.
A: 403 stands for permission denied. You need to check the permissions for "Ginger.jpeg".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: win32 api function to get processor's current speed I am unaware of a win32 api function/functions used to query the local PC processor's current speed. I wish not to use WMI because it seems unlikely to be feasible on all PCs.
A: You can (usually) get the processor speed using the QueryPerformanceFrequency function. I'm saying "usually" since this function returns the frequency of the performance timer component of the system, but virtually all current CPU's available operate at the same frequency as the performance timer component.
This function is available since Windows 2000, so chances are good that it's supported on most of todays PCs.
A: You can call the Windows API function CallNtPowerInformation with the argument ProcessorInformation. It returns a PROCESSOR_POWER_INFORMATION structure which tells you the current and max CPU speed for each of your system's CPUs.
This is only supported on Win32 desktop, not Metro or Windows Phone, though.
A: You read it from the registry using the usual registry functions
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: How to retain layout when webview follows links I have a layout where there are buttons at the top and bottom of a screen with a large webview in the center between the buttons. When a link in webview is clicked, the webview becomes full-screen, but I want to keep the buttons and retain the original layout. How can this be done?
My webview is simple and looks like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("http://ya-dee-ya");
;
;
}
A: Set webview client and use shouldOverrideUrlLoading
myWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
return super.shouldOverrideUrlLoading(view, url);
}
});
A: In My Point of view, You have to do Something with that XML file. .
Just set the top and bottom margin of the Webview according to the height of that buttons. it will show the Buttons while you are loading the webview. . .
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Disable menu when login as guest on Android I have an app where the user is able to choose to login with the ID or only as a guest. I set the default of the app that after the user chooses either to login or with ID or not, there is a menu on the activity.
What I wanna do is, when the user login as guest, the menu is disabled. So when the user clicks the 'menu' button on his phone, nothing will show up.
Can someone help me with the code?
A: I think it's very useful to read the API documentation on first, but still, here is your answer:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Create your menu code
return !isGuestMode;
}
The return value of onCreateOptionsMenu determines whether a manu should be displayed or not.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544065",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: TransformerHandler to output CDATA sections I am trying to output CDATA section using the below code. While other declarations are being honoured the CDATA sections still comes out as plain text without its enclosing tags (CDATA). What am i doing wrong?
private TransformerHandler getHandler(StringWriter sw) {
SAXTransformerFactory stf = (SAXTransformerFactory)SAXTransformerFactory.newInstance();
TransformerHandler th = null;
th = stf.newTransformerHandler();
th.getTransformer().setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "{ns1}elem");
th.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
th.getTransformer().setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
th.setResult(new StreamResult(sw));
}
A: Try re-reading the JavaDoc section for OutputKeys.CDATA_SECTION_ELEMENTS: http://docs.oracle.com/javase/6/docs/api/javax/xml/transform/OutputKeys.html#CDATA_SECTION_ELEMENTS
... as well as the referenced explanation of how to specify a literal QName http://docs.oracle.com/javase/6/docs/api/javax/xml/transform/package-summary.html#qname-delimiter
The parameter value that you specify "{ns1}elem", does NOT look like it includes a namespace URI to me, but rather looks like a namespace prefix (ns1). Find out what the "xmlns:ns1" declaration is, and include the namespace URI in the literal QName.
Example (assuming the namespace declaration for the ns1 prefix looks like xmlns:ns1="http://softee.org" you should specify;
setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "{http://softee.org}elem");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why should we use WSDL4j for developing webservices? I need to develop Webservice Application for our Client .
I dont know anything about WSDL4J
From the net I found this
"The Web Services Description Language for Java Toolkit (WSDL4J) allows the creation, representation, and manipulation of WSDL documents.
Is the reference implementation for JSR110 'JWSDL' (jcp.org)."
But anybody please tell me why should we use WSDL for developing webservices?
Is there any specific advantage we will get?
And can anybody please point me a link where to start for working with WSDL4j?
A: You actually need not to use wsdl4j for developing web services or clients for web services. There are other SOAP stacks developed on top of that. Axis2 is such an open source SOAP stack..
WSDL2Java tool that comes with Axis2 - which been used to generate client side stubs from a given WSDL. uses wsdl4j internally..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544068",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Show soft keyboard (numeric) using AlertDialog.Builder I have an EditText in an AlertDialog, but when it pops up, I have to click on the text box before the keyboard pops up. This EditText is declared in the XML layout as "number", so when the EditText is clicked, a numeric keypad pops up. I want to eliminate this extra tap and have the numeric keypad pop up when the AlertDialog is loaded.
All of the other solutions I found involve using
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
This is NOT an acceptable solution, as this results in the standard keyboard rather than the numeric keyboard popping up. Does anyone have a way to make the numeric keyboard pop up in an AlertDialog, preferably while keeping my layout defined in XML?
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Mark Runs")
.setView(markRunsView)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
EditText runs = (EditText)markRunsView.findViewById(R.id.runs_marked);
int numRuns = Integer.parseInt(runs.getText().toString());
// ...
})
.setNegativeButton("Cancel", null)
.show();
Edit: I want to be perfectly clear that my layout already has:
android:inputType="number"
android:numeric="integer"
I also tried this:
//...
.setNegativeButton("Cancel", null)
.create();
EditText runs = (EditText)markRunsView.findViewById(R.id.runs_marked);
runs.setInputType(InputType.TYPE_CLASS_NUMBER);
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
dialog.show();
but that also did not work. With the setSoftInputMode line, I still get the full keyboard when the AlertDialog loads; without it, I still get nothing. In either case, tapping on the text box will bring up the numeric keypad.
Edit Again:
This is the XML for the EditText
<EditText
android:id="@+id/runs_marked"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="4dip"
android:inputType="number"
android:numeric="integer">
<requestFocus/>
</EditText>
A: Coming a bit late, but today I had this same problem. This is how I solved it:
Call the keyboard when the Dialog opens just like you did:
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
Now, into the Dialog I'm assuming you have a EditText field that accepts only numbers. Just request focus on that field and the standard keybord will automatically transform into the numeric keyboard:
final EditText valueView = (EditText) dialogView.findViewById(R.id.editText);
valueView.requestFocus();
Now you just have to remember to dismiss the keyboard once you're done with the Dialog. Just put this in the positive/negative/neutral button click listener:
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(valueView.getWindowToken(), 0);
A: Just try to set the InputType by using setInputType().
EditText runs = (EditText)markRunsView.findViewById(R.id.runs_marked);
runs.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
A: I think that you should keep on using the setSoftInputMethod hack but also provide hints to android that you want a numeric input.
Using xml layout attributes
For this, you can use several xml attributes to your EditText xml definition (see android:inputType for available options)
Examples:
<EditText android:inputType="phone" ...
<EditText android:inputType="number" ...
<EditText android:inputType="numberSigned" ...
<EditText android:inputType="numberDecimal" ...
You can also both hint android to show digital keyboard and restrict input to acceptable characters with android:numeric
Examples:
<EditText android:numeric="integer" ...
<EditText android:numeric="signed" ...
<EditText android:numeric="decimal" ...
Programatically
*
*Use EditText.setRawInputType(int) with constants such as TYPE_CLASS_NUMBER you will find in android:inputType
*or TextView.setKeyListener(new NumberKeyListener())
EDIT
AlertDialog focus by default on the positive button. It seems that it is what is causing trouble here. You may look at this similar question and its answer.
A: Try to specify in layout xml for your edit box:
<EditText ...>
<requestFocus/>
</EditText>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: raising events in chaining classes say I have three classes: class1, control1 and form1; form1 instantiate contorl. and control1 instantiate class1, the later produces some event that I need to 'bypass' to form1, to achieve that I have made an intermediate function as shown below:
public delegate void TestHandler(String^ str);
public ref Class class1
{
event TestHandler^ TestHappen;
void someFunction()
{
TestHappen("test string");
}
};
public ref Class control1
{
event TestHandler^ TestHappen;
class1^ class1Obj;
control1()
{
class1Obj= gcnew class1();
class1Obj->TestHappen+= gcnew TestHandler(this,&control1::onTest);
}
void onTest(String^ str)
{
TestHappen(str);
}
};
public ref Class form1
{
control1^ control1Obj;
form1()
{
control1Obj= gcenw control1();
control1Obj->TestHappen+= gcnew TestHandler(this,&form1::onTest);
}
void onTest(String^ str)
{
//do something with the string...
}
};
I don't want to use class1 in form1, are there a way to remove the intermediate onTest() function.
A: Yes, if you use a custom event, you can write its add-handler and remove-handler functions so that they add and remove the delegate directly from another object's event.
For example:
public ref class control1 // in "ref class", class is lowercase!
{
class1 class1Obj; // stack-semantics syntax, locks class1Obj lifetime to be same as the containing control1 instance
public:
event TestHandler^ TestHappen {
void add(TestHandler^ handler) { class1Obj.TestHappen += handler; }
void remove(TestHandler^ handler) { class1Obj.TestHappen -= handler; }
}
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How does the MD5 function work? I'd like to implent a function for SuperFastHash that is compatible so openssl's MD5 function.
MD5 is declared in md5.h as:
unsigned char *MD5(const unsigned char *d, size_t n, unsigned char *md);
But I can't find it's definition in the headers and the sourcecode.
So how does it work exactly? The function not the algorithm.
A: https://www.rfc-editor.org/rfc/rfc1321
A: In addition to the answer that was given you, I'd like to point out that openssl implementation if md5 can be found in openssl tarball that is available from here http://www.openssl.org/source/
You are after crypto\md5\asm folder inside it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can a Bayesian filter be used to create multiple outputs I see that Bayesian filters are use well for binary choices - (spam:not spam, male:female etc). Is there any way for it to categorize multiple values (eg php+javascript, house+yard).
I've seen Naive bayesian classifier - multiple decisions but I want to know if multiple outputs are possible.
If not, what are other suggested approaches for categorization (with or without learning). Especially for php.
A: As the accepted answer of the question you linked to says: "It's definitely possible to have more than two classes.". In practice, one approach is to train multiple classifiers in parallel, e.g. one classifier for php vs. not php and another classifier for javascript vs. not javascript.
Other widely used multivariate classification methods include
*
*artificial neural networks (also called multilayer perceptrons)
*(boosted) decision trees
*support vector machines
If you have a more detailed/follow up question on this, post it on http://stats.stackexchange.com .
I'm not sure what libraries for such a task are available for php but Swig is a tool to make libraries written in C/C++ usable from php.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do you change of a Satchmo Store? This seems like something that should be obvious, but I simply can't find it.
I created a Satchmo store using clonesatchmo.py, as indicated by the installation instructions.
I have tried to change the name of the site through the admin interface (going to Sites and changing the display name) and by editing local_setting.py, changing the line:
SITE_NAME = "Simple Satchmo"
to
SITE_NAME = "Anything Else"
By neither change impacts the actual store. Simple Satchmo remains in the title field, mocking me. So, what idiotic thing am I doing wrong?
A: You need to go to Admin, Store configurations and change the Store Name for your store.
A: Modify the tittle by web site Admin on both Shop / Store Configuration: Store Name.
and Sites / Sites: Display Name. They should be the same.
The latter name is used by some utils related to Django, like sending registration email.
Setting the line SITE_NAME has any effect only before the first running "clonesatchmo.py" or "manage.py satchmo_load_store". Note that the line is preceded by a comment
# These are used when loading the test data
This is not enough explanatory IMO. I will suggest in the development team to remove it by installation script in Satchmo 0.9.3. It will be at least better explained now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Long Polling causing server problems? I've finally made a simple chat page that I had wanted to make for a while now, but I'm running into problems with my servers.
I'm not sure if long polling is the correct term, but from what I understand, I think it is. I have an ajax call to a php page that checks a mysql database for messages with times newer than the time sent in the ajax request. If there isn't a newer message, it keeps looping and checking until there is. Else, it just returns the new messages and the client script sends another ajax request as soon as it gets the messages.
Everything is working fine, except for the part where the server on 000webhost stops responding after a few chat messages, and the server on x10 hosting gives me a message about hitting a resource limit.
Maybe this is a dumb way to do a chat system, but it's all I know how to do. If there is a better way please let me know.
edit: Holy hell, it's just occurred to me that I didn't put any sleep time in the while loop on the server.
A: You can find a lot of reading on this, but I disbelieve that free web hosting is going to allow to do what you are thinking of doing. PHP was also not really designed to create chat systems.
I would recommend using WebSockets, and use for example, Node.JS with Socket.IO, or Tornado with Python; There is a lot of solutions out there, but most of them would require you to run your own server since it requires to run a whole program that interacts with many connections at once instead of simple scripts that just start and finish with a single connection.
A: What about using the same strategy whether there are newer messages on the server or not. The server would always return a list of newer messages - this list could be empty when there are no newer messages. The empty list could be also be encoded as a special data token.
The client then proceeds in both cases the same way: it processes the received data and requests new messages after a time period.
A: Make sure you sleep(1) your code on each loop, the code gonna enter the loop several times per second, stressing your database/server.
But still, nodejs or websockets are better tecnologies to deal with real time chats.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: iOS support for Canon RAW format? I know the iPad can read Canon RAW (.CR2) files when used with the Camera Kit but is any of that file format reading accessible to an iOS developer? Or are we just limited to things supported in the UIImage Class Reference document?
(https://developer.apple.com/documentation/uikit/uiimage)
A: For something like this, Apple's image APIs are not going to be sufficient for what you need. However, there are a few third party APIs that should work with the iPhone. Libraw is a good one that I found that has a C interface. Since Objective-C is a strict superset of C, you will probably be able to use it in your iOS application.
From what I see in their docs, you might be able to write a CR2 image as a TIFF, then decode it as a UIImage like this:
NSString * cr2Path = @"path/to/cr2/file";
NSString * tiffPath = [NSTemporaryDirectory stringByAppendingPathComponent:@"x.tiff"];
libraw_data_t * cr2Data = libraw_init(0);
libraw_open_file(cr2Data, [cr2Path UTF8String]);
libraw_unpack(cr2Data);
// setup encoding params
cr2Data->params.output_tiff = 1;
cr2Data->params.use_camera_wb = 1;
// encode and write as tiff
libraw_dcraw_process(cr2Data);
libraw_dcraw_ppm_tiff_writer(cr2Data, [tiffPath UTF8String]);
libraw_recycle(cr2Data); // free the memory
// load the UIImage
UIImage * myImage = [[UIImage alloc] initWithContentsOfFile:tiffPath];
// use myImage here ...
[myImage release];
From what I have seen, it looks like you will be able to download it here and then add the src files from the src/, libraw/, dcraw/, and internal/ directories to your Xcode project. Hopefully you will not run into any weird linking/compiling issues.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544086",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Regarding format date/time in java I have two datetime formats,
*
*'dd-mm-yyyy' and
*'dd-mm-yyyy hh:MM:ss'
in my application. The input value may be a string in any of above forms.
I want to store this date value in database. So, first I format it with SimpleDateFormatter. But how can I check that input string is of type 1 or of type 2?
If input date time type is in form of (2) and I format datetime with formatter 'dd-mm-yyyy' then it returns null.
Whatever input type - it must be converted according to input. In short, how can I check input datetime format?
A:
i want to store this date value in data base. So, first i formate it with SimpleDateFormatter , but how can i check that input string is type of 1 or type of 2.
It sounds like you want to parse the value - you shouldn't be storing it in the database as a string. (Parsing is converting from a string to the natural data type, e.g. Date. Formatting is converting from a value to a string.)
You can just try parsing the value using DateFormat.parse, and catching the exception thrown if the text is invalid - but you should be aware that your format strings are wrong. 'M' is for month-of-year, and 'm' is for minutes, not the other way round. You also probably want the 24 hour clock (H), not the 12 hour clock (h), so you want:
dd-MM-yyyy
dd-MM-yyyy HH:mm:ss
Finally, I'd strongly advise you to use Joda Time instead of the built-in date/time classes. Joda Time is a much better API. (For example, the formatters in Joda Time are thread-safe, unlike those in the JRE...)
A: Firstly, your data format is screwed up - you have minutes (mm) and months (MM) around the wrong way. ie your formats should be:
"dd-MM-yyyy"
"dd-MM-yyyy HH:mm:ss"
Next, rather than being too smart about it, you can simply try each format and see what works:
public static Date parseDate(String input) {
String[] formats = { "dd-MM-yyyy", "dd-MM-yyyy HH:mm:ss" }; // Add more as you like
for (String format : formats) {
try {
return new SimpleDateFormat(format).parse(input);
}
catch (ParseException e) {
// Ignore and continue
}
}
throw new IllegalArgumentException("Could not parse date from " + input);
}
A: There are many possibilities to distinguish the two formats. An easy one is to check the length of the input string.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: load UIWebView - NSData How can I load a uiwebview with nsdata like if have
NSData *da = [[NSData alloc]initwithContentsofURL:[NSURL URLWithString:@"google.com"]]; //not tested
and now use this NSData in UIWebView.
thanks
A: Check out this method
- (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL
in the UIWebView documentation. That should allow you to load the data in the web view.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544092",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Table width, vsapce, will not align correctly on wordpress template My table will not align correctly on this link:
http://www.teampaulmitchellkarate.com/meet-the-team/
Is there something im missing with the CSS/hspace vsapce?
I know a bunch of links are the same but its the layout I'm concerned about.
A: It's just incorrect HTML syntax. You have several places with extra quotation marks before the word align ("align=)
A corrected version is http://jsbin.com/owehit/edit#html,live
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: A weak/shared pointer, detect when one user remains, boost I want a pointer where I can tell when the reference count is one. Essentially the pointer works like a weak_ptr, but the cleanup needs to be manual. That is, every so often the program goes through a loop of its pointers and checks which ones have only one reference remaining. Some it will clean, others it will retain a while longer (in case somebody needs it again).
Now, I know how to do this using a combination of a custom cleanup function and weak_ptr. I just think the same thing could be accomplished, with simpler code, if I could simply figure out when only one user of the shared_ptr remains.
I know that shared_ptr has a use_count function, but it has this ominous note in the docs: "...not necessarily efficient. Use only for debugging and testing purposes..." Naturally I'm not so keen on using something with such a warning. I don't really need the count anyway, just a way to detect when there is only one left.
Is there some boost wrapper that achieves what I want (can be in any library)? Or must I use the technique I already know of custom cleanup function combined with a weak_ptr?
A: You cannot in general accurately determine the number of references. But you can tell when it is exactly one - use unique().
A: Destructively transform your shared_ptrs into weak_ptrs and then to shared_ptrs back again, except that some of those will be null. Of course there's no telling how that fares for performance, but given the interface we have it's either that or use_count.
Could look like:
std::for_each(begin, end, [](element_type& pointer)
{
std::weak_ptr<element_type::element_type> weak = element_type(std::move(pointer));
pointer = weak.lock();
});
auto predicate = [](element_type& pointer) { return !pointer; };
container.erase(std::remove_if(begin, end, predicate), end);
A: When you're doing something complex that can't quite be represented with the normal shared_ptr system, you might want to consider using intrusive_ptr instead - your implementation of intrusive_ptr_release can then queue objects up for later destruction instead of deleting them immediately. Note that intrusive_ptr can't be directly used with weak_ptr, although you can construct your own variant of weak_ptr if you prefer. Keep in mind, though, that if you are using multiple threads the reference counting may get a bit tricky.
If you can't use an intrusive pointer, and it's acceptable to invalidate existing weak_ptrs when the last shared_ptr is lost, you can have the destructor for the shared_ptr put the raw pointer back into your cache (or whatever) marked for eventual cleanup. You can rewrap it in a shared_ptr the next time it is retrieved. However, again, this has the downside of losing all weak_ptrs to the object at the moment of pseudo-destruction.
If you can't use an intrusive pointer, you may be best off simply designing your own smart pointer implementation. Unfortunately, shared_ptr does not have the kind of hooks needed to implement your goals efficiently, so you may be working from scratch.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: scope of a variable How can I get the value of a method parameter "myInteger" in this code.
public void myMethod(int myInteger) {
View.OnClickListener myClearHandler = new View.OnClickListener() {
public void onClick(View v) {
//***How can I get the value of "myInteger" here?***
}
};
}
A: I am guessing the language should support closures and all you need to do in this case is use the variable myInteger in your onClick listener and you should be fine.. This works in fine in many languages I am not sure about Java though.
public void myMethod(final int myInteger) {
View.OnClickListener myClearHandler = new View.OnClickListener() {
public void onClick(View v) {
int myInteger = myInteger * 100;
}
};
}
AS posted by John Skeet: the final keyword is important here.
A: Assuming you're just trying to read it, you just need to make it final:
public void myMethod(final int myInteger) {
View.OnClickListener myClearHandler = new View.OnClickListener() {
public void onClick(View v) {
int foo = myInteger;
}
};
}
In Java, only final parameters and local variables can be accessed within anonymous inner classes.
A: You Cannot refer to a non-final variable myInteger inside an inner class
defined in a different method
You might be getting this error, so for that you have to declare it as final like this
final int myInteger
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is the best way to minimise restore time when de-tombstoning? So i have a number of methods i use to minimise load time when restoring a Windows Phone 7 application when it has been tombstoned and completely closed, and a user hits the back button or (in mango) navigates to your app from the multi-tasking switcher.
What methods do you use to make sure that the user doesn't see the "Resuming..." text for a second or two?
A: With Mango your application will be kept in memory until the device is running low in memory. So when the user comes back you can test it in the Application_Activated method:
if (!e.IsApplicationInstancePreserved)
{ //here your code to initilize database etc.
}else{
// nothing to do !
}
You should read this page on the Execution model of Mango: http://msdn.microsoft.com/en-us/library/ff817008(v=VS.92).aspx
In any case in the application_desactived method you should save all the data because you are not sure to be kept in memory until the user comes back.
For the resuming message (and it's also valid for the startup), you should be fast as you can to display the first page to your user. Even if this first page does the heavy work (query a local database, a remote service etc...). You give to the user the impression that your application is doing something and not stuck in the splash screen.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android - Listview Background Problem I have a problem, and i know that the answer properly is pretty simple, but I've tried everything at the moment, and I can't figure out what I'm doing wrong. In my project I've got the following layouts:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="3dp">
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1"/>
<TabWidget
android:id="@android:id/tabs"
android:background="@layout/customtabshape"
android:layout_width="fill_parent"
android:layout_height="80px"
android:layout_alignBottom = "@android:id/tabcontent"
/>
</RelativeLayout>
</TabHost>
nyheder.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" android:layout_marginBottom="80px">
<ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:src="@drawable/tv2sport" android:layout_width="fill_parent"></ImageView>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/feedtitle" />
<TextView
android:layout_width="0px"
android:layout_height="0px"
android:id="@+id/feeddescribtion"/>
<TextView
android:layout_width="0px"
android:layout_height="0px"
android:id="@+id/feedpubdate"/>
<TextView
android:layout_width="0px"
android:layout_height="0px"
android:autoLink="web"
android:id="@+id/feedlink"/>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/listtitle"
android:textSize="24px"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
<TextView
android:id="@+id/listpubdate"
android:textSize="20px"
android:layout_width="fill_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
rsslist.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/rowtext"
android:layout_width="fill_parent"
android:layout_height="25px"
android:textSize="10sp"/>
My problem is, that I want the same background texture everywhere. I can get it anywhere but the list itself.
According to this article
http://developer.android.com/resources/articles/listview-backgrounds.html
and multiple others, I should be able to fix my problem with black background in the list, by using android:cacheColorHint="#00000000" inside the list. But I've almost tried putting that line everywhere, and the background in the list is still black.
What am I doing wrong?
(I know that there is no background at the moment, I did that not to make things more complicated).
A: You need to just add
android:scrollingCache="false"
in ListView in xml file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544108",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I solve this load error problem in irb? I can't understand why this error occurs. I have a file named hello.rb, it is in "C/Ruby192/bin/hello.rb".
irb(main):005:0>load("hello.rb")
Load Error: no such file to load -- hello.rb
from(irb):5:in`load'
from(irb):5
from C:/Ruby192/bin/irb:12:in`<main>'
I would be very appreciative if you could solve this problem.
A: From the fine manual:
load(filename, wrap=false) → true
Loads and executes the Ruby program in the file filename. If the filename does not resolve to an absolute path, the file is searched for in the library directories listed in $:.
Your "hello.rb" is not an absolute path so load looks through $: to find it in the library directories. Presumably, 'C/Ruby192/bin' isn't in $: (or '.' isn't in $: if you're in C/Ruby192/bin/ already). Try specifying the full path:
> load('C/Ruby192/bin/hello.rb')
> load('./hello.rb') # If you're in C/Ruby192/bin/ already
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to change the 3d axis settings in matplotlib
I have managed to create this graph using matplotlib. I would like to remove the 0.2, 0.4, 0.6.. from the axis named B and change the axis interval from 200 to 100 in the axis named A. I have been trying to do this for quite sometime now...Any suggestions??
here is the code I have written.
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
f_attributes=open("continuous.data","r")
x=[]
y=[]
spam=[]
count=1
skew=[]
fig = plt.figure()
ax = Axes3D(fig)
total=[]
while count<=1024:
attributes=f_attributes.readline()
attributes=attributes.replace(".\n","")
attributes=attributes.split(',')
classification=int(attributes[10].replace(".\n",""))
if float(attributes[8]) >=0:
skew.append(float(attributes[8]))
x.append(count)
y.append(classification)
if classification == 0:
ax.scatter(x, y, skew, c='g', marker='o')
else:
ax.scatter(x, y, skew, c='r', marker='o')
x=[]
y=[]
skew=[]
count+=1
ax.set_xlabel('A')
ax.set_ylabel('B')
ax.set_zlabel('C')
plt.show()
Please ignore the irrelevant details..
A: This isn't so easy actually, you have to delve into the objects. I first assumed since Axes3D is based on Axes, you could use the set_yticklabels method, but apparently that doesn't work. Looking in the code, you can see that the y axis is set through w_yaxis, an axis3d.YAxis, which in turn is eventually based on axis.Axis which has the set_ticklabels method, and this worked:
ax.w_yaxis.set_ticklabels([])
What do you mean with "change the axis interval from 200 to 100 in the axis named A"?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Richfaces poupPanel is shown before action execution I have JSF 2.0 form that looks like this
<h:form id="formId">
.
.
.
<a4j:commandButton action="#{bean.myAction}" value="foo" oncomplete="#{rich:component('popup')}.show();" />
</form>
<rich:popupPanel id="popup" modal="false" autosized="true"
resizeable="false">
<h:form id="form2">
<h:panelGrid columns="1" >
<h:outputText id="idText" value="#{bean.message}" />
<h:commandButton action="#" onclick="#{rich:component('popup')}.hide(); return false;" value="ok"/>
</h:panelGrid>
</h:form>
</rich:popupPanel>
and bean method
public String action(){
message = "Some message";
return "";
}
Clicking the button both "action" and popup show are executed, but looks like calling the popup was executed first. I get message from bean constructor not the changed one. Do you have any idea how to delay popup show action (it is already under the oncomplete attribute)? Is there any usual pattern that can fit here (action dynamically changes content of popup panel, popup should be like outcome message). Or maybe there is a way to invoke popup show from java code(for example from bean.action)?
Thanks
A: You need to re-render the <rich:popupPanel>s content first, otherwise it is still showing the content from the first time it was rendered. You're namely redisplaying already-rendered-but-hidden-by-CSS content by JavaScript.
<a4j:commandButton render=":popup:form2" ... />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to programatically read active window title of any window opened within a Remote Desktop? I have an application which periodically reads the windows title of current active window on a persons desktop. However, when a person accesses any window using Remote Desktop then my application is only able to detect that the person is using Remote Desktop and not able to get details of the active window opened on the Remote Desktop.
Is it possible to get the above details programatically in c#?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: C usual arithmetic conversions I was reading in the C99 standard about the usual arithmetic conversions.
If both operands have the same type, then no further conversion is
needed.
Otherwise, if both operands have signed integer types or both have
unsigned integer types, the operand with the type of lesser integer
conversion rank is converted to the type of the operand with greater
rank.
Otherwise, if the operand that has unsigned integer type has rank
greater or equal to the rank of the type of the other operand, then
the operand with signed integer type is converted to the type of the
operand with unsigned integer type.
Otherwise, if the type of the operand with signed integer type can
represent all of the values of the type of the operand with unsigned
integer type, then the operand with unsigned integer type is converted
to the type of the operand with signed integer type.
Otherwise, both operands are converted to the unsigned integer type
corresponding to the type of the operand with signed integer type.
So let's say I have the following code:
#include <stdio.h>
int main()
{
unsigned int a = 10;
signed int b = -5;
printf("%d\n", a + b); /* 5 */
printf("%u\n", a + b); /* 5 */
return 0;
}
I thought the bolded paragraph applies (since unsigned int and signed int have the same rank. Why isn't b converted to unsigned ? Or perhaps it is converted to unsigned but there is something I don't understand ?
Thank you for your time :-)
A: Indeed b is converted to unsigned. However what you observed is that b converted to unsigned and then added to 10 gives as value 5.
On x86 32bit this is what happens
*
*b, coverted to unsigned, becomes 4294967291 (i.e. 2**32 - 5)
*adding 10 becomes 5 because of wrap-around at 2**32 (2**32 - 5 + 10 = 2**32 + 5 = 5)
A: 0x0000000a plus 0xfffffffb will always be 0x00000005 regardless of whether you are dealing with signed or unsigned types, as long as only 32 bits are used.
A: Repeating the relevant portion of the code from the question:
unsigned int a = 10;
signed int b = -5;
printf("%d\n", a + b); /* 5 */
printf("%u\n", a + b); /* 5 */
In a + b, b is converted to unsigned int, (yielding UINT_MAX + 1 - 5 by the rule for unsigned-to-signed conversion). The result of adding 10 to this value is 5, by the rules of unsigned arithmetic, and its type is unsigned int. In most cases, the type of a C expression is independent of the context in which it appears. (Note that none of this depends on the representation; conversion and arithmetic are defined purely in terms of numeric values.)
For the second printf call, the result is straightforward: "%u" expects an argument of type unsigned int, and you've given it one. It prints "5\n".
The first printf is a little more complicated. "%d" expects an argument of type int, but you're giving it an argument of type unsigned int. In most cases, a type mismatch like this results in undefined behavior, but there's a special-case rule that corresponding signed and unsigned types are interchangeable as function arguments -- as long as the value is representable in both types (as it is here). So the first printf also prints "5\n".
Again, all this behavior is defined in terms of values, not representations (except for the requirement that a given value has the same representation in corresponding signed and unsigned types). You'd get the same result on a system where signed int and unsigned int are both 37 bits, signed int has 7 padding bits, unsigned int has 11 padding bits, and signed int uses a 1s'-complement or sign-and-magnitude representation. (No such system exists in real life, as far as I know.)
A: It is converted to unsigned, the unsigned arithmetic just happens to give the result you see.
The result of unsigned arithmetic is equivalent to doing signed arithmetic with two's complement and no out of range exception.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: jQuery Datepicker Icon Not Showing I'm using a jQuery datepicker in WordPress. The datepicker is working fine. But, I can't get the icon, the little button next to the datepicker's text input to work. Instead of an icon, I've got a tiny little "pill", an oblong 7px high pellet instead of my icon. If I click it, it functions properly and the datepicker opens.
This what I've got:
$('#mydatepicker').datepicker({
dateFormat : 'mm/dd/yy',
yearRange : '2011:2011',
changeMonth: true,
changeYear: true,
defaultDate : new Date(2011, 8-1,1),
minDate : new Date(2011, 1-1,1),
maxDate : new Date(2011, 8-1, 25),
showOn: 'both',
buttonImage : 'images/calendar_month.png',
buttonText : ''
});
calendar_month.png is a 16x16 px png of a calendar. Images is a subfolder of my plugins' main folder.
If I remove the " buttonText : '' " line, then I get an ellipsis in the "pill".
Any ideas as to why the icon isn't showing properly?
Thank you.
A: In Wordpress, an absolute URL can be generated like this: '<?php bloginfo('stylesheet_directory'); ?>/images/calendar.png'
Assuming you have the image folder inside your template's directory (if you're building a child-theme and the datepicker belongs to the parent you can use template_directory instead).
You can use Firebug to find out if the image address is currently wrong and what other image it might be displaying. This could definitely help debugging a lot.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calculate each Word Occurrence in large document I was wondering how can I solve this problem by using which data structure.. Can anyone explain this in detail...!! I was thinking to use tree.
There is a large document. Which contains millions of words. so how you will calculate a each word occurrence count in an optimal way?
This question was asked in Microsoft... Any suggestions will be appreciated..!!
A: I'd just use a hash map (or Dictionary, since this is Microsoft ;) ) of strings to integers. For each word of the input, either add it to the dictionary if it's new, or increment its count otherwise. O(n) over the length of the input, assuming the hash map implementation is decent.
A: Using a dictionary or hash set will result in o(n) on average.
To solve it in o(n) worst case, a trie with a small change should be used:
add a counter to each word representation in the trie; Each time a word that is inserted already exists, increment its counter.
If you want to print all the amounts at the end, you can keep the counters on a different list, and reference it from the trie instead storing the counter in the trie.
A: class IntValue
{
public IntValue(int value)
{
Value = value;
}
public int Value;
}
static void Main(string[] args)
{
//assuming document is a enumerator for the word in the document:
Dictionary<string, IntValue> dict = new Dictionary<string, IntValue>();
foreach (string word in document)
{
IntValue intValue;
if(!dict.TryGetValue(word, out intValue))
{
intValue = new IntValue(0);
dict.Add(word, intValue);
}
++intValue.Value;
}
//now dict contains the counts
}
A: Tree would not work here.
Hashtable ht = new Hashtable();
// Read each word in the text in its order, for each of them:
if (ht.contains(oneWord))
{
Integer I = (Integer) ht.get(oneWord));
ht.put(oneWord, new Integer(I.intValue()+1));
}
else
{
ht.put(oneWord, new Integer(1));
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544127",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What difference does it make to register location updates with location listener and pending intents.? In the Google I/O Session on Android Pro Tips, http://www.google.com/events/io/2011/sessions/android-protips-advanced-topics-for-expert-android-app-developers.html , the speaker mentions to register location updates using pending intents over location listener ?? Does anyone know the reason behind it ?
A: Location listener is an interface implemented by your class, which means that you class (and your activity/app) must be in memory (app/service must be active) to be called.
OTOH, with pending intents OS can start a service and deliver the intent, meaning that your app does not need to be active at that time.
So if you need to get location updates at all times, then use pending intents. They will wake your app and deliver the intent. You should use this with a Service, so that a service is started and does the required work in the background.
But if you only need location updates while your app is active then use location listener. Where you implement the listener is up to your architecture.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: HTML source code doesn't understand Arabic text? I'm trying to read a source code for a webPage that contains Arabic text but all what am getting is this جامعة (which is not Arabic, only a group of characters).
If I reload the page on my localhost I get the Arabic tags and text correctly.
But I really need to read that source code. any suggestions or lines of code I can add?
<html dir=rtl>
<META http-equiv=Content-Type content=text/html;charset=windows-1256>
These are few lines from that include the "encoding" used! The page is written using HTML and PHP
A: The characters are merely escaped to HTML entities. The browser decodes them to "real characters" when it renders the page. You can decode them yourself using html_entity_decode:
html_entity_decode('جامعة', ENT_COMPAT, 'UTF-8')
Note the last parameter, which sets the encoding the characters will be decoded to. Use whatever encoding you're working with internally, I'm just suggesting UTF-8 here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Has anyone tried the new opengraph beta api with rails? I'm wondering if anyone's given the new api introduced with rails yet? I began a mock app through facebook and heroku and it actually generates the beginnings of a sinatra based project. Has anyone crossed over to rails by chance?
A: I'm actually working on an app using the new OpenGraph & Rails. With the koala gem, it's pretty easy for example to post an action on the timeline of an user, you just need to do a
res = api.put_connections(current_user.fbid, "namespace:verb", myobject: "link_to_my_object" )
And you will get the action's id in response if all it's fine.
A: I did the mock app too, and it works fine for the app (stuffed cookies). I need to understand the javascript a bit more to move it over.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544139",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does cvSet2D take in a tuple of doubles, and why is this tuple all 0 save for the first element? cvSet2D(matrix, i, j, tuple)
Hi. I'm dissecting the Gabor Filter code given in http://www.eml.ele.cst.nihon-u.ac.jp/~momma/wiki/wiki.cgi/OpenCV/Gabor%20Filter.html . I have a few questions on cvSet2D especially as used in the following code snippets (as given in the link):
C code:
for (x = -kernel_size/2;x<=kernel_size/2; x++) {
for (y = -kernel_size/2;y<=kernel_size/2; y++) {
kernel_val = exp( -((x*x)+(y*y))/(2*var))*cos( w*x*cos(phase)+w*y*sin(phase)+psi);
cvSet2D(kernel,y+kernel_size/2,x+kernel_size/2,cvScalar(kernel_val));
cvSet2D(kernelimg,y+kernel_size/2,x+kernel_size/2,cvScalar(kernel_val/2+0.5));
}
}
Python code:
for x in range(-kernel_size/2+1,kernel_size/2+1):
for y in range(-kernel_size/2+1,kernel_size/2+1):
kernel_val = math.exp( -((x*x)+(y*y))/(2*var))*math.cos( w*x*math.cos(phase)+w*y*math.sin(phase)+psi)
cvSet2D(kernel,y+kernel_size/2,x+kernel_size/2,cvScalar(kernel_val))
cvSet2D(kernelimg,y+kernel_size/2,x+kernel_size/2,cvScalar(kernel_val/2+0.5))
As I'm aware cvSet2D sets the (j, i)th pixel of a matrix to the equivalent color value of the tuple defined in the last parameter. But why does it take in a tuple of doubles? Isn't it more natural to take in a tuple of ints, seeing that a pixel color is defines as a tuple of ints?
Lastly, if I read the docs correctly, the cvScalar method used returns the 4-tuple <given_value_in_double, 0.000000, 0.000000, 0.000000)>. I surmised that cvSet2D takes the first three values and uses it to as the RGB 3-tuple. But, seeing that the output of Gabor Filters are more or less in grayscale, that won't hold being that, the colors produced in my scheme will lean towards red. So, what does cvSet2D do with this tuple?
Thank you for anyone who'll take the bother to explain!
A: I think that for grayscale images (matrices), CvSet2D sets the only channel (brightness) using the first value in the cvScalar. The documentation for CvSet2D seems broken, I'll try to verify in the code.
EDIT: In the code sample you linked to, kernel has type CV_32FC1 which means it has one channel only. So does kernelImg:
kernel = cvCreateMat(kernel_size,kernel_size,CV_32FC1)
kernelimg = cvCreateImage(cvSize(kernel_size,kernel_size),IPL_DEPTH_32F,1)
So it makes sense that the scalar only needs one channel value set within.
A: In OpenCV, images can have 1 (grayscale), 2, 3 (RGB) or 4 (RGB plus alpha) channels. The one Set2D function is used for all images regardless of how many channels they have. Each of the elements of that tuple is used for specifying a channel value.
You always pass in four values through the tuple, but OpenCV will only use the first N of these, where N is the number of channels in the image. It will ignore the rest. Zero is just an accepted place-holder that means "this value does not matter". Of course, you can pass in any value you want, but the readability of your code will suffer.
The reason double is used as the argument type is probably because that is the highest precision type in Python that you can use. OpenCV will cast this value to the proper underlying type (which it gets from the image).
Since you're dealing with one-channel 32-bit float images (CV_32FC1), just continue using Set2D(image, (value, 0, 0, 0)) and everything should be alright.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Out of memory when passing sequences through Clojure's loop/recur
Possible Duplicate:
Recursive function causing a stack overflow
I wrote a function calculating all the primes below a given natural number, using the Sieve of Eratosthenes. It returns the whole prime sequence.
(defn primes-below [n]
(loop [primes [] source (range 2 n)]
(if (empty? source)
primes
(recur
(conj primes (first source))
(filter #(not (= (rem % (first source)) 0)) source)))))
It works fine till n's magnitude of 10000. However, at n = 100000 it results in Out of Memory exception. Why is that? I thought the arguments of loop/recur aren't stored in the stack. How can I fix that?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the difference between _chdir and SetCurrentDirectory in windows? Are there any difference that I should choose one over the other?
A: _chdir actually uses SetCurrentDirectory internally, so on most cases they are effectively interchangeable. However, _chdir does one more thing: it updates the current directory of the current drive, stored in an environment variable. This is needed, as the remark in _tchdir states, because "other functions (fullpath, spawn, etc) need them to be set".
I'm not sure how much this is needed these days, but I would say - if you're using those POSIX-style functions for file operations, path manipulation, process creation etc., use _chdir accordingly. If you're using Win32 API functions directly, use SetCurrentDirectory.
A: They achieve the same result but belong to different APIs, so they return their results and report errors in different ways.
If you're already using other routines from either API, pick that one. If not, SetCurrentDirectory() is more "Windowsy", while _chdir() is more similar to the POSIX API. If you have a mind to port the code to, say, a Linux platform, use _chdir(); if you know you will only ever run the code on Windows platforms, SetCurrentDirectory().
A: SetCurrentDirectory is a macro that will resolve to SetCurrentDirectoryA or SetCurrentDirectoryW depending on the build settings. There is no system provided macro for _chdir and _wchdir.
The MSDN page for SetCurrentDirectory states that the argument can be relative to the current working directory or absolute. The documentation for _chdir does not say either way, though it seems that it does Can chdir() accept relative paths? on Linux.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: How to get current location in blackberry device? In simulator my gps code work fine. But when I install my app in device I can't get current latitude and longitude.
When I send lat long from simulator it get proper lat long which is send through simulator. I don't know why is not working in device?
I have already enable from Option > Advance option > gps > gps servce and set Location ON.
Is there any other setting for get current location in device?
private boolean currentLocation() {
boolean retval = true;
try {
LocationProvider lp = LocationProvider.getInstance(null);
if (lp != null) {
lp.setLocationListener(new LocationListenerImpl(), interval, 1, 1);
} else {
// GPS is not supported, that sucks!
// Here you may want to use UiApplication.getUiApplication() and post a Dialog box saying that it does not work
retval = false;
}
} catch (LocationException e) {
System.out.println("Error: " + e.toString());
}
return retval;
}
private class LocationListenerImpl implements LocationListener {
public void locationUpdated(LocationProvider provider, Location location) {
if (location.isValid()) {
heading = location.getCourse();
longitude = location.getQualifiedCoordinates().getLongitude();
latitude = location.getQualifiedCoordinates().getLatitude();
altitude = location.getQualifiedCoordinates().getAltitude();
speed = location.getSpeed();
// This is to get the Number of Satellites
String NMEA_MIME = "application/X-jsr179-location-nmea";
satCountStr = location.getExtraInfo("satellites");
if (satCountStr == null) {
satCountStr = location.getExtraInfo(NMEA_MIME);
}
// this is to get the accuracy of the GPS Cords
QualifiedCoordinates qc = location.getQualifiedCoordinates();
accuracy = qc.getHorizontalAccuracy();
}
}
A: Try this code
Thread thread = new Thread(new Runnable() {
public void run() {
bCriteria = new BlackBerryCriteria();
if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_CELLSITE)) {
bCriteria.setMode(GPSInfo.GPS_MODE_CELLSITE);
} else if (GPSInfo.isGPSModeAvailable(GPSInfo.GPS_MODE_ASSIST)) {
bCriteria.setMode(GPSInfo.GPS_MODE_ASSIST);
} else if (GPSInfo
.isGPSModeAvailable(GPSInfo.GPS_MODE_AUTONOMOUS)) {
bCriteria.setMode(GPSInfo.GPS_MODE_AUTONOMOUS);
} else {
bCriteria.setCostAllowed(true);
bCriteria
.setPreferredPowerConsumption(Criteria.POWER_USAGE_LOW);
}
try {
bProvider = (BlackBerryLocationProvider) BlackBerryLocationProvider
.getInstance(bCriteria);
if (bProvider != null) {
bProvider.setLocationListener(new handleGPSListener(),
-1, -1, -1);
try {
bLocation = (BlackBerryLocation) bProvider
.getLocation(60);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (LocationException lex) {
lex.printStackTrace();
return;
}
}
});
thread.start();
then implement Location Listener in the class
public class handleGPSListener implements LocationListener {
public void locationUpdated(LocationProvider provider, Location location) {
if (location.isValid()) {
}
}
public void providerStateChanged(LocationProvider provider, int newState) {
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to send parameters with jquery $.get() I'm trying to do a jquery GET and i want to send a parameter.
here's my function:
$(function() {
var availableProductNames;
$.get("manageproducts.do?option=1", function(data){
availableProductNames = data.split(",");;
alert(availableProductNames);
$("#nameInput").autocomplete({
source: availableProductNames
});
});
});
This doesn't seem to work; i get a null in my servlet when i use request.getParameter("option");
If i type the link into the browser http://www.myite.com/manageproducts.do?option=1 it works perfectly.
I also tried:
$.get(
"manageproducts.do?",
{option: "1"},
function(data){}
which doesn't work either.
Can you please help me?
EDIT:
also tried
$.ajax({
type: "GET",
url: "manageproducts.do",
data: "option=1",
success: function(msg){
availableProductNames = msg.split(",");
alert(availableProductNames);
$("#nameInput").autocomplete({
source: availableProductNames
});
}
});
Still getting the same result.
A: If you say that it works with accessing directly manageproducts.do?option=1 in the browser then it should work with:
$.get('manageproducts.do', { option: '1' }, function(data) {
...
});
as it would send the same GET request.
A: I got this working : -
$.get('api.php', 'client=mikescafe', function(data) {
...
});
It sends via get the string ?client=mikescafe
then collect this variable in api.php, and use it in your mysql statement.
A: This is what worked for me:
$.get({
method: 'GET',
url: 'api.php',
headers: {
'Content-Type': 'application/json',
},
// query parameters go under "data" as an Object
data: {
client: 'mikescafe'
}
});
will make a REST/AJAX call - > GET http://localhost:3000/api.php?client=mikescafe
Good Luck.
A: Try this:
$.ajax({
type: 'get',
url: 'manageproducts.do',
data: 'option=1',
success: function(data) {
availableProductNames = data.split(",");
alert(availableProductNames);
}
});
Also You have a few errors in your sample code, not sure if that was causing the error or it was just a typo upon entering the question.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
} |
Q: Is there a way of storing contents of a file in a database by using anything other than CLOB? For a project, I want to store the contents of my file in a database.
I am aware that using CLOB is one of the options for storing large file contents. But I have heard that it is not an efficient way to do so.
Are there other alternatives.
Thank you for your answers.
A: CLOBs are inefficient because every access returns the entire contents of the field, and every modification rewrites the entire contents of the field. It also makes searching on the data difficult and inefficient. If you can break the data up into smaller units to save in multiple rows in a table, that can lead to better, more efficient programs.
That said, those inefficiencies come from misusing the feature. It sounds like what you have in mind is probably just fine (provided, as you say, that you can't know where the file will end up getting stored; typically in this case what I would do would be to store a path to the file in the database rather than the contents of the file itself).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544167",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can i get the recomendation details from LinkedIn In my application, i have to show the recomendation received by the user.. but using Linkedin API plugin, am able to get only these fileds (ID, RecommendationType, Recommeders).. what should i do to get the "Recommendation Text" for the user.
kindly help me out to solve this issue..
A: Finaly i got the solution.. by passing the following api url can get full recommendation details.. "http://api.linkedin.com/v1/people/~/recommendations-received"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: PHP COUNT_RECURSIVE only count non-array values? I have a multidimensional array to the tune of $doclist['area']['source'][#]['type']
I would like to get a number of all entries of ['type'] = "title" that are not empty.
Is there a simple way of doing it?
While I am at it, is there a way to get a number of all entries of ['type'] = "title" AND ['area'] = "something" that are not empty?
A: Assuming by 'area' and 'source' you mean arbitrary strings, you could nest a few loops like so:
$num_titles = 0;
foreach ($doclist as $area => $arr1) {
foreach ($arr1 as $source => $arr2) {
foreach ($arr2 as $k => $arr3) {
if (isset($arr3['title']) && strlen(trim($arr3['title'])))
$num_titles++;
}
}
}
print "Titles: {$num_titles}\n";
print "Areas: " . sizeof($doclist) . "\n";
A: Here's the function that I wrote based on rfausak's response:
function countdocs($arr,$x="",$y="") {
if (($x) && ($y)) {
return count($arr[$x][$y]);
} else if ($x) {
$r=0;
foreach ($arr[$x] as $arr1) {
$r+=count($arr1);
}
return $r;
} else {
$r=0;
foreach ($arr as $arr1) {
foreach ($arr1 as $arr2) {
$r+=count($arr2);
}
}
return $r;
}
}
I thought that someone may find it useful.
A: $ships = array(
"Passenger ship" =>
array("Yacht", "Liner", "Ferry"),
"War ship" =>
array("Battle-wagon", "Submarine", "Cruiser"),
"Freight ship" =>
array("Tank vessel", "Dry-cargo ship", "Container
cargo ship")
);
function myCount($var, $i = 0){
$cnt = 0;
foreach ($var as $v) {
if (is_array($v) and $i)
$cnt += myCount($v, 0);
$cnt++;
}
return $cnt;
}
echo myCount($ships, 1);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UIView alway show full screen in simulator although setting width and height to 320 x 320 px by Interface Builder I try to show UIView of HomeViewController as modal of TabBarViewController.
I want UIView display over TabBar and there 's TabBar at bottom of screen.
Although, setting setting UIView of HomeController 's width and height to 320 x 320 px does not prevent the view to show full screen.
It cover UITabBar and I can not see UITabBar at button of screen when application start up.
This is my code.
//in TabBarWithHomeAppDelegate.m - (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions method
homeViewController = [[HomeViewController alloc]
initWithNibName:@"HomeViewController" bundle:nil];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
self.tabBarController.view.frame = CGRectMake(0, 0, 320, 320);
[self.tabBarController presentModalViewController:homeViewController animated:NO];
return YES;
Interface builder short screen
in Simulator
and this is my source code
link to download source code
Any suggestion is valuable.
Thanks,
A: You should not be using a modal view with a tab bar as you are doing in the current context. Instead, let the HomeViewController view be full screen. To display the tab bar, go to Simulated Metrics in Interface Builder & select Tab Bar for the bottom bar. That way, your view will not be modal & will be truncated to the space between the navigation bar & the tab bar.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WinRT and the server (ASP.NET, Azure, etc) Has Microsoft made any indication of WinRT's current or future relationship with server development (such as ASP.NET)?
While it's been made clear that WinRT is the intended future of Windows UI programming, it also includes a substantial library of common features like networking and data processing (like JSON). If these libraries are to the future of Windows development, it seems to me like it's only natural that they will eventually move into the world of server development (WinRT is already supported by "Server 8").
(I realise that ASP.NET isn't going anywhere and that MVC, for example, could potentially be completely gutted without affecting the programming model. I'm just curious)
A: Most WinRT APIs are only usable inside Metro style apps. ASP.Net or any server programming for that matter, is done in the context of a desktop application. Thus a large amount of WinRT is not usable there. If you look at the WinRT reference, you will see that most of what is present is aimed at consumer apps, not server applications.
Microsoft has not said what will happen in the future, but for Windows 8/Server 8 WinRT is not aimed at server development.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: alternative to $_POST I have a huge form with inputs of type (text, checkboxes, hidden et). The content of the form inputs are taken from a database. The user has to make some changes and to save the data back into the db.
At this moment I'm using a function which has a foreach($_POST as $key=>$value) loop. As you know, there are problems with post method:
*
*can't make refresh,
*can't go backwards.
I'll like to use $_GET method, but the length of my variables and values are bigger than 2000 characters.
Do you have any advice for me, about what can I do? Maybe there are some tricks in using $_GET. Maybe i didn't understand how to use it right?
A: Use the Post/Redirect/Get pattern.
A: There is absolutely nothing wrong in POST itself. You just have to use it properly
An HTTP standard says you ought to make a GET redirect after receiving POST request.
So, as easy code as this
header("Location: ".$_SERVER['PHP_SELF']);
exit;
after processing your form will solve all your "problems"
in case you want to handle post errors, you can use POST/Redirect/GET pattern.
However it does not redirect on error, the problems you mentioned becoming negligible.
here is a concise example of it:
<?
if ($_SERVER['REQUEST_METHOD']=='POST') {
//processing the form
$err = array();
//performing all validations and raising corresponding errors
if (empty($_POST['name']) $err[] = "Username field is required";
if (empty($_POST['text']) $err[] = "Comments field is required";
if (!$err) {
//if no errors - saving data and redirect
header("Location: ".$_SERVER['PHP_SELF']);
exit;
} else {
// all field values should be escaped according to HTML standard
foreach ($_POST as $key => $val) {
$form[$key] = htmlspecialchars($val);
}
} else {
$form['name'] = $form['comments'] = '';
}
include 'form.tpl.php';
?>
on error it will show the form back. but after successful form submit it will redirect as well.
A: As far as loop processing goes, the foreach loop contruct in PHP makes a copy of the array you are working on. If you want to process $_POST with a different loop construct (for / while) and use functions like count(), current(), reset(), next(), prev(), end(), each(), or key(), have at it.
Programming PHP: Chapter 5, p. 128-129
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to set cookies with GAE/Python for 1 month? I need to implement the following:
*
*User input user id and pass
*We validate that on another server
*If they are correct, cookies with these details should be saved for one month
*Each time user uses my site, we should look for cookies
*If they are not found - go to step 1
How can I set cookies for 1 month?
Will the following work?
self.response.headers.add_header(
'Set-Cookie',
'credentials=%s; expires=Fri, 31-Dec-2020 23:59:59 GMT' \
% credentials.encode())
How to calculate one month from now in the required format?
A: You can use webapp.Response.set_cookie() method:
import datetime
self.response.set_cookie('name', 'value', expires=datetime.datetime.now(), path='/', domain='example.com')
Formatting dates for cookies is something like this:
print (datetime.datetime.now() + datetime.timedelta(weeks=4)).strftime('%a, %d %b %Y %H:%M:%S GMT')
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Unable to compile clippy (swf clipboard utility) I am having trouble compiling clippy using the instructions here: https://github.com/mojombo/clippy/blob/master/README.md
I've downloaded clippy and have tried compiling on Mac, Linux, and Windows and I keep getting the same result: The swf compiles with no apparent errors but when I try to load the clippy.swf in my webpage it is unresponsive. I've tried custom builds that others have done and it works fine - just building my own results in a dud. (and yes I do have haxe and swifmill installed). The only thing I can think of is perhaps the latest version of swifmill or haxe is causing the issue.
Any thoughts would be greatly appreciated!
A: According to the commit date and the haxe news, Haxe 2.02 was the latest version at that time.
There is a pull request Updating for newer swfmill/haxe versions which you could try. Also take a look at some of the other forks, there are several claiming to work with newer haxe versions, like this one for example.
Anyway, I don't see what this widget is doing other than creating a button which calls
flash.system.System.setClipboard(text);
It shouldn't be to hard to recreate this for the latest haxe version, if none of the forks should work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544198",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: center div with adjacent one Is it possible to construct a central div that has equal amounts of space on both sides, and another div that is always adjacent to the big one, on it's exterior left side.
I tried setting the width, but when I enlarge the page it isn't adjacent anymore.
Forgot to mention, the center div has sa fixed size.
A: Is this what you want:
CSS:
#left{
width:25%;
background:#cccccc;
height:500px;
float:left;
}
#center{
width:50%;
background:#adaddd;
height:500px;
margin-left:auto;
margin-right:auto;
}
HTML
<div id="left"></div>
<div id="center"></div>
jsFiddle
In this fiddle center div has equal space on both sides. And central div also have an adjacent left div. Space between both (left and center) div is mostly same in all browser sizes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Windows service start, stop, debug problems I have a service that I don't know the runtime of, I guess around 7 seconds. For some reason the service stops working after the first run and I can't debug it. It keeps saying "starting" on the services manager and I can't find it on the attach process window.
When I try to stop it, the stop button appears for only a second. Even if I press it I get an error saying "windows could not stop the service 'Splive on local computer. the service did not return an error. this could be an internal windows error or internal service error."
What would be the best way to handle this issue?
static void Main(string[] args)
{
ServiceBase.Run(new Program());
ServiceController service = new ServiceController();
service.ServiceName = "SpLive";
service.Start();
//Sp objSportingbet = new Sp();
//objSportingbet.getListingsFromSp();
}
public Program()
{
this.ServiceName = "SpLive";
}
protected override void OnStart(string[] args)
{
base.OnStart(args);
objSportingbet.getListingsFromSp();
timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
timer1.Interval = 7000;
timer1.Enabled = true;
timer1.Start();
}
protected override void OnStop()
{
base.OnStop();
timer1.Elapsed += new ElapsedEventHandler(timer1_Elapsed);
timer1.Interval = 7000;
timer1.Enabled = false;
timer1.Start();
}
private void timer1_Elapsed(object sender, EventArgs e)
{
ServiceController service = new ServiceController();
service.ServiceName = "Sp";
if (service.Status == ServiceControllerStatus.Stopped)
{
service.Start();
}
if (service.Status == ServiceControllerStatus.Running)
{
service.Stop();
}
timer1.Stop();
}
private void InitializeComponent()
{
//
// Program
//
this.CanPauseAndContinue = true;
this.CanShutdown = true;
}
A: Configure the service to start under the debugger: http://support.microsoft.com/kb/824344 Note the section "Configure a service to start with the WinDbg debugger attached"
Addition (now have code in question):
static void Main(string[] args)
{
ServiceBase.Run(new Program());
ServiceController service = new ServiceController();
service.ServiceName = "SpLive";
service.Start();
ServiceBase.Run(instance) will not return until the service is shutdown, so you are running the service, and then after it has shutdown asking the SCM to run the service… this will only lead to confusion.
This, plus having a timer to try and reverse the state (started <-> stopped) of the service makes me think you need to think about the underlying process model of a Windows service:
When there is only one service implemented by the exe:
*
*The service is started (at system startup, from a user request, ...): the SCM runs the registered command line
*Main runs, tell the SCM (via ServiceBase.Run) what service this is. This must match the registration used in step 1.
*The instance passed to ServiceBase.Run has its OnStart called. The service should start activities it will perform and then return (ie. asynchronous operations, new threads and the thread pool are OK; continuing on the thread that calls OnStart is not).
*When the signal to shutdown arrives (from whatever source) OnStop is called. This should trigger stopping all the activities that OnStart started (or started since) and wait for them to stop and then return.
The only reason for a service to stop itself would be if something else (eg. its own management API) triggered it, but it would be better to use the SCM from the UI.
A: Ideally you would want to debug your service's OnStart method to see what's going on. And it is possible:
protected override void OnStart(string[] args)
{
#if DEBUG
Debugger.Launch();
#endif
...
}
This works even when service is not flagged as desktop interactive.
A: The OnStart and OnStop handlers have a fixed time limit for being handled. I don't know how stopping works (whether it waits for a thread to be done..), but for OnStart, in your case (I know its an old thread..) I'd move all of the application code into a timer callback and set the timer in the OnStart function. I set mine to about 1 minute. The OnStart will exit immediately, which satisfies the service managers requirements. But now you have a thread that will start in about a minute, which allows you time to attach your process to the debugger. Obviously set a break point on the first instruction in the OnStart timer callback.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Optimized way for changing all the colors of my UIView's elements programmatically I have an UIView with different kind of elements inside (UIButton, UIImageView, UIImageView animations). At some moment, when the user select it, I want to switch all this view to grayscale.
At the moment I do one element after one so for exemple my element 1 of my UIView:
UIImage *newImg = [[myButton1 backgroundImageForState:UIControlStateNormal] convertToGrayscale];
[myButton1 setBackgroundImage:newImg forState:UIControlStateNormal];
It is working fine but I receive a Memory Warning (=1) when I do so...Maybe because I got more than 20 elements in my UIView to change (including an animation).
So I would like to know if there is a better way for changing all the elements colors of my UIView ? Like maybe blending a white square in Luminosity mode on the top of my UIView...would that be possible ?
Thanks in advance!
A: The final result is probably not using to much memory, just the intermediate objects that are autoreleased (including autoreleased objects the API is using).
Consider creating an autoreleasePool inside you loop so the autoreleased objects are fully released every iteration. The over head of an autoreleasePool is rather small.
Example:
for ( /*your loop */ ) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
/* Your code */
[pool drain];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do I use Redis in Ruby on Rails to take the dot product of two hashes efficiently I have a data structure like this in the database in the features table called token_vector (a hash):
Feature.find(1).token_vector = { "a" => 0.1, "b" => 0.2, "c" => 0.3 }
There are 25 of these features. First, I entered the data into Redis with this in script/console:
REDIS.set( "feature1",
"#{ TokenVector.to_json Feature.find(1).token_vector }"
)
# ...
REDIS.set( "feature25",
"#{ TokenVector.to_json Feature.find(25).token_vector }"
)
TokenVector.to_json converts the hash into JSON format first. The 25 JSON hashes stored in Redis take up about 8 MB.
I have a method, called Analysis#locate. This method takes the dot product between two token_vectors. The dot product for hashes works like this:
hash1 = { "a" => 1, "b" => 2, "c" => 3 }
hash2 = { "a" => 4, "b" => 5, "c" => 6, "d" => 7 }
Each overlapping key in the hash (a, b, and c in this case, and not d) have their values multiplied pairwise together, then added up.
The value for a in hash1 is 1, the value for a in hash2 is 4. Multiply these to get 1*4 = 4.
The value for b in hash1 is 2, the value for b in hash2 is 5. Multiply these to get 2*5 = 10.
The value for c in hash1 is 3, the value for c in hash2 is 6. Multiply these to get 3*6 = 18.
The value for d in hash1 is nonexistent, the value for d in hash2 is 7. In this case, set d = 0 for the first hash. Multiply these to get 0*7 = 0.
Now add up the multiplied values. 4 + 10 + 18 + 0 = 32. This is the dot product of hash1 and hash2.
Analysis.locate( hash1, hash2 ) # => 32
I have a method that is often used, Analysis#topicize. This method takes in a parameter, token_vector, which is just a hash, similar to above. Analysis#topicize takes the dot product of token_vector and each of the 25 features' token_vectors, and creates a new vector of those 25 dot products, called feature_vector. A feature_vector is just an array. Here is what the code looks like:
def self.topicize token_vector
feature_vector = FeatureVector.new
feature_vector.push(
locate( token_vector, TokenVector.from_json( REDIS.get "feature1" ) )
)
# ...
feature_vector.push(
locate( token_vector, TokenVector.from_json( REDIS.get "feature25" ) )
)
feature_vector
end
As you can see, it takes the dot product of token_vector and each feature's token_vector that I entered into Redis above, and pushes the value into an array.
My problem is, this takes about 18 seconds each time I invoke the method. Am I misusing Redis? I think the problem could be that I shouldn't load Redis data into Ruby. Am I supposed to send Redis the data (token_vector) and write a Redis function to have it do the dot_product function, rather than writing it with Ruby code?
A: You would have to profile it to be sure, but I suspect you're losing a lot of time in serializing/deserializing JSON objects. Instead of turning token_vector into a JSON string, why not put it directly into Redis, since Redis has its own hash type?
REDIS.hmset "feature1", *Feature.find(1).token_vector.flatten
# ...
REDIS.hmset "feature25", *Feature.find(25).token_vector.flatten
What Hash#flatten does is turns a hash like { 'a' => 1, 'b' => 2 } into an array like [ 'a', 1, 'b', 2 ], and then we use splat (*) to send each element of the array as an argument to Redis#hmset (the "m" in "hmset" is for "multiple," as in "set multiple hash values at once").
Then when you want to get it back out use Redis#hgetall, which automatically returns a Ruby Hash:
def self.topicize token_vector
feature_vector = FeatureVector.new
feature_vector.push locate( token_vector, REDIS.hgetall "feature1" )
# ...
feature_vector.push locate( token_vector, REDIS.hgetall "feature25" )
feature_vector
end
However! Since you only care about the values, and not the keys, from the hash, you can streamline things a little more by using Redis#hvals, which just returns an array of the values, instead of hgetall.
The second place you might be spending a lot of cycles is in locate, which you haven't provided the source for, but there are a lot of ways to write a dot product method in Ruby and some of them are more performant than others. This ruby-talk thread covers some valuable ground. One of the posters points to NArray, a library that implements numeric arrays and vectors in C.
If I understand your code correctly it could be reimplemented something like this (prereq: gem install narray):
require 'narray'
def self.topicize token_vector
# Make sure token_vector is an NVector
token_vector = NVector.to_na token_vector unless token_vector.is_a? NVector
num_feats = 25
# Use Redis#multi to bundle every operation into one call.
# It will return an array of all 25 features' token_vectors.
feat_token_vecs = REDIS.multi do
num_feats.times do |feat_idx|
REDIS.hvals "feature#{feat_idx + 1}"
end
end
pad_to_len = token_vector.length
# Get the dot product of each of those arrays with token_vector
feat_token_vecs.map do |feat_vec|
# Make sure the array is long enough by padding it out with zeroes (using
# pad_arr, defined below). (Since Redis only returns strings we have to
# convert each value with String#to_f first.)
feat_vec = pad_arr feat_vec.map(&:to_f), pad_to_len
# Then convert it to an NVector and do the dot product
token_vector * NVector.to_na(feat_vec)
# If we need to get a Ruby Array out instead of an NVector use #to_a, e.g.:
# ( token_vector * NVector.to_na(feat_vec) ).to_a
end
end
# Utility to pad out array with zeroes to desired size
def pad_arr arr, size
arr.length < size ?
arr + Array.new(size - arr.length, 0) : arr
end
Hope that's helpful!
A: This isn't really an answer, just a follow up to my previous comment, since this probably won't fit into a comment. It looks like the Hash/TokenVector issue might not have been the only problem. I do:
token_vector = Feature.find(1).token_vector
Analysis.locate( token_vector, TokenVector[ REDIS.hgetall( "feature1" ) ] )
and get this error:
TypeError: String can't be coerced into Float
from /Users/RedApple/S/lib/analysis/vectors.rb:26:in `*'
from /Users/RedApple/S/lib/analysis/vectors.rb:26:in `block in dot'
from /Users/RedApple/S/lib/analysis/vectors.rb:24:in `each'
from /Users/RedApple/S/lib/analysis/vectors.rb:24:in `inject'
from /Users/RedApple/S/lib/analysis/vectors.rb:24:in `dot'
from /Users/RedApple/S/lib/analysis/analysis.rb:223:in `locate'
from (irb):6
from /Users/RedApple/.rvm/rubies/ruby-1.9.2-p290/bin/irb:16:in `<main>'
Analysis#locate looks like this:
def self.locate vector1, vector2
vector1.dot vector2
end
Here is the relevant part of analysis/vectors.rb lines 23-28, the TokenVector#dot method:
def dot vector
inject 0 do |product,item|
axis, value = item
product + value * ( vector[axis] || 0 )
end
end
I am not sure where the problem is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: String object instances
Possible Duplicate:
Basic Java question: String equality
Given
String s= "God";
String k= "God";
Will both s and k be considered to be referring to the same String object? Is there a single instance of String object?
A: Yes, Java should optimize this so that s == k to save memory.
(The references s and k references to the same object).
Since java do not have pointers, you cannot change the string that s or k points at,
but you can of course change what string that s or k points at. If java would allow pointers,
then a change on what s points as, and the optimization above would have bad consequences.
That is why one should NOT use a string like "LOCK" to lock threads on,
since if third-party jar files does the same, you will BOTH, unknowingly, be using the same object as a thread lock, which might yield very strange and hard-to-find bugs.
A: They are the same instance. They are part of the string constant pool. Since strings are considered to be immutable (reflection says otherwise) this is normally no problem at all.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP MYSQL Check Case When Querying Database How do I check the case of a string when querying the database? For example, with this statement:
mysql_query("SELECT id FROM members WHERE username = '$username'");
The value in the database is "Test". The user could, however, type in "test" and it would still work. How do I check the exact case? I've tried === and ==, but apparently they don't work in SQL.
A: Your collation needs to be case sensitive.
Change the collation of the username column to a case sensitive one.
For example if you are using latin characters only in the username column, then change it to latin1_general_cs or latin7_general_cs
ALTER TABLE `members` CHANGE `username` `username` VARCHAR( 500 ) CHARACTER SET latin1 COLLATE latin1_general_cs NOT NULL
or
ALTER TABLE `members` CHANGE `username` `username` VARCHAR( 500 ) CHARACTER SET latin7 COLLATE latin7_general_cs NOT NULL
A: What SQL server are you using? Given that you're using PHP, I'm going to assume it's mysql and send you here.
A: Use the == operator to check the value of the database for example:
$row=mysql_query("SELECT id FROM members WHERE username = '$username'");
while($rowData=mysql_fetch_assoc($row)) {/* fetch the value */
if($rowData['value']=='test') {
echo "yes value is correct";/* code for statement */
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: GWT 2.4 Updated MVP sample I'm looking for a project sample of the latest GWT 2.4 version using MVP and UIBinder.
All the samples i could find, are really old, and most of the functions and classes are deprecated.
The latest sample I found is Contacts from GWT site, that is from March 2010.
Where can I find the most relevant and updated GWT MVP + UIBinder project sample?
A: Have a look at the Expenses and MobileWebapp samples from the GWT SDK.
A: this is one has perfect explanation of what you want and source code
https://developers.google.com/web-toolkit/doc/latest/DevGuideMvpActivitiesAndPlaces?hl=de-DE
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Compiling latest OpenCV from source on OS X (with Cmake) My problem:
I'm using cmake to compile the latest OpenCV from SVN on Mac OS X and it's having an error at the end of the terminal output. I'm not familiar enough with Cmake to really track down the problem. What does it mean?
Here are the last several lines of output:
CMake Error at modules/highgui/cmake_install.cmake:38 (FILE):
file INSTALL cannot find "/Users/Matt/OpenCV/build/tmp/lib/Release/libopencv_highgui.a".
Call Stack (most recent call first):
modules/cmake_install.cmake:36 (INCLUDE)
cmake_install.cmake:45 (INCLUDE)
make: *** [install_buildpart_0] Error 1
Command /bin/sh failed with exit code 2
Command /bin/sh failed with exit code 2
** BUILD FAILED **
The following build commands failed:
opencv_highgui:
CompileC "/Users/Matt/OpenCV/build/tmp/modules/highgui/
OpenCV.build/Release-iphonesimulator/opencv_highgui.build/
Objects-normal/i386/cap_avfoundation.o"
"/Users/Matt/OpenCV/opencv/modules/highgui/src/cap_avfoundation.mm"
normal i386 objective-c++ com.apple.compilers.gcc.4_2
install:
PhaseScriptExecution "CMake PostBuild Rules" "/Users/Matt/OpenCV/build/tmp/
OpenCV.build/Release-iphonesimulator/install.build/
Script-10907B010907B010907B0000.sh"
How did I get here:
I downloaded the Aptogo OpenCV framework from github https://github.com/aptogo/OpenCVForiPhone
This comes with a bash script to compile OpenCV with Cmake, and turn the result into an XCode framework (I think):
https://github.com/aptogo/OpenCVForiPhone/blob/master/opencvbuild.sh
I checked out the latest OpenCV source from the SVN and ran this script on it.
More Errors
Found reference to cap_avfoundation.mm earlier in the log.
CompileC "/Users/Matt/OpenCV/build/tmp/modules/highgui/OpenCV.build/Release-iphonesimulator/opencv_highgui.build/Objects-normal/i386/cap_avfoundation.o" modules/highgui/src/cap_avfoundation.mm normal i386 objective-c++ com.apple.compilers.gcc.4_2
cd "/Users/Matt/OpenCV/opencv"
setenv LANG en_US.US-ASCII
setenv PATH "/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/X11/bin:/Users/mattmontag/Unix/pvc/UTILITIES:/Users/mattmontag/Unix/pvc/bin"
/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin/gcc-4.2 -x objective-c++ -arch i386 -fmessage-length=0 -pipe -Wno-trigraphs -fpascal-strings -fasm-blocks -O3 -DCMAKE_INTDIR="Release" -DHAVE_ALLOCA -DHAVE_ALLOCA_H -DHAVE_LIBPTHREAD -DHAVE_UNISTD_H -DHAVE_CVCONFIG_H -DHAVE_IMAGEIO=1 -DHAVE_COCOA=1 -DHAVE_AVFOUNDATION=1 -isysroot /Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator4.2.sdk -fexceptions -mmacosx-version-min=10.6 -fobjc-abi-version=2 -fobjc-legacy-dispatch -D__IPHONE_OS_VERSION_MIN_REQUIRED=40200 -Wmost -Wno-four-char-constants -Wno-unknown-pragmas "-F/Users/Matt/OpenCV/build/tmp/lib/Release" "-I/Users/Matt/OpenCV/build/tmp/lib/Release/include" "-I/Users/Matt/OpenCV/opencv" "-I/Users/Matt/OpenCV/build/tmp" "-I/Users/Matt/OpenCV/opencv/include" "-I/Users/Matt/OpenCV/opencv/include/opencv" "-I/Users/Matt/OpenCV/opencv/modules/highgui/include" "-I/Users/Matt/OpenCV/opencv/modules/highgui/../core/include" "-I/Users/Matt/OpenCV/opencv/modules/highgui/../imgproc/include" "-I/Users/Matt/OpenCV/opencv/modules/highgui/src" "-I/Users/Matt/OpenCV/build/tmp/modules/highgui" "-I/Users/Matt/OpenCV/build/tmp/modules/highgui/OpenCV.build/Release-iphonesimulator/opencv_highgui.build/DerivedSources/i386" "-I/Users/Matt/OpenCV/build/tmp/modules/highgui/OpenCV.build/Release-iphonesimulator/opencv_highgui.build/DerivedSources" -c "cap_avfoundation.mm" -o "/Users/Matt/OpenCV/build/tmp/modules/highgui/OpenCV.build/Release-iphonesimulator/opencv_highgui.build/Objects-normal/i386/cap_avfoundation.o"
cap_avfoundation.mm:59: error: cannot find protocol declaration for 'AVCaptureVideoDataOutputSampleBufferDelegate'
cap_avfoundation.mm:71: error: expected type-specifier before 'AVCaptureOutput'
cap_avfoundation.mm:71: error: expected `)' before 'AVCaptureOutput'
cap_avfoundation.mm:71: error: expected `;' before '*' token
cap_avfoundation.mm:101: error: ISO C++ forbids declaration of 'AVCaptureSession' with no type
cap_avfoundation.mm:101: error: expected ';' before '*' token
cap_avfoundation.mm:102: error: ISO C++ forbids declaration of 'AVCaptureDeviceInput' with no type
cap_avfoundation.mm:102: error: expected ';' before '*' token
cap_avfoundation.mm:103: error: ISO C++ forbids declaration of 'AVCaptureVideoDataOutput' with no type
cap_avfoundation.mm:103: error: expected ';' before '*' token
cap_avfoundation.mm:104: error: ISO C++ forbids declaration of 'AVCaptureDevice' with no type
cap_avfoundation.mm:104: error: expected ';' before '*' token
cap_avfoundation.mm: In constructor 'CvCaptureCAM::CvCaptureCAM(int)':
cap_avfoundation.mm:236: error: 'mCaptureSession' was not declared in this scope
cap_avfoundation.mm:237: error: 'mCaptureDeviceInput' was not declared in this scope
cap_avfoundation.mm:238: error: 'mCaptureDecompressedVideoOutput' was not declared in this scope
cap_avfoundation.mm: In member function 'void CvCaptureCAM::stopCaptureDevice()':
cap_avfoundation.mm:308: error: 'mCaptureSession' was not declared in this scope
cap_avfoundation.mm:311: error: 'mCaptureDeviceInput' was not declared in this scope
cap_avfoundation.mm:313: error: 'mCaptureDecompressedVideoOutput' was not declared in this scope
cap_avfoundation.mm: In member function 'int CvCaptureCAM::startCaptureDevice(int)':
cap_avfoundation.mm:324: error: 'AVCaptureDevice' was not declared in this scope
cap_avfoundation.mm:324: error: 'device' was not declared in this scope
cap_avfoundation.mm:341: error: 'mCaptureDevice' was not declared in this scope
cap_avfoundation.mm:347: error: 'mCaptureDeviceInput' was not declared in this scope
cap_avfoundation.mm:347: error: 'AVCaptureDeviceInput' was not declared in this scope
cap_avfoundation.mm:348: error: 'mCaptureSession' was not declared in this scope
cap_avfoundation.mm:348: error: 'AVCaptureSession' was not declared in this scope
cap_avfoundation.mm:360: error: 'mCaptureDecompressedVideoOutput' was not declared in this scope
cap_avfoundation.mm:360: error: 'AVCaptureVideoDataOutput' was not declared in this scope
cap_avfoundation.mm:390: error: 'AVCaptureSessionPresetMedium' was not declared in this scope
cap_avfoundation.mm: In member function 'void CvCaptureCAM::setWidthHeight()':
cap_avfoundation.mm:427: error: 'mCaptureDecompressedVideoOutput' was not declared in this scope
cap_avfoundation.mm: In member function 'virtual double CvCaptureCAM::getProperty(int)':
cap_avfoundation.mm:490: error: 'mCaptureDeviceInput' was not declared in this scope
cap_avfoundation.mm:491: warning: no '-formatDescription' method found
cap_avfoundation.mm:491: warning: (Messages without a matching method signature
cap_avfoundation.mm:491: warning: will be assumed to return 'id' and accept
cap_avfoundation.mm:491: warning: '...' as arguments.)
cap_avfoundation.mm:491: error: cannot convert 'objc_object*' to 'const opaqueCMFormatDescription*' in initialization
cap_avfoundation.mm:505: error: 'mCaptureDevice' was not declared in this scope
cap_avfoundation.mm: In member function 'virtual bool CvCaptureCAM::setProperty(int, double)':
cap_avfoundation.mm:545: error: 'mCaptureDevice' was not declared in this scope
cap_avfoundation.mm:558: error: 'mCaptureDevice' was not declared in this scope
cap_avfoundation.mm:571: error: 'mCaptureDevice' was not declared in this scope
cap_avfoundation.mm:584: error: 'mCaptureDevice' was not declared in this scope
cap_avfoundation.mm:597: error: 'mCaptureDevice' was not declared in this scope
cap_avfoundation.mm: At global scope:
cap_avfoundation.mm:657: error: expected type-specifier before 'AVCaptureOutput'
cap_avfoundation.mm:657: error: expected `)' before 'AVCaptureOutput'
cap_avfoundation.mm: In function 'void -[CaptureDelegate captureOutput:](CaptureDelegate*, objc_selector*, <type error>)':
cap_avfoundation.mm:657: error: expected `{' before '*' token
cap_avfoundation.mm:657: error: expected unqualified-id before ')' token
cap_avfoundation.mm:657: error: expected constructor, destructor, or type conversion before ')' token
cap_avfoundation.mm:1324: error: expected `@end' at end of input
cap_avfoundation.mm:1324: warning: incomplete implementation of class 'CaptureDelegate'
cap_avfoundation.mm:1324: warning: method definition for '-getOutput' not found
cap_avfoundation.mm:1324: warning: method definition for '-updateImage' not found
A: Robin from Aptogo here - I wrote the build script that you are talking about. I've just tried running it with the latest OpenCV trunk (svn revision 6769) and it completes successfully. I'm using CMake version 2.8.5. You do know that the script is intended to build a framework for iOS development not OS X development, don't you? You may run into problems if you don't have the iOS SDK installed.
The error that is causing the build to fail is probably 'cannot find protocol declaration for 'AVCaptureVideoDataOutputSampleBufferDelegate'. This protocol is available in iOS 4 and Mac OS 10.7 (Lion). I'm guessing that you are trying to build on Snow Leopard without the iOS SDK installed.
EDIT for anyone else finding this on SO. The original article, pre-built OpenCV framework and build script can be found on my company's website. The pre-built framework is now built against OpenCV svn revision 7017.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to write a function to take any object with an index operator I think I have asked this in the context of C++ (Can't find it in my question history!!) in the past and the solution was to use a template function. As C++ template resolve at compile time, it works. But for C#, it doesn't.
public Hashtable ConvertToHashtable<T>(T source) where T has an index operator
{
Hashtable table = new Hashtable();
table["apple"] = source["apple"];
return table;
}
One usage at the moment is to convert the result in OleDbReader to hashtable, but I am forseeing the need for more source types soon.
A: You can use an interface:
public interface IIndexable<T> {
T this[int index] { get; set; }
T this[string key] { get; set; }
}
and your method will be seen as below:
public Hashtable ConvertToHashtable<T>(T source)
where T : IIndexable<T> {
Hashtable table = new Hashtable();
table["apple"] = source["apple"];
return table;
}
A simple source is:
public class Source : IIndexable<Source> {
public Source this[int index] {
get {
// TODO: Implement
}
set {
// TODO: Implement
}
}
public Source this[string key] {
get {
// TODO: Implement
}
set {
// TODO: Implement
}
}
}
A simple consumer is:
public class Consumer{
public void Test(){
var source = new Source();
var hashtable = ConvertToHashtable(source);
// you haven't to write: var hashtable = ConvertToHashtable<Source>(source);
}
}
A: Could you add a constraint to specify that the type parameter was an IList?
public Hashtable ConvertToHashtable<T>(T source) where T : IList
{
Hashtable table = new Hashtable();
table["apple"] = source["apple"];
return table;
}
The Item property this[int index] is not an operator, its a property member of the containing type. IList exposes this.
A: If runtime checks are good enough, you could use reflection as one of the commentator suggested as follows:
if (typeof (T).GetProperties().Any(property => property.Name.Equals("Item")))
A: There are no generic type constraints for operators in C# - it is one of the limitations of generics in C#.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544227",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: AJAX response - selecting parent of where the post originated? I am using an AJAX post to load all comments from a database. I need the response to load only in the DIV that it originated from.
$('.viewCommentsExpBtn').click(function() {
var trackid=$(this).parent().find(".trackidField2").val();
$.ajax({
type: "POST",
data: "trackid="+trackid,
url: "http://rt.erna.com/viewcomments.php",
success: function(data) {
var parent=$('.viewComments');
$(parent).slideToggle();
$(".userError").html(data);
}
});
});
Right now the response is toggling all divs with the class "viewComments". Is it possible to toggle only in the originating DIV?
A: Your problem is right here:
var parent = $('.viewComments');
That, of course, selects everything with the viewComments class. All you need to do is figure out the correct parent outside your $.ajax call. Without knowing your HTML structure, I'd guess that you want this:
$('.viewCommentsExpBtn').click(function() {
var parent = $(this).parent();
var trackid = parent.find(".trackidField2").val();
$.ajax({
type: "POST",
data: "trackid="+trackid,
url: "http://rt.erna.com/viewcomments.php",
success: function(data) {
parent.slideToggle();
$(".userError").html(data);
}
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: While, do, done flow control in bash Can anyone explain the control flow of the following bash script?
while IFS= read -r file
do
rm -rf "$file"
done < todelete.txt
From what I understand, this would happen:
IFS would be assigned nothing.
The rm -rf command would do nothing because its argument, the variable $file, is blank/empty/nothing.
The two previous steps would then repeat indefinitely.
Clearly this is not the case, because the script works as expected; it deletes all files listed in todelete.txt.
I believe the explanation lies in "done < todelete.txt" but I don't understand what's happening there.
A: The whole while ... done is treated as single command, which is fed a todelete.txt file on its input.
The while IFS= read -r file thing reads the lines from this input file until the EOF, assigning each line to $file variable, and each iteration of the loop removes that file.
A: The redirect after done affects read's input stream. So read will work on the contents of todelete.txt rather than stdin.
You should read the Internal Commands section of the Bash manual for more info. (Browse directly to example 15-7.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: html javascript select option control with huge number of elements (like 10K) I have two controls with huge nubmer of elements and I move elements from one to another with arrows (built as a single control).
however moving elements from one select to another takes lot of time (i have 10K elements)
i want to know if there is already a best practice or a ready made control that can do that and fast.
thanks
A: You may ant to have a look at jQuery UI MultiSelect plugin.
What it does is transform a html select multiple into exactly what you want.
I do not know how well it works with very big lists, though. The nice thing is that it will still work if javascript is disabled.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Difference between implicit conversion and explicit conversion
Possible Duplicate:
Implicit VS Explicit Conversion
What is the difference between "implicit conversion" and "explicit conversion"? Is the difference different in Java and C++?
A: You Mean Casting?
Implicit mean you pass an instance of type, say B, that inherits from a type, say A as A.
For example:
Class A;
Class B extends A;
function f(A a) {...};
main() {
B b = new B;
f(b); // <-- b will be implicitly upcast to A.
}
There are actually other types of implicit castings - between primitives, using default constructors. You will have to be more specific with your question.
implicit with default constructor:
class A {
A (B b) { ... };
}
class B {};
main() {
B b = new B();
A a = b; // Implict conversion using the default constructor of A, C++ only.
}
A: An explicit conversion is where you use some syntax to tell the program to do a conversion. For example (in Java):
int i = 999999999;
byte b = (byte) i; // The type cast causes an explicit conversion
b = i; // Compilation error!! No implicit conversion here.
An implicit conversion is where the conversion happens without any syntax. For example (in Java):
int i = 999999999;
float f = i; // An implicit conversion is performed here
It should be noted that (in Java) conversions involving primitive types generally involve some change of representation, and that may result in loss of precision or loss of information. By contrast, conversions that involve reference types (only) don't change the fundamental representation.
Is the difference different in Java and C++?
I don't imagine so. Obviously the conversions available will be different, but the distinction between "implicit" and "explicit" will be the same. (Note: I'm not an expert on the C++ language ... but these words have a natural meaning in English and I can't imagine the C++ specifications use them in a contradictory sense.)
A: Casting is an explicit type conversion, specified in the code and subject to very few rules at compile time. Casts can be unsafe; they can fail at run-time or lose information.
Implicit conversion is a type conversion or a primitive data conversion performed by the compiler to comply with data promotion rules or to match the signature of a method. In Java, only safe implicit conversions are performed: upcasts and promotion.\
Also I would suggest reading about C++ implicit coversion: http://blogs.msdn.com/b/oldnewthing/archive/2006/05/24/605974.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: NSTextView, bindings and displaying an NSString My second day working with Cocoa. I've got an NSTextView set up, its attributed string is bound to an NSArrayController (I'm using Core Data):
controller key: selection
model key path: myString
I've read that an NSTextView needs an NSAttributedString, which is why it's throwing an exception when trying to set the value of the attribute.
NSInvalidArgumentException', reason: 'Unacceptable type of value for attribute: property = "myString"; desired type = NSString; given type = NSConcreteAttributedString;
Any ideas how I can get my managedObject's NSString attribute to be shown in an NSTextView?
A: You can use a NSValueTransformer subclass to go back and forth
@interface XXStringTransformer: NSValueTransformer {}
@end
@implementation XXStringTransformer
+ (Class)transformedValueClass
{
return [NSAttributedString class];
}
+ (BOOL)allowsReverseTransformation
{
return YES;
}
- (id)transformedValue:(id)value
{
return (value == nil) ? nil : [[[NSAttributedString alloc] initWithString:value] autorelease];
}
- (id)reverseTransformedValue:(id)value
{
return (value == nil) ? nil : [[(NSAttributedString *)value string] copy];
}
@end
Caveat Emptor - This might be upside down and the reverser might leak. I just made it now but it should point you in the right direction. Let me know and ill correct the answer if its wrong.
You can type the class name XXStringTransformer into the binding panel or do it programmatically.
A: You can bind your NSString to NSTextView's value instead of attributedString. For this, you need to turn off "Rich Text" for NSTextView.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Problem with Kohana 3.2 Validation class. It seems it is not sending Exception when there is an error When the POST data is send to:
Auth::instance()->register( $_POST );
The data is then validated... If it's not I assume the Validation Class in Kohana throws an Exception. And then try-catch function catches it. The problem I am having is with this method:
$this->send_confirmation_email($_POST);
It is called even if the data is not valid. I believed that if the data was not valid it would skip everything else and jump to catch... But it seems I was wrong because I am getting a nasty Fatal error from the method to send an email because it cannot find the email address...
try {
if( ! $optional_checks ) {
//throw new ORM_Validation_Exception("Invalid option checks");
}
$_POST['email_code'] = Auth::instance()->hash(date('YmdHis', time()));
Auth::instance()->register( $_POST );
$this->send_confirmation_email($_POST);
// sign the user in
Auth::instance()->login($_POST['username'], $_POST['password']);
// redirect to the user account
$this->request->redirect('user/profile');
} catch (Validation_Exception $e) {
So, is there a way so that the method to send an email is skip if the data is not valid?
One could say I should use check() method. Here is why it is a problem:
Validation::factory($fields)
->rules('username', $this->_rules['username'])
->rule('username', 'username_available', array($this, ':field'))
->rules('email', $this->_rules['email'])
->rule('email', 'email_available', array($this, ':field'))
->rules('password', $this->_rules['password'])
->rules('password_confirm', $this->_rules['password_confirm']);
if (Kohana::config('useradmin')->activation_code) {
Validation::factory($fields)->rule('activation_code', 'check_activation_code', array($this, ':field'));
}
Thanks in advance for any help.
UPDATE:
It seems now that there is a problem with Kohana Validation class.
Here is the method in my Model_User class:
public function create_user($fields)
{
Validation::factory($fields)
->rules('username', $this->_rules['username'])
->rule('username', 'username_available', array($this, ':field'))
->rules('email', $this->_rules['email'])
->rule('email', 'email_available', array($this, ':field'))
->rules('password', $this->_rules['password'])
->rules('password_confirm', $this->_rules['password_confirm']);
//->labels($_labels);
if (Kohana::config('useradmin')->activation_code) {
Validation::factory($fields)->rule('activation_code', 'check_activation_code', array($this, ':field'));
}
// Generate a unique ID
$uuid = CASSANDRA::Util()->uuid1();
//CASSANDRA::selectColumnFamily('UsersRoles')->insert($username, array('rolename' => 'login'));
CASSANDRA::selectColumnFamily('Users')->insert($uuid, array(
'username' => $fields['username'],
'email' => $fields['email'],
'password' => Auth::instance()->hash($fields['password']),
'logins' => 0,
'last_login' => 0,
'last_failed_login' => 0,
'failed_login_count' => 0,
'created' => date('YmdHis', time()),
'modify' => 0,
'role' => 'login',
'email_verified' => $fields['email_code'],
));
}
The code after the Validation class is executed. So even when the data is not valid it still adds a new user to the database.
The test I am doing is with empty inputs.
Here are the rules:
protected $_rules = array(
'username' => array(
'not_empty' => NULL,
'min_length' => array(4),
'max_length' => array(32),
'regex' => array('/^[-\pL\pN_.]++$/uD'),
),
'password' => array(
'not_empty' => NULL,
'min_length' => array(8),
'max_length' => array(42),
),
'password_confirm' => array(
'matches' => array('password'),
),
'email' => array(
'not_empty' => NULL,
'min_length' => array(4),
'max_length' => array(127),
'validate::email' => NULL,
),
);
Thanks again in advance for any help.
A: The way I setup the rules was wrong and the way I setup the Validation custom rules. Here is the code that resolved the problem:
protected $_rules = array(
'username' => array(
array('not_empty'),
array('min_length', array(4)),
array('max_length', array(32)),
array('regex', array('/^[-\pL\pN_.]++$/uD')),
),
'password' => array(
array('not_empty'),
array('min_length', array(8)),
array('max_length', array(42)),
),
'password_confirm' => array(
array('matches', array(':validation', ':field', 'password')),
),
'email' => array(
array('not_empty'),
array('min_length', array(4)),
array('max_length', array(127)),
array('email'),
),
);
Validation:
$validation = Validation::factory($fields)
->rules('username', $this->_rules['username'])
->rule('username', array($this, 'username_available'), array(':validation', ':field'))
->rules('email', $this->_rules['email'])
->rule('email', array($this, 'email_available'), array(':validation', ':field'))
->rules('password', $this->_rules['password'])
->rules('password_confirm', $this->_rules['password_confirm'])
->errors('register/user');
//->labels($_labels);
if (Kohana::config('useradmin')->activation_code) {
$validation->rule('activation_code', array($this, 'check_activation_code'), array(':validation', ':field'));
}
if(!$validation->check())
{
throw new Validation_Exception($validation, __('Your registering information is not valid.'));
}
Thank you all for your support!
A: There's this thing called an if-else you could use... ;)
Your idea about how the try-catch works is correct: When an exception is thrown inside the try-block, all the remaining code in it is skipped, and it jumps directly into the catch-block.
Most likely the register function is simply not throwing an exception like you assumed, which would be the reason your code is not doing what you think it should.
A: In this case, the Kohana Auth class dons't have the method register() as default.
I have implemented this method to use in a specific case, with AmfPHP gateway for Kohana Useradmin module.
The right way is to use the model method to add user and it roles, you will get a throw if the array with fields isn't valid.
You can get the result from Auth->instance()->register() like:
if(! Auth::instance()->register( $_POST )) throw new Validation_Exception(...);
Try or the best way is to change the Auth->instance()->register($_POST) to:
$user->create_user($_POST, array(
'username',
'password',
'email',
));
// Add the login role to the user (add a row to the db)
$login_role = new Model_Role(array('name' =>'login'));
$user->add('roles', $login_role);
It will make your try catch work as needed for Kohana_Validation exception.
To finish, here is the code from register method, it could help you:
/**
* Register a single user
* Method to register new user by Useradmin Auth module, when you set the
* fields, be sure they must respect the driver rules
*
* @param array $fields An array witch contains the fields to be populate
* @returnboolean Operation final status
* @see Useradmin_Driver_iAuth::register()
*/
public function register($fields)
{
if( ! is_object($fields) )
{
// Load the user
$user = ORM::factory('user');
}
else
{
// Check for instanced model
if( $fields instanceof Model_User )
{
$user = $fields;
}
else
{
throw new Kohana_Exception('Invalid user fields.');
}
}
try
{
$user->create_user($fields, array(
'username',
'password',
'email',
));
// Add the login role to the user (add a row to the db)
$login_role = new Model_Role(array('name' =>'login'));
$user->add('roles', $login_role);
}
catch (ORM_Validation_Exception $e)
{
throw $e;
return FALSE;
}
return TRUE;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Single slave - multiple master MySQL replication I need to replicate different MySQL databases from multiple servers into a single slave server. How can this be done? Do I need a separate MySQL instance on the slave for each master server? Or is there a way to define multiple master hosts?
We're basically using the slave as a hot backup for multiple websites. Should we be thinking about clustering instead of replication?
A: Best way to achieve that would be a real backup solution... but when you do it the way you describe define one slave instance per master - this way you stay flexible, for example if any change is needed you could even move one or more of the slave instances to another machine without any influence on the other slaves/masters...
EDIT - as per comments:
For a description on how to setup multiple instances of MySQL on the same machine see for example
*
*http://dev.mysql.com/doc/refman/5.1/en/multiple-servers.html
*http://www.ducea.com/2009/01/19/running-multiple-instances-of-mysql-on-the-same-machine/
*Multiple MySQL instances on a single machine
This keeps you even flexible enough to have different MySQL versions in parallel (identical per slave/master combination)...
A: Since 2011 the environment has changed a bit. Replication from multiple masters is now supported in MySQL 5.7 and MariaDB 10 - but they use slightly different syntax.
MySQL 5.7: http://www.percona.com/blog/2013/10/02/mysql-5-7-multi-source-replication/
MariaDB 10: https://mariadb.com/kb/en/mariadb/documentation/managing-mariadb/replication/standard-replication/multi-source-replication/
A: You will have to use multiple instances of mysql. If you are having 6 masters and you are trying to put all the slaves on one physical machine, you will need 6 instances,
*
*Each mysql slave instance will connect to a different master.
*Each slave instance will be on a different port
*The datadir for each slave instance will also be separate.
Assuming you are using some flavour of unix OS, you could set up a cron job to stop and start each instance to keep the load average to a minimum.
It would be good to let one slave instance run and catch up with its master before doing hot backup. The same steps would apply to next slave and so on. Each time you start up a slave instance you shutdown the other mysql slave instances can be shutdown to keep load avg. to a minimum.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544241",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: HTML5 audio duration using jQuery I am trying to get the audio duration using jQuery but having hard time getting it. The method I am using is defined below
var audioElement = document.createElement('audio');
audioElement.setAttribute('src','song.mp3');
audioElement.play();
var duration = audioElement.duration;
$(".songtime").html(duration);
But it says nan Does anybody have any idea how to solve this?
A: Probably issue is not valid any more but issue is that audio doesnt load file yet.
You should add event when file is loaded
$(audioElement).on("canplay", function () {
alert(this.duration);
});
A: You are trying to read the duration before the audio file has been loaded. You have to wait until the browser knows what the duration is (i.e. after it has had time to download the file header).
A: Since the audio isn't still loaded, you need to wait until your element has the metadata loaded, there is a simple way to do it:
audioElement.addEventListener("loadedmetadata", function(_event) {
var duration = audioElement.duration;
//TODO whatever
});
A: Others have had this issue and it looks like Safari can get thrown off if your web server does not send the proper HTTP header tags. I am having the same issue -- my demo was loading and playing the audio just fine but the duration always returned 'infiniti' due to the http headers my local server was using to serve the mp3 file.
The basic gist is that the content-type should be as follows:
Content-Type:audio/mpeg; name="name_of_file.mp3"
Instead of:
Content-Type:application/octet-stream
For more info see the original post here:
http://groups.google.com/group/jplayer/browse_thread/thread/256d29fcc158f8ec
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544243",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Finish() Activity from other one without starting it with StartActivityForResult()? I have an AsyncTask in separate file (as it uses it about half of my activities) and in that AsyncTask I'm having a constructor with context in it so I can show progress dialog etc. Only problem I have is that Context does not contain StartActivityForResult only StartActivity. Any ideas how to then finish activities from another one activity as I can't send SetResult() ?
Here is my code of AsyncClass :
public class AsyncClass extends AsyncTask<String, Integer, Boolean> {
private ProgressDialog progressDialog;
private Context context;
private String message;
private String url;
private String methodName;
private String get;
private List<Shops> list;
private LinearLayout linearLayout;
public AsyncClass(Context context, String message, String methodName,
String url, LinearLayout view) {
this.context = context;
this.message = message;
this.methodName = methodName;
this.url = url;
this.linearLayout = view;
initialize();
}
private void initialize() {
list = new ArrayList<ShopList>();
get = context
.getString(R.string.web_service_method_name_get);
}
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setMessage(message);
progressDialog.show();
}
@Override
protected Boolean doInBackground(String... params) {
if (methodName.equalsIgnoreCase(get)) {
boolean isResultEmpty;
int totalPropertyCount;
SoapObject partialResult = SoapObjectOperations.InvokeMethod(url,
methodName);
SoapObject result = (SoapObject) partialResult.getProperty(0);
totalPropertyCount = result.getPropertyCount();
if (totalPropertyCount > 0) {
for (int detailCount = 0; detailCount < totalPropertyCount; detailCount++) {
SoapPrimitive soapPrimitive = (SoapPrimitive) result
.getProperty(detailCount);
String name = soapPrimitive.getAttribute("name").toString();
String id = soapPrimitive.toString();
Shop shop = new Shop(id, name);
list.add(shop);
}
}
if (list.isEmpty()) {
isResultEmpty = true;
} else {
isResultEmpty = false;
}
return isResultEmpty;
}
else {
return false;
}
}
@Override
protected void onPostExecute(Boolean result) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
if (methodName.equalsIgnoreCase(get)) {
if (result) {
TextView textViewEmpty = new TextView(context);
textViewEmpty
.setText("Bla Bla Bla");
linearLayout.addView(textViewEmpty);
} else {
for (int i = 0; i < list.size(); i++) {
Button button = new Button(context);
button.setText(list.get(i).getName());
button.setId(list.get(i).getId());
button.setOnClickListener(new OpenShop());
linearLayout.addView(button);
}
}
}
}
class OpenShop implements View.OnClickListener {
@Override
public void onClick(View view) {
ShopDetail.SetId(view.getId());
Intent intent = new Intent(view.getContext(), ShopDetail.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
}
A: The question is not exactly clear, but a way to signal that an activity finished is by means of an intent. You can have your activity broadcast a private intent when it finishes, and the original application would receive this intent, perhaps even get results from it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Changing classes with javascript My code is here: http://jsfiddle.net/PXU2w/8/
CODE
$('#navigation').hover(function() {
//Check if element with class 'author' exists, if so change it to 'authornew'
if ($('div.menu-description').length != 0) $('div.menu-description').removeClass('menu-description').addClass('menu-descriptionnew');
//Check if element with class 'authornew' exists, if so change it to 'author'
else if ($('div.menu-descriptionnew').length != 0) $('div.menu-descriptionnew').removeClass('menu-descriptionnew').addClass('menu-description');
});
});
What I want is when hovered on the background text color of the menu-description class should change to menu-descriptionnew.
A: The id attribute of an HTML element should not contain spaces. The selector #navigation li a is looking for an anchor inside a list item that is a descendent of an element with id = navigation.
A: You have two problems. Your html:
<div id="navigation li a">
Hover over me
</div>
And your CSS:
#navigation li a {
}
Id attributes cannot contain spaces, and it looks like your trying to apply a complete CSS selector as the Id of the div element. If you look at your CSS, the selector is for an achor (a), within a list item (li), within the element with id #navigation. Change two things:
<div id="navigation">Hover over me</div>
And:
#navigation { }
That will correctly apply the background to your div element.
A: "navigation li a" is a selector for this html
<ul id="navigation">
<li><a>you select this element</a></li>
</ul>
here is working example: http://jsfiddle.net/Xe9B3/
A: You almost got it right, but you have a syntax error in the Javascript part.
The last closing brackets were not necessary.
http://jsfiddle.net/PXU2w/9/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Javascript demo hosting I have a blog http://justgagan.wordpress.com/, where I want to show some demo of my javascript's scripts. I know I could do this with tweaking my example for WordPress, but it will increase my pages load time, since I had to add this on body. Is there any site, which could host my example in raw form and provides Apis for embedding that example in my blog. Link would also work for me.
A: Maybe you are looking for http://jsfiddle.net/. You can embed fiddles easily.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Chained callback readability in Javascript? What's the best way to write a series of deeply nested callbacks?
You have several functions, each of which performs an asynchronous operation and which depends on the prior function's output. For two functions, this typically looks like foo(bar).
A long series of callbacks will look like foo(bar(baz(qux(...)))). This quickly becomes very difficult to read, let alone maintain. Especially once you begin passing additional parameters to the function calls! Step improves on this a bit, but adds an extra parameter to each function call.
This post (section 3.1) suggests a wait function, which is used like this: wait(foo, qux) and supports multiple dependencies like so: wait([foo, bar, baz], qux). Unfortunately, this won't help for nested callbacks.
Step and wait both help a bit, but neither seems ideal. Is there a better way to write long callback chains?
A: In functional programming there is function call compose which create new function composition from two function f o g = f(g(x))
function compose(f, g) {
return function() {
//apply is use to pass multiple arguments to function g
return f(g.apply(null, Array.prototype.slice.call(arguments, 0)));
};
}
and if you have reduce function also from functional programming paradigm.
// this function need at least 2 arguments and it don't check if you pass
// one element array or empty array.
function reduce(fun, array) {
var result = fun(array[0], array[1]);
for (var i=2; i<array.length; ++i) {
result = fun(result, array[i]);
}
return result;
}
you can create chain function using the two above
function chain() {
return reduce(compose, arguments);
}
and you can use chain to create new function which is a chain of functions
var quux = chain(foo, bar, baz);//quux is function that call foo(bar(baz(...)));
you can also pass this to the other function as argument as a callback
some_function(chain(foo, bar, baz, quux));
in this case some_function get callback function as argument.
A: While inline functions are neat and can be clearer, sometimes explicitly defining a method, say within an object literal, and then making reference to those methods is more maintainable and reusable.
This is a trivial example, but is generally how I tend to structure my callbacks.
container = {};
container.method = function(arg) {
//do your thing
return container.method2(arg) ;
};
container.method2 = function(arg) {
return function() {
// work with arg, etc
};
};
$('#element').click(container.method);
A: Consider using something like this...
//Prepare a command graph
var fn = {};
fn["getAccount"] = function(){$.ajax(url, fn["getAccount.success"], fn["getAccount.failure"]);};
fn["getAccount.success"] = function(data){fn["getTransaction"]();};
fn["getAccount.failure"] = function(){fn["displayError"]();};
fn["getTransaction"] = function(){$.ajax(url, fn["getTransaction.success"], fn["getTransaction.failure"]);};
fn["getTransaction.success"] = function(data){fn["displayData"];};
fn["getTransaction.failure"] = function(){fn["displayError"]();};
//Initiate the command graph
fn["getAccount"](data);
I don't know why, but I really dislike underscores in variable and function names.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Need help on PHP/jQuery comments script I asked this question previously but i didnt post the code. So here it goes...
<?php require(database.php); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
.comment-wrap {
width: 300px;
overflow: hidden;
margin-bottom: 10px;
}
.reply {
overflow: hidden;
margin-top: 10px;
}
.comment-wrap .replyLink {
float: right;
}
.comment-wrap .comment {
float: left;
margin-left: 5px;
}
.comment-wrap .img {
background-color: #F00;
height: 50px;
width: 50px;
float: left;
}
</style>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".reply").hide();
});
$(document).ready(function() {
$('.replyButton').click(function() {
$(".reply").show();
});
});
</script>
</head>
<body>
<?php
$sql= "SELECT * FROM comments";
$result = $database->query($sql);
while($row = mysql_fetch_array($result)) {
echo '<div class="comment-wrap">';
echo '<div class="img">' . $row['img'] .'</div>';
echo '<div class="comment">' . $row['comment'] . '</div>';
echo '<div class="replyLink">';
echo '<a href="#" class="replyButton" ">Reply</a></div>';
echo '</div>';
echo '<div class="reply">
Type your message: <br />
<form id="form1" name="form1" method="post" action="">
<label for="reply"></label>
<textarea name="replyMessage" class="replyMessage" cols="45" rows="5"></textarea>
</form>';
echo '</div>';
}
?>
</body>
</html>
When the user clicks on reply button reply class is expanded on all the comments which was hidden previously. But i want the reply class to expand only on that comment on which the user has clicked the reply button.
The content will be stored in MySQL database and retrieved through PHP. But here i just need help on jQuery part. I'm not asking for full code, just give me some hints so that i can solve it.
A: http://andylangton.co.uk/articles/javascript/jquery-show-hide-multiple-elements/
Give class "toggle" to any element you want to apply show/hide functionality and here's the JS
// Andy Langton's show/hide/mini-accordion - updated 23/11/2009
// Latest version @ http://andylangton.co.uk/jquery-show-hide
// this tells jquery to run the function below once the DOM is ready
$(document).ready(function() {
// choose text for the show/hide link - can contain HTML (e.g. an image)
var showText='Show';
var hideText='Hide';
// initialise the visibility check
var is_visible = false;
// append show/hide links to the element directly preceding the element with a class of "toggle"
$('.toggle').prev().append(' (<a href="#" class="toggleLink">'+showText+'</a>)');
// hide all of the elements with a class of 'toggle'
$('.toggle').hide();
// capture clicks on the toggle links
$('a.toggleLink').click(function() {
// switch visibility
is_visible = !is_visible;
// change the link depending on whether the element is shown or hidden
$(this).html( (!is_visible) ? showText : hideText);
// toggle the display - uncomment the next line for a basic "accordion" style
//$('.toggle').hide();$('a.toggleLink').html(showText);
$(this).parent().next('.toggle').toggle('slow');
// return false so any link destination is not followed
return false;
});
});
A: There should be only one element with the same id in the document so you can change id for the class
echo '<a href="#" class="replyButton" ">Reply</a></div>';
and use this jQuery code instead
$('.replyButton').click(function() {
$(this).parent().next().show();
});
this will dispay the next element after the parent. The parent is .comment-wrap and the next element is .reply
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Using FiltersUnitTestCase to unit test Shiro security filters, IllegalStateException Update: I have changed this question to be about the specific problem I am having. This is because unit testing of Filters will be supported in Grails 2.0 so hopefully the documentation will be better then.
I am trying to write unit tests for the filters I set up to implement Shiro security in my grails app. I am using Grails 1.3.7 and wont be able to use 2.0 for a while (if ever) for this particular project.
The idea behind my filter is that I need to give anonymous access to a number or controller/action combinations but protect access to the others. I also want it to fail safe, i.e. if you forget to explicitly allow access then access is prohibited.
The filter class
class SecurityFilters {
def filters = {
homeAccess(controller: "home", action: "*") {
before = {
// Allow all access
request.accessAllowed = true
}
}
serverAccess(controller: "server", action: "list") {
before = {
// Allow all access
request.accessAllowed = true
}
}
layerAccess(controller: "layer", action: "list|listBaseLayersAsJson|listNonBaseLayerAsJson|showLayerByItsId") {
before = {
// Allow all access
request.accessAllowed = true
}
}
all(uri: "/**") {
before = {
// Check if request has been allowed by another filter
if (request.accessAllowed) return true
// Ignore direct views (e.g. the default main index page).
if (!controllerName) return true
// Access control by convention.
accessControl(auth: false)
}
}
}
}
The Unit tests
import org.codehaus.groovy.grails.plugins.web.filters.FilterConfig
class SecurityFiltersTests extends FiltersUnitTestCase {
protected void setUp() {
super.setUp()
}
protected void tearDown() {
super.tearDown()
}
void testHomeControllerFilter() {
checkFilter('homeAccess')
}
void testServerControllerFilter() {
checkFilter('serverAccess')
}
void testLayerControllerFilter() {
checkFilter('layerAccess')
}
void testAllFilter() {
assertTrue "Write tests", false
}
void checkFilter(String filterName) {
FilterConfig filter = initFilter(filterName)
assertNotNull filterName + " filter should exist", filter
assertExistsBefore(filterName)
assertEquals "accessAllowed should be null to start with", null, filter.request.accessAllowed
// Run filter
filter.before()
assertEquals "accessAllowed should be true now", true, filter.request.accessAllowed
}
}
The Exception
The problem is that when these test are run I get the following exception:
No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at grails.test.MockUtils$_addCommonWebProperties_closure32.doCall(MockUtils.groovy:316)
at shiro.SecurityFilters$_closure1_closure5_closure12.doCall(SecurityFilters.groovy:40)
at shiro.SecurityFilters$_closure1_closure5_closure12.doCall(SecurityFilters.groovy)
at shiro.SecurityFiltersTests.checkFilter(SecurityFiltersTests.groovy:92)
at shiro.SecurityFiltersTests$checkFilter.callCurrent(Unknown Source)
at shiro.SecurityFiltersTests.testLayerControllerFilter(SecurityFiltersTests.groovy:65)
Additionally I have placed the following line in the Unit test:
println "filter.request: " + filter.request
Which prints the following:
filter.request: org.codehaus.groovy.grails.plugins.testing.GrailsMockHttpServletRequest@2914cca4
So it certainly seems to be using a mock request object.
So, the questions.
Am I using FiltersUnitTestCase correctly to execute my filters?
And, if so:
Why am I experiencing this exception?
A: A reminder to the rules of debugging for everyone out there: Keep removing code until you find the exact line the problem is on. Even if it is obvious that the line is not causing the problem. Because: sometimes it actually is.
As part of my debugging work I had the following line of code in my filter:
println "controllerName = '${controllerName}', actionName = '${actionName}'"
This was directly before the line:
request.accessAllowed = true
I had taken it out of the code pasted into this question to try and keep it tidy, but apparently I hadn't tried commenting it out when running the tests. Sorry to anyone who looked-into that code and couldn't find a problem. You were right, the problem wasn't in any of the code I provided.
So the answer is you may see the exception reported here if you try and access the controllerName or actionName variables.
The solution is to use the setControllerName() and setActionName() methods in FiltersUnitTestCase before executing any filter that might reference controllerName or actionName.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: getting matrix element using dictionary-like index in Python Numpy can manipulate matrix. And matrix element can be got via numerical indexes.
Now, say I have a 3*3 square matrix M
(Actually, it is a Malcov transition matrix, where each element speaks the probability from one state switching to another).
And the row and column both represent rain, snow, niceday in order.
[0.5 ,0.25,0.25
1 , 0 , 0
0.25,0.25,0.5]
Ordinarily, if I want to get the (rain,snow) element, I would have to write M[0,1].
But I think this is not readable enough.
So I wonder if I can get such element M['rain','snow'], if I have defined such dict-like matrix before(if it is allowed numpy matrix manipulation rule)
A: You can set the variables rain, snow and niceday and use this variables instead the numbers
rain = 0
snow = 1
M[rain, snow]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: The diagram for the many to many relationship table does not appear in the edmx I am using a databse first method. I generated edmx from the database. But diagrams for the tables which are in many to many relationships do not display in the generated edmx.
A: If your Many to many lookup table consists of just Foreign Keys and no other fields, then it will not show up in your edmx file as a Table. It will show up under Navigation Properties of each table though.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CGContextSetRGBFillColor not working I am creating sprites from the CGImage I have drawn using the CGContext functions. I have also a color changing mechanism implemented as a menu. But even though I clear the context and change the color the color which is used for drawing remains the same. Do anybody have anyidea what is wrong?
CGContextSaveGState(UIGraphicsGetCurrentContext());
UIGraphicsBeginImageContext(CGSizeMake(40, 40));
if ([color isEqualToString:@"black"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 0,0,0, 1);
}
else if ([color isEqualToString:@"red"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 1.0,0,0, 1);
}
else if ([color isEqualToString:@"green"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 0,1.0,0, 1);
}
else if ([color isEqualToString:@"blue"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 0,0,1.0, 1);
}
CGRect rect1 = CGRectMake(0,0,40,40);
CGContextAddEllipseInRect(UIGraphicsGetCurrentContext(),rect1);
CGContextFillPath(UIGraphicsGetCurrentContext());
UIImage *myImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGContextFlush(UIGraphicsGetCurrentContext()) ;
CGContextRestoreGState(UIGraphicsGetCurrentContext());
CCSprite *newSprite = [CCSprite spriteWithCGImage:[myImage CGImage] key:@"blackCircle"];
[itemsArray addObject:newSprite];
[newSprite setPosition:point];
[self addChild:newSprite];
A: Are you sure your color variable is being set, and that it is the right encoding of string to pass the isEqualToString test? (i.e are you sure you're actually hitting the code to set the color).
I copied your code above, up to creation of the image from the context, into the viewDidLoad method of a view controller and then added the image into an imageview subview of the view, and the color came out right.
This is the code I put into the viewDidLoad method of a view controller - the view ended up with a blue circle on it, so it seems like your code should work:
CGContextSaveGState(UIGraphicsGetCurrentContext());
UIGraphicsBeginImageContext(CGSizeMake(40, 40));
NSString *color = @"blue";
if ([color isEqualToString:@"black"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 1,0,0, 1);
}
else if ([color isEqualToString:@"red"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 1.0,0,0, 1);
}
else if ([color isEqualToString:@"green"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 0,1.0,0, 1);
}
else if ([color isEqualToString:@"blue"]) {
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 0,0,1.0, 1);
}
CGRect rect1 = CGRectMake(0,0,40,40);
CGContextAddEllipseInRect(UIGraphicsGetCurrentContext(),rect1);
CGContextFillPath(UIGraphicsGetCurrentContext());
UIImage *myImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
CGContextFlush(UIGraphicsGetCurrentContext()) ;
CGContextRestoreGState(UIGraphicsGetCurrentContext());
UIImageView *imgV = [[UIImageView alloc] initWithFrame:CGRectMake(30,30,200,200)];
imgV.image = myImage;
[self.view addSubview:imgV];
A: You need to add the full colour code parameters like so...
CGContextSetRGBFillColor(UIGraphicsGetCurrentContext(), 1.0/255,0.0/255,0.0/255, 1.0);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Algorithm to find related words in a text I would like to have a word (e.g. "Apple) and process a text (or maybe more). I'd like to come up with related terms. For example: process a document for Apple and find that iPod, iPhone, Mac are terms related to "Apple".
Any idea on how to solve this?
A: Like all of AI, it's a very difficult problem. You should look into natural language processing to learn about some of the issues.
One very, very simplistic approach can be to build a 2d-table of words, with for each pair of words the average distance (in words) that they appear in the text. Obviously you'll need to limit the maximum distance considered, and possibly the number of words as well. Then, after processing a lot of text you'll have an indicator of how often certain words appear in the same context.
A: What I would do is get all the words in a text and make a frequency list (how often each word appears). Maybe also add to it a heuristic factor on how far the word is from "Apple". Then read multiple documents, and cross out words that are not common in all the documents. Then prioritize based on the frequency and distance from the keyword. Of course, you will get a lot of garbage and possibly miss some relevant words, but by adjusting the heuristics you should get at least some decent matches.
A: As a starting point: your question relates to text mining.
There are two ways: a statistical approach, and one form natural language processing (nlp).
I do not know much about nlp, but can say something about the statistical approach:
*
*You need some vector space representation of your documents, see
http://en.wikipedia.org/wiki/Vector_space_model
http://en.wikipedia.org/wiki/Document-term_matrix
http://en.wikipedia.org/wiki/Tf%E2%80%93idf
*In order to learn semantics, that is: different words mean the same, or one word can have different meanings, you need a large text corpus for learning. As I said this is a statistical approach, so you need lots of samples.
http://www.daviddlewis.com/resources/testcollections/
Maybe you have lots of documents from the context you are going to use. That is the best situation.
*You have to retrieve latent factors from this corpus. Most common are:
*
*LSA (http://en.wikipedia.org/wiki/Latent_semantic_analysis)
*PLSA (http://en.wikipedia.org/wiki/Probabilistic_latent_semantic_analysis)
*nonnegative matrix factorization (http://en.wikipedia.org/wiki/Non-negative_matrix_factorization)
*latent dirichlet allocation (http://en.wikipedia.org/wiki/Latent_Dirichlet_allocation)
These methods involve lots of math. Either you dig it, or you have to find good libraries.
I can recommend the following books:
*
*http://www.oreilly.de/catalog/9780596529321/toc.html
*http://www.oreilly.de/catalog/9780596516499/index.html
A: The technique that you are looking for is called Latent Semantic Analysis (LSA). It is also sometimes called Latent Semantic Indexing. The technique operates on the idea that related concepts occur together in text. It uses statistics to build the word relationships. Given a large enough corpus of documents it will definitely solve your problem of finding related words.
A: Take a look at vector space models.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Is it possible to record calls both sides(mic,speaker) in android? i'm trying to develop an application to record calls bothside(mic and speaker). I've seen there is one app vrecorder providing this vrecorder for android 1.6.
Now i want to do this for android 2.2 and above. Can i know is this possible with MediaRecorder.AudioSource.
I've read some forums they are saying that there are some issues on doing this.
In Stackoverflow itself several questions are about record voice calls saying that not posible. But these posts are older. Is it possible to record phone calls via an Android App? .
But http://code.google.com/p/android/issues/detail?id=2117 in this discussion they are saying that some issues are there but we can implement.
Atlast, please I need some descriptive answers, that can we record voice calls in android both way (from mic and speaker).
Thanks in advance.
A: Call recording is not yet possible on Android. The feature request you are referencing is still not resolved.
People that have been able to do call recording use rooted phones with custom kernel.
On stock Android phones, you can only record your voice from microphone, but you can not record the sound of the other party. If you only want to record your voice use android.media.MediaRecorder.AudioSource.MIC
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: A "modern" look of Manifest file A "traditional" Manifest files consisted of application/activities tags, uses-sdk tag and uses-persmission eventually.
What are the new tags that you advise to include in the "modern" Manifest file? I am referring to the tags that deals with screens and resolutions, and possibly something else.
A: Some of attributes which we Android developers should normally include in the AndroidManifest.xml. Here it is:
Those common tags/attributes are:
*
*android:versionCode
*android:versionName
*android:icon
*android:label
*android:debuggable
*android:installLocation
*supports-screens
*uses-sdk
*uses-permission
*uses-library
Still, I know there are many other new tags/attributes. Those are:
Refer to The AndroidManifest.xml File for more information about the same:
A: You can look at the one from Barcode Scanner, if that's a helpful data point. I don't think manifests are that different from what you describe. <supports-screens> is common now. <compatible-screens>, <uses-configuration>, and <receiver> pop up too. The complete docs are here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Committing a set of svn file/directory actions in a single check-in I’ve recently decided to re-structure my svn repositories. This job includes lots of file/directory actions (renaming, copying, moving and deleting) in my repository. By default, each action is required to be committed in the context of a check-in. Is there any method to commit lots of these actions in a single check-in? I use TortoiseSVN and Collabnet Subversion 1.6.x.
A: TortoiseSVN has 2 different tools to work with:
*
*SVN windows explorer, and there the integrated TortoiseSVN menu.
*TortoiseSVN repository browser.
The repository browser is a UI tool that works directly on the repository, and it does not know when you "begin and end a transaction". So each command is a commit in itself, if a commit is necessary. I do not know any possibility to say for example.
*
*I declare now the start of a commit session.
*I do then change something, move files, rename directories, ...
*I then finish my commit session.
When you work with the TortoiseSVN windows menu integrated into your windows explorer, you first have to checkout the whole repository. Then you may work locally for some time, use the SVN variations for rename, move and copy, and after some time, commit all your changes at once.
The command line version allows you both things, but it behaves the same. From the documentation for move:
This command moves files or directories in your working copy or in the repository. ... Move a file in the repository (this is an immediate commit, so it requires a commit message):
$ svn move -m "Move a file" http://svn.red-bean.com/repos/foo.c \
http://svn.red-bean.com/repos/bar.c
So even when you write a batch file for doing all the stuff, and call that, each svn move (and svn copy ...) has to have a commit message in itself, if you use the variant that works directly on the repository.
So there is no option to restructure your repository (with the repository browser only) with a single commit. You have to check out the whole repository (at least the part you want to restructure), do your svn something commands locally, and commit then at the end. This has the disadvantage that you have a lot of network traffic, you need some place locally, and it costs much more time. But this is the only way to have a single commit.
Perhaps there could be an option with svnadmin, but that has a lot of disadvantages in itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544280",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Anybody has android honeycomb source? I wanted to attach the source for android.jar in eclipse, but for this I need to download an actual source for android 3.0 honeycomb, however android.git.kernel.org is down since Sep.7. Does anybody have a backup repository or maybe just honeycomb source?
A: Google did not share honeycomb source yet. Wait.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: get/use radio button value android I FIGURED OUT WHAT I WAS DOING. I HAD THE VARIABLE NAME IN QUOTES WITH THE REST OF THE URL STRING.
How do you save the value of a Radio button into a variable and use that variable later.
I can see the variable Day_Item in my LogCat and the value is in there but when try using Day_Item later it does not show the valuable.
Below is a section of my code that shows the buttons.
String Day_Item = null;
public class SearchDB extends Activity {
private static final String TAG = "MyApp";
String start_log = "STARTED";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_layout);
final RadioButton radio_monday = (RadioButton) findViewById(R.id.monday);
radio_monday.setOnClickListener(radio_listener);
cityspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position,long arg3)
{
int id = parent.getId();
if (spinner2_count2 < spinner2_count1 ) {
spinner2_count2++; }
else
{
String city_spinner_log = "CITY SPINNER";
Log.d(TAG, city_spinner_log);
String item = cityspinner.getSelectedItem().toString();
String nameContentType = "name";
String cityURL = "GetRestaurant.php?day=Day_Item&city=" + item;
Log.d(TAG, cityURL);
String shop_data = DataCall.getJSON(cityURL,nameContentType);
Log.d(TAG, shop_data);
Bundle bundle = new Bundle();
bundle.putString("shopData", shop_data);
Intent myIntent = new Intent(SearchDB.this, ShowRestaurant.class);
myIntent.putExtras(bundle);
startActivityForResult(myIntent, 0);
}
}
}
//ONCLICKLISTENER that saves RADIO value into a variable.
public OnClickListener radio_listener = new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
RadioButton rb = (RadioButton) v;
Day_Item = (String) rb.getText();
Log.d(TAG,Day_Item);
Toast.makeText(SearchDB.this, Day_Item, Toast.LENGTH_SHORT).show();
}
};
}
A: You would need a bit more code to get a good solid answer. Such as how is Day_Item allocated? And is it's scope global? Are you calling it from another activity or the one it's allocated within? These are just guesses at this point:
1) Are you sure your onClickListener isn't firing multiple times? Thus setting Day_Item to an undesired text or nothing at all?
2) Rather a question/answer,
"but when try using Day_Item later it does not show the valuable"
I'm assuming this means that it is null? Well if it's being set properly, and then it is being null'd... it either is being explicitly null'd by you somewhere (such as (1)) or else the allocation and scope are the issue area I believe...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: find complete object in list of objects is it possible to find a complete object in list of objects?
dim list1 as list(of class1) = alist
dim x as class1
how to find x in list1 if it exists without comparing a single property like ID ?
A: The Contains method will return true if the element is in the list.
dim list1 as list(of class1) = alist
dim x as class1
list1.Contains(x)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: linux-wide semaphore with a Java API I need to prevent a certain application function from being run concurrently with itself. The risk is significant because this function is in code submitted to java.util.Timer (to repeat every minute for several hours) and the process that sets up the function completes and goes back to the bash command line. The user might then invoke the same program. Another risk is from the user that has two or more console windows and they mistakenly run the program in both console windows.
I think an operating system-wide semaphore with a Java API might do the trick. Is there such a Java archive available?
I was asked if multiple JVMs are used. I think if multiple consoles are opened then multiple JVMs are implied.
This is my wrapper to use Java's Timer and TimerTask.
public final class TimedExecutorWrapper
{ ... various private members ...
public Timer go()
{
Timer myTimer = new Timer();
myTimer.scheduleAtFixedRate(this.myTask,
this.startTodayAtThisTime,
this.frequencyInSeconds * 1000);
TimerTask myTaskToInvokeCancel = new TaskToInvokeCancel(myTimer);
// use the same Timer to schedule the task that cancels and purges
myTimer.schedule(myTaskToInvokeCancel,
this.stopTodayAtThisTime);
return myTimer;
}
private final class TaskToInvokeCancel extends TimerTask
{
private Timer timer; // to be cancelled and purged
TaskToInvokeCancel(Timer timer)
{
this.timer = timer;
}
public void run()
{
this.timer.cancel(); // discards any scheduled tasks without
// interfering with any running task
this.timer.purge();
}
}
}
A: You could create a 0 byte file 'methodname.LOCK' in a shared directory when you begin the operation, and delete it when you are done. Creating it with a no recreate flag in Java should solve your problem.
Make sure to delete it in a 'finally' block so you are never left in a state where the file exists and continues to block the process from ever running
A: just open a serversocket at a specific port. if this succeeds there is no other application, if not an exception is thrown.
A: The only standard Java feature I've seen that prohibits multiple instances of the same program is the SingleInstanceService in Java WebStart.
http://download.oracle.com/javase/1.5.0/docs/guide/javaws/developersguide/examples.html#SingleInstanceService
It requires you to create a JNLP file for your application, which is a bit cumbersome but may be very useful to you anyway. Note that Java does not allow command line parameters to be passed to your program which may be very inconvenient in this situation. Depends on what your command line says.
If Java WebStart does not work for you, then you must ask the operating system for a resource which is denied for subsequent requests and have it automatically released. The only one of these not platform specific is the TCP/IP socket but these are rare and may be used by another program. Under Linux you may ask for shared memory but I do not have personal experience with this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Apache CXF with Spring I am using Apache CXF with Spring , please tell me how the CXFServlet reads the myapp-ws-context.xml
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:myapp-ws-context.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<display-name>CXF Servlet</display-name>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>CXFServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
A: Have you seen sources of org.apache.cxf.transport.servlet.CXFServlet (open source)?
Everything is more than explicit:
@Override
protected void loadBus(ServletConfig sc) {
ApplicationContext wac = WebApplicationContextUtils.
getWebApplicationContext(sc.getServletContext());
String configLocation = sc.getInitParameter("config-location");
if (configLocation == null) {
try {
InputStream is = sc.getServletContext().getResourceAsStream("/WEB-INF/cxf-servlet.xml");
if (is != null && is.available() > 0) {
is.close();
configLocation = "/WEB-INF/cxf-servlet.xml";
}
} catch (Exception ex) {
//ignore
}
}
if (configLocation != null) {
wac = createSpringContext(wac, sc, configLocation);
}
if (wac != null) {
setBus(wac.getBean("cxf", Bus.class));
} else {
setBus(BusFactory.newInstance().createBus());
}
}
Note that WebApplicationContextUtils is a Spring class that tries to find an application context in servlet context attribute named: org.springframework.web.context.WebApplicationContext.ROOT.
A: Actually your classpath:myapp-ws-context.xml is read by Spring, not CXF.
By adding below configuration in your web.xml, it would be read by Spring and the context would be loaded:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:myapp-ws-context.xml</param-value>
</context-param>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
But you could configure your Servlet/WebApp scope of Spring objects, like multipartResolver etc., to make the objects' scopes clearly, by enhancing your CXFServlet configuration like below:
<servlet>
<display-name>CXF Servlet</display-name>
<servlet-name>CXFServlet</servlet-name>
<servlet-class>
org.apache.cxf.transport.servlet.CXFServlet
</servlet-class>
<init-param>
<param-name>config-location</param-name>
<param-value>/WEB-INF/your-webapp-scope-spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
*Please take note that from your web-app context, you can access all objects in the context loaded from contextConfigLocation. *
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery each loop currently this is static code :
if you compare div ids no to that of a hrefs of second list is getting added by +1
for example
slide0 » #pic1 to #pic5
slide1 » #pic2 to #pic6
and so on.. how should i achieve this with jquery each loop or any other jquery method ?
thanks in advance
<div id="my-slides">
<div id="slide0">
<ol>
<li><img class="blank" src="images/thumbnails/blank.png" alt="" /></li>
<li><a href="#pic1"><img src="images/thumbnails/pic1.jpg" alt="Winter branches" /></a></li>
<li><a href="#pic2"><img src="images/thumbnails/pic2.jpg" alt="Wading birds" /></a></li>
<li><a href="#pic3"><img src="images/thumbnails/pic3.jpg" alt="Bird on a post" /></a></li>
<li><a href="#pic4"><img src="images/thumbnails/pic4.jpg" alt="Early bloomers" /></a></li>
<li><a href="#pic5"><img src="images/thumbnails/pic5.jpg" alt="Green lizard" /></a></li>
<li><a href="#slide1" ><b>Next</b></a></li>
</ol>
</div>
<div id="slide1">
<ol>
<li><a href="#slide0"><b>Previous</b></a></li>
<li><a href="#pic2"><img src="images/thumbnails/pic2.jpg" alt="Wading birds" /></a></li>
<li><a href="#pic3"><img src="images/thumbnails/pic3.jpg" alt="Bird on a post" /></a></li>
<li><a href="#pic4"><img src="images/thumbnails/pic4.jpg" alt="Early bloomers" /></a></li>
<li><a href="#pic5"><img src="images/thumbnails/pic5.jpg" alt="Green lizard" /></a></li>
<li><a href="#pic6"><img src="images/thumbnails/pic6.jpg" alt="Feeding the birds" /></a></li>
<li><a href="#slide1" ><b>Next</b></a></li>
</ol>
</div>
<div id="slide2">
<ol>
<li><a href="#slide1"><b>Previous</b></a></li>
<li><a href="#pic7"><img src="images/thumbnails/pic7.jpg" alt="Feeding the birds" /></a></li>
<li><a href="#pic8"><img src="images/thumbnails/pic8.jpg" alt="A group of butterflies" /></a></li>
<li><a href="#pic9"><img src="images/thumbnails/pic9.jpg" alt="Ladybirds" /></a></li>
<li><a href="#pic10"><img src="images/thumbnails/pic10.jpg" alt="Butterfly" /></a></li>
<li><a href="#pic11"><img src="images/thumbnails/pic11.jpg" alt="Trees in the mist" /></a></li>
<li><img class="blank" src="images/thumbnails/downx.png" alt="" /></li>
</ol>
</div>
A: Is this what you're looking for?
$('a[href^=#pic]').each(function() {
alert($(this).attr('href').match(/^#pic(\d+)/)[1]);
});
A: $("ol li a:not(:first-child),ol li a:not(:last-child)").each(function()
{
$(this).attr("href",<value>);
})
A: Try this:
$('#my-slides a img').each(function() {
var pic_number = $(this).parent().attr('href').substr(3);
$(this).parent().parent().attr('href', pic_number);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Drawable resource using a variable I want to use a variable instead of R.drawable.myimage because I have a database with the image's names. I get the name from the database and I want to use the drawable resource with this name.
String flagimage = "R.drawable." + myHelper.getFlagImage(5);
int resourceId = Integer.parseInt(flagimage);
Bitmap flag = BitmapFactory.decodeResource(getResources(), resourceId);
A: You can use the name of a resource like
getIdentifier (String name, String defType, String defPackage);
getResources().getIdentifier("us","drawable","com.app");
The above function will return an integer value same as R.drawable.us.
This is how you access with resource names.
A: You can use this code to get the identifier...
Resources res = this.getResources();
int resID = res.getIdentifier(imagename, "drawable", this.getPackageName());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: error when trying to edit status of Order in admin interface(playframework) In my app ,I have a class Order that contains a collection of cartItems .The Order can have status 'pending' ,'confirmed' etc.
After the customer placed the order,it has a status 'confirmed'.Since wrong payment info was provided by customer,the admin decides to change the status of Order to 'pending'.Using the CRUD/admin interface ,I selected the Order entry and tried to edit the status field.This caused the following error.
PersistenceException occured : org.hibernate.HibernateException:
A collection with
cascade="all-delete-orphan" was no longer referenced
by the owning entity instance: models.Order.cartItems
The error shown on page is :
In {module:crud}/app/controllers/CRUD.java (around line 100)
96: } catch (TemplateNotFoundException e) {
97: render("CRUD/show.html", type, object);
98: }
99: }
100: object._save();//Here error marked in red
101: flash.success(Messages.get("crud.saved", type.modelName));
102: if (params.get("_save") != null) {
103: redirect(request.controller + ".list");
104: }
105: redirect(request.controller + ".show", object._key());
106: }
The models in my app are;
@Entity
public class Order extends Model {
@ManyToOne
private Customer customer;
@OneToMany( cascade=CascadeType.ALL,orphanRemoval=true)
private Set<CartItem> cartItems;
private String status;
...
}
@Entity
public class CartItem extends Model implements Comparable<CartItem>{
@OneToOne
private Product product;
private int quantity;
...
}
I don't really understand why this happened.How can changing the value of a field cause this? What should I do to avoid this error? I need the admin to be able to edit this field..
If anyone can suggest a solution,it would be nice.
A: What about setting mappedBy in the Order class and adding @ManyToOne to the CartItem?
@Entity
public class Order extends Model {
@ManyToOne
private Customer customer;
@OneToMany(mappedBy="order",cascade=CascadeType.ALL,orphanRemoval=true)
private Set<CartItem> cartItems;
private String status;
...
}
@Entity
public class CartItem extends Model implements Comparable<CartItem> {
@OneToOne
private Product product;
@ManyToOne
private Order order;
private int quantity;
...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544315",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Does push technology work successfully on a mobile browser? If I had a webpage that had a square on it and if I was using push technology to update the coordinates of this square on the page, could I see these updates well in a mobile browser (how much in "real-time" would the responses be)? I want to use Sencha to make a board game and want to be able to use push messaging to update coordinates of items. Is this at all possible? If so how scalable would it be?
A: Yes and no.
It entirely depends on the specific browser on the mobile device. For example, the iPhone browser will most likely support more than one push tech, but something like Opera Mini or a simpler browser in an older phone might not.
Then again, older/less feature-rich browsers might not support "normal" Ajax either.
As for scalability, the type of the device used as the client does not have an effect on scalability.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET Active Directory C# field specification We've got an active directory here. provided the unique user id of the user, I need to access the organization->manager->name attribute related to that userid. Basically this will be used to send an approval form to the manager of the person submitting request.
Any idea how this could be done?
A: You can use the following code :
/* Retreiving object from SID
*/
string SidLDAPURLForm = "LDAP://WM2008R2ENT:389/<SID={0}>";
System.Security.Principal.SecurityIdentifier sidToFind = new System.Security.Principal.SecurityIdentifier("S-1-5-21-3115856885-816991240-3296679909-1106");
/*
System.Security.Principal.NTAccount user = new System.Security.Principal.NTAccount("SomeUsername");
System.Security.Principal.SecurityIdentifier sidToFind = user.Translate(System.Security.Principal.SecurityIdentifier)
*/
DirectoryEntry userEntry = new DirectoryEntry(string.Format(SidLDAPURLForm, sidToFind.Value));
string managerDn = userEntry.Properties["manager"].Value.ToString();
But you can also find in this post other ways to seach bind to Active-directory.
A: Since you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:
*
*Managing Directory Security Principals in the .NET Framework 3.5
*MSDN docs on System.DirectoryServices.AccountManagement
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
if(user != null)
{
// do something here....
}
// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");
// if found....
if (group != null)
{
// iterate over members
foreach (Principal p in group.GetMembers())
{
Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
// do whatever you need to do to those members
}
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!
I'm not 100% sure what you want to do in your concrete case... the UserPrincipal has an EmployeeId property - is that what you want to search for?
A: Use the System.DirectoryServices.DirectoryEntry class to read out the appropriate property of the user object. The constructor of DirectoryEntry requires that you have an LDAP path to the user. Getting the LDAP path can often be tricky though as IIS prefers handing over the SAM account name only. If you provide more details of what the user id you have looks like it is easier to point you in the right direction.
To do this the account which runs the ASP.NET application needs read access to the AD, which probably doesn't have by default. Changing the application pool to run under "NetworkService" is the easiest way if the web server belongs to the AD. The ASP.NET app will then use the MACHINE$ account of the server to access the AD.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Python google search explicit phrase I am trying to define a google search with the AJAX interface using the very good function described here (A Martelli)
Google Search from a Python App
........
query = urllib.urlencode({'q': searchfor})
....
If I define the variable searchfor = "big car", the query generated is big+car. However I want to generate the query "big car" (those two words ocurring together).
Q1) That is, I would like to define an explicit phrase in my query (in google I would enter the "phrase" within double quotes).
Q2) How can I define a query where I wxclude a certain term. (In google you enter the "-" sign).
A: 1) Put the quotes in searchfor string, searchfor = '"big car"'. You can also define the strings with double quotes and escape the double quote character: searchfor = "\"big car\"". See Googles Python class for information about string literals in Python.
Just to be clear, the + is the urlencoded space character, it will be interpreted as a plain space when Google retrieves it. The urlencoded query with the quotes will be q=%22big+car%22, where %22 is a double quote.
urllib.urlencode will encode the string correctly to be submitted in the URL.
2) Just use the same syntax as you would when you use Google normally. searchfor = '"big car" -hummer'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I utilize XAML objects specified in a resource dictionary in other XAML source? If i have a resource dictionary that contains something like
<RibbonTab x:Key="HomeRibbonComponent" Header="test">
</RibbonTab>
how can I have my Ribbon control add this as a child? (in code it seems easy, in XAML not so much...)
A: Use the resource extension directly as if you were binding it but in XAML.
e.g.,
<StaticResource ResourceKey="HomeRibbonComponent" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544327",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Maven copy resources in multi module project My need is pretty basic but I could not find any clean answer to it: I simply need to be able to distribute a resource in a multi-module project.
Let us consider for example the LICENSE file, which I hereby assume to be the same for all modules. I prefer not to manually copy it into each and every module because the file could change over time. I also prefer not to statically link to resources (even if using relative paths) outside the project folder, because the modular structure can possibly change too.
Is there any plugin that can be used to robustly guarantee that each module is given the required file? It would be equally acceptable for such copy to be obtained by exploiting the POM of the parent project or directly performed by the super project in the modular hierarchy.
A: you could use the assembly and the dependency plugins.. did you stumble over that link?
http://www.sonatype.com/people/2008/04/how-to-share-resources-across-projects-in-maven/
it describes that option ..its from 2008, but maven is around for quite some time.. so I guess its more or less up to date
edit regarding comment
Another option is the maven-remote-resources-plugin.
For a more detailed example see:
http://maven.apache.org/plugins/maven-remote-resources-plugin/examples/sharing-resources.html
Since their intro speaks actually for itself, I quote (maven.apache.org)
This plugin is used to retrieve JARs of resources from remote repositories, process those resources, and incorporate them into JARs you build with Maven. A very common use-case is the need to package certain resources in a consistent way across your organization: at Apache it is required that every JAR produced contains a copy of the Apache license and a notice file that references all used software in a given project.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7544330",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.