text stringlengths 8 267k | meta dict |
|---|---|
Q: Create parameterized Persistence Unit + JTA DataSource at Runtime (context dependent) i'm trying to write an EJB3 Stateless Session Bean which gets the parameter "customerCode" (String).
Dependent on this "customerCode" i want to create an EntityManager (Persistence.createEntityManagerFactory...) with a (dynamically?) created PersistenceUnit.
I can not define the PU in the persistence.xml, because it's name (and underlying datasource) must be able to be added/removed at runtime (e.g. deploying a new datasource/persistence unit that belongs to a specific customer code).
I could define the PUs in the persistence.xml, because i know all the customerCodes in advance, but if the datasource XML file is missing, i can not deploy my EAR correctly, because the container (JBOSS) looks for a matching datasource.
what can i do?
thanks in advance!
A: Yes you can do this.A rough cut is below.
private static Map<String, EntityManagerFactory> emfMap
= new HashMap<String, EntityManagerFactory>();
private static List<String>customerCodes;
You need to populate this list of customerCodes obviously before calling populateEmfMap
public static void populateEmfMap()
{
for (String customerCode : customerCodes)
{
emfMap.put(customerCode,Persistence.createEntityManagerFactory(customerCode));
}
}
You can just get it from the Hasmap by key.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create a packet which contains two images and two strings and send it via post method in iPhone? I have two images and two strings which have been converted to base64 strings and I wish to send them as packet using POST method. Should i concatenate the base64 strings or is there any other way around?
A: Have you tried this ASIHTTPRequest? It can do a lot of things.
It can send POST parameters, images etc. Check out the "How to use it" section, it includes the sample codes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: XMPP SMACK file receiving not working on android I am unable to recive the file, which I am transfering from SPARK client.
I am using ASMACK jar Library so it's not possible to get into the library.
ServiceDiscoveryManager sdm = ServiceDiscoveryManager.getInstanceFor(connection);
if (sdm == null){
sdm = new ServiceDiscoveryManager(connection);
sdm.addFeature("http://jabber.org/protocol/disco#info");
sdm.addFeature("jabber:iq:privacy");
}
// new ServiceDiscoveryManager(connection);
FileTransferNegotiator.setServiceEnabled(connection, false);
FileTransferManager manager = new FileTransferManager(connection);
manager.addFileTransferListener(new FileTransferListener() {
public void fileTransferRequest(FileTransferRequest request) {
Log.d("", "allows file...");
if (request != null) {
// Accept it
IncomingFileTransfer transfer = request.accept();
try {
// String pathsd = Environment.getExternalStorageDirectory().toString();
String path = "/sdcard/"+ request.getFileName();
transfer.recieveFile(new File(path));
// transfer.recieveFile(new
// File(request.getFileName()));
System.out.println("File " + request.getFileName() + "Received Successfully");
// Log.d("", "rece: " + request.getFileName());
// Log.d("", "path: " + request.getFileName());
// InputStream input = transfer.recieveFile();
} catch (XMPPException ex) {
Log.d("", "er: " + ex);
}
} else {
Log.d("", "reject file...");
request.reject();
}
}
});
A: Don't know what version of Smack your asmack is based on, but there is a known issue with file transfer in Smack, which both asmack and Spark are based on.
A: Beems asmack build process is well documented and also the sources are open for everyone.
Your code looks right, but why do you set this
FileTransferNegotiator.setServiceEnabled(connection, false);
to false?
File transfer in XMPP is a rather complex topic. There are various methods (at least 4), to get a file from one resource to another. As you provided no further details I can only give you general device on how to debug this:
Enable connection debug in smack, which will print out and log all XMPP packets that go in and out. Trace the XMPP stanzas that relate to the file transfer and make sure they behave as specified in the XEPs. This may provides a hint about whats going wrong.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: two keys one value in android How do I implement the following data ?
somelisttype <int>obj ;
obj 0,0 => val0
obj 0,1 => val1
obj 0,2 => val2
obj 1,0 => val8
obj 2,0 => val9
obj 2,1 => val10
0,0 ; 0,1 are the keys ( or in other way the row index or column index.)
I would like to have following functionality ..
obj 0.add(val11) == obj 0,3 => val11
obj 3.add(val12) == obj 3,0 => val12
obj 2.length => 2
obj 3.length => 1
obj 0,2 => val2
ValXX => are values and not objects ( would be integers )
I don't want to create 2d array since I don't know length of total obj or individual obj0,obj1
What variable type can be used for this in android ??
A: What's about List<List<Integer>>?
You can't avoid the generic type to be an object here but since cast from Integer to int is implicit you would see any difference in use.
Update
Okay here it is:
MyList l = new MyList();
l.set(0, 0, 1);
l.set(1, 0, 2);
l.set(1, 1, 3);
Log.d("TAG", l.get(0, 0) + " " + l.get(1, 0) + " " + l.get(1, 1));
Here the implementation (o course you have to make sure that used index is right, so you can't add index 1 when 0 is not already set):
class MyList {
private List<List<Integer>> mList = new ArrayList<List<Integer>>();
public void set(int i, int k, int value) {
List<Integer> list;
if (i == mList.size()) {
list = new ArrayList<Integer>();
mList.add(i, list);
} else {
list = mList.get(i);
}
if (k == list.size()) {
list.add(value);
} else {
list.set(k, value);
}
}
public int get(int i, int k) {
return mList.get(i).get(k);
}
}
A: You can use HashMap which is based on key value pair.
You find a simple eg over here.
A: This is really a basic Java question, and has little to do with Android. You might want to change your tags to get better answers. A List of List<Integer> will probably do, unless you need to put/get by key, in which case you need a HashMap with a composite key, that holds two integers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Remove class if checkbox is checked I want that onload the <span> and <checkbox> classes to be blank:
<span id="checkboxx_<?php echo $nrs['id']; ?>" class="highlight" >
<input type="checkbox" class="checkboxx" id="checkboxx_<?php echo $nrs['id']; ?>" style="padding: 0px; margin: 2px;" <?php echo $value == 1 ? 'checked="checked"' : ''?>>
</span>
i have tried this
<?php
if($value==1)
{
?>
<script>
if (this.checked) {
document.getElementById("checkboxx_<?php echo $nrs['id']; ?>").className = "";
}
</script>
<?php
} else {
?>
<script>$j("#"+pos).addClass("highlight");</script>
<?php
}
but this doesn't work.
A: document.getElementById("MyElement").className =
document.getElementById("MyElement").className.replace(/(?:^|\s)MyClass(?!\S)/ , '')
A: actually you have duplicate IDs in your code checkboxx_<?php echo $nrs['id']; ?> for span and checkbox, and also this code is buggy and wont work
<script>if (this.checked) {
document.getElementById("checkboxx_<?php echo $nrs['id']; ?>").className = "";
}
</script>
i think it will a be better way to use smth like this:
<span class="<?php echo ($value !== 1 ? 'highlight' : '') ?>" >
<input type="checkbox" class="checkboxx" style="padding: 0px; margin: 2px;" <?php echo $value == 1 ? 'checked="checked"' : ''?>>
</span>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512412",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JSF and automatic reload of xhtml files I had some problems with hot-reloading XHTML files using JRebel, Spring, JSF Mojarra 2.0.3 and WebLogic 10.3.
JRebel reloads regular Java classes and js/css files under /WebContent successfully, but not JSF's .xhtml files. A full republish was necessary to get xhtml files updated on the server.
By trial and error I finally got it to work by adding some facelets parameters to web.xml and creating a custom ResourceResolver as described in this blog post.
However, I wonder WHY this works, and more specifically:
*
*Why is a custom ResourceResolver needed?
*Isn't JRebel supposed to handle this by monitoring /WebContent where the xhtml files reside?
*I'm guessing it has something to do with Facelets/JSF compiling xhtml to servlets(?) via FacesServlet which JRebel is unable to detect?
A: JRebel handles /WebContent folder changes.
The problem is that Facelets do caching and do not reread changed files. To force reread specify the following parameters in web.xml.
JSF 2 (Facelets 2.x):
<!-- Time in seconds that facelets should be checked for changes since last request. A value of -1 disables refresh checking. -->
<context-param>
<param-name>javax.faces.FACELETS_REFRESH_PERIOD</param-name>
<param-value>0</param-value>
</context-param>
<!-- Set the project stage to "Development", "UnitTest", "SystemTest", or "Production". -->
<!-- An optional parameter that makes troubleshooting errors much easier. -->
<!-- You should remove this context parameter before deploying to production! -->
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
For JSF 1.2 (Facelets 1.x) parameters are:
<context-param>
<param-name>facelets.REFRESH_PERIOD</param-name>
<param-value>0</param-value>
</context-param>
<context-param>
<param-name>facelets.DEVELOPMENT</param-name>
<param-value>true</param-value>
</context-param>
More on JSF context params: http://docs.jboss.org/jbossas/6/JSF_Guide/en-US/html/jsf.reference.html#standard.config.params
That custom resource resolver is not needed in your case. That resource resolver is just a tricky way to get xhtml files from custom file system folder. In your case JRebel does that (and even more).
A: Here's how I fixed this for me:
*
*Verify that facelets plugin is enabled in your JRebel settings &
*Verify that you're using Project Stage Development in your web.xml
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: >Call to a member function exec() on a non-object< when I try to call PEAR MDB2 class I have a problem which I seem unable to solve on my own, although the script is kind of simple... I simply want to write sth. in a MySQL database (auto_increment id) with the following script:
<?php
// Create a valid MDB2 object named $mdb2
// at the beginning of your program...
require_once 'MDB2.php';
// Once you have a valid MDB2 object named $mdb2...
class addToDb extends MDB2 {
function __construct() {
$mdb2 =& MDB2::connect('mysql://************************');
if (PEAR::isError($mdb2)) {
die($mdb2->getMessage());
}
}
// 1) Add general information into trips
function addTrip() {
$title = $_POST['title'];
$author = $_POST['author'];
$description = $_POST['description'];
$date_start = $_POST['date_start'];
$date_end = $_POST['date_end'];
if(isset($title)) echo $title;
else echo "!!";
//$id = $mdb2->extended->getAfterID($id);
$sql = "INSERT INTO trips (title, author, description, date_start, date_end)
VALUES ($title, $author, $description, $date_start, $date_end)";
$affected =& $mdb2->exec($sql);
// Always check that result is not an error
if (PEAR::isError($affected)) {
die($affected->getMessage());
}
}
// Disconnect
function disconnectDb() {
$mdb2->disconnect();
}
}
?>
And that's how I want to call the object:
$input = new addToDb();
$input->addTrip();
$input->disconnectDb();
I have tried many things including just executing the code without putting it in a class, always the same error:
Fatal error: Call to a member function exec() on a non-object in /www/htdocs/w007bba1/v3/_class/_general/_db.php on line 36
Line 36 represents
$affected =& $mdb2->exec($sql);
in my addToDb class. I'd be thankful if somebody could tell me where my script is incorrect, I couldn't find any help in other posts so far...
Regards!
Stocki
A: Seems as if $mdb2 is no object, AS THE ERROR SAYS.
Your problem is that you initialize $mdb2, but the variable is only available in the scope of __construct. You have to store it in a class variable to be able to use it in addTrip().
A: PDO uses Cpanel user and password instead of DB user and password.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to data bind Entity Framework objects to a FormView I am data binding to many FormView controls using EF entity instances, but I have to resort to this ridiculous kludge in order to achieve what I want without using EntityDataSource controls:
propertyHeaderSection.DataSource = new List<PropertyDetailsModel> { _propertyDetails };
I suspect I will have to derive my own control from FormView and enable it to accept an almost POCO as a data source. Where do I start?
A: Not sure it's the best idea in the world, but this is how you could derive from FormView to allow single object data source values. It basically does the same check that the ValidateDataSource does internally, and then creates a list wrapper for the item if it's not already a valid type.
public class SingleObjectFormView : System.Web.UI.WebControls.FormView
{
public override object DataSource
{
get
{
return base.DataSource;
}
set
{
//will check if it's an expected list type, and if not,
//will put it into a list
if (! (value == null || value is System.Collections.IEnumerable || value is System.ComponentModel.IListSource || value is System.Web.UI.IDataSource) )
{
value = new List<object> { value };
}
base.DataSource = value;
}
}
}
A: This is my implementation, sort of the same idea as patmortech, but i also found out that the ValidateDataSource method on the BaseDataBoundControl is what throws the exception at run-time if your datasource isn't enumerable.
public class CustomFormView : System.Web.UI.WebControls.FormView
{
public override object DataSource
{
get
{
if (!(base.DataSource is IEnumerable))
return new[] {base.DataSource};
return base.DataSource;
}
set
{
base.DataSource = value;
}
}
// This method complains at run time, if the datasource is not
// IListSource, IDataSource or IEnumerbale
protected override void ValidateDataSource(object dataSource)
{
//base.ValidateDataSource(dataSource);
}
}
EDIT:
Considering the suggestion, i've made some changes to the way i check if the assigned DataSource is enumerable or not. I have also managed to create a sample app (VS 2010 Solution) to demo the changes. The app can be downloaded from http://raghurana.com/blog/wp-content/attachments/FormViewDataProblem.zip
In short this is what i am checking to ensure that the existing datasource can be enumerated already or not:
public static bool CanEnumerate( this object obj )
{
if (obj == null) return false;
Type t = obj.GetType();
return t.IsArray ||
t.Implements(typeof (IEnumerable).FullName) ||
t.Implements(typeof (IListSource).FullName) ||
t.Implements(typeof (IDataSource).FullName);
}
Please feel free to suggest more changes, if this isnt quite the desired functionality. Cheers.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to use my Entities and Entity Managers in Symfony 2 Console Command? I want to a few terminal commands to my Symfony2 application. I've gone through the example in the cookbook, but I couldn't find out how to access my settings, my entity manager and my entities here. In the constructor, I get the container (which should yield me access to settings and entities) using
$this->container = $this->getContainer();
But this call generates an error:
Fatal error: Call to a member function getKernel() on a non-object in /Users/fester/Sites/thinkblue/admintool/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Command/ContainerAwareCommand.php on line 38
Basically, in ContainerAwareCommand->getContainer() the call to
$this->getApplication()
returns NULL and not an object as expected. I guess that I left some important step out, but which one? And how will I finally be able to use my settings and entities?
A: I think you should not retrieve the container in the constructor directly. Instead, retrieve it in the configure method or in the execute method. In my case, I get my entity manager just at the start of the execute method like this and everything is working fine (tested with Symfony 2.1).
protected function execute(InputInterface $input, OutputInterface $output)
{
$entityManager = $this->getContainer()->get('doctrine')->getEntityManager();
// Code here
}
I think that the instantiation of the application object is not done yet when you are calling getContainer in your constructor which result in this error. The error comes from the getContainer method tyring to do:
$this->container = $this->getApplication()->getKernel()->getContainer();
Since getApplication is not an object yet, you get the a error saying or are calling a method getKernel on a non-object.
Update: In newer version of Symfony, getEntityManager has been deprecated (and could have been removed altogether by now). Use $entityManager = $this->getContainer()->get('doctrine')->getManager(); instead. Thanks to Chausser for pointing it.
Update 2: In Symfony 4, auto-wiring can be used to reduce amount of code needed.
Create a __constructor with a EntityManagerInterface variable. This variable will be accessible in the rest of your commands. This follows the auto-wiring Dependency Injection scheme.
class UserCommand extends ContainerAwareCommand {
private $em;
public function __construct(?string $name = null, EntityManagerInterface $em) {
parent::__construct($name);
$this->em = $em;
}
protected function configure() {
**name, desc, help code here**
}
protected function execute(InputInterface $input, OutputInterface $output) {
$this->em->getRepository('App:Table')->findAll();
}
}
Credits to @profm2 for providing the comment and the code sample.
A: I know that Matt's answer solved the question, But if you've more than one entity manager, you can use this:
Make model.xml with:
<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">
<services>
<service id="EM_NAME.entity_manager" alias="doctrine.orm.entity_manager" />
</services>
</container>
Then load this file in your DI extension
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('model.xml');
Then you can use it anywhere.
In Console Command execute:
$em = $this->getContainer()->get('EM_NAME.entity_manager');
and don't forget at end to :
$em->flush();
You can now use it as a argument in another service in services.yml:
services:
SOME_SERVICE:
class: %parameter.class%
arguments:
- @EM_NAME.entity_manager
Hope this help someone.
A: extends your command class from ContainerAwareCommand instead of Command
class YourCmdCommand extends ContainerAwareCommand
and get entity manager like this :
$em = $this->getContainer()->get('doctrine.orm.entity_manager');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "42"
} |
Q: error: expected declaration specifiers before ‘namespace’ File name: widgets.c
#include <QtGui>
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
return app.exec();
}
Pro file:
anisha@linux-dopx:~/Desktop/notes/qt> cat qt.pro
######################################################################
# Automatically generated by qmake (2.01a) Thu Sep 22 14:53:10 2011
######################################################################
TEMPLATE = app
TARGET =
DEPENDPATH += .
INCLUDEPATH += .
# Input
SOURCES += widgets.c
anisha@linux-dopx:~/Desktop/notes/qt>
Error messages:
anisha@linux-dopx:~/Desktop/notes/qt> make
gcc -c -m64 -pipe -O2 -Wall -W -D_REENTRANT -DQT_NO_DEBUG -DQT_GUI_LIB -DQT_CORE_LIB -DQT_SHARED -I../../../qtsdk-2010.05/qt/mkspecs/linux-g++-64 -I. -I../../../qtsdk-2010.05/qt/include/QtCore -I../../../qtsdk-2010.05/qt/include/QtGui -I../../../qtsdk-2010.05/qt/include -I. -I. -o widgets.o widgets.c
In file included from ../../../qtsdk-2010.05/qt/include/QtCore/qobjectdefs.h:45:0,
from ../../../qtsdk-2010.05/qt/include/QtCore/qobject.h:47,
from ../../../qtsdk-2010.05/qt/include/QtCore/qabstractanimation.h:45,
from ../../../qtsdk-2010.05/qt/include/QtCore/QtCore:3,
from ../../../qtsdk-2010.05/qt/include/QtGui/QtGui:3,
from widgets.c:12:
../../../qtsdk-2010.05/qt/include/QtCore/qnamespace.h:51:1: warning: return type defaults to ‘int’
../../../qtsdk-2010.05/qt/include/QtCore/qnamespace.h: In function ‘QT_MODULE’:
../../../qtsdk-2010.05/qt/include/QtCore/qnamespace.h:54:1: error: expected declaration specifiers before ‘namespace’
../../../qtsdk-2010.05/qt/include/QtCore/qnamespace.h:1775:1: error: expected declaration specifiers before ‘Q_DECLARE_OPERATORS_FOR_FLAGS’
../../../qtsdk-2010.05/qt/include/QtCore/qnamespace.h:1796:1: error: expected declaration specifiers before ‘class’
../../../qtsdk-2010.05/qt/include/QtCore/qnamespace.h:1851:2: error: expected declaration specifiers before ‘;’ token
In file included from ../../../qtsdk-2010.05/qt/include/QtCore/qobject.h:47:0,
from ../../../qtsdk-2010.05/qt/include/QtCore/qabstractanimation.h:45,
from ../../../qtsdk-2010.05/qt/include/QtCore/QtCore:3,
from ../../../qtsdk-2010.05/qt/include/QtGui/QtGui:3,
from widgets.c:12:
../../../qtsdk-2010.05/qt/include/QtCore/qobjectdefs.h:51:1: error: expected declaration specifiers before ‘QT_MODULE’
../../../qtsdk-2010.05/qt/include/QtCore/qobjectdefs.h:55:1: error: expected declaration specifiers before ‘class’
../../../qtsdk-2010.05/qt/include/QtCore/qobjectdefs.h:142:1: error: expected declaration specifiers before ‘template’
../../../qtsdk-2010.05/qt/include/QtCore/qobjectdefs.h:145:1: error: expected declaration specifiers before ‘template’
../../../qtsdk-2010.05/qt/include/QtCore/qobjectdefs.h:212:1: error: expected declaration specifiers before ‘Q_CORE_EXPORT’
../../../qtsdk-2010.05/qt/include/QtCore/qobjectdefs.h:240:1: error: expected declaration specifiers before ‘class’
../../../qtsdk-2010.05/qt/include/QtCore/qobjectdefs.h:241:1: error: expected declaration specifiers before ‘class’
../../../qtsdk-2010.05/qt/include/QtCore/qobjectdefs.h:242:1: error: expected declaration specifiers before ‘class’
../../../qtsdk-2010.05/qt/include/QtCore/qobjectdefs.h:243:1: error: expected declaration specifiers before ‘class’
What's the point that I am missing here?
A: Looks like you are using the C Compiler to compile C++. Try renaming your file to widgets.cpp.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Iterating Performance Comparison I have an array:
deleteIds= ["User1"];
and try to iterate over it as like:
first one:
for (var index = 0; index < len; index++) {
alert(deleteIds[index]);
}
second one:
for (var index in deleteIds) {
alert(deleteIds[index]);
}
What is the performance comparison of them?
A: This is a micro optimisation at best. Unless you have hundreds of thousands of elements in your deleteIds array, you should not be looking at optimising this.
It turns out that the for(;;;) version is quicker than for in: http://jsperf.com/iterating-over-a-loop/2 (thanks to @Jamiec for the jsperf).
However, what's more important than the performance comparison of these, is that both code snippets are functionally different to each other (live example).
var array = new Array(100);
for (var i = 0; i < array.length; i++) {
console.log(i); // shows 0 - 99
}
for (var x in array) {
console.log(x); // shows nothing
}
Furthermore, if you add methods to either the array, or to an object in the arrays' prototype chain, they will show up in the for (var x in y) loop, but not in for (;;;); (live example):
Array.prototype.foo = function() {};
var array = [];
for (var i = 0; i < array.length; i++) {
console.log(i); // nothing
}
for (var x in array) {
console.log(x); // `foo`
}
You can use hasOwnProperty to eliminate the attributes inherited from the prototype chain, but that won't stop you receiving methods directly on the object (live example):
Array.prototype.foo = function() {};
var array = [];
array.bar = function () {};
for (var i = 0; i < array.length; i++) {
console.log(i); // nothing
}
for (var x in array) {
if (array.hasOwnProperty(x)) {
console.log(x); // `bar`
}
}
It is because of these reasons that using for in for iterating over an array is discouraged, and the for(;;;) version should always be used instead. for in should be used for iterating over an object.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how extracts values from a char array? HI I have following char array in C,
char array[1024] = "My Message: 0x7ffff6be9600"
i have to extract the value "0x7ffff6be9600" only from above char array.
how can i extract the value with the use scanf() type functions?
Thanks in advance.
A: Use the sscanf function, precisely for that.
For example:
unsigned long l;
if (3 == sscanf(array, "%*s %*s %lx", &l)) //ignore the words before the number
{
// got something
}
A: Look ma, no scanf ...
printf("%.14s", strstr(array, " 0x") + 1);
or, still no scanf
#include <stdio.h>
#include <string.h>
int main(void) {
char array[] = "My Message: 0x7ffff6be9600----";
char result[100];
char *tmp;
tmp = strstr(array, " 0x");
if (tmp) {
strncpy(result, strstr(array, " 0x") + 1, 14);
result[14] = 0;
printf("result: %s\n", result);
} else {
printf("invalid input\n");
}
return 0;
}
A: Here's a simple example using sscanf(), which is fairly close to scanf():
> cat 7512438.c
#include <stdio.h>
int main() {
char array[1024] = "My Message: 0x7ffff6be9600";
unsigned long hex = 0UL;
if (sscanf(array, "My Message: 0x%lx", &hex) == 1) {
printf("%lx\n", hex);
} else {
printf("Sorry, could not extract anything useful from %s\n", array);
}
return 0;
}
> make 7512438
cc -Wall -I /opt/local/include -L/opt/local/lib 7512438.c -o 7512438
> ./7512438
7ffff6be9600
A: Perhaps something like this would work for you :
char IsDigit(char val)
{
if((val>47 && val<58))
return 1;
else if(val>64 && val<70)
return 2;
else if(val>96 && val<103)
return 3;
return 0;
}
__int64 GetHexInt64(char* text,int maxlen)
{
int i=0;
char state=0;
char dig;
__int64 res = 0;
int digcnt = 0;
while(i<maxlen && text[i]!='\0')
{
switch(state)
{
case 0:
if(text[i]=='0')
state++;
else
state=0;
break;
case 1:
if(text[i]=='x' || text[i]=='X')
state++;
else
state=0;
break;
}
i++;
if(state==2)
break;
}
if(state!=2)
return (__int64)-1;
while(i<maxlen && text[i]!='\0' && digcnt<16)
{
dig = IsDigit(text[i]);
if(dig)
{
digcnt++;
switch(dig)
{
case 1:
res<<=4;
res|=(text[i]-48) & 0x0f;
break;
case 2:
res<<=4;
res|=(text[i]-55) & 0x0f;
break;
case 3:
res<<=4;
res|=(text[i]-87) & 0x0f;
break;
}
}
else
{
break;
}
i++;
}
return res;
}
Sorry about the __int64 but I am unsure what is the correct type for a 64-bit integer in your compiler.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Image upload to facebook from clientside using FormData() - what's wrong? On input file change event, I am executing the following code.
*
*create a form data by encoding the image to "multipart/form-data"
*alert('before calling FB.api-post :' + imgFile.name) - this works
*create the param to be used in FB.api
*call FB.api - but this never
gets executed. - what's wrong ?
var fData = new FormData();
var imgFile = $('input[type="file"]')[0].files[0];
fData.append("image", imgFile);
alert('before calling FB.api-post :' + imgFile.name);
var params = {
"access_token": $D("access_token"),
"message": $D("img_message"),
"upload file": true,
"source":fData
}
FB.api('/me/photos', 'POST', params,
function (response) {
alert('asasasasasasasasasasasasas');
if (!response || response.error) {
$D("preview").innerHTML = "Error in facebook Photo UPLOAD : " + response.error;
alert('Error in facebook Photo UPLOAD : ' + response.error);
}
else {
$D("preview").innerHTML = "Photo UPLOADED : " + response;
alert('uploaded');
}
}
);
});
Note: $D is nothing but the following shortcut
function $D(element) {
return document.getElementById(element);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Persistent FTP connection with file wrapper in php If I do something like that:
rename('ftp://user:password@example.com/pub/file1.txt','ftp://user:password@example.com/pub/fileA.txt');
rename('ftp://user:password@example.com/pub/file2.txt','ftp://user:password@example.com/pub/fileB.txt');
rename('ftp://user:password@example.com/pub/file3.txt','ftp://user:password@example.com/pub/fileC.txt');
rm('ftp://user:password@example.com/pub/fileA.txt');
rm('ftp://user:password@example.com/pub/fileB.txt');
rm('ftp://user:password@example.com/pub/fileC.txt');
will php keep ftp connection between different operations on the same server? In other words I wonder if in such case php creates separate connection or keeps it alive? And if it creates separate connections then how could force it to use one when I transfer files using file wrappers. I know I could use different methods instead of ftp wrapper but I want to know how this works with file wrappers.
A: Just been looking at it with Wireshark and the answer is definitely No. Tested with PHP/5.2.19-win32.
As Robik suggests use the PHP FTP extension if you want connection persistence.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I start Xdebug over an internal HTTP request? I have Xdebug set up nicely using an SSH tunnel. When connecting from the command line I use the XDEBUG_CONFIG environmental variable and when connecting over HTTP I use the XDEBUG_SESSION cookie. Both work brilliantly.
My issue is that the project I am working on makes internal HTTP requests to an internal API. As the request is repeated internally, it doesn't continue the session and I therefore cannot debug anything in the API when it comes from a front-end request.
Is there a way to fix this so that I can debug both?
A: There is http://xdebug.org/docs/remote#remote_autostart that will always (try to) start a remote debugging session. If it's just from the browser, you might want to look at one of the browser extensions that automatically add a cookie without any user interference: http://xdebug.org/docs/remote#browser-extensions
cheers,
Derick
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make your own eclipse? Who knows how to customize your own eclipse? I want to include some plugins and use it as bundled solution and not to install additional plugin when I want to use it on other machine.
A: This is what I've done in the past.
The first thing you have to do is a fresh install of eclipse, all the plugins you intend to use, and their configurations. After that just copy the eclipse folder AND the workspace/.metadata folder (this one could be an hidden folder) to the new machine.
Copying those folders to a new machine and running eclipse with the -clean flag (only needed the first time) seems to work fine so far.
I ran into some problems when trying to use 32bit eclipse in an 64bit environment, but I guess it's normal that it doesn't work. Also, this is not a cross-platform solution, i.e you cannot use your Mac installation of eclipse in Windows, or vice-versa.
A: I think you are referring to so called Individual Source Bundle, which you can build and create your own setup that will install your custom Eclipse bundle on desired machine.
Another solution would be just creating simple install/archive that will unpack c:\eclipse\ to c:\eclipse\ (or whatever) on target machine. This will work since Eclipse is not hardware dependent (but sure, it is OS dependent) because it's Java based.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: @font-face for the drop down is not working in ie8 While using @font-face I am facing a problem that is when I am going to convert the font from hindi to english, this is working fine in each and every browser for each datacontrol. but for dropdownlist this is not good in IE8 but fine in other browsers.I am using it in the following way:
1) in app_theme folder
@font-face
{
font-family: "MyCustomFont";
src: url('../font/MFDEV010.ttf') format('truetype')
}
@font-face
{
font-family: "MyFont";
src: url('../font/MFDEV010.eot?iefix') format('eot')
}
.HindiSkin
{
font-family: "MyFont", "MyCustomFont";
font-size:17px;
}
.EngSkin
{
font-family: Arial Unicode MS ;
font-size:15px;
}
.InputSelect
{
/*border: 1px solid #b0b0b0;*/
font-family: verdana;
font-size: 12px;
color: #090908;
font-weight: normal;
width: 190px;
padding:1px;
height:25px;
}
.InputSelectHindi
{
/*border: 1px solid #b0b0b0;*/
font-family: "MyCustomFont","MyFont";
font-size: 18px;
color: #090908;
font-weight: normal;
width: 190px;
padding:1px;
height:30px;
}
2) in the skin file i have include:
<asp:DropDownList runat="server" cssclass="InputSelect" />
<asp:DropDownList SkinID="Blue" runat="server" cssclass="InputSelectHindi" />
3) on the page
on the page i have add the reference of the theme here like this:
StylesheetTheme="EnglishFontSkin"
Note: this is working fine everywhere but not IE8, please give the solution for it.
thnx in advance
A: IE doesn't support TTF format in font-face (acording to this page). Maybe that's the reason?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: .htaccess file affecting include files (including images) I'm currently trying to use a script that ensures users are logged into a central sign-on system.
The problem is that any files, including PHP and image files, in this sub-folder are not accessible when included, whether simply when using <?php include 'file.php' ?>, just as an image, i.e. <img src="image.png" />, etc.
The code that I am using in the .htaccess file is below:
RewriteEngine on
# The original URL is set as an environment variable SSO_REQUESTED rather than
# a query parameter, so it's not vulnerable to hacking.
# It shows up in PHP as $_SERVER['REWRITE_SSO_REQUESTED'].
RewriteCond %{REQUEST_URI} !ssoclient
RewriteRule (.+) /sso/ssoclientfilter.php [E=SSO_REQUESTED:$1,L]
Any help here would be greatly appreciated.
A: To use the relative paths for include is pretty bad behavior. You really should set some variable or constant with your document root path in your script. Same for HTML: you should include BASE tag into the header to set the base (root) for relative paths of your images, styles, scripts, etc. Also, could be useful to set RewriteBase in your htaccess.
However, it is strange, that the htaccess affects also php's include which usually uses file system's path, not URI.
A: If the point of your code is to make sure that your users are logged into a central sign-in system wouldn't the PHP code:
<?php
if (!isset ($_COOKIE[ini_get('session.name')])) {
session_start();
}else{
print "<SCRIPT>window.location='/sso/ssoclientfilter.php';</SCRIPT>";
}
In the above code, anyone without a session previously started gets directed to your ssoclientfilter.php and your other images and folders aren't touched. This placed where your session_start() is located should cover your issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android - Overlapping Adjacent LinearLayouts, Overlaying LinearLayouts I am porting an iOS application so the design is pretty much out of my hand. What I have is two LinearLayouts, one with what is basically a bump (shown in pictures) that I want to overlap the second LinearLayout.
I get aesthetically what I want desire I use FrameLayout to contain the two layouts. However, here I run into two functional problems. The first, I need to be able to allow the bottom, overlapping LinearLayout which is composed of five adjacent image buttons to change size (preferably, using layout_weight). The second is anything that is in the bottom of the top LinearLayout it is hidden by the bottom LinearLayout.
When I switch to using LinearLayout, from FrameLayout to contain the two I get functionally what I want, however, aesthetically it smashes the button to fit.
Both cases are pictured. All feedback is appreciated. I am hoping to find a solution to this without designing a custom widget.
Thanks.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: fetchAll statement to return only some columns I am developing a web app using zend framework in which I want to enable my users to search from other users using zend fetchAll function. But its returning complete column and I want several values only. Here is my sample code:
$query=$table->select('id')->where("name LIKE ?",'%'.$str.'%')->limit(10);
$model=new Application_Model_Users();
$rowset=$model->getDbTable()->fetchAll($query)->toArray();
I want to get only name and some other columns. Its returning all columns including password too.:p
A: $select = $db->select();
$select->from('some_tbl', array('username' => 'name')); // SELECT name AS username FROM some_tbl
$select->from('some_tbl', 'name'); // SELECT name FROM some_tbl
$select->from('some_tbl', array('name')); // SELECT name FROM some_tbl
$select->from('some_tbl', '*'); // SELECT * FROM some_tbl
$select->from('some_tbl'); // SELECT * FROM some_tbl
// in case of joins, to disable column selection for a table
$select->from('some_tbl', array());
A: You can add a columns call to fetch only specific columns. In this case, we request the id and name columns:
$columns = array('id', 'name');
$query = $table->select()->columns($columns)->where("name LIKE ?",'%'.$str.'%')->limit(10);
A: // Create the Zend_Db_Select object
$select = $db->select();
// Add a FROM clause
$select->from( ...specify table and columns... )
// Add a WHERE clause
$select->where( ...specify search criteria... )
// Add an ORDER BY clause
$select->order( ...specify sorting criteria... );
Building Select queries - Zend Framework programming documentation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512458",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: making a label as a url link in flex builder I need to make a label in flex as if you click on it you can open a specific URL let us say Google.
Any ideas?
regards.
A: Here is sample:
<fx:Script>
<![CDATA[
import flash.net.navigateToURL;
protected function clickHandler(event:MouseEvent):void
{
var urlReq:URLRequest = new URLRequest("http://www.google.com");
navigateToURL(urlReq, "_self");
}
]]>
</fx:Script>
<s:Label x="110" y="149" text="Open Google" click="clickHandler(event)"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Using a custom (ttf) font in CSS I have a mac, and have installed a font called "7 Segment" (it shows up in Font Book). When I use font-family: "7 Segment"; I get Helvetica (or similar) rather than the browser's default font, but it still isn't showing the correct font. The page only needs to be shown on this computer. How would I use the font on this page? Thanks.
A: You need to use the css-property font-face to declare your font. Have a look at this fancy site: http://www.font-face.com/
Example:
@font-face {
font-family: MyHelvetica;
src: local("Helvetica Neue Bold"),
local("HelveticaNeue-Bold"),
url(MgOpenModernaBold.ttf);
font-weight: bold;
}
See also: MDN @font-face
A: This is not a system font. this font is not supported in other systems. you can use font-face, convert font from this Site or from this
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512468",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: "key cannot be null" when parsing xaml in a datagrid text column I have a DataGrid and it has a text column in it, configured this way:
<dg:DataGridTextColumn Header="{x:Static ResViewModel:SC.Resources.HelloWorld}" />
Here ResViewModel is the xmlns:namespace, SC is the project namespace, Resources is the resource file name and HelloWorld is a string property.
But I try to parse this xaml, I get an error like
Key cannot be null. Parameter name: key...
Can you help me to understand why is this error occuring? Also what is the best way to access resource file without using the LocBAML tool?
A: I see some issues:
*
*"SC is the project namespace" - that should go into the xmlns definition.
*You can't access files with this syntax, unless you have a dependency object with the same name.
There's a good approach to retrieving strings that is described here. It's focusing on Localisation, but it will work for a single language as well. This approach has it's downsides, but it's the lesser evil than other routes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Extracting synonymous terms from wordnet using synonym() Supposed I am pulling the synonyms of "help" by the function of synonyms() from wordnet and get the followings:
Str = synonyms("help")
Str
[1] "c(\"aid\", \"assist\", \"assistance\", \"help\")"
[2] "c(\"aid\", \"assistance\", \"help\")"
[3] "c(\"assistant\", \"helper\", \"help\", \"supporter\")"
[4] "c(\"avail\", \"help\", \"service\")"
Then I can get a one character string using
unique(unlist(lapply(parse(text=Str),eval)))
at the end that looks like this:
[1] "aid" "assist" "assistance" "help" "assistant" "helper" "supporter"
[8] "avail" "service"
The above process was suggested by Gabor Grothendieck. His/Her solution is good, but I still couldn't figure out that if I change the query term into "company", "boy", or someone else, an error message will be responsed.
One possible reason maybe due to the "sixth" synonym of "company" (please see below) is a single term and does not follow the format of "c(\"company\")".
synonyms("company")
[1] "c(\"caller\", \"company\")"
[2] "c(\"company\", \"companionship\", \"fellowship\", \"society\")"
[3] "c(\"company\", \"troupe\")"
[4] "c(\"party\", \"company\")"
[5] "c(\"ship's company\", \"company\")"
[6] "company"
Could someone kindly help me to solve this problem.
Many thanks.
A: You can solve this by creating a little helper function that uses R's try mechanism to catch errors. In this case, if the eval produces an error, then return the original string, else return the result of eval:
Create a helper function:
evalOrValue <- function(expr, ...){
z <- try(eval(expr, ...), TRUE)
if(inherits(z, "try-error")) as.character(expr) else unlist(z)
}
unique(unlist(sapply(parse(text=Str), evalOrValue)))
Produces:
[1] "caller" "company" "companionship"
[4] "fellowship" "society" "troupe"
[7] "party" "ship's company"
I reproduced your data and then used dput to reproduce it here:
Str <- c("c(\"caller\", \"company\")", "c(\"company\", \"companionship\", \"fellowship\", \"society\")",
"c(\"company\", \"troupe\")", "c(\"party\", \"company\")", "c(\"ship's company\", \"company\")",
"company")
A: Those synonyms are in a form that looks like an expression, so you should be able to parse them as you illustrated. BUT: When I execute your original code above I get an error from the synonyms call because you included no part-of-speech argument.
> synonyms("help")
Error in charmatch(x, WN_synset_types) :
argument "pos" is missing, with no default
Observe that the code of synonyms uses getSynonyms and that its code has a unique wrapped around it so all of the pre-processing you are doing is no longer needed (if you update);:
> synonyms("company", "NOUN")
[1] "caller" "companionship" "company"
[4] "fellowship" "party" "ship's company"
[7] "society" "troupe"
> synonyms
function (word, pos)
{
filter <- getTermFilter("ExactMatchFilter", word, TRUE)
terms <- getIndexTerms(pos, 1L, filter)
if (is.null(terms))
character()
else getSynonyms(terms[[1L]])
}
<environment: namespace:wordnet>
> getSynonyms
function (indexterm)
{
synsets <- .jcall(indexterm, "[Lcom/nexagis/jawbone/Synset;",
"getSynsets")
sort(unique(unlist(lapply(synsets, getWord))))
}
<environment: namespace:wordnet>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: BOM randomly appears in JSON reply I'm implementing communication between two servers using JSON and cURL. The problem is, that sometimes there's BOM (byte order mark), appended before opening bracket in JSON reply. I've managed to trim it and successfully parse JSON string, but considering that JSON is generated by my own code, I've no idea, where does that BOM come from.
I'm using json_encode() to generate reply and header() + echo to print it, an as far as I cant tell, json_decode() does not produce any BOMs. Corresponding .php files are encoded in UTF-8 and have no BOM in them (according to Notepad++). Apart from cURL, I've also tried to perform requests using Chrome and python (urllib2). While Chrome does not register any BOM at all, python regularly fails to parse incoming JSON because of it.
So, is there some nuance in using echo, that somehow produces such a result? Where should I start looking for the source of the problem and what may be the solution?
A: I had the same problem. I was outputting json from PHP and there were other class files included at the top of the page. These files output nothing, but when they were included I was getting as many Byte Order Marks as I had included files. So if I had 4 includes, I also had 4 BOMs at the start of my json.
I made sure the includes were not printing any data and there were no stray carriage returns outside the PHP tags. I tried headers such as "application-json", etc., but nothing worked.
In the end, I simply opened each PHP file in notepad++, went to "Encoding" and changed it from UTF-8 to ANSI, then saved. That was all it took to get it working and returning valid json. I made no code changes to the PHP at all.
This solution still feels less than ideal. Since we are not outputting anything from those included files there shouldn't be anything affected.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: JAXB and Guice: How to integrate and visualize? I find using JAXB together with Guice possible, but challenging: Both libraries "fight" for control over object creation, you have to be careful to avoid cyclic dependencies, and it can get messy with all the JAXB Adapters and Guice Providers and stuff. My questions are:
*
*How do you deal with this configuration? What general strategies / rules of thumb can be applied?
*Can you point me to a good tutorial or well written sample code?
*How to visualize the dependencies (including the Adapters and Providers)?
A: For some sample code, some example work was done here: http://jersey.576304.n2.nabble.com/Injecting-JAXBContextProvider-Contextprovider-lt-JAXBContext-gt-with-Guice-td5183058.html
At the line that says "Wrong?", put in the recommended line.
I looks like this:
@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {
private JAXBContext context;
private Class[] types = { UserBasic.class, UserBasicInformation.class };
public JAXBContextResolver() throws Exception {
this.context =
new JSONJAXBContext(
JSONConfiguration.natural().build(), types);
}
public JAXBContext getContext(Class<?> objectType) {
/*
for (Class type : types) {
if (type == objectType) {
return context;
}
} // There should be some kind of exception for the wrong type.
*/
return context;
}
}
//My resource method:
@GET
@Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
public JAXBElement<UserBasic> get(@QueryParam("userName") String userName) {
ObjectFactory ob = new ObjectFactory();
UserDTO dto = getUserService().getByUsername(userName);
if(dto==null) throw new NotFoundException();
UserBasic ub = new UserBasic();
ub.setId(dto.getId());
ub.setEmailAddress(dto.getEmailAddress());
ub.setName(dto.getName());
ub.setPhoneNumber(dto.getPhoneNumber());
return ob.createUserBasic(ub);
}
//My Guice configuration module:
public class MyServletModule extends ServletModule {
public static Module[] getRequiredModules() {
return new Module[] {
new MyServletModule(),
new ServiceModule(),
new CaptchaModule()
};
}
@Override
protected void configureServlets() {
bind(UserHttpResource.class);
bind(JAXBContextResolver.class);
serve("/*").with(GuiceContainer.class);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Installation of AX 2012 I want to install Ax 2012 in my local machine. Does anyone know the steps involved in installing Ax2012
A: Highlights are you need 64 bit for the AOS, Help Server and EP (if you want it). I agree with the previous answer, 8GB memory is minimum. We tried on 4GB but it just won't work.
Our developers all have 2012 installed on their windows 7 (64 bit) machines. Remember you need SQL reporting installed to run ANY reports. You can run AX 2012 without SQL reporting just fine, but you won't have any reports at all (no invoice and packing slip etc).
Some of our guys have reporting and EP all running on their win7 machines. Remember that that is officially not supported though.
A: Follow the instructions in the Installation Guide.
For testing purposes you may use a preinstalled image. Requires PartnerSource or CustomerSource login.
Either option require lots of memory, 8 GB should be a bearable minimum.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Ruby on rails: Yielding specific views in a specific places in the layout If I have one <%= yield %> tag then all my views render in the same place in the layout. Can I have different <%= yield %> tags for different views? Is so how do I do this? Thanks
A: Look into ActionView::Helpers::CaptureHelper. You can do something like this in your views:
<% content_for :sidebar do %>
<!-- sidebar content specific to this page -->
<% end %>
This will run the template inside the content_for block, but will not output as part of the regular template yield buffer, it will be stored in a separate buffer for later. Then later on, including in the layout, you can use yield :content_name to output the content:
<div class="content">
<%= yield %>
</div>
<div class="sidebar">
<%= yield :sidebar %>
</div>
So in a sense you can have different yields for different views, you just have to give the differing content a name with content_for in the views, and yield it with that same name in the layout.
Consider your case, where you want different views in different places. Let's say you have three panels, panel1, panel2, and panel3. You can do this in your layout:
<div id="panel1"><%= yield :panel1 %></div>
<div id="panel2"><%= yield :panel2 %></div>
<div id="panel3"><%= yield :panel3 %></div>
You don't even need to include a plain <%= yield %> if you don't want to. Then in your views, you can choose which panel to display the content in by surrounding the entire view with the appropriate content_for. For example, one of your views might be changed like this:
<% content_for :panel2 do %>
<!-- Your View -->
<% end %>
To show in panel 2. Another one might be intended for panel 3, like this:
<% content_for :panel3 do %>
<!-- Your View -->
<% end %>
A: Yes, you can have multiple <%= yield %> tags. You can specify each yield tag with names like these in the base view.
<%= yield :head %>
<%= yield :footer %>
Then use the content_for tag in your individual views.
<% content_for :head do %>
<%= stylesheet_link_tag 'custom' %>
<% end %>
A: You can use yield and content for:
For example:
<%= yield :head %>
<% content_for :head do %>
<title>A simple page</title>
<% end %>
*
*Refer :layout and rendering guide.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: retrieving NSString from array in iPhone I have an array which contains description of a route on map. I got this array by parsing JSON. My arrays contains string in this format:
"<b>Sri Krishna Nagar Rd</b> \U306b\U5411\U304b\U3063\U3066<b>\U5317\U6771</b>\U306b\U9032\U3080",
"\U53f3\U6298\U3057\U3066\U305d\U306e\U307e\U307e <b>Sri Krishna Nagar Rd</b> \U3092\U9032\U3080",
"\U5927\U304d\U304f\U5de6\U65b9\U5411\U306b\U66f2\U304c\U308a\U305d\U306e\U307e\U307e <b>Bailey Rd/<wbr/>NH 30</b> \U3092\U9032\U3080<div class=\"\">\U305d\U306e\U307e\U307e NH 30 \U3092\U9032\U3080</div><div class=\"google_note\">\n<b landmarkid=\"0x39ed57bfe47253b7:0x779c8bf48892f269\" class=\"dir-landmark\">Petrol Bunk</b>\U3092\U901a\U904e\U3059\U308b<div class=\"dirseg-sub\">\Uff083.9 km \U5148\U3001\U53f3\U624b\Uff09</div>\n</div>",
Now I want to get name of places from this array like Sri Krishna Nagar Rd , NH 30 Petrol Bunk. First two should give Sri Krishna Nagar Rd and last on should give NH 30 Petrol
Bunk
How can I get result like this.Any help would be appreciated. Thanx In Advance.
Again, suppose I have string in this format..."\U5de6\U6298\U3059\U308b" which don't have ny place name.How will i handle this scenarios.
A: You can get like below:
NSString *strName=[yourArray objectAtIndex:index];
NSString *yourPlaceString=[[strName componentsSeparatedByString:@"<b>"] objectAtIndex:1];
yourPlaceString=[[yourPlaceString componentsSeparatedByString:@"</b>"] objectAtIndex:0];
you can get all places like this.
A: First of all, you should check if you don't have any other cleaner API available for the service you query this data. If the service returns such garbage in its JSON response, that shouldn't be your responsability to clean up that mess: the service should return some text that is more usable if it is a real clean API.
Next, if you really don't have any other choice and really need to clean this text, you have two options:
*
*If the text is XHTML (I mean real XHTML, conforming to the XML standard) you may use an NSXMLParser to filter out any tags and only keep the text from your string. This may be a bit too much for this anyway so I don't really recommand it.
*You can use regular expressions. If you are developping for iOS4.0+ you can use the NSRegularExpressionclass for this purpose. The tricky part is to get the right regex (can help you with that if needed)
*You can use the NSScanner class (which is available in iOS since 2.0 IIRC) to scan characters in you string and parse it. This is probably easier to understand and the way to go if you are not a regex expert, so I recommand this approach
For example if you choose the NSScannersolution, you can scan your string for characters in the alphanumeric character set, to scan letters and digits and accumulate it (you may also add ponctuation characters to your NSCharacterSetyou are using if needed). You will have the NSScanner to stop when it encounter characters such as the unicode characters \Uxxxx or like < and >. When you encounter < you can then ask the NSScanner to ignore the characters up to the next >, then start to scan the alphanumeric characters again and accumulating... and so on until the end of the string.
Finally, if you really find a pattern in the response string you are receiving, like if your place names is always between the first <b> and </b> pair (but you have to be sure of that), you can handle it other ways, like:
*
*splitting your string using the <b> text as the separator (e.g. componentsSeparatedByString)
*or asking the rangeOfString for the string <b> and then for string </b> and once you have their position, only extract substringWithRange from your original string to extract only the place name (using rangeOfString will be faster that componentsSeparatedByString because it will stop on the first occurrence found)
A: It looks like an encoding problem - can you change the encoding of the source or target to a different format. I had similar issues with German ö ä ü characters when UTF-8 was turned off....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: What is the right method of escaping string before using it as json object I have to create JSON string from database values and push it back to database again. My Python code is:
json = "{"
for row in cursor_mysql:
#mainkey = row[0]
#name = row[1]
#value = row[2]
mainkey = """" " \n \ / """ #for testing only
name = """ {} " \r \t """ #for testing only
value = """ ' " \ & """ #for testing only
json += """"%s":{"name":"%s","value":"%s"},""" % (re.escape(mainkey), re.escape(name), re.escape(value))
json = json[:-1]
json += "}"
#print json
query = """UPDATE table SET json = '%s' WHERE id = '%d' RETURNING id""" % (json, rowId)
cursor_postgres.execute(query)
conn_postgres.commit()
insertId = cursor_postgres.fetchone()[0]
This code works great when there are no malicious characters around. However, it doesn't work when sprinkled with non-alphanumeric values, as in the test cases above.
The bad JSON making it to my db is:
{
"""
\ / ": {
"name": " {} "","value":"'" "
},
"""
\ / ": {
"name": " {} "","value":"'" "
}
}
How to sanitize the string, so that when deserialized the json output is same as input?
A: import json
data = json.dumps(BIG_STRUCTURE_GOES_HERE)
query = """UPDATE table SET json = %s WHERE id = %s RETURNING id"""
cursor_postgres.execute(query, (data, rowId))
conn_postgres.commit()
A: http://docs.python.org/library/json.html
http://pypi.python.org/pypi/simplejson/
django.utils.simplejson
A: Simply use the json library:
import json
mainkey = """" " \n \ / """ #for testing only
name = """ {} " \r \t """ #for testing only
value = """ ' " \ & """ #for testing only
d = {mainkey: {"name": name, "value": value}}
jsonValue = json.dumps(d)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Attached properties Clearing local value but xaml not refreshing I derived the StackPanel class in a OrderableStack Class.
My aim is to allow a Stack's child to set an attached property Named 'First' to true and so this child becomes the first element in the stack.
When the attached property is set to true, the PropertyChangedCallback procedure defined in Metadata is called and it first removes the child element from the stack , then inserts it at position 0. Finally all the other children have their 'First' attached property set to False.
It works , but :
-if the attached property is already defined in xaml when i display it in VS 2010, VS 2010 is indicating that 'a reference is not set...'
-i can check that every other child, except the one defined as 'first' , has its OrderableStack.First set to false in the Properties Window, but the xaml is not updated. So many children can have the OrderableStack.First attached property set to true (in XAML), even if actually only the last child to be set has the True value.
Could you help me?
A:
if the attached property is already defined in xaml when i display it in VS 2010, VS 2010 is indicating that 'a reference is not set...'
Does this stop you from building and running your app? The way you can avoid this "designer" error is to put some nullability checks around your attached property's PropertyChangedCallback code.
i can check that every other child, except the one defined as 'first'
, has its OrderableStack.First set to false in the Properties Window,
but the xaml is not updated.
I didnt get that last bit. Do you expect your XAML designer to "simulate" the ordering in design mode? Then the best candidate designer is XAML Pad or Expression Blend. Visual Studio designers are sadly not the best out there. They also do not "simulate" animations / triggers.
I hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I access Microsoft Dynamics CRM from android device? I would like to know if Android OS is compatible with Dynamics CRM 4 Mobile Express.
When I open the CRM web page https://server/m, I receive a white screen. The same request works on an iPhone and Blackberry.
I already disabled the Popup-Blocker and enabled JavaScript.
A: IMHO there is no dedicated requirements overview for Dynamics CRM 4, but as the mobile interface has not really changed I would say that the requirements for Dynamics CRM 2011 are the same as for Dynamics CRM 4: http://technet.microsoft.com/en-us/library/hh367440.aspx
Mobile Express will only run on a mobile device that has a web browser that supports HTML 4.0 or a later version and JavaScript.
As it works on your other devices it could be some network related error.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting the number of rows with a GROUP BY query within a subquery I'm building a MySQL query with subqueries. The query requires, as described in Getting the number of rows with a GROUP BY query, the number of records returned by a group-by query, because I want the number of days with records in the database. So I'm using the following:
SELECT
COUNT(*)
FROM
(
SELECT
cvdbs2.dateDone
FROM
cvdbStatistics cvdbs2
WHERE
cvdbs2.mediatorId = 123
GROUP BY
DATE_FORMAT( cvdbs2.dateDone, "%Y-%d-%m" )
) AS activityTempTable
Now, I want this as a subquery, because I need some more data with different WHERE statements. So my query becomes:
SELECT
x,
y,
z,
(
SELECT
COUNT(*)
FROM
(
SELECT
cvdbs2.dateDone
FROM
cvdbStatistics cvdbs2
WHERE
cvdbs2.mediatorId = mediators.id
GROUP BY
DATE_FORMAT( cvdbs2.dateDone, "%Y-%d-%m" )
) AS activityTempTable
) AS activeDays
FROM
mediators
LEFT JOIN
cvdbStatistics
ON
mediators.id = cvdbStatistics.mediatorId
WHERE
mediators.recruiterId = 409
GROUP BY
mediators.email
(I left out some irrelevant WHERE-statements from my queries. 409 is just an example id, this is inserted by PHP).
Now, I'm getting the following error:
#1054 - Unknown column 'mediators.id' in 'where clause'
MySQL forgot about the mediators.id in the deepest subquery. How can I build a query, with the number of results of a GROUP-BY query, which requires a value from the main query, as one of the results? Why isn't the deepest query aware of 'mediators.id'?
A: Try the following:
SELECT
x,
y,
z,
(
SELECT
COUNT(distinct DATE_FORMAT( cvdbs2.dateDone, "%Y-%d-%m" ))
FROM
cvdbStatistics cvdbs2
WHERE
cvdbs2.mediatorId = mediators.id
) AS activeDays
FROM
mediators
LEFT JOIN
cvdbStatistics
ON
mediators.id = cvdbStatistics.mediatorId
WHERE
mediators.recruiterId = 409
GROUP BY
mediators.email
A: Did you try to put also the "mediators" table in the FROM of the deepest subquery ? Because they are two different queries and the tables of the first one are not called in the subquery. I'm not sure of what i say but i think the only relation between the query and the subquery is the result return by the subquery.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: dnn fck editor source code I need dotnetnuke fck editor's source code. Can you please give me directions for editing the fck editors source?
I need to add images to portal root folder externally.after uploading image it cannot select from the image manager. Image manager only show files uploaded from image manager.
A: FCKeditor provider is not a part of the DNN source package anymore, but you can find it at:
http://dnnfckeditor.codeplex.com
Image gallery checks that the portal has read permissions to the folder, and filters the files by extension, allowing only image files. But you should see all the image files, regardless if they show up in the DNN file manager.
But still, I would check if the files are visible in the DNN file manager, and if not, run "Synchronize Files" from the root level.
A: There's a source package for the editor provider at http://dnnfckeditor.codeplex.com/
A: working:
the dnn source editor image gallery is working from the database.ie.if you manually copy a file into the portal folder it does not visible in the fck editor gallery.the file listing is done from the databese.
so the solution is,you should make a uploader section for uploading images and give an entry in nuke's file table.then it will visible in gallery.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is wrong with this PHP code - Unexpected T_CONSTANT I keep getting the following error in my log
PHP Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';'
The error is related to this line but I'm not sure what's wrong with it
<?php
if ($num != null) {
$query_string = 'msisdn=' . $num . '&ref=' . get_post_meta($post->ID, "ref", $single = true) ;
echo '<div class="highlight"><a href="http://www.site.com/exJoin?signup=y&' . htmlentities($query_string) . '"><b>Join Now</b></a></div>';
}
else{
echo '<div class="highlight"><a href="<?php echo TeraWurflHelper::getPhoneHref('+2711111111'); ?>"><b>Join Now</b></a></div>';
}
?>
A: else{echo '<div class="highlight"><a href="<?php echo TeraWurflHelper::getPhoneHref('+2711111111'); ?>"><b>Join Now</b></a></div>';}
There lays the problem. You see the '+2711111111'. it uses " ' ". You'll have to escape that one, because it will end your string there.
Also, you do not need the opening tags for php in their... just remove them as you are already in a php-snippet.
A: Your adding PHP opening tags when you are already within a PHP tag. You should change to:
<?php
if ($num != null) {
$query_string = 'msisdn='.$num.'&ref='.get_post_meta($post->ID, "ref", $single = true);
echo '<div class="highlight"><a href="http://www.site.com/exJoin?signup=y&'.htmlentities($query_string).'"><b>Join Now</b></a></div>';
} else {
echo '<div class="highlight"><a href="' . TeraWurflHelper::getPhoneHref('+2711111111') . '"><b>Join Now</b></a></div>';
}
?>
A: Try this:
<?php
if ($num != null) {
$query_string = 'msisdn=' . $num . '&ref=' . get_post_meta($post->ID, "ref", $single = true);
echo '<div class="highlight"><a href="http://www.site.com/exJoin?signup=y&'.htmlentities($query_string).'"><b>Join Now</b></a></div>';
} else {
echo '<div class="highlight"><a href="'.TeraWurflHelper::getPhoneHref('+2711111111').'"><b>Join Now</b></a></div>';
}
?>
Your problem was that you had a <?php echo... ?> in the middle of a string that was already being echoed. This had a ' in it, which was the type of quote used to encapsulate the string that was already being echoed. You could escape it (like \') but this would have your resulted in <?php echo... ?> being echoed into your HTML, which I doubt is what you want, instead your should remove this and put the function call into the middle of your echo.
This should be easy spot if you are using an editor/IDE with syntax highlighting. If your are not, look at EditPad, Notepad++ (editors) or Eclipse (IDE). Or Google it...
A: You are trying to echo a string containing <?php ?> tags
echo '<div class="highlight"><a href="<?php echo TeraWurflHelper::getPhoneHref('+2711111111'); ?>"><b>Join Now</b></a></div>';
Should propably be
echo '<div class="highlight"><a href="'.TeraWurflHelper::getPhoneHref('+2711111111').'"><b>Join Now</b></a></div>';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to access database with Φ character in column
The sql server 2008 responded with the following error in some computer while other computer worked just fine.What is the cause of this error? There is difference in version though 6.01.7600 and 6.01.7601
Actual column name is Azi_Direction_A_Φ but it is taking a
Azi_Direction_A_o is there any relation with unicode or installing unicode support
A: I'd check to see what's different between the two machines:
*
*Different schemas (one with that column, the other without)
*ODBC driver versions.
A: Some options:
*
*The 2 machines are calling different SQL Server Instances with different schemas
*The same database changed between calls (is it reproducible?)
The ODBC driver is part of the OS since Windows XP so there should be no differences
Edit:
*
*Are regional settings the same on both PCs?
*Check the DSN setting for translations etc
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android OnApplicationPause/OnApplicationResume Is there any way to handle when my android application goes into background and back?
I want to use notification service for a on-line game - I use a service, which shows an alert when something happens in the game. I want alerts to show only if my application is active (on the foreground), so I need to start my service when application goes foreground and stop it when application goes background.
Note that I cannot use Activity.OnPause/OnResume methods. I have many activities in my application, and if I'll handle OnPause/OnResume, it is possible in a moment, when a user swtches one activity to another, application will look like background, thorough it will be foreground actually
A:
Note that I cannot use Activity.OnPause/OnResume methods. I have many
activities in my application, and if I'll handle OnPause/OnResume, it
is possible in a moment, when a user swtches one activity to another,
application will look like background, thorough it will be foreground
actually
Why don't you write a base class that extends Activity and enables or disables the service in these methods? After that extend all your activities from this base activity.
All you have to do is call the superclass method if you override these methods in your activties, e.g. by calling super.onResume() inside onResume(), to make sure these get still called. If you don't override them, everything works directly.
A: Not a clean way of doing this that I know of but,
You could perhaps send an Intent to your Service onCreate() and onPause() with a unique identifier.
You Service can then start a timer (with a delay which will be longer than the difference between onPause and onCreate being called in each activity) which, if not notified of an onCreate() within this time will set the Activity as "Paused".
If you add this functionality in a parent class which extends Activity you can then pull this same functionality into every class by extending that it rather than Activity (with the contract that you must call super.onCreate() and super.onPause() in each respective method).
A: Problem solved in a following way (C# code, mono for android)
class MyService : Service{
OnSomethingHappened(){
ActivityManager am = (ActivityManager) GetSystemService(ActivityService);
if(am.RunningAppProcesses.Any((arg) =>
arg.ProcessName == "myprocessname" &&
arg.Importance == ActivityManager.RunningAppProcessInfo.ImportanceForeground
)){
Trace("FOREGROUND!!!!");
}else{
Trace("BACKGROUND!!!!");
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Me.Close does not work I'm working with VB.net.
I’m having problems while I connect my application to my database today so I wanted to add an error handling to close the form.
The problem is that when I put Me.close in a form, this form still open. I used the Form.Closing event handler to verify that it was called, and then ran my application in step by step which showed that the event handler was called, but the application continues and the errors appears to the user.
Does anyone knows how to close a form properly without closing the application?
A: Close will close a form, but only if it has no more code to run.
That is, there are two conditions that need to be fulfilled for a form to close:
*
*Close must be called
*Any method still running must be left
I suspect that another method is still running code, for instance a loop or other code that causes the form to remain open.
Furthermore, the form will get re-opened automatically once you start accessing its members form elsewhere, due to an infuriating property of VB to auto-instantiate forms.
A: You can check for what reason the form don't get closed.
Private Sub Form1_Closing(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) _
Handles MyBase.FormClosing
MsgBox(e.CloseReason.ToString)
End Sub
You can add to the Form_Closing event the following
The e.Cancel will close the open operation. But first check the reason.
Private Sub Form1_Closing(ByVal sender As System.Object, _
ByVal e As System.Windows.Forms.FormClosingEventArgs) _
Handles MyBase.FormClosing
e.Cancel = True
End Sub
A: Technically the form is closed but not disposed, which means you can still reach the object but all controls in it are no longer reachable.
So you will have to call dispose from somewhere to get rid of it completely.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Bounding ellipse constrained to horizontal/vertical axes Context: I'm trying to clip a topographic map into the minimum-size ellipse around a number of wind turbines, to minimize the size of the map. The program doing this map clipping can clip in ellipses, but only ellipses with axes aligned along the x and y axes.
I know the algorithm for the bounding ellipse problem (finding the smallest-area ellipse that encloses a set of points).
But how do I constrain this algorithm (or make a different algorithm) such that the resulting ellipse is required to have its major axis oriented either horizontally or vertically, whichever gives the smallest ellipse -- and never at an angle?
Of course, this constraint makes the resulting ellipse larger than it "needs" to be to enclose all the points, but that's the constraint nonetheless.
A: The algorithm described here (referenced in the link you provided) is about solving the following optimization problem:
minimize log(det(A))
s.t. (P_i - c)'*A*(P_i - c)<= 1
One can extend this system of inequalities with the following constraint (V is the ellipse rotation matrix, for detailed info refer the link above):
V == [[1, 0], [0, 1]] // horizontal ellipse
or
V == [[0, -1], [1, 0]] // vertical ellipse
Solving the optimization problem with either of these constraints and calculating the square of the resulting ellipses will give you the required result.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Editable datagrid inside a combo box in WPF? Is it possible to show an editable datagrid inside a combo box? I have to show the columns of another datagrid in one column and the filter condition in the second column.
which is the best way to do this?
A: Yes you can template the combobox to display a datagrid in it.
If you are not using dotnet 4, you will find the DataGrid control in the WPF Toolkit
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to parse string into date time format? I have string having value "August-25-2011". How can I parse that into Datetime format?
A: Try:
DateTime dt = DateTime.ParseExact(
your_date,
"MMMM-dd-yyyy" ,
CultureInfo.InvariantCulture);
A: Try this out.
var date = DateTime.Parse("August-25-2011");
A: DateTime.ParseExact(
your_date,
"MMMM-dd-yyyy" ,
CultureInfo.InvariantCulture);
For TryParseExact
DateTime parsedDate;
string pattern = "MMMM-dd-yyyy" ;
DateTime.TryParseExact(dateValue, pattern, null,
DateTimeStyles.None, out parsedDate)
Converts the specified string representation of a date and time to its
DateTime equivalent using the specified array of formats,
culture-specific format information, and style. The format of the
string representation must match at least one of the specified formats
exactly. The method returns a value that indicates whether the
conversion succeeded.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Reactive Extensions... Examples in CRUD application I am just coming to grips with Reactive Extensions but still haven't had that "A-Ha" moment, the moment when it all seems to fit into place. As a result of this, I need some help and want to know what kind of a role reactive extensions might have in a simple CRUD program.
Does anyone have any examples how RX extensions has helped in their CRUD application. As you can imagine I am writing a CRUD application in C# ... any examples are accepted and this is posted so that I can think about how RX might fit into the type of programming that I am doing.
Perhaps you might list how a programming task has benefited from RX and how the task was being accomplished prior to the use of RX.
A: I have done this kind of thing that has worked well:
public interface IStorage : IDisposable
{
IObservable<int> GetOperationsCount(IScheduler scheduler);
IObservable<Node> FetchNodes(IObservable<NodeId> nodeIds, IScheduler scheduler);
IObservable<Node> StoreNodes(IObservable<Node> nodes, IScheduler scheduler);
}
It allows me to perform a fetches and stores on a background thread and have values returned to me on the UI thread quite easily.
Each call to StoreNodes also sets up a transaction and I can get any errors from the return observable.
I also use the GetOperationsCount observable to display to the user the number of pending operations, etc.
My personal experience with Rx has made me want to use it for anything asynchronous at all - events, begin/end invoke, async, tasks, thread, etc. It makes everything fit under one model and can be a significant code saver.
A: if you do static CRUD (get a window/dialog with create, read, update, write, whatever) then I guess it might only help you on your UI. For example, maybe you want some kind of AutoCompletion of certain inputs. Or you have to query a service for additional info to show.
Then RX can help you do this. It will hide many async-realated difficulties and gives you readable, declerative expressions you can easily read and quickly do.
In this sense it's just the same as LINQ only for UI/async
A: A typical CRUD application have some UI (winform, WPF etc) and a data store to fetch data and show in the UI. The data flow between these two components (UI and data store) can be modeled using Rx.
Using Rx we can connect the 2 components (UI and data store) such as:
UI can exposes 3 observable for Create, Update and Delete (ex: which are passed in the constructor to data store). For ex: The Submit button event can be mapped to generate Create observable values and similarly for Update and delete. So basically the data store needs to subscribe to these 3 observable and doesn't need to bother how the data is generated (this will also help in UT as you can create fake observable easily).
Read would be a simple read method on data store as that is about pulling data on demand.
So basically Rx has worked as a abstraction to compose the 2 components.
A: Maybe I am wrong, consider the two answers. MS tends to divide their bussiness into to many layers, because they have an interest here.
CRUD is the physical implementation - Create - Read - ...
But UI seems to be logical - in the context - for the user ...
Sometimes you need to have a layer - bussiness layer - that controls the flow to and from RDMS.
Imo this is very complex.
In finance business the "update" or "delete" action is a replication of the current row with a new timestamp.
This makes it difficult to have a clean operation - physical at least ...
And on top of all this yout might consider that CRUD is just a part of a transaction - making "a logical unit of work" in flight until all is ok - then you should do a COMMIT.
Hope this will help ...
A: A CRUD app will have some sort of search functionality. You could implement a textbox search with "type and wait to search" just like in my demo that I recently wrote on my blog :
http://blog.andrei.rinea.ro/2013/06/01/bing-it-on-reactive-extensions-story-code-and-slides/
Essentially using Throttle and other Reactive Extensions you can create a quick search feature.
A: Rx is great for collections. Right now, I can't imagine working with a language that doesn't have LINQ like functionality.
Recently, it became the same for Rx, mostly because of a library that uses Rx for LINQ: DynamicData
ReadOnlyObservableCollection<TradeProxy> list;
var myTradeCache = new SourceCache<Trade, long>(trade => trade.Id);
var myOperation = myTradeCache.Connect()
.Filter(trade=>trade.Status == TradeStatus.Live)
.Transform(trade => new TradeProxy(trade))
.Sort(SortExpressionComparer<TradeProxy>.Descending(t => t.Timestamp))
.ObserveOnDispatcher()
.Bind(out list)
.DisposeMany()
.Subscribe()
Basically, you can create LINQ like queries, that refresh themselves dynamically after any change - new item in the source list (just DTO is enough!), some property change, signal from elsewhere (passed as observable), etc.
You want to display number of entities with a flag? One liner.
You want to display easily display dynamic groups based on property chosen by user? One liner.
You want to do paging? 3 lines :P
Also, there is a MVVM framework called ReactiveUI - it provides you with a ReactiveCommand and few more tricks.
Among them is binding framework with converters based on lambdas, ability to react in a View to something very specific that happened in your VM, managing activation of view models (like initial command execution, but not in constructor).
You want the login button to be enabled only if user and password are not empty?
Login = ReactiveCommand.CreateFromTask(async () => { /* your async implementation, it can return a value! */},
this.WhenAnyValue(x => x.Username, x => x.Password, (user, psw) => !string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(psw)); // define when the command can execute by providing IObservable<bool>
Login.Where(x => x == true) // only successful logins, ==true for clarity
.InvokeCommand(DisplayMainScreen); // or something
In view you can do:
Login.Where(x => !x).Subscribe(_ =>{ // if login failed, set focus on password and select all text so user can just retype the password
PasswordBox.SelectAllText(); // can't remember exact methods, but you get the idea
PasswordBox.SetFocus();
});
It just becomes very natural for you to make functionality like "When something, do this"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Ckeditor: on dom change event Is it possible to hook into the process of creating elements in the dom of ckeditor? For example, every time the editor wants to append a p element into the dom, I would like to set some custom attributes on the element before it is appended.
A: Going throught the specs I stumbled upon the dataprocessor, which transforms the dom into html and allows to hook into the process of building the element's html.
<script type="text/javascript">
CKEDITOR.on('instanceReady', function(e) {
var editor = e.editor;
editor.dataProcessor.htmlFilter.addRules({
elements: {
p: function(e) {
e.attributes.style = 'padding: 20px;';
}
}
});
});
</script>
Mind that data processor in specific for each instance of ckeditor.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Using integer from one class in another Android I need some help with using integer from one activity to another.
I am making some basic math program(game). It gets two random numbers, random operator, and 30 secs to solve math problems as much as you can.
If you solve problem u get 1 point.
Anyway right now, I want to get number of points that user have made and use it in another activity called *RankActivity*.
Main activity is called *BrzoRacunanjeActivity* and it contains button and one *int* called *poenibrojanje* which get number of points that user have made, and when I click on button, it opens new Activity with this line:
startActivity(new Intent(this, RankActivity.class));
As you can see another Activity is called RankActivity, and there I wrote :
*BrzoRacunanjeActivity a1 = new BrzoRacunanjeActivity();*
*System.out.println("Number of points:" + a1.poenibrojanje);;*
and I get all time this reuslt: 09-22 09:09:14.940: INFO/System.out(289): Number of points:0
A: Try this:
Intent intent = new Intent(this, RankActivity.class);
intent.putExtra("points", pointsVar);
startActivity(intent);
In onCreate of RankActivity:
getIntent().getIntExtra("points", 0);
A: so you want to pass integer value from one activity to another activity? right...
try:
Intent intent = new Intent(currentclass.this, destination.class);
intent.putExtra("point", pointvalue);
startActivity(intent);
at destination activity:
final int getpoint = getIntent().getExtras().getInt("point");
This will solve your problem.
A: first of all make
static variable like as public static int poenibrojanje;
in your BrzoRacunanjeActivity.class file now you can use this variable in any other class like as
BrzoRacunanjeActivity.poenibrojanje
or you can use putExtras(); method.
in you main activity.
Intent i = new Intent(this, RankActivity.class);
i.putExtra("Value",poenibrojanje);
in your next activity
int v = (getIntent().getExtras().getInt("Value")) ;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: escaping characters in apache vhost - osx Simple apache question -
How do I escape the following folder name to allow apache to understand it?
NameVirtualHost *:80
<VirtualHost *:80>
ServerName calgary-ng-wrapper.lvh.me
DocumentRoot /Users/myname/workspaces/mysite/week-two-09232011 (branch)
<Directory "/Users/myname/workspaces/mysite/week-two-09232011 (branch)">
Order allow,deny
Allow from all
AllowOverride All
</Directory>
</VirtualHost>
I thought backslashes would work, but they seem not to.
EDIT to clarify question -
The problem is with this line -
DocumentRoot /Users/myname/workspaces/mysite/week-two-09232011 (branch)
I need apache to recognise the bracketes
A: You should also put the first occurance of the path within quotes:
DocumentRoot "/Users/myname/workspaces/mysite/week-two-09232011 (branch)"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to make multiple buttons visible in listview on one buttons click in android? i had made one layout, in this layout one button is in header and now i want that when user clicks on the header button in the listview, multiple button become visible. How can i do this? Pls reply
public View getView( final int position, View convertView, ViewGroup parent) {
String mText = mlist.get(position);
LayoutInflater vi = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.custom_will, null);
TextView txt = (TextView) convertView
.findViewById(R.id.txtcustomwill);
final Button deletbtn = (Button)convertView.findViewById(R.id.btndelete);
Button bt = (Button)convertView.findViewById(R.id.btnchange);
Log.v("palak", "bar " + position );
txt.setText(mText);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View v,
int position, long Id) {
if(position == 0){
dba = DBAdapter.getDBAdapterInstance(getApplicationContext());
try {
dba.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
if (save) {
sqldb = dba.openDataBase();
ContentValues cv = new ContentValues();
cv.put("todayDate", "UnNamed Entry");
cv.put("fname", "UnNamed Entry");
cv.put("sname", "UnNamed Entry");
cv.put("add1", "UnNamed Entry");
cv.put("add2", "UnNamed Entry");
cv.put("add3", "UnNamed Entry");
cv.put("pcode", "UnNamed Entry");
sqldb.insert("urdet", null,cv);
cv.clear();
Toast.makeText(getApplicationContext(), "inserted", Toast.LENGTH_SHORT).show();
}
dba.close();
Intent i = new Intent(Yourwill.this, Section.class);
startActivity(i);
finish();
}
else
{
Willdto.setposition(Integer.parseInt(aId.get(position)));
Intent i = new Intent(Yourwill.this, Section.class);
startActivity(i);
finish();
}
}
});
deletbtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SQLiteDatabase sqldb = dba.openDataBase();
String[] arr = { "" + aId.get(position) };
sqldb.delete("urdet", "Id = ?", arr);
Toast.makeText(getApplicationContext(), "Delete", Toast.LENGTH_SHORT).show();
Log.v("log_tag", "pos " + aId.get(position));
dba.close();
Intent i = new Intent(Yourwill.this,Yourwill.class);
startActivity(i);
finish();
}
});
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
deletbtn.setVisibility(View.VISIBLE);
}
});
return convertView;
}
}
A: The way to do this would be to
*
*Have those buttons created with attribute android:visibility="gone"
*Inside the onClick handler for top button change the visibility using setVisibility(View.VISIBLE)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Qt QIODevice::write / QTcpSocket::write and bytes written We are quite confused about the behavior of QIODevice::write in general and the QTcpSocket implementation specifically. There is a similar question already, but the answer is not really satisfactory. The main confusion stems from the there mentioned bytesWritten signal respectively the waitForBytesWritten method. Those two seem to indicate the bytes that were written from the buffer employed by the QIODevice to the actual underlying device (there must be such buffer, otherwise the method would not make much sense). The question then is though, if the number returned by QIODevice::write corresponds with this number, or if in that case it indicates the number of bytes that were stored in the internal buffer, not the bytes written to the underlying device. If the number returned would indicate the bytes written to the internal buffer, we would need to employ a pattern like the following to ensure all our data is written:
void writeAll(QIODevice& device, const QByteArray& data) {
int written = 0;
do {
written = device.write(data.constData() + written, data.size() - written);
} while(written < data.size());
}
However, this will insert duplicate data if the return value of QIODevice::write corresponds with the meaning of the bytesWritten signal. The documentation is very confusing about this, as in both methods the word device is used, even though it seems logical and the general understanding, that one actually indicates written to buffer, and not device.
So to summarize, the question is: Is the number returned bye QIODevice::write the number of bytes written to the underlying device, and hence its save to call QIODevice::write without checking the returned number of bytes, as everything is stored in the internal buffer. Or does it indicate how much bytes it could store internally and a pattern like the above writeAll has to be employed to safely write all data to the device?
(UPDATE: Looking at the source, the QTcpSocket::write implementation actually will never return less bytes than one wanted to write, so the writeAll above is not needed. However, that is specific to the socket and this Qt version, the documentation is still confusing...)
A: QTcpSocket is a buffered QAbstractSocket. An internal buffer is allocated inside QAbstractSocket, and data is copied in that buffer. The return value of write is the size of the data passed to write().
waitForBytesWritten waits until the data in the internal buffer of QAbstractSocket is written to the native socket.
A: That previous question answers your question, as does the QIODevice::write(const char * data, qint64 maxSize) documentation:
Writes at most maxSize bytes of data from data to the device. Returns the number of bytes that were actually written, or -1 if an error occurred.
This can (and will in real life) return less than what you requested, and it's up to you to call write again with the remainder.
As for waitForBytesWritten:
For buffered devices, this function waits until a payload of buffered written data has been written to the device...
It applies only to buffered devices. Not all devices are buffered. If they are, and you wrote less than what the buffer can hold, write can return successfully before the device has finished sending all the data.
Devices are not necessarily buffered.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512559",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Return entity key after savechanges doesn't work I have this piece of code
IMG_UPLOAD_FILES tObjUploadedFile = new IMG_UPLOAD_FILES();
tObjUploadedFile.UPLOAD_FILE_NAME = "testname.png";
tObjUploadedFile.SETTINGS_FOLDER_ID = 2;
dbHandler.IMG_UPLOAD_FILES.AddObject(tObjUploadedFile);
dbHandler.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
decimal tmpID= tObjUploadedFile.UPLOAD_FILE_ID;
the tmpID is still 0 and never return a key.
I have set StoreGeneratedPattern to Identity on the required field.
I'm using the latest ODB.NET from against the ORACLE database.
\T
A: The closest I can come to finding an answer is:
Because Oracle uses a Sequence + Trigger to make "Auto Ident" values, it seems like when the entity framework adds an object at saves it, the value return is still 0, because the trigger/sequence haven't updated it yet.
So the only way to come round this is to get the object again after you have save it.
\T
A: For me the fix was to manually (yes, manually!) go into the edmx, add the StoreGeneratedPattern="Identity" attribute in the SSDL part, AND the annonation:StoreGeneratedPattern="Identity" in the CSDL part.
It's not broken on the SQL side, however it is definitely broken on the Oracle side of things.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Changing the elements of an array member of a const object Can anyone explain to me why the following code works:
#include <iostream>
class Vec
{
int *_vec;
unsigned int _size;
public:
Vec (unsigned int size) : _vec (new int [size]), _size(size) {};
int & operator[] (const int & i)
{
return _vec[i];
}
int & operator[] (const int & i) const
{
return _vec[i];
}
};
int main ()
{
const Vec v (3);
v[1] = 15;
std::cout << v[1] << std::endl;
}
It compiles and runs just fine, even though we're changing the contents of a const object. How is that okay?
A: The constness is with regards to the members of the class. You cannot change the value of v._vec, but there's no problem changing the content of the memory that v._vec points to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512569",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: AutorotateToInterfaceOrientation of a UIviewcontroller Inside a UITabViewController Hi I have an iphone app in which 2 button .when I click on the one of the button there a UITabViewController with 4 tab is opened modally. I need to rotate both Portrait and lanscape the viewcontroller inside this UITabViewController. I Don't need to rotate all the view controller inside the Tabviewcontroller ,Only one viewController. Please help me .
Thanks in Advance.
A: any view controller you don't want rotating needs define it's own version of the shouldAutorotateToInterfaceOrientation method like this
- (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return NO;
}
To do that, you may have to subclass a specific view controller just to incorporate this one custom method
UPDATE:
It sounds like you have multiple view controllers active at once.
If you place some debug code in all of your shouldAutorotateToInterfaceOrientation methods on all of your viewcontroller based objects, my guess is only one will be receiving the notification of a rotation event.
In which case, since it is difficult to know which one will receive the rotation event notification, you will have to modify them all to disseminate the notice to each other in some way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512570",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Spring form object binding, works when submitted normally. But how to convert to json and use ajax I have a form when submitted to a controller works fine, the controller signature :
@RequestMapping(value = "/Save", method = RequestMethod.POST)
public ModelAndView save(@ModelAttribute MyDTO myDTO) {}
I have another controller method for handling an ajax request with this signature:
@RequestMapping(value = "/Preview", method = RequestMethod.POST)
public ModelAndView preview(@RequestBody MyDTO myDTO) {}
However submitting the serialized form returns this error : org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "myList[0]" (Class myPackage.dto.MyDTO), not marked as ignorable
The javascript/jquery is :
var json = jq("#dtoForm").serializeObject();
json = JSON.stringify(json);
jq.ajax({
cache:false,
type: 'POST',
url: "${Preview}",
data:json,
contentType: "application/json",
success: function(data) {
previewDialog.html(data);
previewDialog.dialog('open');
}
});
What am I missing ? I am confused becuase the form submits fine (the dto is correctly mapped) when not converted json. The dto contains, amongst other things, a list.
Edit if I remove the json = JSON.stringify(json); as suggested by springsource I get a slightly different error (one of the fields in dto is called "title"):
org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON: Unrecognized token 'til': was expecting 'null', 'true' or 'false'
A: In case anyone else has same problem, I got the code from here : http://code.google.com/p/form2js/
included the libs, and changed my code to this :
var json = jq("#dtoForm").toObject(); //the new lib I dl'd from link
json = JSON.stringify(json);
...
//and then to do the same ajax call
However, it is not completely solved as the spring-mvc form creates a hidden form element for each checkbox, which I then delete manually :
delete json._MyBoolean;
A side note, this all seems rather messy - shouldn't spring/jackson be able to convert pojo's to an html form and json in both directions with out all this extra stuff.
(original stack ref to library is here)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512572",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Linking the static version of a library instead of the dynamic one I am trying to use libjpeg in my application. Making the project yields a libjpeg.a in .libs folder. What I would like to do is to use this file in the linkage stage. I have tried the following: I copied the libjpeg.a into the folder where my C code resides. Trying to link with
gcc libjpeg.a mycode.c -o executable_name
fails. If I do gcc -ljpeg mycode.c, the compilation is successful when I change my header to point to instead of "libjpeg.h", but this obviously links to the system-wide dynamic version of the library.
Trying to link with relative or absolute path also fails:
gcc ./libjpeg.a mycode.c -o executable_name
I have tried the static option as well:
gcc -static libjpeg.a mycode.c -o executable_name
The linker error is the following:
Linking...
gcc -std=c99 -Wall -Wextra -g -pedantic ./libjpeg.a ./libjpeg.a -lm obj/read_jpeg.o obj/utils.o -o test_jpeg
obj/read_jpeg.o: In function `read_JPEG_file':
/home/ustun/Downloads/jpeg_test/read_jpeg.c:37: undefined reference to `jpeg_std_error'
/home/ustun/Downloads/jpeg_test/read_jpeg.c:45: undefined reference to `jpeg_CreateDecompress'
/home/ustun/Downloads/jpeg_test/read_jpeg.c:46: undefined reference to `jpeg_stdio_src'
/home/ustun/Downloads/jpeg_test/read_jpeg.c:47: undefined reference to `jpeg_read_header'
/home/ustun/Downloads/jpeg_test/read_jpeg.c:48: undefined reference to `jpeg_start_decompress'
/home/ustun/Downloads/jpeg_test/read_jpeg.c:62: undefined reference to `jpeg_read_scanlines'
/home/ustun/Downloads/jpeg_test/read_jpeg.c:74: undefined reference to `jpeg_finish_decompress'
/home/ustun/Downloads/jpeg_test/read_jpeg.c:75: undefined reference to `jpeg_destroy_decompress'
obj/read_jpeg.o: In function `read_JPEG_file_props':
/home/ustun/Downloads/jpeg_test/read_jpeg.c:93: undefined reference to `jpeg_std_error'
/home/ustun/Downloads/jpeg_test/read_jpeg.c:100: undefined reference to `jpeg_CreateDecompress'
/home/ustun/Downloads/jpeg_test/read_jpeg.c:101: undefined reference to `jpeg_stdio_src'
/home/ustun/Downloads/jpeg_test/read_jpeg.c:102: undefined reference to `jpeg_read_header'
/home/ustun/Downloads/jpeg_test/read_jpeg.c:103: undefined reference to `jpeg_start_decompress'
/home/ustun/Downloads/jpeg_test/read_jpeg.c:113: undefined reference to `jpeg_read_scanlines'
/home/ustun/Downloads/jpeg_test/read_jpeg.c:116: undefined reference to `jpeg_finish_decompress'
/home/ustun/Downloads/jpeg_test/read_jpeg.c:117: undefined reference to `jpeg_destroy_decompress'
collect2: ld returned 1 exit status
make: *** [test_jpeg] Error 1
You can download a simple project with a Makefile here.
A: You'd have to give the full path to libjpeg.a, If you have libjpeg.a in a .libs folder relative to where you compile:
gcc mycode.c -o executable_name .libs/libjpeg.a
If your special libjpeg.a is elsewhere, give a full path to it.
If this fails, you have to tell us what happens. (the details are important, so please copy paste the exact errors and the exact command line that is run).
A: You need to use -static:
gcc -static -o exec_name mycode.c -ljpeg
No need to copy the archive (.a). You could have found out by reading man ld.
A: This may help you if you have the same problem as mine. In my system, I have
libjpeg.so.62 -> libjpeg.so.62.0.0
libjpeg.so.62.0.0
After I added symbolic link:
sudo ln -s libjpeg.so.62 libjpeg.so
My problem got solved.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512575",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Globally available database connection without using Global/Singleton I'm creating a new PHP application and want to make sure I get the ground work right to save any future problems. I know my application will have more than one class that will need a database connection (PDO) and after a long time scouring the internet i can't find a definitive solution.
I like the singleton design pattern personally, but there are a lot of people out there that say singletons in general should be avoided at all costs. These people, however, don't give a specific solution to this problem.
I understand that an application may need more than one database connection but could i not create a singleton that contained each required DB connection (i.e. DB::getInst('conn1')->query(); )?
Is it a case of having to pass round the PDO (or PDO wrapper) object to every class that may need it? I've done this before found it annoying keeping track of it.
A: I personally thing a singleton (or a multiton, if you need several DB connections) is fine for such an usage.
But if you do not want to use it, you should then take a look at the Registry pattern.
This way, you can have your database class instance(s) available for all your application's classes, without having to pass an additional parameter each time (which is very ugly, IMHO).
A:
but could i not create a singleton that contained each required DB connection (i.e. DB::getInst('conn1')->query(); )?
you can, it's called multiton pattern
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512579",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to set different heights for each row in a ListView? I have problem setting the height of a single row in a ListView. I have already read hundreds of forums and blog posts, but nothing seems to work for me.
I have a ListView with an ArrayAdapter<Order>. Depending on an attributes of the Order object, different Layouts are used, with different heights for each row. However, in the end, all rows have the same height. I suppose it is the height of the layout given to the constructor of the ArrayAdapter. Does anybody know how to control the height of each row separately?
Thanks for your answers,
Filip
A: The trick is in the view in your layout item, you need to set the layout_height to wrap_content and that's it.
I made the screen shot of my listView with items with differents heights.
in case you are beginner, this will give you a starting point :
public static final String[] bzz = new String[] { "1", "2", "3", "4", "5" };
ArrayAdapter<String> addap = new ArrayAdapter<String>(this,
R.layout.list_item, R.id.text_view, bzz);
lv.setAdapter(addap);
A: I solve this problem by changing my code as follow
*
*Change the list_item layout to LinearLayout
*adding android:layout_height="wrap_content" in list_item layout properties
*adding android:inputType="textMultiLine" in text view in list_item
hope it works for you too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512592",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: How to send ">' string in a java code to server When i try to send a value "Login>Success" to server i get the value as Login%3ESuccess.
How can i send the greater than symbol in the java string.
A: Why don't you URLDecode the values on the server side?
A: This question probably needs more context to be properly answerable, but I believe that you are looking at URL encoding at some point. You can use the methods on the java.net.URLDecoder class to do the decoding.
A: Doc is here : http://download.oracle.com/javase/6/docs/api/java/net/URLDecoder.html
And a code sample :
/**
* @param yourText an urlencoded string.
* @return utf8 decoded string.
*/
public String decodeString(String yourText) {
return URLDecoder.decode( yourText, "UTF-8" ); // feel to change enconding
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: How can I implement Push method in a C# desktop application? I have my software(.NET) running on clients. I need to push the updates to the clients whenever available.
I thought to implement a web service which is running on the main server which broadcasts the update notifications to the client. For dat, CLient has to register their identity over the web to the server.
Server will send the notification on availability of the update. Client has to download the update from the server.
Will WCF would be the good option? .. Is that possible to implement? .. I know there are so many constraints in the networked environment. Suggestions are welcome...
A: You can make a table for application details including version and in application loading check the version of the application against last version number in database via a webservice if the versions are different fire error method to notify the client there is a new version of his application
but that I think valid from the start but you says the application is already running so I think you have to add this feature to the application and reinstall it on client machine.
check the following posts it may help you to find what you looking for
http://www.installsite.org/cgi-bin/frames.cgi?url=http://www.installsite.org/pages/en/tt_patch.htm
Is there a standard way for .NET Winforms apps to auto-upgrade?
http://www.devx.com/dotnet/Article/10045/1763
http://www.codeproject.com/KB/install/DDayUpdate_Part1.aspx
A: Maybe "long polling" is a solution. Consider this scenario: Your clients connect to a server using a timeout of lets say 60 minutes. If your server has an update it sends the data and closes the connection causing your client to reconnect and wait for the next update.
Wikipedia: Comet (Programming)
Since you provided details regarding infrastructure and communications I'll go with long polling again. Here is an example (first hit for "WCF long polling" on Google):
Simple Long Polling in WCF - Server
A: Write a windows service which runs on the clients and periodically checks the update server for new version of your software.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512607",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Google Analytics _trackEvent - always root of site I am trying to do some quite strange stuff with Google Analytics, I will try and explain as best as possible.
I have a holding site, that loads a form in via jQuery, the main site has its own tracking code, and the ajax loaded content using a different tracking code, this works fine.
_gat._createTracker('UA-XXXXXXXX-2', 'myTracker');
var _gaq = _gaq || [];
_gaq.push(['myTracker._setAccount', 'UA-XXXXXXXX-2']);
The form is broken up into multiple parts and I push a page track event with a custom page url through as each part is completed, again this seems to work fine.
_gaq.push(['myTracker._trackPageview', '/form/stage1/']);
But what I want to do is track events for changes in the form (dropdown changes, etc...), this is kinda working, the events as visible in the Google Analytics interface, but in the pages tab, they all appear under "/" not "/form/stage1/" as I would like (I think that the "/" is coming from the main site which it is sat in.
_gaq.push(['myTracker._trackEvent', 'Sample', ddValue]);
So what I am asking is there any way to tell _trackEvent to track against a different page url?
Thanks in advance.
A: There is not; _trackEvent uses location.pathname+location.search, regardless of what the most recent _trackPageview call passed as its custom value.
However, you're only use the "Category" and "Action" fields of the Event; you still have the "Label" to which you can pass that value in.
_gaq.push(['myTracker._trackEvent', 'Sample', ddValue, "/form/stage/1"]);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Howto successfully register certadm.dll in order to be able to use ICertView2 in C# Code Motivation:
*
*I want be able to retrieve and view Certificates from a Windows CA on a local Machine. I don't want to access the Browser-Keystores of the Machine, but the Windows CA (Windows Certifcate Authority (Service)).
*I want to to do this in C#-Code.
My Investigation so far:
I found several Examples that are using the following line:
ICertView2 certView = new CERTADMINLib.CCertView();
...
I think i'm able to use this line and the ICertView2 Structure, i reached my Goal.
If a write this Line into my C#-Code in Visual Studio, it says to me, that it don't know ICertView2 and CERTADMINLib.
So if searched the Web again and found out the i need to import a Reference. I need the COM Library certadmin.dll, that fortunately exists in my C:\Windows\System32 Folder.
So i tried to add the Reference over the Solutionexplorer->Project->References->Add Reference->COM. But it is not listed there, only a similar looking Library called "CertCli 1.0 Type Library". I added this and also was able to type an
using CERTCLIENTLib;
but unfortuneatly, the needed "ICertView2" Class is not in there.
If i type
using CERTADMINLib;
that should be typed in order to be able to use the ICertView2, Visual Studio says to me, that it also don't know "CERTADMINLib".
Further i found hints on the net, that one need to register the certadm.dll beforehand, in order to make it available in Visual Studio. I tried to register the dll-File, but it doesn't work.
If i invoke the following Command:
C:\Windows\System32>regsvr32.exe C:\Windows\System32\certadm.dll
and get a Dialogbox telling me the following:
'Error while loading the Module "C:\Windows\System32\certadm.dll". ... The specified Module could not be found.'
The Version of certadm.dll ist "5.2.3790.3959".
I'm using "Windows 7 Enterpise SP1".
Can you tell me, how i'm able to register and futher make the appropriate Reference available in Visual Studio?
If i've forgotten further Information, please let me know, so i can add them.
A: Microsoft changed much from XP to Win7. To be able to reference it you will have to tlbimp certadm.dll. Tlbimp.exe can be found in your .NET SDK's and such. Then you will have to import this library in your .NET solution.
Although i have to warn you, i have not mangaged to get any code working in Win7 that works in XP.
You can also look at this link:
http://blogs.msdn.com/b/alejacma/archive/2012/04/04/how-to-get-info-from-client-certificates-issued-by-a-ca-c-vs-2010.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Problem with GtkTextBuffer , Confusing Runtime Error. Need Help? I am using this code:
class editbook
{
GtkWidget* _nbook;
std::vector<GtkWidget*> _srcset; //and so on...
...........................................................................................
void editbook::add_page()
{
GtkWidget* tmp = gtk_source_view_new();
_srcset.push_back(tmp);
gtk_notebook_append_page(GTK_NOTEBOOK(_nbook),tmp,gtk_label_new("untitled"));
}
...........................................................................................
void editbook::set_text(const std::string& text)
{
int index = gtk_notebook_get_current_page(GTK_NOTEBOOK(_nbook));
GtkTextBuffer* tbuffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(_srcset[index]));
gtk_text_buffer_set_text(GTK_TEXT_BUFFER(tbuffer),text.c_str(),-1);
}
Compiles fine. But gives this weird runtime error:
Segementation Fault: return 139
I have traced down the problem to: gtk_text_view_get_buffer(GTK_TEXT_VIEW(_srcset[index]));
NOTE: I am using GtkSourceView instead of GtkTextView, but that may not be a problem because I am gettin the same error when I try GtkTextView.
NOTE: I am using Gtk 2x
NOTE: I am not sure whether to tag this question with C or C++. bec. Gtk+ is a C lib. But I am using C++. So I'll just tag both for now.
A: The problem in your code could be that the child widget added to GtkNotebook through gtk_notebook_append_page is not visible, try showing the child widget through gtk_widget_show call. Something on these lines :
void editbook::add_page()
{
GtkWidget* tmp = gtk_source_view_new();
_srcset.push_back(tmp);
gtk_widget_show(tmp); //Show the child widget to make it visible
gtk_notebook_append_page(GTK_NOTEBOOK(_nbook),tmp,gtk_label_new("untitled"));
}
When you use gtk_notebook_get_current_page if none of the child widget are visible then it returns -1, which I think might be happening in your case & as index is -1 when you use operator[] which doesn't check for bounds the program crashes. I strongly suggest you use vector::at instead of using operator[] so that you get std::out_of_range exception during run time to indicate the problem. You could use:
void editbook::set_text(const std::string& text)
{
int index = gtk_notebook_get_current_page(GTK_NOTEBOOK(_nbook));
GtkTextBuffer* tbuffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(_srcset.at(index)));
gtk_text_buffer_set_text(GTK_TEXT_BUFFER(tbuffer),text.c_str(),-1);
}
Hope this helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512619",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Programming Theory - Proving Invariants I have defined this pseudo-code for recognising strings using a relaxed-trie where the function Next[u,x] gives the set of nodes with u-edges from u ( basically the set of nodes such that (u,x,v) is an edge in T).
Here it is:
U := {1};
while s ≠ λ and U ≠ Ø do
U:= U in u Union Next [u, head(s)];
s:= tail(s)
od;
if U ≠ Ø then
if Final[u] for some u in U then
Accept
else reject
fi
else
reject
fi
Basically I have defined a postcondition for the loop, and given a loop invariant ( I think I have these elements covered, but if you think it will help to explain it go for it).
So I need to give a short argument stating why the invariant is invariant, (ie how it is preserved by the loop body, when the loop condition holds).
I then need to extend this pseudocode such that it can move to a new node without advancing the input :
(I think I would do this by adding another array (say Null) where Null[u] is the set of states it can move to from u without advancing the input)
It should also be changed such that each iteration before looking at the input all states can be reached from a state in U without advancing the input.
Thanks for all your help, am finding these two steps quite difficult, but think my psuedo-code for the first part is fine
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is there such thing as system images available in Android? I'd like to use basic images like the ones in the menu of the alarm application. Are these images integrated in the Android SDK ? I didn't find any way to access them.
If not, do you know a good free library ?
Thanks in advance,
Regards,
C.Hamel
A: http://www.darshancomputing.com/android/1.5-drawables.html is your answer
and than you access like this android:icon="@android:drawable/ic_menu_delete"
A: if you want to use image of android system then you can use that all image which are in android's system..
you just need to write android.R.drawable and you will get all image ...
android.R.drawable.btn_dialog
A: Look in your android-sdk folder, you will find folders for each version of android including all the system images. You can copy the images you need to your own ressource folder and use them from there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Update problem with listbox form fed from a query I am feeding a listbox in my form with a query result that depend on other controls of the same form. The problem is that my listbox doesn't update wheareas when I launch the query manually, the result is good.
A: As Remou suggests put Me.listBox.Requery in the AfterUpdate event of the control it is depending on:
Private Sub yourDataSourceUIElement_AfterUpdate()
yourListBox.Requery
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calling the items.add method twice causes the two items to overlap on the card Here is my add item code:
myapp.cards.vehicleInfo.items.add(
new Ext.List({ ...})
)
If after this I then do:
myapp.cards.vehicleInfo.items.add(
new Ext.Panel(
{html: 'test' }
)
);
The panel with 'test' appears on top of my list (overlapping), rather than vertically below it. I have tried doing a componenet dolayout inbetween adding the two items.
Any ideas? If I only do one or the other of the above it works as expected but if I do both together it leads to the above behaviour.
Thanks
A: You should dock the panel to the bottom.
myapp.cards.vehicleInfo.dockedItems.add( new Ext.Panel(
{html: 'test' }
)
);
Update
Ext.regModel('Contact', {
fields: ['firstName', 'lastName']
});
var store1 = new Ext.data.JsonStore({
model : 'Contact',
data: [
{firstName: 'Tommy', lastName: 'Maintz'},
{firstName: 'Rob', lastName: 'Dougan'},
{firstName: 'Ed', lastName: 'Spencer'},
{firstName: 'Jamie', lastName: 'Avins'},
{firstName: 'Aaron', lastName: 'Conran'},
{firstName: 'Dave', lastName: 'Kaneda'},
{firstName: 'Michael', lastName: 'Mullany'},
{firstName: 'Abraham', lastName: 'Elias'},
{firstName: 'Jay', lastName: 'Robinson'},
{firstName: 'Tommy', lastName: 'Maintz'},
{firstName: 'Rob', lastName: 'Dougan'},
{firstName: 'Ed', lastName: 'Spencer'},
{firstName: 'Jamie', lastName: 'Avins'},
{firstName: 'Aaron', lastName: 'Conran'},
{firstName: 'Dave', lastName: 'Kaneda'},
{firstName: 'Michael', lastName: 'Mullany'},
{firstName: 'Abraham', lastName: 'Elias'},
{firstName: 'Jay', lastName: 'Robinson'}
]
});
new Ext.Application({
launch: function() {
var panel = new Ext.Panel({
fullscreen: true,
id:'thePanel',
layout: 'vbox',
style: 'background-color:darkblue',
scroll:'vertical'
});
//do this in your dynamically called function
var list = new Ext.List({
id :'theList',
itemTpl : '{firstName} {lastName}',
store: store1,
width: '100%',
scroll:false
});
var smallPanel = new Ext.Panel({layout: 'auto',width:'100%',height:200,style:'background-color:darkgreen;color:white',html:"Hello I'm the panel"});
panel.items.add(list);
panel.items.add(smallPanel);
panel.doLayout();
}
});
A: You should check the layout option in the container to which you are adding Panels. I've had the same issue last week, and seting layout property to layout : {type : 'vbox', align : 'stretch' } provided me with a nice one column layout. I'm not sure if this is the issue, but try it anyway:)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: DBContext, state and original values I'm working with ASP.NET MVC3 using EF and Code First.
I'm writing a simple issue tracker for practice. In my Controller I have a fairly standard bit of code:
[HttpPost]
public ActionResult Edit(Issue issue) {
if (ModelState.IsValid) {
dbContext.Entry(issue).State = EntityState.Modified
.....
}
}
Question part 1
I'm trying to get my head around how the dbcontext works -
Before I've set the State on the dbContext.Entry(issue), I assume my issue object is detached. Once I set the state to be modified, the object is attached - but to what? the dbContext or the database? I'm kind of missing what this (attaching) actually means?
Question part 2
For argument's sake, let's say I decide to set the "Accepted" field on my issue. Accepted is a boolean. I start with it being false, I'm setting it to true in the form and submitting. At the point that my object is attached, what is the point of the OriginalValues collection? for example if I set a breakpoint just after setting EntityState.Modified but before I call SaveChanges() I can query
db.Entry(issue).OriginalValues["Accepted"]
and this will give me the same value as simply querying the issue object that has been passed in to the Edit....i.e. it is giving the same result as
issue.Accepted
I'm clearly missing something because the documentation says
"The original values are usually the entity's property values as they were when last queried from the database."
But this is not the case because the database is still reporting Accepted as being false (yeah, I noted the word "usually" in the docs but my code is all pretty much standard generated by MS code so....).
So, what am I missing? what is actually going on here?
A: The context can work only with attached entities. The attaching means that context know about the entity, it can persists its data and in some cases it can provide advanced features like change tracking or lazy loading.
By default all entities loaded from the database by the context instance are attached to that instance. In case of web applications and other disconnected scenarios you have a new context instance for every processed HTTP request (if you don't you are doing a big mistake). Also your entity created by model binder in HTTP POST is not loaded by that context - it is detached. If you want to persist that entity you must attach it and inform context about changes you did. Setting state to Entry to Modified will do both operations - it will attach entity to the context and set its global state to Modified which means that all scalar and complex properties will be updated when you call SaveChanges.
So by setting state to Modified you have attached the entity to the context but until you call SaveChanges it will not affect your database.
OriginalValues are mostly useful in fully attached scenarios where you load entity from the database and make changes to that attached entity. In such case OriginalValues show property values loaded from database and CurrentValues show actual values set by your application. In your scenario context doesn't know original values. It thinks that original values are those used when you attached the entity.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to make floating HTML work? I have a script (jsfiddle demo) that keeps the row title and column title of a large table visible while scrolling. The second row of the header has a < select > element in each cell. The problem is that when I scroll the table and the header "floats", the selects are not working anymore. They are not selectable. And the first row is not active too (cannot select the text, for copy-paste). Is there any solution to fix this? Thanks.
A: this doesn't affect all browsers and is caused by pointer-events: none; set in CSS for clone - just remove that declaration and everything works like a charm:
if (clone_table.length == 0) {
clone_table = $("#main_table")
.clone()
.attr('id', 'clone')
.css({
width: $("#main_table").width()+"px",
position: 'fixed',
//pointerEvents: 'none', // this is the problem
left: $("#main_table").offset().left+'px',
top: 0
})
.appendTo($("#table_container"))
.css({
visibility: 'hidden'
})
.find("thead").css({
visibility: 'visible'
});
}
looking at the documentation this is intended behaviour:
The element is never the target of mouse events [...]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Yii CMenu & CSS I am having problems having my CSS applied when a menu item links to a specific record.
Take the simple menu below, the CSS as defined in Menu works just fine for 'Account' but when I click on 'My Account' it doesn't.
<div id="Menu">
<?php $this->widget('zii.widgets.CMenu',array(
'items'=>array(
array('label'=>'Account', 'url'=>array('/account/view'),
// CSS works fine
array('label'=>'My Account', 'url'=>array('/account/view/id/'.Yii::app()->user->id),
// CSS applied to active link does not work
),
));
?>
</div>
CSS
#Menu ul li.active a {
color: #CCC;
text-decoration:none;
}
Any ideas???
Thanks
A: <div id="Menu">
<?php $this->widget('zii.widgets.CMenu',array(
'items'=>array(
array('label'=>'Account', 'url'=>array('/account/view'),
// CSS works fine
array(
'label'=>'My Account',
'url'=>array('/account/view/id/'.Yii::app()->user->id),
'active'=>($this->getId() == 'account' && $this->getAction()->getId() == 'view' && isset($_GET['id'])))
// you have to set manually the rule for "active"
),
));
?>
</div>
Also you should correct your Url rules so you can create URLs properly like this:
'url'=>array('account/view', 'id'=>Yii::app()->user->id)
To obtain the correct url from this you should create URL rule in config file like this:
'rules'=>array(
....
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
....
),
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery UI calculate sizing of content inside dialog to avoid scroll bars in the dialog I'm putting some content inside a JQuery UI dialog. The HTML is as follows:
<div id="dialog">
<div id="content">
<div id="scrollable">
<div id="data">
<ul>
<li/>
<li/>
....
</ul>
</div>
</div>
<div id="footer">
</div>
</div>
</div>
And the JQuery code is sth like:
$('#dialog').dialog({
width : 500,
height: 300
})
As you see, the sizing that is important to me is the sizing of the main container, the dialog. I want the content to feet inside the dialog without scrollbars in the dialog. The content has two pieces, the data itself that always has a vertical scroll bar and a footer that is always visible (this part has already been solved)
The solution should resize the content div. I have tried several calculations taking into account that the available height inside the dialog is:
var height=$('#dialog').height()-$('.ui-dialog-titlebar').height();
var dataHeight = height-$('#footer').height();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512649",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: codeigniter view in construct class Index extends MY_Controller {
public function __construct() {
parent::__construct();
}
}
class MY_Controller extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->view('index');
die();
}
}
Why in this way the view is not rendering in browser?
Can I use something like this as a solution? Or there is another better way?
class MY_Controller extends CI_Controller{
function __construct(){
parent::__construct();
$this->load->view('index');
$this->CI =& get_instance();
$this->CI->output->_display();
exit();
}
}
A: Because you are using die() after loading view, remove that line it will work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512656",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Clickonce update without overwriting config I want deploy many client (WPF) with Clickonce, i would not overwriting configuration file when i update client. It is possible ?
not include the file for update ? or make a differential update ?
In fact I do not want to crush the connectionString in the updated with ClickOnce.
A: Use Settings.settings file (go to project properties -> settings) instead of App.config.
For ClickOnce Settings.settings will be stored in "%InstallRoot%\Documents and Settings\username\Local Settings" and won't be overwritten with every new update.
More about that: http://msdn.microsoft.com/en-us/library/8eyb2ct1.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to improve quality of live streaming video in Flash? I created Flash application that is broadcasting/watching live streaming with Adobe Media Server, and it's quality is low even with microphone turned off...
I set quality and bandwidth to 0, meaning that application has to decide which one is better to use in each moment.
It's much better than manually setting, since if I put lower quality and bandwidth it might have bad results with users with better broadcast( better upload ).
How does Skype and MSN handle theirs video talks?
Since it's the same upload/download used there, but quality is much better and video is synchronized with audio, which is not the case in Flash...
In Flash I am getting image frizzing, audio skipping...
And if for example DJ is broadcasting watchers won't be able to see/hear anything...
Is there a way to improve this?
Here is the camera configuration set before broadcasting:
camera.setQuality(0, 0); //bandwidth and quality set to auto
camera.setMode(595,415,15, true); //width, height, frame-rate, camera closest resolution
I haven't changed anything else, just attached this to streamer...
Is there something that should be changed/added?
Thank you!
A: It depends on user connection, and camera quality, and it can't be changed.
For HD mode just change to:
camera.setMode(1280,720,30, true);
and back to normal set it with:
camera.setMode(595,415,15, true);
There is no need to reset netStream connection to change this, just run this code and camera will "restart" with this quality.
-Closed-
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Output of urllib.urlopen doesn't display when render to a template I'm using Python 2.7 - how can I convert the output of urllib.urlopen to a string?
data = urllib.urlopen('http://www.google.com').read()
test = "testone"
return render_to_response('home.html', locals())
home.html:
{{data}}
<br/>
{{test}}
Only 'testone' displays in the browser.
A: On my system it's already a string, so no conversion is required:
In [4]: type(urllib.urlopen('http://www.google.com').read())
Out[4]: <type 'str'>
A: >>> import urllib
>>> data = urllib.urlopen('http://www.google.com').read()
>>> type(data)
<type 'str'>
It's already a string.
A: when I change the url www.example.org.Its worked.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Showing java.lang.illegalargumentexception at LocationManager in android I have an application in which I am getting current location at the first page. In India Application is working fine and getting current location. When we run the application in US, application is getting crashed at the first page itself and throwing IllegalArgumentException.
A: The phone doesn't have any provider enabled to detect the location, i.e it is neither connected to GPS nor WI-FI, in which case the provider is being passed as null. This is assuming that you are providing provider argument to requestLocationUpdates() function by, finding the best provider, which will return null, if it can't find any.
I would first check if any provider is enabled, before proceeding any further in to this matter. To avoid passing null as a provider, check if the provider is null before calling for location update.
if (provider != null) {
requestLocationUpdates()
} else {
// alert user asking him to enable one of the providers.
}
This is how you do it.
HTH.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Backward compatiblity of iOS static library I am creating an iOS static library and trying to integrate the new iOS5 Twitter framework. So I have implemented the new Twitter framework and made the library, the static library will work on Xcode 4.2 (iOS5) without any problem.
The problem with me is that, the library wont work with the older iOS SDK since the Twitter Framework are not present. I get the following error when I try to use the library in XCode 4.02 :
Undefined symbols for architecture i386:
"_OBJC_CLASS_$_TWTweetComposeViewController", referenced from:
objc-class-ref in libTest.a(TestViewController.o) ld:
symbol(s) not found for architecture i386 collect2: ld returned 1 exit
status
Here libTest.a is the static library which I am trying to make.
So basically want I am trying to achieve is, compile a static library with Xcode 4.2 (iOS 5 SDK) and use it in Xcode < 4.2 (ie iOS SDK < 5) without causing error. ie, the static library should show the new Twitter APi in iOS-5 SDK and my own OAuth Twitter views in older iOS SDKs.
A: Check out the concept of "weak linking". That should solve your issues.
http://developer.apple.com/library/ios/#documentation/DeveloperTools/Conceptual/cross_development/Using/using.html#//apple_ref/doc/uid/20002000-SW6
A: You can't use frameworks that were introduced in future versions of iOS
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to add fix number of rows to gridview in c#? I have to insert fix number of rows to gridview. I am not using database and also not creating row one by one.
I initially want 7 rows with 3 column, with first column having text stored in my array.
I am creating gridview as,
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" Height="146px"
OnLoad="row_created" Width="308px">
<Columns>
<asp:BoundField HeaderText="Day" />
<asp:TemplateField HeaderText="Available rooms">
<ItemTemplate>
<asp:TextBox ID="txt1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price">
<ItemTemplate>
<asp:TextBox ID="txt2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
A: why not creating a class object then bind it to the grid, set default values for index to display it as Row Number, and all other members Day, price and Rooms filled back from user
something like:
class MyObject
{
public int Index { get; set; }
public string Day { get; set; }
public decimal Price { get; set; }
public string Rooms { get; set; }
}
use it like this
List<MyObject> lst = new List<MyObject>();
lst.Add(new MyObject { Index = 1});
lst.Add(new MyObject { Index = 2});
p.s.: Names and usage is just for explaining the idea
A: There are many ways to do that.
Some ways are either to create a DataTable and insert the data into it, and then bind it to the GridView.
A better solution would be to create objects with your data, store them in some sort of a collection(List or array will do), and then bind your collection to the DataGrid.
If you don't want to create a class for this, you can use anonymous types.
A: Here is a suggested solution:
*
*Define the data-source for the grid as a data-table
*And just change the structure of the data-table object and rebind to the grid, as applicable
*Example:-
==>
public partial class WebPage : System.Web.UI.Page
{
protected DataTable GridSource
{
get { return ViewState["GridSource"] as DataTable; }
set
{
ViewState["GridSource"] = value;
gridViewControl.DataSource = value;
gridViewControl.DataBind();
}
}
private void AddRow(DataRow row)
{
// Get the lastly binded structure and data
DataTable tableSource = this.GridSource;
// Add row to data-table "tableSource"
//..
// Apply the new structure and data
this.GridSource = tableSource;
}
// .. Add relevant implementation (methods) for remove, modify operations
//..
}
A: I once encountered the same problem .. This tutorial helped me solve my prob .. You can check it out ..
http://geekswithblogs.net/dotNETvinz/archive/2009/06/04/adding-dynamic-rows-in-gridview-with-textboxes.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512667",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calculate the date after 6 months from compare the date of database using java i want to send an auto mail after every 6 months from the registration date.
i am using CornJob for this auto mail.
now i am collecting date from database and want to get that date after 6 months.
(now.get(Calendar.MONTH) + 1) this will increment month to 5 month, but what if current month in 9(sep.).
how can i get that date after 6 months ?
thanks in advance
A: It's not really clear what you're doing, or where the database comes in... but you can use
calendar.add(Calendar.MONTH, 6);
to add 6 months to a Calendar value. Is that what you're after?
In general, I would recommend using Joda Time instead of Calendar / Date for date and time calculations, just because it's simpler - but without more information about how your code fits together, it's hard to know whether that's appropriate in this particular case.
A: not sure how are SQL-92 standards implemeted for all SQL Interpreters DATE_ADD(CURDATE(),INTERVAL 6 MONTH),
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Best way to deal with many image resources? I have a doubt regarding the best way to deal with many image resources.
These images are the flags of all the Countries in the world so they are circa 200.
Usually I store all the images in the res/drawable folder but in this case, they are too many.
What would you suggest??
( I have to use them in an ImageView in a ListView )
A: What's wrong in putting them in your drawable folder?
What you could do is two different versions, one for phones that have A2SD were you put them in your drawable folder and the other one downloads the flags to the users sd-card. At least let the user choose where to save them.
That way if the user wants the can be stored on the sdcard.
A: If you believe that the size of your images will push the size of your APK too high then perhaps create a thumbnail of each flag for most of your display purposes and use a WebView with a link to a larger version. This however will eat battery life & data & would only be available when the user is connected to the network.
Not recommended but if there is no other choice...
You could also download all of these flags on app initial start if it's the initial download of the apk you're worried about.
Otherwise keep your image sizes small and/or low quality to reduce the impact.
A: what 's your problem exactly ?as far as I know,android limits the apk file up to 50M.When you have a lot of resources, your app may exceed this limit.Is this your problem?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512673",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to get specified text pos through xpdf or mupdf? I want to extract some specified text in pdf files and the text position.
I know xpdf and mupdf can parse pdf files,so i think they may help me to fulfill this task.
But how to use these two lib to get text position?
A: If you don't mind using a Python binding for MuPDF, here is a Python solution using PyMuPDF (I am one of its developers):
import fitz # the PyMuPDF module
doc = fitz.open("input.pdf") # PDF input file
page = doc[n] # page number n (0-based)
wordlist = page.getTextWords() # gives you a list of all words on the
# page, together with their position info (a rectangle containing the word)
# or, if you only are interested in blocks of lines belonging together:
blocklist = page.getTextBlocks()
# If you need yet more details, use a JSON-based output, which also gives
# images and their positions, as well as font information for the text.
tdict = json.loads(page.getText("json"))
We are on GitHub if you are interested.
A: Mupdf comes with a couple of tools, one being pdfdraw.
If you use pdfdraw with the -tt option, it will generate an XML containing all characters and their exact positioning information. From there you should be able to find what you need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: which one is a better choice for android webservice developing,Rest or Soap?why? I am going to develop a app which uses webservice, i don not know clearly what are differents between soap and rest for android developing,which one is better?why
Thanks
A: Rest is to prefer. Soap is for large project and are not suitable for mobile applications.
But have you thought about JSON? I've made projects with JSON with great success.
Take a look at this:
http://geeknizer.com/rest-vs-soap-using-http-choosing-the-right-webservice-protocol/
A: The difference has nothing to do with Android: REST is simpler. If a client can make an HTTP request, they can deal with a REST service.
SOAP services require an XML envelope to contain the message. The client has to marshal data into the XML format, encode the request, and only then POST it to the service for processing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to keep a variable value across requests in web.py I want to update logfile as soon as a request comes. I have a class variable event_logging_enabled which is initialised to TRUE. and in the POST() function I check the value of event_logging_enabled.
Now at run time, I modify the value of this flag to FALSE for subsequent requests. But It remains TRUE.
During debugging, I found that when a request is received, a new object get created to handle each request, so, will pick initialized value i.e.TRUE.
This is not the case for other functions like getlogEnabled() of same class.
Can you please suggest any work around.
import web
import threading
class webServer(threading.Thread):
port = "1234"
event_logging_enabled = "True"
def getlogEnabled(self):
print "Stub getlogEnabled(): ",self.event_logging_enabled
def __init__(self):
threading.Thread.__init__(self)
""" Logging """
print "Init------------------------",self.event_logging_enabled
self.event_logging_filename = "ueLogs.log"
def run(self):
urls = (
'/','webServer',
)
app = web.application(urls,globals())
sys.argv.append(webServer.port)
app.run()
def POST(self):
print "in POST"
print "Stub POST(): Logging Enabled : ",self.event_logging_enabled
A: I'm not too familiar with web.py framework but in general with web applications, if you need to preserve the state across multiple requests you'll have to manage it with a session object. The session object can be separate for each web user or common for the whole application.
There is a session object in the web.py framework:
http://webpy.org/docs/0.3/api#web.session
It lets you decide whether to store the content of the session in a database or directly in a file. The code sample under "DiskStore" on that page shows you how to place a variable in the session.
(By the way in Python boolean literals are True and False, not "True").
A: What I've done in the past and it seems to work alright is if I need to have a variable that's persistent throughout all requests, I jam it onto the web object right before the app.run()
For example, if I want to have a variable called 'foo' that's shared throughout all requests and is persistent between requests, I will do this
web.app = web.application(urls, globals())
# Add my custom foo
web.foo = 'some value'
# Start the app
web.app.run()
Then if I need to modify or use the foo variable, in my code somewhere I'll just
import web
web.foo = 'some other value'
Anything you jam onto the web object in the startup script will be persistent until the app is restarted. A bit of a hack, but it works.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Process multi-level xml with collection in element I have an xml document that I would to parse using SSIS 2005 to an SQL table.
But I'm having some trouble with it because it is multi-level and contains collections(?) in each post.
I have found a solution to get multilevel XML to one row using Merge Join in SSIS, but I can't figure out a way to handle the multiple <adress> elements to get them to one row.
Hope someone can help me out with this.
Edit:
So I would like the output to contain the following data in one row.
Personnummer, fornamn, efternamn, kon, epost, avdelning, foretagsnr, anstnr,
arbetsledare, signatur, pkontering3, adress.hemadress.gatuadress,
adress.hemadress.adress2, adress.hemadress.co_adress, adress.hemadress.postnr,
adress.hemadress.postort, adress.hemadress.land, adress.mobiltelefon.telefonnr,
adress.hemtelefon.telefonnr
Hope you understand my adress.hemadress/mobiltelefon/hemtelefon notation. The <befattningar> element is not used atm, and if it will be used the same solution for <adresser> will probably work. :)
Here's an example of the xml structure, as you can see there are three <adress> elements in the <adresser> element, and I would like them all to be output to a single row. If it was possible to ignore some of the elements inside the <adress> element based on the text in the <adresstyp> element that would be great, but I guess I can manage without that functionality.
<PersonCollection>
<Person>
<Personnummer>190001010101</Personnummer>
<Fornamn>firstname</Fornamn>
<Efternamn>lastname</Efternamn>
<Kon>K</Kon>
<Epost>mail@mail.com</Epost>
<Avdelning>B</Avdelning>
<Foretagsnr>1</Foretagsnr>
<Anstnr>1</Anstnr>
<Arbetsledare>firstname lastname</Arbetsledare>
<Signatur>X</Signatur>
<PKontering3>XXXX</PKontering3>
<Befattningar>
<Befattning>
<Status>X</Status>
<Namn>Position</Namn>
</Befattning>
</Befattningar>
<Adresser>
<Adress>
<Adresstyp>Hemadress</Adresstyp>
<Telefonnr />
<Gatuadress>Streetadress 1</Gatuadress>
<Adress2 />
<Co_Adress />
<Postnr>111 22</Postnr>
<Postort>City</Postort>
<Land>Country</Land>
</Adress>
<Adress>
<Adresstyp>Mobiltelefon</Adresstyp>
<Telefonnr>010-010 01 01</Telefonnr>
<Gatuadress />
<Adress2 />
<Co_Adress />
<Postnr />
<Postort />
<Land />
</Adress>
<Adress>
<Adresstyp>Hemtelefon</Adresstyp>
<Telefonnr>01-01 01 01</Telefonnr>
<Gatuadress />
<Adress2 />
<Co_Adress />
<Postnr />
<Postort />
<Land />
</Adress>
</Adresser>
</Person>
</PersonCollection>
A: I solved this by using three SQL Server destinations in my SSIS and pointing the output of <person> to one table, <adress> to one table and then <adresser> (which just contained personid and adresserid) to one table for match with adress and person table.
Then I used a view in SQL Server to put together the information I wanted and used the personid and adresserid generated by SSIS (is it SSIS that generated the ids for my xml?).
But I'm still curious if it can be solved inside SSIS.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Should I need to make the iTunes Artwork image round cornered? Do I need to make my iTunes artwork have rounded corners when submitting an app to the App Store?
A: Apple will add round corners to your icons by itself.
A: You don't need to make an icon round-cornered for submission to Apple. They add the corners, and optionally the highlight. However if you want to display an icon similar to the way it is displayed by Apple, but on your own website, you will need to make matching round-cornered artwork for your own use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Deploying cakephp application onto server my config/database.php is as follows,
var $default = array(
'driver' => 'mysql',
'persistent' => false,
'host' => 'ftp.example.sg ',
'login' => 'xxx',
'password' => 'xxx',
'database' => 'testdatabase',
'prefix' => '',
);
How can I make it deploy onto the server? What should be the value for host?
A: It depends where the MySQL server is, if its on the same server just use localhost. Otherwise put in the mysql servers IP address or hostname.
A: You can just put "localhost", it should be fine, at least for me :D
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to make a class Non-Inheritable
Possible Duplicate:
Making a template parameter a friend?
C++ Faq 23.11 How can I set up my class so it won't be inherited from?
lists the following code:
class Fred;
class FredBase {
private:
friend class Fred;
FredBase() { }
};
class Fred : private virtual FredBase {
public:
...
};
I tried to make a generic template for the same.
#include <stdio.h>
template<typename MAKE_ME_NONINHERITABLE >
class NonInheritable{
private:
NonInheritable(){
}
friend MAKE_ME_NONINHERITABLE; //<--- error here
};
This give me an error:
xxx.cpp:11: error: a class-key must be used when declaring a friend
So I tried:
template<typename MAKE_ME_NONINHERITABLE >
class NonInheritable{
private:
NonInheritable(){
}
friend class MAKE_ME_NONINHERITABLE; //<--- error here
};
class A : virtual public NonInheritable<A>{
};
And I get this error:
xxx.cpp:11: error: using typedef-name `MAKE_ME_NONINHERITABLE' after `class'
Is there a way to make this work?
A: You can use final from c++11 or sealed from microsoft extensions for c++.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512690",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Bilateral filter algorithm I'm trying to implement a simple bilateral filter in javascript. This is what I've come up with so far:
// For each pixel
for (var y = kernelSize; y < height-kernelSize; y++) {
for (var x = kernelSize; x < width-kernelSize; x++) {
var pixel = (y*width + x)*4;
var sumWeight = 0;
outputData[pixel] = 0;
outputData[pixel+1] = 0;
outputData[pixel+2] = 0;
outputData[pixel+3] = inputData[pixel+3];
// For each neighbouring pixel
for(var i=-kernelSize; i<=kernelSize; i++) {
for(var j=-kernelSize; j<=kernelSize; j++) {
var kernel = ((y+i)*width+x+j)*4;
var dist = Math.sqrt(i*i+j*j);
var colourDist = Math.sqrt((inputData[kernel]-inputData[pixel])*(inputData[kernel]-inputData[pixel])+
(inputData[kernel+1]-inputData[pixel+1])*(inputData[kernel+1]-inputData[pixel+1])+
(inputData[kernel+2]-inputData[pixel+2])*(inputData[kernel+2]-inputData[pixel+2]));
var curWeight = 1/(Math.exp(dist*dist/72)*Math.exp(colourDist*colourDist*8));
sumWeight += curWeight;
outputData[pixel] += curWeight*inputData[pixel];
outputData[pixel+1] += curWeight*inputData[pixel+1];
outputData[pixel+2] += curWeight*inputData[pixel+2];
}
}
outputData[pixel] /= sumWeight;
outputData[pixel+1] /= sumWeight;
outputData[pixel+2] /= sumWeight;
}
}
inputData is from a html5 canvas object and is in the form of rgba.
My images are either coming up with no changes or with patches of black around edges depending on how i change this formula:
var curWeight = 1/(Math.exp(dist*dist/72)*Math.exp(colourDist*colourDist*8));
Unfortunately I'm still new to html/javascript and image vision algorithms and my search have come up with no answers. My guess is there is something wrong with the way curWeight is calculated. What am I doing wrong here? Should I have converted the input image to CIElab/hsv first?
A: I'm no Javasript expert: Are the RGB values 0..255? If so, Math.exp(colourDist*colourDist*8) will yield extremely large values - you'll probably want to scale colourDist to the range [0..1].
BTW: Why do you calculate the sqrt of dist and colourDist if you only need the squared distance afterwards?
A: First of all, your images turn out black/weird in the edges because you don't filter the edges. A short look at your code would show that you begin at (kernelSize,kernelSize) and finish at (width-kernelSize,height-kernelSize) - this means that you only filter a smaller rectangle inside the image where your have a margin of kernelSize on each side which is unfilterred. Without knowing your javscript/html5, I would assume that your outputData array is initialized with zero's (which means black) and then not touching them would leave them black. See my link the comment to your post for code that does handle the edges.
Other than that, follow @nikie's answer - your probably want to make sure the color distance is clamped to the range of [0,1] - youo can do this by adding the line colourDist = colourDist / (MAX_COMP * Math,sqrt(3)) (directly after the first line to calculate it). where MAX_COMP is the maximal value a color component in the image can have (usually 255)
A: I've found the error in the code. The problem was I was adding each pixel to itself instead of its surrounding neighbours. I'll leave the corrected code here in case anyone needs a bilateral filter algorithm.
outputData[pixel] += curWeight*inputData[kernel];
outputData[pixel+1] += curWeight*inputData[kernel+1];
outputData[pixel+2] += curWeight*inputData[kernel+2];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Embeded comment paging in mongodb if I got a collection for storing Articles with it's Comments embedded, when retriving data from db, I will get a Article object with a completely Comment list, support there are a lot of comments, so this could be a problem of loading efficience, how can I handler this by paging Comments? do I have to use a seperate collection for Comments? or what else? thanx in advance.
A: You looking for the $slice operator.
To retrieve comments by paging you need code like this:
db.articles.find({}, {comments:{$slice: [20, 10]}}) // skip 20, limit 10
This operation will return articles with only sliced comments. )
A: The biggest question is:
Are your users more interested in comments or in context viewed?
Highly:
Put comments in separate documents, and load them first!
Then send "secondary" content via AJAX.
Moderately:
Use Andrew's solution. (And do not forget that you can also omit fields in queries)
Hardly:
Put comments in separate documents, and load them last (via AJAX).
(Also using AJAX can give you nice feature of expanding loaded comments via simple scrolling down)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Cannot type in textarea after requesting with ajax I'm doing an ajax request and the output of this request is a textarea that is injected into a div. But for some reason I can't type in it in firefox. In google chrome I can't do ctrl-A.
I tried removing all of the css classes, but it still has weird behaviour.
Jquery:
$.get(settingsUrl, {}, function(response) {
$(".action-remove").hide();
container.addClass("editing-settings");
var settingsPage = $(response).find("#settings").hide();
container.html(settingsPage);
}
injected html:
<h2>Edit block settings</h2>
<form action="{{ path('snippet_settings_block', { 'sequenceNumber' : sequenceNumber }) }}" method="post">
<textarea class="regular-text" cols="60" rows="4" required="required" name="form[text]" id="form_text"></textarea>
<br />
<input type="hidden" name="ref" value="{{ref}}" />
{{ form_rest(form) }}
<div id="actions">
<input type="submit" class="update-button" value="Update" />
</div>
</form>
A: The textarea that was inserted into the page, was interfering with a script that said all textareas should be disabled.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Flask app that routes based on subdomain I want to have my top-level domain as a portal for various subdomains that correspond to different sections of my site. example.com should route to a welcome.html template. eggs.example.com should route to an "eggs" subsection or application of the site. How would I achieve this in Flask?
A: @app.route() takes a subdomain argument to specify what subdomain the route is matched on. Blueprint also takes a subdomain argument to set subdomain matching for all routes in a blueprint.
You must set app.config['SERVER_NAME'] to the base domain so Flask knows what to match against. You will also need to specify the port, unless your app is running on port 80 or 443 (i.e in production).
As of Flask 1.0 you must also set subdomain_matching=True when creating the app object.
from flask import Flask
app = Flask(__name__, subdomain_matching=True)
app.config['SERVER_NAME'] = "example.com:5000"
@app.route("/")
def index():
return "example.com"
@app.route("/", subdomain="eggs")
def egg_index():
return "eggs.example.com"
ham = Blueprint("ham", __name__, subdomain="ham")
@ham.route("/")
def index():
return "ham.example.com"
app.register_blueprint(ham)
When running locally, you'll need to edit your computer's hosts file (/etc/hosts on Unix) so that it will know how to route the subdomains, since the domains don't actually exist locally.
127.0.0.1 localhost example.com eggs.example.com ham.example.com
Remember to still specify the port in the browser, http://example.com:5000, http://eggs.example.com:5000, etc.
Similarly, when deploying to production, you'll need to configure DNS so that the subdomains route to the same host as the base name, and configure the web server to route all those names to the app.
Remember, all Flask routes are really instances of werkzeug.routing.Rule. Consulting Werkzeug's documentation for Rule will show you quite a few things that routes can do that Flask's documentation glosses over (since it is already well documented by Werkzeug).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512698",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: MVC 3 partial view validation problem I'm trying to validate a form in a Partal View using the DataAnnotations.
The problem is when I check if the form is valid in the javascript, it always returns true, even if the form doesn't meet the requirements.
This is the line who always returns true: var valid = $("#create-language-form").valid();
In my model I got this:
[Required(ErrorMessage="Please enter a name")]
public string Name { get; set; }
In my view I got this:
@using(Html.BeginForm(null, null, FormMethod.Post, new { id = "create-language-form" }))
{
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
}
In my javascript I got this:
$("#create-language-dialog").dialog({
modal: true,
open: function (event, ui) {
$('#create-language-dialog').load("/Languages/CreatePartial", { id: objectid });
},
buttons: {
"Save": function () {
var valid = $("#create-language-form").valid();
if (valid) {
//do stuff
}
}
}
});
What might be wrong? Anything I miss to make the MVC validation work in a partial view?
A: This will validate the form and return true or false.
var valid = $("#create-language-form").validate().form();
A: I had similar problem and I wrote my own function as below
function isFormValid() {
var valid = true;
$(".field-validation-error").each(function () {
if ($(this).attr("data-valmsg-for") == "Name") {
valid = false;
}
});
return valid;
}
This will check for elements corresponding to ValidationMessageFor which are in error. My page had multiple forms and I wanted this to only work for few fields on a form so I added the if condition on data-valmsg-for. If you have got a single form and want to check if any field is in error then you can have it as below
function isFormValid() {
var valid = true;
$(".field-validation-error").each(function () {
valid = false;
});
return valid;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ViewExpiredException, Page could not be restored I've tried to follow different posts on how to handle the ViewExpiredException in Mojarra 2.1.0 (with RichFaces 4) on GlassFish 3.1. But what I define in web.xml doesn't seams to have any effect. I use form base security and the user has to logon to access the content. I just want Glassfish (catalina) to redirect the user to a simple JSF page when the session times-out, with a link back to the login page.
I always get the the following error message;
javax.faces.application.ViewExpiredException: viewId:/app_user/activity/List.xhtml - View /app_user/activity/List.xhtml could not be restored.
at com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:202)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:113)
Who can I redirect the user when the user session has timed-out and trap the exception in the server log ?
Greetings, Chris.
layout.xhtml
<!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"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:rich="http://richfaces.org/rich">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<!-- Had no effect
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
-->
<h:outputStylesheet name="css/default.css"/>
<h:outputStylesheet name="css/cssLayout.css"/>
<title>
<h:outputText value="Partner Tapestry - " /> <ui:insert name="title">Browser Title</ui:insert>
</title>
</h:head>
<h:body>
<div id="top" >
<ui:insert name="top">Top Default</ui:insert>
</div>
<div id="messages">
<rich:messages id="messagePanel"/>
</div>
<div id="content">
<ui:insert name="content">Content Default</ui:insert>
</div>
</h:body>
</html>
web.xml
...
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
2
</session-timeout>
</session-config>
<error-page>
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>/faces/resources/sessionExpired.xhtml</location>
</error-page>
...
login.xhtml
<ui:composition template="/resources/masterLayout.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:a4j="http://richfaces.org/a4j">
<ui:define name="title">
<h:outputText value="Login"></h:outputText>
</ui:define>
<ui:define name="top">
<h:outputText value="Welcome" />
</ui:define>
<ui:define name="content">
<h:form>
<h:panelGrid columns="3">
<h:outputLabel for="username" value="Username" />
<h:inputText id="username" value="#{userController.userAuthentication}" />
<br />
<h:outputLabel for="password" value="Password" />
<h:inputSecret id="password" value="#{userController.passwordAuthentication}" />
<br />
<h:outputText value=" " />
<a4j:commandButton action="#{userController.login()}" value="Login"/>
</h:panelGrid>
</h:form>
</ui:define>
</ui:composition>
finally sessionExpire.xhtml
<ui:composition template="/resources/masterLayout.xhtml"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:a4j="http://richfaces.org/a4j">
<ui:define name="title">
<h:outputText value="Session Exired"></h:outputText>
</ui:define>
<ui:define name="top">
<h:outputText value="Session expired, please login again" />
</ui:define>
<ui:define name="content">
<h:form>
<a4j:commandLink action="/resources/login?faces-redirect=true" value="Login" />
</h:form>
</ui:define>
</ui:composition>
A: Your approach should work perfectly fine for synchronous POST requests. However, you're using asynchronous (ajax) POST requests. Exceptions on ajax requests needs to be handled by either the jsf.ajax.addOnError init function in JavaScript or a custom ExceptionHandler.
See also
*
*javax.faces.application.ViewExpiredException and error page not working
*JSF: Cannot catch ViewExpiredException
A: Solved the problem by following this link on implementing a ExceptionHandlerFactory. A nice solution where you can have an exception navigation rule, but maybe a bit long. Thanks for the help @BalusC.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Play framework: Sorting crud table fields How do i set the sort order to DESC as default? This sort doesn't really do anything but make postedAt the only sortable item:
<div id="crudListTable">
#{crud.table fields:['title', 'postedAt'], sort:['postedAt']}
#{crud.custom 'postedAt'}
${object.postedAt.format("dd-MM-yyyy")}
#{/crud.custom}
#{/crud.table}
</div>
A: You can do this on the Entity if you want:
@Entity
public class Course {
...
@ManyToMany
@OrderBy("lastname ASC")
public List<Student> students;
...
}
A: Could you try to set the order attribute to DESC?
#{crud.table fields:['title', 'postedAt'], sort:['postedAt'], order: 'DESC'}
...
#{/crud.table}
A: Here is my hack:
First thing you have to do is to implement Comparable on the class that you want to sort, and further create a compareTo method.
Next, enter the crud module in your project. In app/views/tags.crud you will find a file called relationField.html, which handles the fields for adding relations. This file is divided into two parts, one for creating select-boxes with multiple=true, and one for creating dropdown select boxes. If you want both of these sorted you will have to edit in both these cases.
Substitute %{ _field.choices.each() { } with %{ _field.choices.sort().each() { }% (basically adding groovy syntax for sorting a collection), and the input fields will be sorted.
Full example of Java-classes:
Referencing class:
@Entity
public class Book extends Model {
@Required
public String title;
@Required
@ManyToMany(cascade=CascadeType.PERSIST)
public List<Author> authors;
@Required
@ManyToOne
public Publisher publisher;
//omitted
}
Referenced class:
public class Author extends Model implements Comparable {
@Required
public String firstName;
@Required
public String lastName;
public int compareTo(final Author otherAuthor) {
if (this.lastName.equals(otherAuthor.lastName)) {
if (this.firstName.equals(otherAuthor.firstName)) {
return 0;
} else {
return this.firstName.compareTo(otherAuthor.firstName);
}
} else {
return this.lastName.compareTo(otherAuthor.lastName);
}
}
//omitted
}
This structure compared with the hack on relationField.html will make the possibilities in the select appear sorted.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: rjs type error in rails? I add a link_to_remote to load a modal dialog box from a partial. But when I run the application I get the following error..
RJS error:
TypeError: $("create_event_dialog").dialog is not a function
When I click ok then again I got another dialog box.
Element.update("create_event", "<form action=\"/countries\" class=\"new_country\" id=\"new_country\" method=\"post\" onsubmit=\"new Ajax.Request('/countries', {asynchronous:true, evalScripts:true, parameters:Form.serialize(this)}); return false;\"><div style=\"margin:0;padding:0;display:inline\"><input name=\"authenticity_token\" type=\"hidden\" value=\"qWXCu2zMmlMhJG+GRf35kMbAIfzYAtFBee142ThmmMw=\" /></div>\n <p>\n <label for=\"country_name\">Name</label><br />\n <input id=\"country_name\" name=\"country[name]\" size=\"30\" type=\"text\" />\n </p>\n <p>\n <input id=\"country_submit\" name=\"commit\" type=\"submit\" value=\"Create\" />\n </p>\n</form>\n");
$('create_event_dialog').dialog({
title: 'New Event',
modal: true,
width: 500,
close: function(event, ui) { $('create_event_dialog').dialog('destroy') }
});
Why do I got this kind of error? I have a div with the id of create_event_dialog. I am using Prototype and I could not find the way to solve this. Please help me.
A: Your code looks like you want to actually use the jQuery UI dialog feature. As far as I know Prototype (or Scriptaculous) has no built-in dialog support.
If want to have a jQuery UI dialog you have two options:
*
*Use jQuery and jQuery UI alongside Prototype.
*Replace Prototype and only use jQuery
Option 1:
To use jQuery alongside Prototype you have to include the jQuery Javascript libraries and enable the compatibility mode by calling jQuery.noConflict(). After that the $ function belongs to Prototype and for all jQuery features you have to use jQuery(...) instead. For example jQuery('create_event_dialog').dialog(... in your case.
You can find details on Using jQuery with Other Libraries.
Option 2:
You have to remove the Prototype libraries and instead include the jQuery libraries. You also need the jRails compatibility library to keep your prototype helpers. And you have to change your existing Prototype code to jQuery code.
For example your Element.update statement would look like this:
$("#create_event".html("<form action=...")
See Using jQuery with Ruby on Rails for more details.
Careful: Depending on your existing code option 2 can be a lot of work, but will result in cleaner Javascript code. Also it might be worth considering switching to Rails 3.1 with UJS and jQuery as the official Javascript library.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Searching for a specific JOB by the procedure it calls Is it possible to search a JOB by the code it executes?
I.E. I want to find the JOB that launches a certain stored procedure.
Is there a query to do it?
A: select
*
from
user_jobs
where
what like '%my_token%';
A: Try using the all_dependencies view.
select * from all_dependencies where referenced_name = 'YOUR_STORED_PROC';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512711",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Programatically setting the user and password for authentication. How to avoid the security question? I'm developing an application for a Hotel where the costumers capture some snapshots and then upload them to their facebook.
Using the graph API it makes you identify yourself on facebook using the security question or identifying your friends.
I want to be able to identify the clients on facebook without the need of pop ups, specifying the user and password that they have previously given me
Is that possible?
If not, if I use the same computer to connect a lot of different people onto facebook, I get asked all the security questions. Can this be avoided with a digital certificate or anything like that?
Edited to add back info that was in an answer
The user 'Authorise my app' already. It's part of the facebook login process.
This should be right way:
*
*The user captures a photo with the webcam.
*The user introduces the email and password IN MY OWN FORM
*I connect to facebook through my application, submitting the email & password and write some nice text in the user's wall.
This is what i'm doing now:
*
*The user captures a photo with the webcam.
*I connect to facebook using my desktop app. A facebook login window appears.
*Sometimes, facebook indicates that this computer is login too much accounts, and ask for an aditional security ( phrase or friend's name).
*The user grant access to my application.
*My application write some nice text in the user's wall.
I need that the user write its own email & password in my form, because there is no keyboard ( it's a touch screen system) And if i show the Windows Touch Screen Window, there is some 'dangerous' keys like 'window' that i do not wan
A: What you need to do instead is have the user "Authorise your app" this way your application will be given an AccessToken which can then be used to perform the activities you need.
Look into the OAuth protocol and the Graph API
Start here:
http://oauth.net/2/
http://developers.facebook.com/docs/reference/api/
http://developers.facebook.com/tools/explorer/?method=GET&path=616612017
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512719",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Powershell - filtering WMIObject processes by more than one name I am trying to get a list of running processes and filter by two process names - can any one tell me how to get this working?
I've so far got it working and filtering out one process name:
$rn = Get-WMIObject Win32_Process -computer servername `
-credential mydomain\administrator -filter "Name='program1.exe'" |
select -expand path
$lst = Get-Content “C:\path\path2\List.txt”
Compare-Object $lst $rn
What I want it to do is filter two process names but nothing I've tried works. Any ideas?
A: Here's how to get a complete set of Process objects which match a list of process names you're interested in.
$ProcessNames = @( 'explorer.exe', 'notepad.exe' )
Get-WmiObject Win32_Process -Computer 'localhost' |
Where-Object { $ProcessNames -contains $_.Name } |
Select-Object ProcessID, Name, Path |
Format-Table -AutoSize
This example finds all processes, then filters that list by sending them to a pipeline filter that checks to see if the process name is contained in the list of interesting process names. The main benefit of using the pipeline this way is that you can easily access other attributes (such as ProcessID) of the returned processes.
ProcessID Name Path
--------- ---- ----
5832 explorer.exe C:\Windows\Explorer.EXE
4332 notepad.exe C:\Windows\system32\NOTEPAD.EXE
2732 notepad.exe C:\Windows\system32\notepad.exe
A: Use WQL operators like OR, AND, LIKE etc:
Get-WMIObject Win32_Process -computer servername -credential mydomain\administrator -filter "Name='program1.exe' OR Name='program2.exe'"
A: Create an array of the processes you're after:
$processes = @('winword.exe', 'notepad.exe', 'excel.exe') | `
% {
$rn = Get-WMIObject Win32_Process -computer servername -credential mydomain\admin -filter "Name='$_'" | select -expand path
#$lst = Get-Content “C:\path\path2\List.txt”
#Compare-Object $lst $rn
write-host $rn
}
I've commented out your compare so you can see how we are looping through the array clearly.
A: if I understood well try this:
$rn = Get-WMIObject Win32_Process -computer servername -credential mydomain\administrator -filter "Name='program1.exe OR Name='program2.exe'"
Compare-Object $rn[0].path $rn[1].path # if there are only one instance for process with name program1.exe and program2.exe
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512734",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: EmguCV Shape Detection affected by Image Size I'm using the Emgu shape detection example application to detect rectangles on a given image. The dimensions of the resized image appear to impact the number of shapes detected even though the aspect ratio remains the same. Here's what I mean:
Using (400,400), actual img size == 342,400
Using (520,520), actual img size == 445,520
Why is this so? And how can the optimal value be determined?
Thanks
A: I replied to your post on EMGU but figured you haven't checked back but this is it. The shape detection works on the principle of thresh-holding unlikely matches, this prevents lots of false classifications. This is true for many image processing algorithms. Basically there are no perfect setting and a designer must select the most appropriate settings to produce the most desirable results. I.E. match the most objects without saying there's more than there actually is.
You will need to adjust each variable individually to see what kind of results you get. Start of with the edge detection.
Image<Gray, Byte> cannyEdges = gray.Canny(cannyThreshold, cannyThresholdLinking);
Have a look at your smaller image see what the difference is between the rectangles detected and the one that isn't. You could be missing and edge or a corner which is why it's not classified. If you are adjust cannyThreshold and observe the results, if good then keep it :) if bad :( go back to the original value. Once satisfied adjust cannyThresholdLinking and observe.
You will keep repeating this until you get a preferred image the advantage here is that you have 3 items to compare you will continue until the item that's not being recognised matches the other two.
If they are the similar, likely as it is a black and white image you'll need to go onto the Hough lines detection.
LineSegment2D[] lines = cannyEdges.HoughLinesBinary(
1, //Distance resolution in pixel-related units
Math.PI / 45.0, //Angle resolution measured in radians.
20, //threshold
30, //min Line width
10 //gap between lines
)[0]; //Get the lines from the first channel
Use the same method of adjusting one value at a time and observing the output you will hopefully find the settings you need. Never jump in with both feet and change all the values as you will never know if your improving the accuracy or not. Finally if all else fails look at the section that inspects the Hough results for a rectangle
if (angle < 80 || angle > 100)
{
isRectangle = false;
break;
}
Less variables to change as hough should do all the work for you. but still it could all work out here.
I'm sorry that there is no straight forward answer, but I hope you keep at it and solve the problem. Else you could always resize the image each time.
Cheers
Chris
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Simple window shadow/freeze between registration steps with spinner Basically, i have a 4 steps registration process.
4 .html with 4 forms each one. Since you click next step in step one until you reach the step two it takes abouts 5 to 10 secs (it depends on the server...)
I want to shadow the window (and prevent users clicks etc etc) and show a spinner (to represent load process) while the transition to step two occurs.
In the site i have already colobox.js and jquery.js, I supose that it must be a jquery pluging tha accomplish perfectly the need or similar.
Any suggestion o pluggin or code sinppet??
Thanks in advice!!
A: I like jquery-loadmask.
With it, you can start masking with:
$("#mydiv").mask("Loading...");
The loading text optional, if you leave it out, it will just mask without displaying a message. Unmasking is just as easy:
$("#mydiv").unmask();
Here are some other options that I'm not as familiar with:
*
*http://plugins.jquery.com/project/loading
*http://www.malsup.com/jquery/block/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: mysql cast as interval is it possible to cast as an interval in MySQL?
I want to evaluate a value from the query as an interval, like this:
select DATE_SUB(NOW(),CAST(user.expiry_interval AS interval))
where user.expiry_interval is 'INTERVAL 1 WEEK' or something like that
select DATE_SUB(NOW(),CAST('INTERVAL 1 week' AS INTERVAL))
A: INTERVAL is not a data type, but a keyword that converts a human-readable "duration" string into an integer. As such, "casting to INTERVAL" makes no sense.
If your "interval" input is variable, then this can work but you can't take the entire thing from a string any more than you can "cast" the string "SELECT * FROM tbl" into a query expression. You can use a variable for the numeric operand (see below) but I think that's it.
SELECT DATE_SUB(NOW(), INTERVAL `x` DAY) FROM `tbl`;
You'll have to resort to CASE if you want logic that's stronger than that. Or... store integer durations in the first place.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Newbie needs to multiple select of the same table I have a single table with people's info such as
*
*ID
*Family (last name)
*Name (first name)
*Status
*IDFather
*IDMother
I'd like to bring up the information containing childs' Name and Family, as well as their parent's ID, Name and Family, but only those records where parents are dead. So far I've done this, but it only selects children who are dead, not parents (status 5 is deceased).
select * from A1 where (IDFather IS NOT NULL and IDMother IS NOT NULL) and [Status] = '5'
Table sample below:
ID Family Name Status IDFather IDMother
001 Watson Jason 1 123 321
002 Smith Matt 5 333 111
003 Smith Mike 1 002 NULL
004 Derulo Sam 5 NULL NULL
005 Pitt Jenny 1 NULL 004
I tried this statement:
select * from Table1 where [Status] = '5'
I then wrote a select statement in C#
select ID,Name,Family from Table1 where IDFather = "value" or IDMother = "value"
At the end of the day I need the Name, Family of the child and Name and Family of their parents with parents ID.
A: select father.id,
father.family,
father.name
mother.id,
mother.family,
mother.name
child.id,
child.family,
child.name
from A1 father,
A1 mother,
A1 child
where child.IDFather = father.id
and child.IDMother = child.id
and (father.status = 5 OR mother.status = 5)
Replace the OR with AND if you want to retrieve records where both parents are dead
Oh, and if this is a homework assignment, you may want to rewrite my archaic join syntax with the more modern vernacular. I'm stuck in my ways...
A: Try this:
SELECT * from your_table
WHERE
IDFather IN
(SELECT ID from your_table WHERE Status = 5)
AND IDMother IN
(SELECT ID from your_table WHERE Status = 5)
If you want also dead people you could try:
SELECT * from your_table
WHERE
Status = 5
OR (
IDFather IN
(SELECT ID from your_table WHERE Status = 5)
AND IDMother IN
(SELECT ID from your_table WHERE Status = 5))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery ajax call errors with sendToValue is not defined, what is wrong with this jquery code ? I'm kind of new to jquery/ajax calls, I have this code below to pull from php page json values.
$(function(){
$('#search').keyup(function() {
sendValue($(this).val);
});
});
function sendValue(str)
{
$.post(
"back/search.php",
{ sendToValue: str },
function(data) {
if(!data.empty){
//Put the result in the suggest div
$("#suggest").html(data.returnedFromValue);
}
},"json"
);
}
and here is the search.php file
$values = $database->get_by_name($_POST['sendToValue']);
if( !$values ) {
echo json_encode(array("returnedFromValue" => "ERROR"));
}
else
{
foreach($values as $value) {
echo json_encode(array("returnedFromValue" => $value));
}
}
The problem that that the value doesn't appear in the suggest div, the only output there is "error", when I check the ajax request in firebug under post section it gives me the message that sendToValue is not defined any ideas? Thanks!
A: The first thing that leaps out at me (there may be other problems, but this is the one I noticed first) is that you're missing the parentheses after val in the call to sendValue:
sendValue($(this).val);
should be:
sendValue($(this).val());
Currently, you're passing the val method itself into the sendValue function, rather than the result of calling that method.
A: $(this).valprobably needs to be $(this).val()
When programming JavaScript Firebug and console.log()are your friends.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Changing ListBox ItemsPanelTemplate has gotten me into trouble? I have a CustomControl (say CC) that has been inherited from ContentControl and contains a ScrollViewer which includes a ContentPresenter. When I put a ListBox into the CC it works without any problem. But when I set the ItemsPanelTemplate of the ListBox it doesn't notify CC to scroll into the ListBox selected item.
What's the reason for it? -Thanks
UPDATE:
I'll encounter the problem described above only if I set HorizontalScrollBarVisibility or VerticalScrollBarVisibility to Hidden and customize the ItemsPanelTemplate of the ListBox simultaneously. (I need to hide scollbars.)
I wonder if hiding Scrollbars prevents ScrollViewer contents from notifying it to bring selected item into view, why this issue doesn't happen when I don't change items panel???
Generic.xaml:
<ResourceDictionary ...>
<Style TargetType="{x:Type local:CustomControl1}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:CustomControl1}">
<Border ...>
<ScrollViewer ...
CanContentScroll="True"
HorizontalScrollBarVisibility="Hidden" « PROBLEM
VerticalScrollBarVisibility="Hidden"> «
<ContentPresenter Content="{TemplateBinding Content}"/>
</ScrollViewer>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</ResourceDictionary>
MainWindow.xaml:
<Window x:Class="MyNamespace1.MainWindow"
...
xmlns:proj="clr-namespace:MyNamespace0;assembly=...">
<Grid>
<proj:CustomControl1 x:Name="CC">
<ListBox>
<ListBox.ItemsPanel> «
<ItemsPanelTemplate> «
<StackPanel Orientation="Horizontal"/> « PROBLEM
</ItemsPanelTemplate> «
</ListBox.ItemsPanel> «
<!--content goes here-->
</ListBox>
</proj:CustomControl1>
</Grid>
</Window>
A: Have you set the IsItemsHost property for the Panel in the ItemsPanelTemplate to True?
E.g. if the itemspaneltemplate should use a Canvas:
<ItemsPanelTemplate>
<Canvas IsItemsHost="True" />
</ItemsPanelTemplate>
Related
A: StackPanel treats its content has having infinite space..
You will have to limit its size explicitly, or change it to other panel, Grid for example.
Try this:
<ItemsPanelTemplate>
<Grid/>
</ItemsPanelTemplate>
Or:
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" Width="100" Height="100"/>
</ItemsPanelTemplate>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7512748",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.