text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Setting optional elements in mapping in Biztalk? I have a mapping with a input-schema and a outputschema. If I send a xml-file with two fields that are not provided with the schema the element fields are written out, but with empty values. I would like to that it didn't write the elements at all in the output file.
Is it possible?
A: Use a "Logical Existence" Functoid to only produce the element in the output when it is supplied in the input.
To do this;
a) Drag the logical existence functoid to the mapper surface.
b) Drag a value map functoid to the map surface
c) connect the element from the source schema to the logical existence functoid
d) connect the logical existence functoid to your value mapping functoid.
e) connect the element to your value mapping functoid
f) connect your value mapping functoid to the destination element to conditionally map to.
This says "when i have element X in the source, then map its value to element Y in the destination. otherwise don't perform the mapping".
Do the steps above in order to ensure that the functoid inputs are configured correctly.
HTH
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: pushviewcontroller not working because self.navigationController is null I have a big problem: on method didSelectRowAtIndexPath I always get null to self.navigationController. I have a UIViewController that contains a UIsegmentedControl and a subView. On this subView I add the controllers for each segment selected. For each segment a have a tableview. Here is the problem: when I select a row from this tableview I can't do push for next controller because self.navigationController is null.
Please help me..Here is my code : http://pastebin.com/qq0vf7mq
without the code :
navigationTelephone=[[UINavigationController alloc] init];
[self.view addSubview:self.navigationTelephone.view];
[self.navigationTelephone setNavigationBarHidden:YES];
[self.view addSubview:tableViewTelephone];
A: I think You have initialize the UINavigationController like below
[[UINavigationController alloc] initWithRootViewController:ViewControllerOBj]
A: Updated:
You initialize an instance variable navigationTelephone and display it, but you use self.navigationController to push!
Use [navigationTelephone push...] instead
A: Try this one:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
myAudiPhoneInputViewController *myViewController = [[myAudiPhoneViewController alloc] initWithNibName:@"NIB NAME HERE" bundile:nil];
self.myaudiPhoneInputViewController = myViewController;
[myViewController release];
[tableViewTelephone deselectRowAtIndexPath:indexPath animated:NO];
if(indexPath.row==0){
NSLog(@"Tel.personnel... %@",self.navigationTelephone);
[self.navigationController pushViewController:self.myaudiPhoneInputViewController animated:YES];
}
}
You haven't instantiate your myaudiPhoneViewController that is why it's not pushing the view.
A: Just check by changing,
self.navigationTelephone=[[UINavigationController alloc] init];
Naveen Shan
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to set Content-Length when object is passed as response I have JSON object in my ASP.Net app which I pass to response using code
context.Response.Write(jsonObject)
The problem is that I need to set the Content-Length header to indicate response size and I do not know how to count it. How do I get filesize of Object?
A: Given that the JSON object is a string, something like
Response.AddHeader("Content-Length", jsonObject.Length);
should work.
A: usually you do like this:
Response.AddHeader("Content-Length", yourLength);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What does this specific C++ code mean? I have this code:
Kuvio::Kuvio(Piste& paikka, string& nimi) : paikka(paikka), nimi(nimi) {}
Do not care about the words. I'd like to know is that a function definition, a function call or what? I'm not familiar with C++.
A: It's a definition of the constructor of class Kuvio using an initialization list.
It's almost equivalent to:
Kuvio::Kuvio(Piste& paikka, string& nimi)
{
paikka = paikka;
nimi = nimi;
}
, which is redundant. In general however, the difference is that the members are not initialized two times, as it would happen with my snippet of code, but only once in the initialization list.
A: Function definition, constructor of class Kuvio.
A: It's defining the constructor of class Kuvio. The part between : and {} is an initializer list - it takes paikka and nimi member variables and initializes them with the values of paikka and nimi parameters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: overload array operator with templates and pointers The following code compiles (without warnings) on both clang++-2.9 and g++-4.6. However, the g++ binary Seg Faults, while the clang++ binary runs as intended.
What is the proper way to access template class data members through pointers when overloading []?
Here's the code:
#include <iostream>
template <typename T>
class A {
private:
T val1;
T val2;
public:
T& getVal1() { return val1; }
void setVal1(T aVal) { val1 = aVal; }
T& getVal2() { return val2; }
void setVal2(T aVal) { val2 = aVal; }
};
template <typename T>
class B {
private:
A<T>* aPtr;
public:
A<T>* getAPtr() { return aPtr; }
T& operator[](const int& key) {
if(key == 0) { T& res = getAPtr()->getVal1();
return res; }
else { T& res = getAPtr()->getVal2();
return res; }
}
};
int main()
{
B<int> foo;
foo[0] = 1;
int x = foo[0];
std::cout << foo[0] << " " << x << std::endl; // 1 1
}
A: You are returning a reference to a local variable (res). The reference won't be valid after returning from operator[]. It could be overwritten by other stuff. What really happens is Undefined: that is why compilers are allowed to eat your children or grow a moustache: Undefined Behaviour
You probably want to return by value.
Edit
Since you have a setter, you don't need the reference: See the solution live at http://ideone.com/oxslQ
Note: there was another problem with aPtr not being initialized. I proposed a simple constructor for that. _You might want to initialize this from elsewhere OR you need
*
*assignment and copy constructors
*or use a shared_ptr for aPtr
.
#include <iostream>
template <typename T>
class A
{
private:
T val1;
T val2;
public:
T getVal1()
{
return val1;
}
void setVal1(T aVal)
{
val1 = aVal;
}
T getVal2()
{
return val2;
}
void setVal2(T aVal)
{
val2 = aVal;
}
};
template <typename T>
class B
{
private:
A<T>* aPtr;
B(const B&); // TODO , disallow for now
B& operator=(const B&); // TODO , disallow for now
public:
B() : aPtr(new A<T>()) {}
~B() { delete aPtr; }
A<T>* getAPtr()
{
return aPtr;
}
T operator[](const int& key)
{
if(key == 0)
{
T res = getAPtr()->getVal1();
return res;
}
else
{
T res = getAPtr()->getVal2();
return res;
}
}
};
int main()
{
B<int> foo;
foo.getAPtr()->setVal1(1);
int x = foo[0];
std::cout << foo[0] << " " << x << std::endl; // 1 1
}
A: If you want to return by ref, then your A::getValX() functions should also return by ref, and your res variable inside B::operator should also be T& instead of T:
#include <iostream>
template <typename T>
class A {
private:
T val1;
T val2;
public:
T& getVal1() { return val1; }
void setVal1(T aVal) { val1 = aVal; }
T& getVal2() { return val2; }
void setVal2(T aVal) { val2 = aVal; }
};
template <typename T>
class B {
private:
A<T>* aPtr;
public:
A<T>* getAPtr() { return aPtr; }
T& operator[](const int& key) {
if(key == 0) { T& res = getAPtr()->getVal1();
return res; }
else { T& res = getAPtr()->getVal2();
return res; }
}
};
int main()
{
B<int> foo;
foo[0] = 1;
int x = foo[0];
std::cout << foo[0] << " " << x << std::endl; // 1 1
}
(Note that it will still crash at runtime, since aPtr isn't initialized anywhere.)
Your original code returns a reference to the local variable res, not to A::val1 / A::val2 as you probably intended. If res is a non-reference variable, then it will be a simple copy of the val1 / val2 value, that is only valid for inside the scope (in this case the function) where it was declared. So you need a reference here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JAXP - debug XSD catalog look up I have a situation where we want to validate an XML document held as a byte stream in memory, against an XSD placed amongst others in a file system. We would like to avoid having the file name explicitly mentioned in the XML file but instead tell the XML parser to use a catalog of one or more XSD files for validation.
My attempt to create a DocumentBuilder provider (for Guice 3.0) looks like:
public class ValidatingDocumentBuilderProvider implements
Provider<DocumentBuilder> {
static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
Logger log = getLogger(ValidatingDocumentBuilderProvider.class);
DocumentBuilderFactory dbf;
public synchronized DocumentBuilder get() { // dbf not thread-safe
if (dbf == null) {
log.debug("Setting up DocumentBuilderFactory");
// http://download.oracle.com/javaee/1.4/tutorial/doc/JAXPDOM8.html
dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setValidating(true);
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
// parser should look for schema reference in xml file
// Find XSD's in current directory.
FilenameFilter fileNameFilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".xsd");
}
};
File[] schemaFiles = new File(".").listFiles(fileNameFilter);
dbf.setAttribute(JAXP_SCHEMA_SOURCE, schemaFiles);
log.debug("{} schema files found", schemaFiles.length);
for (File file : schemaFiles) {
log.debug("schema file: {}", file.getAbsolutePath());
}
}
try {
return dbf.newDocumentBuilder();
} catch (ParserConfigurationException e) {
throw new RuntimeException("get DocumentBuilder", e);
}
}
}
(and I have also tried with file names too). Eclipse accepts the XSD - when put in the catalog it can validate the XML dealt with here
It appears to the naked eye that the parser halts briefly when trying to validate. This might be a network lookup.
-Djaxp.debug=1 only adds these lines
JAXP: find factoryId =javax.xml.parsers.DocumentBuilderFactory
JAXP: loaded from fallback value: com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
JAXP: created new instance of class com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl using ClassLoader: null
How can I get the parser in JDK 6 to tell me what it is doing? If I cannot do that, how do I inspect the XML Catalog usage inside it to see why the XSDs provided are not selected?
What obvious thing have I overlooked?
A: You say
We would like to avoid having the file name explicitly mentioned in the XML file
How then would the parser be able to select the appropriate schema?
What you can try, is to create a Schema, using a SchemaFactory, based on all the available schema resources and attach that to the document builder factory. The parser will then automatically validate the document against this "super schema".
If your set of schemas has internal dependencies (i.e. import or include), make sure that those references are resolved correctly using relative URLs or a specialised resolver.
UPDATE:
After reading this, http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JAXPDOM8.html, a bit more carefully, I realize that you approach should have the same effect as my proposal, so something else is going n. I can only say that what I describe works very well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Constraint-based unit testing framework for Python Is there a constraint-based unit testing framework for CPython (much like my beloved NUnit) or will I have to roll my own?
EDIT:
This is what I mean by constraint-based:
http://www.nunit.org/index.php?p=constraintModel&r=2.6
i.e. instead of:
assert(z.Count > 5)
it's more like:
assert.that(z.Count, Is.GreaterThan(5))
A: I don't know if such a thing exists for Python unit testing tools, but it seems like something that can be solved quite easily if you have to roll your own, using Python's functional capabilities. For example, let's have a function called assertThat as follows:
def assertThat(val, constraint):
assert(constraint(val))
Constraint could be defined this way:
def equal(testVal):
def c(val):
return testVal == val
Then, you can just use it like this:
assertThat(myVal, equal(5))
which does what you expect it to do.
That's just the start of it; I suspect that with decorators, the operator module and an afternoon off, you could create a pretty comprehensive set of very useful constraint functions!
A: The built-in library unittest provides the functionality you seek. You will find the list of assert methods very useful for making specific assertions.
from unittest import TestCase
class SomeTest(TestCase):
def setUp(self):
self.value = 5
def testMyValue(self):
self.assertEqual(self.value, 5)
This is somewhat different to the constraints in NUnit but it is easy to adapt an can be quite powerful.
A: To answer my own question: there is none. And really, there's no point. It's useful in languages like C#/Java, but not in Python where you can do things like assert(i in [1, 2, 3]).
A: You might like to check out testtools, which appears to have the syntax you are after. It makes the tests more readable, and works in Python 2.6+
class TestSillySquareServer(TestCase):
def test_server_is_cool(self):
self.assertThat(self.server.temperature, Equals("cool"))
def test_square(self):
self.assertThat(self.server.silly_square_of(7), Equals(49))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632425",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to avoid error message window we're having an application on server instance and quite rarely, but we have out of memory exception (program is not leaking, just instance is quite small and it operates with quite big amounts of data).
That would be not a problem, as we monitor processes on that server instance and if some of the processes are not found in process list, alert email is sent.
Now the problem is with this:
That prevents process from disappearing from process list, so we don't get alert email about it's failure. Is it possible to disable this message, that if program fails on something we don't catch, it would close without user interaction?
A: don't know if you can deactivate this - but I think you should not.
Find the bug/problem in your application and handle the problem with a craceful shutdown or by preventing the problem in first case.
Everything else will be a real crude workaround and I don't think your client will be pleased to have such a behavior (after all won't there be data lost? If not this has allways the buggy / not finished touch)
A: Assuming Windows Forms, I typically do multiple steps to prevent this message box.
First, I connect several handlers in the Main function:
[STAThread]
private static void Main()
{
Application.ThreadException +=
application_ThreadException;
Application.SetUnhandledExceptionMode(
UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException +=
currentDomain_UnhandledException;
Application.Run(new MainForm());
}
Those handlers are being called when an otherwise unhandled exception occurs. I would define them something like:
private static void application_ThreadException(
object sender,
ThreadExceptionEventArgs e)
{
doHandleException(e.Exception);
}
private static void currentDomain_UnhandledException(
object sender,
UnhandledExceptionEventArgs e)
{
doHandleException(e.ExceptionObject as Exception);
}
The actual doHandleException function that is then called does the actual error handling. Usually this is logging the error and notifying the user, giving him the options to continue the application or quit it.
An example from a real-world application looks like:
private static void doHandleException(
Exception e)
{
try
{
Log.Instance.ErrorException(@"Exception.", e);
}
catch (Exception x)
{
Trace.WriteLine(string.Format(
@"Error during exception logging: '{0}'.", x.Message));
}
var form = Form.ActiveForm;
if (form == null)
{
MessageBox.Show(buildMessage(e),
"MyApp", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
MessageBox.Show(form, buildMessage(e),
"MyApp", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
With the helper function:
public static string buildMessage(Exception exception)
{
var result = new StringBuilder();
while (exception != null)
{
result.AppendLine(exception.Message);
result.AppendLine();
exception = exception.InnerException;
}
return result.ToString().Trim();
}
If you are using not Windows Forms but e.g. a Console application or WPF, some handlers are not present, while others are present instead.
The idea stays the same: Subscribe to event handlers that are being called if you have no try...catch around your code blocks.
Personally, I try to have as few of those try...catch blocks as possible (ideally none).
A: You could put a global try/catch block in your program and exit the program on any unexpected exception.
A: If using WPF you can try-catch the following two exceptions in your app.xaml.cs. There may be other/complementary exceptions to handle, but this are the two I am usually looking for:
AppDomain.CurrentDomain.UnhandledException - "This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application. If sufficient information about the state of the application is available, other actions may be undertaken — such as saving program data for later recovery. Caution is advised, because program data can become corrupted when exceptions are not handled."
Dispatcher.UnhandledException - "Occurs when a thread exception is thrown and uncaught during execution of a delegate by way of Invoke or BeginInvoke."
ie:
public partial class App : Application
{
public App()
{
this.Dispatcher.UnhandledException += DispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;
}
private void CurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
// log and close gracefully
}
private new void DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
e.Handled = true;
// log and close gracefully
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is this possible in C++? toString(ClassName* class) I'd like to use toString with class argument, but for some reason there is an error.
The code is:
Animal.h
#include "Treatment.h"
#include "jdate.h"
#include <vector>
class Animal{
protected:
int id;
double weight;
int yy;
int mm;
int dd;
double accDose;
char sex;
vector<Treatment*> treatArray;
public:
Animal();
Animal(int newid, double newweight, int yy, int mm, int dd, char newsex, vector<Treatment*> treatArray);
~Animal();
};
Treatment.h
#ifndef TRE_H
#define TRE_H
#include <string>
#include <sstream>
#include "jdate.h"
#include "Animal.h"
#include "Cattle.h"
#include "Sheep.h"
class Treatment{
private:
int id;
jdate dayTreated;
double dose;
public:
Treatment(int id,jdate dayTreated, double dose);
Treatment();
~Treatment();
string toString(Animal* a);
};
#endif
Treatment.cpp
#include "Treatment.h"
using namespace std;
Treatment::Treatment(int newid,jdate newdayTreated, double newdose){
id=newid;
dayTreated = newdayTreated;
dose = newdose;
}
Treatment::Treatment(){
id=0;
dose=0;
}
Treatment::~Treatment(){}
string Treatment::toString(Animal* a)
{
string aa;
return aa;
}
toString is in Treatment class. I'm not sure but I think it's because Animal has
vector treatArray;. Does it actually matter?
Sorry that I cannot put the error messages here, because once I declare toString, for some reason tons of errors occur, such as
Error 1 error C2065: 'Treatment' : undeclared identifier l:\2011-08\c++\assignment\drug management\drug management\animal.h 30 1 Drug Management
A:
// Animal.h
// #include "Treatment.h" remove this
class Treatmemt; // forward declaration
class Animal
{
...
};
In your version, Treatment.h and Animal.h include each other. You need to resolve this circular dependency using forward declaration. In .cpp files, include all necessary h-files.
A: You include Animal.h in Treatment.h before the class Treatment is defined, that's why you're getting the error.
Use forward declaration to solve this:
In Animal.h add line
class Treatment;
A: You've not used std namespace in both header files.
So, use std::string instead of string. Because string is defined in std namespace.
Simillarly use std::vector instead of vector.
A: There are a few problems with your code. First of all, Animal.h should have an include guard as Treatment.h has:
#ifndef ANIMAL_H
#define ANIMAL_H
// Your code here
#endif
I'd also suggest that you give a longer name to Treatment.h's guard, you'll reduce the risk of using the same name elsewhere.
Using guards will ensure that you don't have a circular inclusion. Still you do have a circular dependency because the Treatment class needs to know about the Animal class and vice versa. However, as in both cases you used pointers to the other class, the full definitions are not required and you can - should, actually - replace in both header files the inclusion of the other with a simple declaration. For instance in Animal.h remove
#include "Treatment.h"
and add
class Treatment;
Both Treatment.cpp and Animal.cpp must include both Treatment.h and Animal.h.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do you use "git --bare init" repository? I need to create a central Git repository but I'm a little confused...
I have created a bare repository (in my git server, machine 2) with:
$ mkdir test_repo
$ git --bare init
Now I need to push files from my local repository (machine 1) to the bare repository (machine 2). I have access to machine 2 by SSH. The thing is that I think I don't understand the concept of a bare repository...
What is the right way of storing my code in the bare repository? How can I push changes from my local repository to the bare repository?
Is the right way of having a central repository to have a bare repository?
I'm a little confused with this subject. Please give me a clue on this.
A: Based on Mark Longair & Roboprog answers :
if git version >= 1.8
git init --bare --shared=group .git
git config receive.denyCurrentBranch ignore
Or :
if git version < 1.8
mkdir .git
cd .git
git init --bare --shared=group
git config receive.denyCurrentBranch ignore
A: It is nice to verify that the code you pushed actually got committed.
You can get a log of changes on a bare repository by explicitly setting the path using the --relative option.
$ cd test_repo
$ git log --relative=/
This will show you the committed changes as if this was a regular git repo.
A: Firstly, just to check, you need to change into the directory you've created before running git init --bare. Also, it's conventional to give bare repositories the extension .git. So you can do
git init --bare test_repo.git
For Git versions < 1.8 you would do
mkdir test_repo.git
cd test_repo.git
git --bare init
To answer your later questions, bare repositories (by definition) don't have a working tree attached to them, so you can't easily add files to them as you would in a normal non-bare repository (e.g. with git add <file> and a subsequent git commit.)
You almost always update a bare repository by pushing to it (using git push) from another repository.
Note that in this case you'll need to first allow people to push to your repository. When inside test_repo.git, do
git config receive.denyCurrentBranch ignore
Community edit
git init --bare --shared=group
As commented by prasanthv, this is what you want if you are doing this at work, rather than for a private home project.
A: Answering your questions one by one:
Bare repository is the one that has no working tree. It means its whole contents is what you have in .git directory.
You can only commit to bare repository by pushing to it from your local clone. It has no working tree, so it has no files modified, no changes.
To have central repository the only way it is to have a bare repository.
A: I'm adding this answer because after arriving here (with the same question), none of the answers really describe all the required steps needed to go from nothing to a fully usable remote (bare) repo.
Note: this example uses local paths for the location of the bare repo, but other git protocols (like SSH indicated by the OP) should work just fine.
I've tried to add some notes along the way for those less familiar with git.
1. Initialise the bare repo...
> git init --bare /path/to/bare/repo.git
Initialised empty Git repository in /path/to/bare/repo.git/
This creates a folder (repo.git) and populates it with git files representing a git repo. As it stands, this repo is useless - it has no commits and more importantly, no branches. Although you can clone this repo, you cannot pull from it.
Next, we need to create a working folder. There are a couple of ways of doing this, depending upon whether you have existing files.
2a. Create a new working folder (no existing files) by cloning the empty repo
git clone /path/to/bare/repo.git /path/to/work
Cloning into '/path/to/work'...
warning: You appear to have cloned an empty repository.
done.
This command will only work if /path/to/work does not exist or is an empty folder.
Take note of the warning - at this stage, you still don't have anything useful. If you cd /path/to/work and run git status, you'll get something like:
On branch master
Initial commit
nothing to commit (create/copy files and use "git add" to track)
but this is a lie. You are not really on branch master (because git branch returns nothing) and so far, there are no commits.
Next, copy/move/create some files in the working folder, add them to git and create the first commit.
> cd /path/to/work
> echo 123 > afile.txt
> git add .
> git config --local user.name adelphus
> git config --local user.email [email protected]
> git commit -m "added afile"
[master (root-commit) 614ab02] added afile
1 file changed, 1 insertion(+)
create mode 100644 afile.txt
The git config commands are only needed if you haven't already told git who you are. Note that if you now run git branch, you'll now see the master branch listed. Now run git status:
On branch master
Your branch is based on 'origin/master', but the upstream is gone.
(use "git branch --unset-upstream" to fixup)
nothing to commit, working directory clean
This is also misleading - upstream has not "gone", it just hasn't been created yet and git branch --unset-upstream will not help. But that's OK, now that we have our first commit, we can push and master will be created on the bare repo.
> git push origin master
Counting objects: 3, done.
Writing objects: 100% (3/3), 207 bytes | 0 bytes/s, done.
Total 3 (delta 0), reused 0 (delta 0)
To /path/to/bare/repo.git
* [new branch] master -> master
At this point, we have a fully functional bare repo which can be cloned elsewhere on a master branch as well as a local working copy which can pull and push.
> git pull
Already up-to-date.
> git push origin master
Everything up-to-date
2b. Create a working folder from existing files
If you already have a folder with files in it (so you cannot clone into it), you can initialise a new git repo, add a first commit and then link it to the bare repo afterwards.
> cd /path/to/work_with_stuff
> git init
Initialised empty Git repository in /path/to/work_with_stuff
> git add .
# add git config stuff if needed
> git commit -m "added stuff"
[master (root-commit) 614ab02] added stuff
20 files changed, 1431 insertions(+)
create mode 100644 stuff.txt
...
At this point we have our first commit and a local master branch which we need to turn into a remote-tracked upstream branch.
> git remote add origin /path/to/bare/repo.git
> git push -u origin master
Counting objects: 31, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (31/31), done.
Writing objects: 100% (31/31), 43.23 KiB | 0 bytes/s, done.
Total 31 (delta 11), reused 0 (delta 0)
To /path/to/bare/repo.git
* [new branch] master -> master
Branch master set up to track remote branch master from origin.
Note the -u flag on git push to set the (new) tracked upstream branch.
Just as before, we now have a fully functional bare repo which can be cloned elsewhere on a master branch as well as a local working copy which can pull and push.
All this may seem obvious to some, but git confuses me at the best of times (it's error and status messages really need some rework) - hopefully, this will help others.
A: You could also ask git to create directory for you:
git init --bare test_repo.git
A: The general practice is to have the central repository to which you push as a bare repo.
If you have SVN background, you can relate an SVN repo to a Git bare repo. It doesn't have the files in the repo in the original form. Whereas your local repo will have the files that form your "code" in addition.
You need to add a remote to the bare repo from your local repo and push your "code" to it.
It will be something like:
git remote add central <url> # url will be ssh based for you
git push --all central
A: The --bare flag creates a repository that doesn’t have a working directory. The bare repository is the central repository and you can't edit(store) codes here for avoiding the merging error.
For example, when you add a file in your local repository (machine 1) and push it to the bare repository, you can't see the file in the bare repository for it is always 'empty'. However, you really push something to the repository and you can see it inexplicitly by cloning another repository in your server(machine 2).
Both the local repository in machine 1 and the 'copy' repository in machine 2 are non-bare.
relationship between bare and non-bare repositories
The blog will help you understand it. https://www.atlassian.com/git/tutorials/setting-up-a-repository
A: You can execute the following commands to initialize your local repository
mkdir newProject
cd newProject
touch .gitignore
git init
git add .
git commit -m "Initial Commit"
git remote add origin user@host:~/path_on_server/newProject.git
git push origin master
You should work on your project from your local repository and use the server as the central repository.
You can also follow this article which explains each and every aspect of creating and maintaining a Git repository.
Git for Beginners
A: This should be enough:
git remote add origin <url-of-bare-repo>
git push --all origin
See for more details "GIT: How do I update my bare repo?".
Notes:
*
*you can use a different name than 'origin' for the bare repo remote reference.
*this won't push your tags, you need a separate git push --tags origin for that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632454",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "368"
} |
Q: How to iterate through known tables and unknown columns to get the MAX date per SSN? I am to create a function to read a table containing some 65 tables and find all columns containing dates, which are stored mostly as int, sometimes as char or datetime. Column names are unknown but I assume ending in '%Date'.
I need to find the MAX ie latest date for each client based on his/her SSN. However, the SSN is also called different names, e.g. SSN, SSN_Nr, SSN_No, etc. My code below is hopelessly wrong:
CREATE FUNCTION dbo.LastActivityDate (@SSN varchar(10))
RETURNS datetime
AS
BEGIN
DECLARE @Result datetime
DECLARE @SSN varchar(10)
DECLARE @tableSSN varchar(10)
DECLARE @table varchar(100)
DECLARE @column_name nvarchar(100)
DECLARE @tableDate datetime
DECLARE @LastActivityDate datetime
SET @column_name='%DATE' --only ends in date, so as not to pick up 'update_office',etc
if @SSN IS NULL OR @SSN = '' OR @SSN = ' '
begin
BREAK
end
else
begin
WHILE select Table_Name,Field1 from dbo.MERGE_TABLES where [Enabled]='Y' AND Field1=@SSN
BEGIN
SET @table = Table_Name
SET @tableSSN = Field1
declare @column_name nvarchar(100)
set @table = 'e_client'
set @column_name='%DATE' --only ends in date, so as not to pick up 'update_office',etc
SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name=@table AND column_name LIKE @column_name ORDER BY ordinal_position
IF ISDATE(SELECT .... FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name=@table AND column_name LIKE @column_name)=1
begin
CONVERT(datetime,(SELECT .... FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name=@table AND column_name LIKE @column_name))
end
.
.
.
IF (Select MAX([@tableDate]) from @table where @tableSSN=@SSN) > @LastActivityDate --column like FinishDate, proposedFinishDate or startdate if finish is empty
begin
@LastActivityDate=@tableDate
end
END
end--@SSN
SET @Result=@LastActivityDate
RETURN @Result
END
GO
A: *
*You've got an undocumented database.
*You don't know the column names.
*You don't know which columns contain dates.
*The dates are stored using at least three different data types.
*You don't know which columns contain SSANs.
*Columns are inconsistently named.
Some problems cry out for automation. I don't think this is one of them.
I wouldn't trust a script to get it right in this database. I think you should look at each table, and determine by eye which columns contain dates and which columns contain SSANs. Even if it takes you 5 minutes a table, that's still less than a day's work.
If you have to do it a second time, then you can automate it, based on your new-found knowledge of the tables and columns.
If you worked here, you could use a text tool to find all the SSAN columns, because they'd all be based on a CREATE DOMAIN statement, like (PostgreSQL)
CREATE DOMAIN SSAN AS CHAR(9) CHECK (VALUE ~ '^\\d{9}$');
CREATE TABLE users (
user_id INTEGER PRIMARY KEY,
ssan SSAN NOT NULL UNIQUE, -- These *are* unique where I work. YMMV.
...
);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to post premium and free version of a game to game center? I build an app with two different version. One with add integrated into it and another with premium version(without add). How to post my app in to game center.
A: They have to appear separately on game center if they are two different apps. This is why you are encouraged to use in-app purchasing to add "premium" features.
Game Center is accessed via the bundle identifier, which must be unique to one application. See here:
CFBundleIdentifier (String - iOS, Mac OS X) uniquely identifies the
bundle. Each distinct application or bundle on the system must have a
unique bundle ID. The system uses this string to identify your
application in many ways. For example, the preferences system uses
this string to identify the application for which a given preference
applies; Launch Services uses the bundle identifier to locate an
application capable of opening a particular file, using the first
application it finds with the given identifier; in iOS, the bundle
identifier is used in validating the application’s signature.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: MS Word extensibility: VBA macro versus .Net VSTO? One of my customers asked us to develop a "VBA macro". However, in the 2010s, it seems weird to me to still use such outdated language, and I'm thinking about trying to convince the customer to use VSTO dev instead. However, as I'm new to both worlds, I need help to fill a pro/cons page to be able to argue this.
Of course, the answer can't come without the actual requirement, let me try to resume:
Target : Word 2003/2007 (but I'm suspecting 2010 as a not yet known requirement) edit 2010 requirement confirmed
An external publishing system requires .doc file as input. The .doc file must have some specific styles applied : "Custom Header 1", "Custom header 2", etc.
The user can build documents, using Word, using two possible ways:
*
*Start the new document using a .dot file deployed on the computer
*Transform any existing document to match the target template
Users can "apply" the styles "simply" (simple UI): context menu, styles menu, custom action pane, etc.
By now, I see the following pro/cons:
*
*VBA
*
*Pros:
*
*?
*quick and dirty development (quick part of the sentence)
*The customer has already some in production macro
*Cons:
*
*hard to find skilled developer
*quick and dirty development (dirty part of the sentence)
*VSTO
*
*Pros:
*
*benefits of the .Net language (compiled, typed, rigorous, class library, etc.)
*security model more flexible and powerful (trusting code signed with a trusted authority)
*bridge to WPF panes possible
*You work in Visual Studio and have access to its full set of features: refactoring, source control, etc.
*Cons:
*
*requires installation of the .Net framework (probably not an issue today) and VSTO runtime
*harder to deploy
*slightly more work at the start (but less in long term)
A: I am not familiar enough to .NET but here is my humble opinion about VBA:
VBA
*
*Pros :
*
*easy to deploy and to make it work with the Office apps
*quick and dirty development (quick part of the sentence) - agreed
*Cons :
*
*hard to find skilled developer
*hard to select a skilled developer and explain your customer he needs to invest in this skill
*quick and dirty development (dirty part of the sentence) - partial agreement. It will be dirty if:
*
*you give the project to a VBA beginner and don't frame him/her
*your project gets too big in terms of requirements
*requires to have the .Net framework installed (probably not an issue today) I don't think so (maybe a CONS of VSTO?)
I would say that if you only want to have some code or add-in to merge some syles, you could easily do it with VBA and it won't be dirty (unless you really want it to).
A: I'm answering myself to the question, as the project is finished.
I finally decided to write the application using a VBA macro. Here is the post-mortem conclusion of this choice :
Pros:
*
*The team that will maintains the application has no C# knowledge, only VBA (main reason of my choice).
*Poor security model : it's a pro because there is no other setup that putting the files in the right place.
*No runtime prerequisites
Cons:
*
*The deployment was supposed to be simple.
*
*I was counting of the possibility to play with Word options "User-template directory" and "Startup template directory". But it wasn't possible, because the app is not related to a specific entity in the customer organisation. I wasn't allowed to "take ownership" of this settings for this application.
*I ended in writing a custom NSIS script to deploy the application on the correct folders. With VSTO, a simple setup project (clickonce?) would have done the job.
*The language is so prehistoric ! Collections index starts to 1, array to 0, no OOP, poor out-of-the box language and library feature. That is not always a problem, but in my case, modeling the business rule was a bit painful (representing hierarchical data in a tree was not an easy job)
*Very limited integration with source control (code, as it's embeded in the .dot files, was not historisable. Only the full .dot was)
*Error management very limited with VBA
*Poor IDE
Remark:
As an experienced C# developer, the pros/cons may be partial a bit.
A: I am a heavy Excel VBA developer.
VBA pro:
One of the major hurdles for me switching over to VSTO from VBA - and believe me, I love C# coding - is that there's no debug-on-the-fly which my userbase has got used to. I often jump straight into a VBA problem on the user's PC as it is happening, but with VSTO, that's not possible. (Unless someone can correct me.)
If your users have no such expectations this might be something you can easily live without.
VBA con:
VBA is one of the those languages that are easy to play with and thus easy to make a mess with. It doesn't enforce "clean coding" principles which means while decent programmers can make great applications with them, VBA can become associated with hackjobs and sprawling, organic code due to its low bar of entry. VBA developers are often considered a lower class of developer for this reason, when really there is a failure to distinguish between those that use it wisely and those that don't.
I doubt anyone chooses VBA as their career language of choice, it just sort of happens to them. Aside from being hard to find skilled developers, too much VBA work might turn away potential hires as they don't want to be associated with the "quagmire of another unmanaged VBA sprawl". Some people take use of VBA as a statement about how "serious" you are about technology.
(I tend to see Perl in the same light; great for short scripts but when someone used to using for scripting starts to use for a larger piece of work - you tend to get something that's a bit unwieldy.)
A: In this article I tried to summarize similar questions, in the context of Excel. Same arguments apply for all of the Office applications including word.
A: According to my observations :
VSTO :
CONS : that if we have developed Addins ribbons control for word 2007, we can only deploy with word 2007, but we can not deploy with word 2010 or word 2013.
This is major drawback for me to develop Addins for word and excel for all its versions like 2007, 2010 and 2013. plz correct me if am wrong or suggest me how could I develop Single Addins for all office version.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: How to assign height to data table element using jquery when we resize window I am using jquery data table for displaying data. On body onload its sets height using following code
<table id="RequestsTable" cellpadding="0" cellspacing="0" border="0" class="display" style="width:100%;">
In script i have write down following code.
ScrollY calculates height base on window height and assign to data table on form load.
<script type="text/javascript">
var scrollY = $(window).height()*58/100;
var oTable = $('#RequestsTable').dataTable({
"sScrollY": scrollY,
"bPaginate": true,
"bScrollCollapse": true,
} );
I want to calculate height again when window resize and assign to data table.
I have tried following code but not worked for me.
var scrollY = $(window).height()*58/100;
$(window).resize(function () {
scrollY = $(window).height()*58/100;
});
var oTable = $('#RequestsTable').dataTable({
"sScrollY": scrollY,
"bPaginate": true,
"bScrollCollapse": true,
} );
anybody have any idea ow can implement this.
Thanks in advance.
I tried this but no luck
function calcDataTableHeight () {
return $(window).height()*58/100;
};
$(window).resize(function () {
var oSettings = oTable.fnSettings();
oSettings.sScrollY = calcDataTableHeight();
oTable.fnDraw();
});
var oTable = $('#reqAllRequestsTable').dataTable({
"sScrollY": calcDataTableHeight()});
Any other way is possible to set height using css ??
A: It isn't sufficient to update the variable, you need to pass the new height to the datatable plugin (as it doesn't update automatically when the variable's content changes):
var $window = $(window);
var calcDataTableHeight = function() {
return Math.round($window.height() * 0.58);
};
var oTable = $('#RequestsTable').dataTable({
"sScrollY": calcDataTableHeight(),
"bPaginate": true,
"bScrollCollapse": true,
});
$window.resize(function() {
var oSettings = oTable.fnSettings();
oSettings.oScroll.sY = calcDataTableHeight(); // <- updated!
// maybe you need to redraw the table (not sure about this)
oTable.fnDraw(false);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Use of g key in vim normal mode In vim's normal mode, the g prefix is used for a number of commands. Some commands go somewhere in the document, but other commands deal with file encodings and swapping upper/lower case letters.
*
*ga - show character encoding
*10gg - go to line 10
*gg - go to line 1
*gH - start Select line mode
*gr{char} - virtual replace N chars with {char}
What is the missing connection between all these commands?
A: There's no greater connection to g-commands: it's a mixed bunch. It is an easy prefix and the unbound keys were getting extinct so the less-used maps found a good place behind g.
A: Simply you're talking about two different things. In some cases g is the short way of "global" (for range command for example), for line moving the g stands for goto.
In VIM commands are often shortened for quick of use.
:help global may help
Btw: for line navigation I've always used the :<lineno> syntax.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "79"
} |
Q: Encoding error while writing data from excelfile to database (mysql) I get this error when writing to database:
Encoding::UndefinedConversionError "\xD0" from ASCII-8BIT to UTF-8
After googling around a bit the problem seems to lie in ruby 1.9.2 string handling but no real solution found.
I use magic_encoding to force utf-8 on all data. My database runs on utf-8 as well.
I'm running rails 3.1 and ruby 1.9.2.
Anyone that can shine some light on this error?
A: You should add this line to the top of your .rb file
# encoding: utf-8
Or you can use this gem
magic_encoding
Related topic:
Add "# coding: utf-8" to all files
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is there a C++ implementation of Node.js Net API? Node.js has a very good and well thought Net API.
I wonder is there a good C++ only implementation of that API as for example LuaNode do for Lua?
A: Take a look at node.native - attempt to implement api similar to node.js core lib, but with c++11 (and evented IO is also based on libuv)
A: There is nothing very similar that I know of.
However there are several reactor frameworks out there which give the same event queue driven environment. For example boost::asio provides an event queue that makes callbacks to handle network events, timers, and arbiatary events that you push onto the event queue.
It's largely the same idea, used in the same way. Howver it's nowhere near as simple as node.js to get started with, and does provide any non-blocking functions other than the basics I said above.
It does provide you with the environment to build your own system though. It's an excellent library, but probably rather lower level than you are looking for. There are other simiar libraries such as ACE and parts of the POCO c++ libraries too, but again, they are lower level than node.js with much less library support.
edit:
I've not looked at it too much but how about this https://github.com/joyent/libuv . This is a library that is used to implement some of the node.js features in a cross platform way. Maybe it's possible to use some of it for what you need?
A: Boost.Asio is conceptually very similar to Node.js. The primary difference being Asio is implemented as a library and Node.js is a language construct. Asio therefore exposes the event queue, requiring some initial setup to post callback handlers, and eventually a blocking call to start the event loop (io_service.run()).
If you're looking for a pure C++ API similar to Node.js, Boost.Asio is definitely the way to go. It is the de-facto networking library for many C++ applications. It's also discussed heavily on SO in the boost-asio tag.
A: I'm quite sure you could embed a Javascript engine into your program
*
*v8 (building guide)
*SpiderMonkey (building guide)
Actually tying that to your C code needs tinkering with the eval functions of both, but I think I remember seeing sample programs doing that for both engines
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Handling Device error with JSON I'm using rails 3 and Devise and i'm trying to restrict some actions to ed in users. REST calls in my application are done using JSON.
When i have to be logged in, Device returns this:
{
"email": "",
"password": ""
}
How can i change this message to contain a custom JSON message ?
NOTE: i'm protecting my controllers using: before_filter authenticate_user!
A: Answer here: https://github.com/plataformatec/devise/issues/1361
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jQuery UI CSS not overriding I have some anchor icons that inherit from .ui-widget-content and .ui-state-default. The background-position of .ui-widget-content .ui-state-default is overriding the background-position of .ui-icon-play.
When the anchor icons only inherit from .ui-state-default, the background-position of .ui-icon-play has higher priority than that of .ui state default.
I want .ui-icon-play to override .ui-widget-content .ui-state-default so that I get the correct icon image from the image sprite. How does the priority get decided when they are both classes and according to chrome dev tools, .ui-icon-play is line 232 of the ui css whereas the .ui-state-default, .ui-widget-content .ui-state-default is line 69?
Also when I do addClass('.ui-icon-play'), the background-position still doesn't override that of the .ui-widget-content .ui-state-default.
Here is simplified version of my code:
html
<div class="controls-container ui-widget-content">
<div class="rep-controls">
<a id="play" class="ui-state-default ui-corner-all ui-icon ui-icon-play"
title="Play/Pause"></a>
<a id="stop" class="ui-state-default ui-corner-all ui-icon ui-icon-stop"
title="Stop"></a>
</div>
</div>
js
$("#play").click(function() {
if(playing == true) {
$("#play").removeClass('ui-icon-pause');
else {
$("#play").addClass('ui-icon-pause');
}
});
A: Presuming you are able to modify the CSS, just try making the selector:
.ui-widget-content a.ui-icon-play {[...]}
Adding the 'a' will make the selector override .ui-widget-content .ui-state-default because it is more specific.
A: Go for specifity or !important
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UITabBar standard icons location I want to get standard xcode icons for UITabBar. Does anybody know where location of this icons? Or give link to same, FREE and Retina display icons please.
A: You can use the UIKit Artwork Extractor to get the icons, but note that those belong to apple and you would deploy them as part of "your" application..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How started with google docs in asp.net? I have a task to implement into web asp.net project (web site) a google docs solutions for manage with documents like word/excel. Now I read about Google Documents List Data API v2.0 on http://code.google.com/intl/en/apis/documents/docs/3.0/developers_guide_protocol.html#UploadingDocs.
I'm getting the file from google docs like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DocumentsService myService = new DocumentsService("exampleCo-exampleApp-1");
myService.setUserCredentials("[email protected]", "test");
DocumentsListQuery query = new DocumentsListQuery();
DocumentsFeed feed = myService.Query(query);
Console.WriteLine("Your docs: ");
foreach (DocumentEntry entry in feed.Entries)
{
Label1.Text = entry.Title.Text;
}
}
I understand google docs like some word application that works in browser. How I can view file in browser like this???
A: Each entry in feed.Entries contains a URL to the document. Use that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL Query works but equivalent C# query doesn't. . I've got a not particularly complex SQL query that returns exactly what I want when run in Server Mgt Studio, but when I run it in C# the DataGrid comes up blank. (And yes - hostnames sanitized, I don't just have a terrible naming scheme.)
Hopefully someone with sharper eyes than I can pick up the issue.
SQL query:
SELECT MachineName, InstanceName, CounterName,
AVG(CASE WHEN CounterValue > 0 THENCounterValue ELSE NULL END)/1024 as 'Mean (KB)'
FROM DataCollector.dbo.JobCounterSummary
WHERE
((MachineName = '\\HOST001' AND (InstanceName = 'D:' OR InstanceName = 'E:')) OR
(MachineName = '\\HOST002' AND (InstanceName = 'E:' OR InstanceName = 'G:')) OR
(MachineName = '\\HOST003' AND (InstanceName = 'G:' OR InstanceName = 'H:')) OR
(MachineName = '\\HOST004' AND (InstanceName = 'G:' OR InstanceName = 'H:') OR
(MachineName = '\\HOST005' AND InstanceName = 'G:') OR
(MachineName = '\\HOST006' AND InstanceName = 'C:') OR
(MachineName = '\\HOST007' AND InstanceName = 'C:'))) AND
InstanceName != '_Total' AND
InstanceName NOT LIKE 'Harddisk%' AND
(CounterName = 'Avg. Disk Bytes/Write' OR CounterName = 'Avg. Disk Bytes/Read')
GROUP BY MachineName, CounterName, InstanceName
ORDER BY MachineName, InstanceName, CounterName
And the C# code:
public DataTable dtJobReadWrite = new DataTable();
private void GetReadWriteStats()
{
dtJobReadWrite.Clear();
string connstr = @"Server=SQLSERVER\SQL;Database=DataCollector;Trusted_Connection=True; MultipleActiveResultSets=true";
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
string commandstr =
"SELECT MachineName, InstanceName, CounterName, AVG(CASE WHEN CounterValue > 0 THEN CounterValue ELSE NULL END)/1024 as \"Mean (KB)\" " +
"FROM dbo.JobCounterSummary " +
"WHERE " +
"((MachineName = @HOST001 AND (InstanceName = @DriveD OR InstanceName = @DriveE)) OR " +
"(MachineName = @HOST002 AND (InstanceName = @DriveE OR InstanceName = @DriveG)) OR " +
"(MachineName = @HOST003 AND (InstanceName = @DriveG OR InstanceName = @DriveH)) OR " +
"(MachineName = @HOST004 AND (InstanceName = @DriveG OR InstanceName = @DriveH) OR " +
"(MachineName = @HOST005 AND InstanceName = @DriveG) OR " +
"(MachineName = @HOST006 AND InstanceName = @DriveC) OR " +
"(MachineName = @HOST007 AND InstanceName = @DriveC))) AND " +
"InstanceName != @_Total AND " +
"InstanceName NOT LIKE @HardDisk AND " +
"(CounterName = @AvgDiskBytesWrite OR CounterName = @AvgDiskBytesRead) " +
"GROUP BY MachineName, CounterName, InstanceName " +
"ORDER BY MachineName, InstanceName, CounterName";
SqlCommand jobsCommand = new SqlCommand(commandstr, conn);
jobsCommand.Parameters.AddWithValue("@HOST001", "\\HOST001");
jobsCommand.Parameters.AddWithValue("@HOST002", "\\HOST002");
jobsCommand.Parameters.AddWithValue("@HOST003", "\\HOST003");
jobsCommand.Parameters.AddWithValue("@HOST004", "\\HOST004");
jobsCommand.Parameters.AddWithValue("@HOST005", "\\HOST005");
jobsCommand.Parameters.AddWithValue("@HOST006", "\\HOST006");
jobsCommand.Parameters.AddWithValue("@HOST007", "\\HOST007");
jobsCommand.Parameters.AddWithValue("@DriveC", "C:");
jobsCommand.Parameters.AddWithValue("@DriveD", "D:");
jobsCommand.Parameters.AddWithValue("@DriveE", "E:");
jobsCommand.Parameters.AddWithValue("@DriveG", "G:");
jobsCommand.Parameters.AddWithValue("@DriveH", "H:");
jobsCommand.Parameters.AddWithValue("@_Total", "_Total");
jobsCommand.Parameters.AddWithValue("@HardDisk", "Harddisk%");
jobsCommand.Parameters.AddWithValue("@AvgDiskBytesWrite", "Avg. Disk Bytes/Write");
jobsCommand.Parameters.AddWithValue("@AvgDiskBytesRead", "Avg. Disk Bytes/Read");
SqlDataAdapter jobsAdapter = new SqlDataAdapter(jobsCommand);
jobsAdapter.Fill(dtJobReadWrite);
dgvReadWrites.DataSource = dtJobReadWrite;
conn.Close();
}
A: My guess is that it's your strings:
"\\HOST001"
You're not escaping out your backslashes, so the strings only contain a single backslash. Fix it by either:
"\\\\HOST001"
//or
@"\\HOST001"
A: as \"Mean (KB)\"
I guess those ought to be single qoutes...
And probably you don't have to escape them in that case too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: modx htaccess links are not working Hello MODx developers,
I am using MODx revolution. I have just transferred site from one domain to another. as it was a IP based server i have created virtual host with the same name it had previously.
On previous server the files were located at the root but in new server files are located at tab3, so i have created virtual host that points inside that directory. ie. I have all files in modx/ dir so my virtual host config set to /var/www/modx/
Now the problem is whenever i open home page as well as subdomains (contexts) it works and shows the page but when i open any internal links it says 404 page
Ex : if i open www.abc.com => It works
but when i open www.abc.com/contacts => It doesnt works
I see its issue with .htaccess because
1) if i remove htaccess
all the subdomains and domains works perfect but inner links like "abc.com/contact" doesnt open up and says 404
2) If i add it again only the main domain and its inner links open...no subdomain or inner links of subdomain works
One more thing....and CLUE is that
when i try to access the same 404 page with ID like this
www.abc.com/index.php?id=8056
It works
DO i need to add/remove something from htaccess ??
A: Is the new server running Apache? I had a similar problem where the server was running Zeus & therefore .htaccess didnt work. There is a solution but was too advanced for me. Was easier to install on an Apache server instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Magento Filter By Relative Value I would like to filter a collection by relative value per that row. For example,
SELECT * FROM table WHERE column_1 > column_2
The only thing I know how to do in Magento would be
$q = Mage::getModel('table')->getCollection()
->addAttributeToFilter('column_1', array('gt' => $some_number));
or something of that sort. I can only give it a value to compare against, not a column name. I also looked at the Zend_Db_Select method at the where clause but didn't find anything that would help. Do I actually have to go all the way down to a direct SQL query (something which is, of course, avoided at all costs)? (I'm running Magento 1.3.2.4)
Thank you.
A: Try something like
$q = Mage::getModel('table')->getCollection()
->addAttributeToSelect('column_1')
->addAttributeToSelect('column_2')
->addAttributeToFilter('column_1', array('gt' => Zend_Db_Expr('`column_2`')));
A: OK, this is probably not the ideal solution, but it's one way of getting what you need.
This is how I got a collection of products that were on sale, where a products final price is lower than its price.
I first made a new empty data collection. Then defined the collection I was going to loop through filtering what I could first. After that I looped through that collection and any products that matched my requirements got added to the empty collection.
$this->_itemCollection = new Varien_Data_Collection();
$collection = Mage::getResourceModel('catalog/product_collection');
$collection->setVisibility(Mage::getSingleton('catalog/product_visibility')->getVisibleInCatalogIds());
$category = Mage::getModel('catalog/category')->load($this->getCategoryId());
$collection = $this->_addProductAttributesAndPrices($collection)
->addStoreFilter()
->addCategoryFilter($category)
->addAttributeToSort('position', 'asc');
$i=0;
foreach($collection as $product){
if($product->getFinalPrice() > $product->getPrice() && !$this->_itemCollection->getItemById($product->getId())){
$this->_itemCollection->addItem($product);
$i++;
}
if($i==$this->getProductsCount()){
break;
}
}
$this->setProductCollection($this->_itemCollection);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Create IIS Application from Code I'm working on a web service installation.
One of the things I need to do is creating a new virtual directory under the default web site.
The problem is I need to set a different application pool for that virtual directory (please don't ask why...these are the requirements and nothing I can do about it).
In IIS6, since there is no difference between virtual directories and applications I have no problem doing so.
In IIS7, it is not possible setting an application pool to a virtual directory so I need to create a new "application" and attach an application pool to it.
I couldn't find any reasonable example/tutorial for doing so in C#. I need some help please :-)
Thanks.
A: Found the answer somewhere out there.
I'm using the same code for creating the virtual directory in IIS6 and the application on IIS7:
DirectoryEntry defaultWebSite = GetWebSiteEntry(DEFAULT_WEB_SITE_NAME);
DirectoryEntry defaultWebSiteRoot = new DirectoryEntry(defaultWebSite.Path + "/Root");
//Create and setup new virtual directory
DirectoryEntry virtualDirectory = defaultWebSiteRoot.Children.Add(applicationName, "IIsWebVirtualDir");
virtualDirectory.Properties["Path"][0] = physicalPath;
virtualDirectory.Properties["AppFriendlyName"][0] = applicationName;
virtualDirectory.CommitChanges();
// IIS6 - it will create a virtual directory
// IIS7 - it will create an application
virtualDirectory.Invoke("AppCreate", 1);
object[] param = { 0, applicationPoolName, true };
virtualDirectory.Invoke("AppCreate3", param);
A: With C# you can try running some server side script that creates virtual directory.
Take a script similar to:
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5adfcce1-030d-45b8-997c-bdbfa08ea459.mspx?mfr=true
And run it with 'Execute' command:
http://www.codeproject.com/KB/cs/Execute_Command_in_CSharp.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android spinner prompt text not showing The first year from the data array is shown instead of the text from prompt in my spinner. I tried adding the prompt in XML, but I also tried from code. Furthermore, it gives me a "resource not found error", when adding the spinnerSelector attribute.
XML
<Spinner
android:id="@+id/spinnerYear"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:drawSelectorOnTop="true"
android:padding="5dip"
android:prompt="@string/spinner_header"
android:background="@drawable/selector_yearspinnerback"
android:layout_below="@+id/linearLayout_gender_btns"
android:layout_centerHorizontal="true"></Spinner>
-- android:spinnerSelector="@drawable/category_arrow"
Code
ArrayList<String> yearList = new ArrayList<String>();
int now = new Date().getYear() + 1900;
for (int i = now; i > now - 110; i--) {
yearList.add(i + "");
}
Spinner spinner = (Spinner) findViewById(R.id.spinnerYear);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, yearList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
A: Perhaps you are seeing the spinner drop down items as list without any prompt text. There are two modes in which spinner shows the items, dropdown and dialog.
Add this attribute to your spinner as an XML atrtribute:
android:spinnerMode="dialog"
And you will now get items in a popup dialog select list instead of drop down list.
A: You have to set adapter.setDropDownViewResource (android.R.layout.simple_spinner_dropdown_item); after
spinner.setAdapter(adapter);
So the fixed code would be:
ArrayList<String> yearList = new ArrayList<String>();
int now = new Date().getYear() + 1900;
for (int i = now; i > now - 110; i--) {
yearList.add(i + "");
}
Spinner spinner = (Spinner) findViewById(R.id.spinnerYear);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, yearList);
spinner.setAdapter(adapter);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
(I hope it works for you like it works for me :D!)
A: For me, both android:prompt XML attibute as well as Spinner.setPrompt work, and list selector displays correct title.
Try to find bug in your code, or make call to Spinner.getPrompt at some point and print this to log, to find our from where you get invalid title.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Delphi XE2 background IDE compiler unable to find source path I just bought XE2 version, installed the update 1 ISO, and made my Open Source projects compile with it.
In fact:
*
*I added the source code paths of the library to the general settings IDE (for all platforms I use, i.e. Windows 32 bit and 64 bit up to now);
*I compiled the TestSQLite3.dpr regression tests of our framework - no problem: EXE is compiled and all tests passed;
*I've a strange issue with the IDE background compilers: even if the project compiled, the IDE displays some errors about unknown files (not in the bottom compiler messages, but in the top of the classes navigation tree - left to the source code editor), and in the .dpr source code, the unit names are underlined in red, and I'm not able to navigate inside the source (using Ctrl+Click on a symbol).
I've added the source code paths of the library to the project options (for Win32/Win64 - even if it was already set at the global IDE level). Now the errors about unknown files disappeared, but the unit names are still underlined in red in the source code, and the Ctrl+Click does not work.
The TestSQLite3.dpr source code do not specify the full path of the units:
uses
{$I SynDprUses.inc}
Windows,
Messages,
SysUtils,
Classes,
SynCrypto,
SynCrtSock,
SynCommons,
SynDB,
SynOleDB,
SynDBOracle,
(...)
In the above lines, SynCrypto, SynCrtSock, SynCommons are underlined in red.
My actual guess is that full paths are needed in the .dpr (SynCrypto in '..\SynCrypto.pas'). I did not test this because I don't have XE2 at work.
Since there was no issue with the previous IDE with this kind of source code (it worked from Delphi 6 up to XE), I wonder if there is a possibility of regression, or a new option not available with the previous version of the IDE (probably platform-based) which I did not set properly. Or perhaps the full path is now needed in .dpr - but this sounds like a regression in the Code/Error Insight compiler to me.
A: I asked the question to Dr Bob (by whom I bought the XE2 license - since the 1 $ = 1 € equation sounded a bit unfair, I wanted at least to have a real Delphi expert for being my reseller).
Here is his answer:
You did not make a mistake. The problem is that the there are three
compilers in XE2 (like in previous versions of Delphi): the real
compiler (which works fine), the Code Insight compiler (which is
faster), the Error Insight compiler (which must be even more faster),
and the syntax highlighting parser (which is the fastest).
XE2 introduced a number of features that made the normal compiler
slower, and gave the Code Insight and Error Insight compilers a bit of
trouble. First of all, we have the new targets: Win32, Win64 and OSX
which cause the search paths to be different for each target (see
$PLATFORM directive), as well as build configuration, although there
is only one "Library path" for each PLATFORM (and not for the build
configurations).
The second complexing factor is the dotted unit names (scoped unit
names) that were introduced. Windows is no longer Windows, but
Winapi.Windows.
My guess is that these two additional complexing factors cause
problems for the Code Insight and Error Insight compilers. Note that
the real compiler still works. But the Error Insight shows incorrect
errors, and the Code Insight doesn't always work for these units.
You could try to explicitly add them to the project again (in which
case the full path will be used, like you mention in your question on
stack overflow as well).
So I'm afraid this is some regression...
Edit at closing question:
First point is that adding full paths:
SynPdf in '..\SynPdf.pas',
in the .dpr did let the files been found - but the background compiler is still lost, unable to find a class declaration in this body.
Just another regression sample:
var Thread: array[0..3] of integer;
Handle: array[0..high(Thread)] of integer;
Is a perfectly safe syntax, compiles just fine, was interpreted by the previous Error Insight compiler without any problems (works since Delphi 5), but fails under XE2.
I'm a bit disappointed about XE2 IDE. Compiler makes it work. But IDE is really disappointing. It is not usable, from my point of view. I'll continue using Delphi 7 as my main editor, and just use XE2 as cross-platform compiler and debugger.
A: Might be related to what Barry Kelly mentions here:
http://blog.barrkel.com/2011/10/delphi-xe2-compiler-performance.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: MySQL many-to-many complement set I've been looking all over the net and asking people for guidance but nobody seems to know the right (relatively fast) solution to the problem:
I have three tables, classic many-to-many solution:
*
*entries: id (int), title (varchar[255]), content (text)
*tags: id (int), name (varchar[255]), slug (varchar[255])
*entries_tags: id (int), entry_id (int), tag_id (int)
Nothing out of ordinary so far. Now let's say I have test data in tags (I'm keeping out slugs as they are not important):
ID | name
1. | one
2. | two
3. | three
4. | four
5. | five
I also have three entries:
ID | title
1. | Something
2. | Blah blah blah
3. | Yay!
And relations:
ID | entry_id | tag_id
1. | 1 | 1
2. | 1 | 2
3. | 2 | 1
4. | 2 | 3
5. | 3 | 1
6. | 3 | 2
7. | 3 | 3
8. | 4 | 1
9. | 4 | 4
OK, we have our test data. I want to know how to get all entries that have tag One, but doesn't have tag Three (that'd be entries 1 and 4).
I know how to do it with subquery, the problem is, it takes a lot of time (with 100k entries it took about 10-15 seconds). Is there any way to do it with JOINs? Or am I missing something?
edit I guess I should've mentioned I need a solution that works with sets of data rather than single tags, so replace 'One' in my question with 'One', 'Two' and 'Two' with 'Three','Four'
edit2 The answer provided is right, but it's too slow to be used practically. I guess the only way of making it work is using a 3rd-party search engine like Lucene or ElasticSearch.
A: The following script selects entries that have tags One and Two and do not have tags Three and Four:
SELECT DISTINCT
et.entry_id
FROM entries_tags et
INNER JOIN tags t1 ON et.tag_id = t1.id AND t1.name IN ('One', 'Two')
LEFT JOIN tags t2 ON et.tag_id = t2.id AND t2.name IN ('Three', 'Four')
WHERE t2.id IS NULL
Alternative solution: the INNER JOIN is replaced with WHERE EXISTS, which allows us to get rid from the (rather expensive) DISTINCT:
SELECT
et.entry_id
FROM entries_tags et
LEFT JOIN tags t2 ON et.tag_id = t2.id AND t2.name IN ('Three', 'Four')
WHERE t2.id IS NULL
AND EXISTS (
SELECT *
FROM tags t1
WHERE t1.id = et.tag_id
AND t1.name IN ('One', 'Two')
)
A: This should do what you want.
(It may or may not be faster than the sub query solution, I suggest you compare the query plans)
SELECT DISTINCT e.*
FROM tags t1
INNER JOIN entries_tags et1 ON t1.id=et1.tag_id
INNER JOIN entries e ON e.entry_id=et1.entry_id
INNER JOIN tags t2 on t2.name='three'
INNER JOIN tags t3 on t3.name='four'
LEFT JOIN entries_tags et2 ON (et1.entryid=et2.entryid AND t2.id = et2.tag_id )
OR (et1.entryid=et2.entryid AND t3.id = et2.tag_id )
WHERE t1.name IN ('one','two') AND et2.name is NULL
By LEFT Joining the entries_tags table et2 (the data you do not want), you can then only select the records where the et2.name IS NULL (where the et2 record does not exist).
A: You mentioned trying a subquery. Is this what you tried?
SELECT entries.id, entries.content
FROM entries
LEFT JOIN entries_tags ON entries.id=entries_tags.entries_id
LEFT JOIN tags ON entries_tags.tag_id=tags.id
WHERE tag.id=XX
and entries.id NOT IN (
SELECT entries.id
FROM entries
LEFT JOIN entries_tags ON entries.id=entries_tags.entries_id
LEFT JOIN tags ON entries_tags.tag_id=tags.id
WHERE tag.id=YY
)
(Where XX is the tag you do want and YY is the tag you do not want)
With indices on the ID fields, that shouldn't be as slow as you say it is. It will depend on the data set, but it should be fine with indices (and with string comparisons omitted).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632510",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to create your own properties for element in SilverLight Can someone help me with this question?) In My XAML I have Listbox element. I want to add my user property into it(in my case - ConnectorStyle)
My XAML code:
<ListBox ItemsSource="{Binding Nodes}" ItemsPanel="{StaticResource CanvasItemsPanelTemplate}"
ItemTemplate="{StaticResource NodePictureTemplate}"
ItemContainerStyle="{StaticResource CanvasItemStyle}"
ConnectorStyle="{StaticResource ConnectorLineStyle}"/>
In my Model I have prepared this property:
public partial class MainPage : UserControl
{
public static readonly DependencyProperty ConnectorStyleProperty = DependencyProperty.Register(
"ConnectorStyle", typeof(Style), typeof(NodePicture), null);
public MainPage()
{
InitializeComponent();
}
public Style ConnectorStyle
{
get { return (Style)GetValue(ConnectorStyleProperty); }
set { SetValue(ConnectorStyleProperty, value); }
}
}
But I is a mistake - Cannot resolve ConnectorStyle.
Is there a simple (or a right way ) way of doing this?
A: There are two ways to do this: Either you can write a subclass for the ListBox that adds the DependencyProperty or you can write an attached property.
In your case you probably want to write a subclass that adds the property. Try something like this:
public class MyListBox : ListBox
{
public static readonly DependencyProperty ConnectorStyleProperty = DependencyProperty.Register(
"ConnectorStyle", typeof(Style), typeof(MyListBox), null);
public Style ConnectorStyle
{
get { return (Style)GetValue(ConnectorStyleProperty); }
set { SetValue(ConnectorStyleProperty, value); }
}
}
This will add a new type of ListBox that you can add in your xaml code. It will have all the same properties as a regular ListBox, but it will also have the ConnectorStyle property.
If you need to respond to changes to the ConnectorStyle property in your listbox then you should change the code for the Dependency Property, but that is outside the scope of this question.
And in XAML it shoul be :
<local:ListBoxEx
ConnectorStyle="{StaticResource ConnectorLineStyle}"/>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: VoIP + Ruby on Rails web application I have a project written in Ruby on Rails 2.1.
There a login & password needed to pass to my site (user & admins i have). Simple web-site.
But i want to create button "CALL ME". If i click on this button user can talk with (for example) admins.
What i need for this? Maybe some tools or already created apps?
P.S I can have my own voip server. (but is it necessary?))
A: There are 'livechat' text based services out there - most 'Call Me' features I've seen simply get a few details from the visitor which generates an email to internal staff to call the user back - works for out of hours too :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Saving client address to response again and again How can I save the client's complete address in asp application? Actually I want to send a response multiple times to same client without new call request by him. I don't want to end the response, when he called first time a service.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Correct behavior of OrderBy I have encountered something that puzzles me and I would like to see your opinion on the matter. It turns out that linq to sql and entity framework threats consecutive order by's differently.
The following code is used just for example and I am not claiming it has any sense at all:
Linq to sql:
DataClasses1DataContext db = new DataClasses1DataContext();
var result = (from c in db.Products
orderby c.ProductName
orderby c.UnitPrice
orderby c.UnitsOnOrder
select c).ToList();
What it generats on the server side:
SELECT [t0].[ProductID], [t0].[ProductName], [t0].[SupplierID], [t0].[CategoryID], [t0].[QuantityPerUnit], [t0].[UnitPrice], [t0].[UnitsInStock], [t0].[UnitsOnOrder], [t0].[ReorderLevel], [t0].[Discontinued]
FROM [dbo].[Products] AS [t0]
ORDER BY [t0].[UnitsOnOrder], [t0].[UnitPrice], [t0].[ProductName]
The same test with Entity Framework generates this:
SELECT
[Extent1].[ProductID] AS [ProductID],
[Extent1].[ProductName] AS [ProductName],
[Extent1].[SupplierID] AS [SupplierID],
[Extent1].[CategoryID] AS [CategoryID],
[Extent1].[QuantityPerUnit] AS [QuantityPerUnit],
[Extent1].[UnitPrice] AS [UnitPrice],
[Extent1].[UnitsInStock] AS [UnitsInStock],
[Extent1].[UnitsOnOrder] AS [UnitsOnOrder],
[Extent1].[ReorderLevel] AS [ReorderLevel],
[Extent1].[Discontinued] AS [Discontinued]
FROM [dbo].[Products] AS [Extent1]
ORDER BY [Extent1].[UnitsOnOrder] ASC
As you can see Linq To Sql adds all the requested order by's where the last one has the highest priority (which in my opinion is correct).
On the other hand entity framework respects only the last order by and disregards all the others.
Now I know there is an order by then by clause that can be used but I am just wondering which behavior is more correct. Also as far as I remember the query extenders used in asp are working with a separate order by which if applied on a query generated from a different data source will not work correctly (according to the above example one of the order by's will be omitted)
A: My opinion is that EF is correct. I don't know why L2S would do what you're describing - in my opinion, if you add an OrderBy clause instead of using ThenBy, it should overwrite any existing OrderBys.
When you're working with Linq-To-Objects, you should see OrderBy replace any previous ones, so it makes more sense to me to have the data-driven LINQ act the same.
If the behavior changed the way you're describing, then it seems that Microsoft agrees, since EF was designed to replace L2S.
A: What i've learned is that the order by is written like this:
DataClasses1DataContext db = new DataClasses1DataContext();
var result = (from c in db.Products
orderby c.UnitsOnOrder, c.UnitPrice, c.ProductName
select c).ToList();
And like that you can see the order clear to every one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Catch Fault Exception in Silverlight with Channel Factory I am trying to call a WCF service from a Silverlight client using channel factory as per this link. Working with channel factory is something new for me so please bear with me!
Everything mentioned in the article works just fine. But now I am trying to implement Fault exceptions so that I can catch the actual exceptions on the Silverlight side. But for some reason I always end up catching CommunicationException which doesn't serve my purpose.
Here is my service contract:
[OperationContract]
[FaultContract(typeof(Fault))]
IList<Category> GetCategories();
Catch block of the service:
catch (Exception ex)
{
Fault fault = new Fault(ex.Message);
throw new FaultException<Fault>(fault, "Error occured in the GetCategories service");
}
Service contract for client with async pattern:
[OperationContract(AsyncPattern = true)]
[FaultContract(typeof(Fault))]
IAsyncResult BeginGetCategories(AsyncCallback callback, object state);
IList<Category> EndGetCategories(IAsyncResult result);
Here is the service call from client:
ICommonServices channel = ChannelProviderFactory.CreateFactory<ICommonServices>(COMMONSERVICE_URL, false);
var result = channel.BeginGetCategories(
(asyncResult) =>
{
try
{
var returnval = channel.EndGetCategories(asyncResult);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
CategoryCollection = new ObservableCollection<Category>(returnval);
});
}
catch (FaultException<Fault> serviceFault)
{
MessageBox.Show(serviceFault.Message);
}
catch (CommunicationException cex)
{
MessageBox.Show("Unknown Communications exception occured.");
}
}, null
);
I am sharing the DataContract .dll between both the service and client applications and hence they are referring to same data contract classes (Category & Fault)
Please tell me what I am doing wrongly?
UPDATE: I do clearly see the fault exception sent from the service in Fiddler. Which makes me believe I am missing something in the client side.
A: For catching normal exceptions in sivleright you must create "Silverlight-enabled WCF Service" (Add -> New Item -> Silverlight-enabled WCF Service).
If you already created standard WCF service you can add attribute [SilverlightFaultBehavior] to your service manually.
Default implementation of this attribute is:
public class SilverlightFaultBehavior : Attribute, IServiceBehavior
{
private class SilverlightFaultEndpointBehavior : IEndpointBehavior
{
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new SilverlightFaultMessageInspector());
}
public void Validate(ServiceEndpoint endpoint)
{
}
private class SilverlightFaultMessageInspector : IDispatchMessageInspector
{
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
return null;
}
public void BeforeSendReply(ref Message reply, object correlationState)
{
if ((reply != null) && reply.IsFault)
{
HttpResponseMessageProperty property = new HttpResponseMessageProperty();
property.StatusCode = HttpStatusCode.OK;
reply.Properties[HttpResponseMessageProperty.Name] = property;
}
}
}
}
public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
{
}
public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
foreach (ServiceEndpoint endpoint in serviceDescription.Endpoints)
{
endpoint.Behaviors.Add(new SilverlightFaultEndpointBehavior());
}
}
public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
{
}
}
A: We use our own custom ServiceException class on the server e.g.
[Serializable]
public class ServiceException : Exception
{
public ServiceException()
{
}
public ServiceException(string message, Exception innerException)
: base(message, innerException)
{
}
public ServiceException(Exception innerException)
: base("Service Exception Occurred", innerException)
{
}
public ServiceException(string message)
: base(message)
{
}
}
And then in our server side service methods we use error handling like this:
try
{
......
}
catch (Exception ex)
{
Logger.GetLog(Logger.ServiceLog).Error("MyErrorMessage", ex);
throw new ServiceException("MyErrorMessage", ex);
}
We then use a generic method for all web service calls:
/// <summary>
/// Runs the given functon in a try catch block to wrap service exception.
/// Returns the result of the function.
/// </summary>
/// <param name="action">function to run</param>
/// <typeparam name="T">Return type of the function.</typeparam>
/// <returns>The result of the function</returns>
protected T Run<T>(Func<T> action)
{
try
{
return action();
}
catch (ServiceException ex)
{
ServiceLogger.Error(ex);
throw new FaultException(ex.Message, new FaultCode("ServiceError"));
}
catch (Exception ex)
{
ServiceLogger.Error(ex);
throw new FaultException(GenericErrorMessage, new FaultCode("ServiceError"));
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: SQL: How to make a query that return last created row per each user from table's data Consider following table's data
ID UserID ClassID SchoolID Created
2184 19313 10 28189 2010-10-25 14:16:39.823
46697 19313 10 27721 2011-04-04 14:50:49.433
•47423 19313 11 27721 2011-09-15 09:15:51.740
•47672 19881 11 42978 2011-09-19 17:31:12.853
3176 19881 11 42978 2010-10-27 22:29:41.130
22327 19881 9 45263 2011-02-14 19:42:41.320
46661 32810 11 41861 2011-04-04 14:26:14.800
•47333 32810 11 51721 2011-09-13 22:43:06.053
131 32810 11 51721 2010-09-22 03:16:44.520
I want to make a sql query that return the last created row for each UserID in which the result will be as below ( row that begin with • in the above rows ) :
ID UserID ClassID SchoolID Created
47423 19313 11 27721 2011-09-15 09:15:51.740
47672 19881 11 42978 2011-09-19 17:31:12.853
47333 32810 11 51721 2011-09-13 22:43:06.053
A: You can use a CTE (Common Table Expression) with the ROW_NUMBER function:
;WITH LastPerUser AS
(
SELECT
ID, UserID, ClassID, SchoolID, Created,
ROW_NUMBER() OVER(PARTITION BY UserID ORDER BY Created DESC) AS 'RowNum')
FROM dbo.YourTable
)
SELECT
ID, UserID, ClassID, SchoolID, Created,
FROM LastPerUser
WHERE RowNum = 1
This CTE "partitions" your data by UserID, and for each partition, the ROW_NUMBER function hands out sequential numbers, starting at 1 and ordered by Created DESC - so the latest row gets RowNum = 1 (for each UserID) which is what I select from the CTE in the SELECT statement after it.
A: I know this is an old question at this point, but I was having the same problem in MySQL, and I think I have figured out a standard sql way of doing this. I have only tested this with MySQL, but I don't believe I am using anything MySQL-specific.
select mainTable.* from YourTable mainTable, (
select UserID, max(Created) as Created
from YourTable
group by UserID
) dateTable
where mainTable.UserID = dateTable.UserID
and mainTable.Created = dateTable.Created
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PyQt4 Application Launch Alright, so I have two applications that won't launch now, a important one and a test one, the test one used to run, but now it is saying: AttributeError: 'StartQt4' object has no attribute 'filename'
So, I have no idea why that is happening, and that only happens when I try to use either the save feature or open feature.
Here is the launch code for that app:
Link to the code
Now, the important app is for a project at school, I have made it in PyQt, and just tried launching it using this code:
Code
If you need the ui file to the second code, just ask and I'll post a DL Link.
I would love to get both of those working, soon! And any tips on some good PyQt tutorials? They also have to be compatible with Python 3...
A: What did you change between it working and not working?
For the test code without knowing what the Ui_LQNotepad class does it's hard to say, but QMainWindow objects don't have a filename attribute so your code as given will never have worked. I suspect you may mean self.ui.filename but I can't say for certain that the Ui_LQNotepad class has a filename attribute. Search your code for filename and you'll see that you only ever read that attribute, you never set it. Where should this filename come from?
I'm not clear on the difference your your test app and the main code, they seem to be pretty much the same so I think the same applies to that.
Please not that in future it is helpful if you post the full traceback as well as the exception message.
A: Answer are in exception : 'StartQt4' object has no attribute 'filename'.
Just add filename attribute in your __init__.
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_LQNotepad()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.button_open,QtCore.SIGNAL("clicked()"), self.file_dialog)
QtCore.QObject.connect(self.ui.button_save,QtCore.SIGNAL("clicked()"), self.file_save)
QtCore.QObject.connect(self.ui.charInput,QtCore.SIGNAL("textChanged()"), self.enable_save)
self.filename = ""
self.ui.button_save.setEnabled(False)
A: Fixed, one problem was that in the test code, the website with the tutorial actually had a error, so I found it myself, and my project code had a problem with importing a module that was useless and just causing errors.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: git push failed with large repository (MOVE *some commit* failed,aborting (7/0)) We are using https protocol for git (to get synchronized with our wiki username/password), and try to push the local git repository to a bared remote repository with sslVerify = false. It works perfect with small repository but failed with our 3 Gigabytes repository. With the following error:
Fetching remote heads...
refs/
refs/tags/
refs/heads/
updating 'refs/heads/tflux-middle-end-partition'
from 0000000000000000000000000000000000000000
to 2062f4b5b77bd698dd3f7b6dd43a51e37ca10a27
sending 1026854 objects
MOVE da8e0adc291bb4690c57d0572f8006dbcf59ca17 failed, aborting (7/0)
Updating remote server info
fatal: git-http-push failed
At first glance, we thought it could be some time out error due to the https protocol, so we change the time out time to 4hours DavMinTimeout 14400, but it still didn't work.
Any suggestions will be welcomed.
A: The message comes from http-push.c, and is printed when curls does report a successful transmission. So either there is some error on the webserver (protocol permissions, file permissions), or you found a bug in curl. Maybe you can find traces about what is going wrong in your web server log. Also you can git push -v <args> to see more details of the transmission.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add new items to combobox which is bound to Entities? Design class which is generated by C# :
//
// usepurposeComboBox
//
this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
this.usepurposeComboBox.DisplayMember = "Name";
this.usepurposeComboBox.FormattingEnabled = true;
this.usepurposeComboBox.Location = new System.Drawing.Point(277, 53);
this.usepurposeComboBox.Name = "usepurposeComboBox";
this.usepurposeComboBox.Size = new System.Drawing.Size(218, 21);
this.usepurposeComboBox.TabIndex = 4;
this.usepurposeComboBox.ValueMember = "id";
//
// usepurposeBindingSource
//
this.usepurposeBindingSource.DataSource = typeof(mydatabaseEntities.usepurpose);
Then I bound the BindingSource (usepurposeBindingSource) to Entities :
usepurposeBindingSource.DataSource = mydatabaseEntities.usepurposes;
And I can not add a new row to usepurposeComboBox because it's been bound. Is there a workaround ?
A: The shortest way is to add a new row to your dataTable and then bind your comboBox to it something like this:
Company comps = new Company();
//pupulate dataTable with data
DataTable DT = comps.getCompaniesList();
//create a new row
DataRow DR = DT.NewRow();
DR["c_ID"] = 0;
DR["name"] = "Add new Company";
DR["country"] = "IR";
//add new row to data table
DT.Rows.Add(DR);
//Binding DataTable to cxbxCompany
cxbxCompany.DataSource = DT;
cxbxCompany.DisplayMember = "name";
cxbxCompany.ValueMember = "c_ID";
A: I'm assuming that you want to add for example a first item sometimes called "Choose One" as if you want to live data you should just see where the data comes from and add more items to that "table".
this.usepurposeBindingSource is an object ... why not adding into it before it binds?
if it's a List<T> this will be fine
this.usepurposeBindingSource.Insert(0, new T() {
Name = "Choose one",
Id = ""
});
Then Bind() it...
Remember to validate as it's a string and will not be the object you want
This is working:
List<MyObject> usepurposeBindingSource { get; set; }
private void FillUpData()
{
// Simulating an External Data
if (usepurposeBindingSource == null || usepurposeBindingSource.Count == 0)
{
this.usepurposeBindingSource = new List<MyObject>();
this.usepurposeBindingSource.Add(new MyObject() { Name = "A", ID = 1 });
this.usepurposeBindingSource.Add(new MyObject() { Name = "B", ID = 2 });
this.usepurposeBindingSource.Add(new MyObject() { Name = "C", ID = 3 });
}
}
private void FillUpCombo()
{
FillUpData();
// what you have from design
// comment out the first line
//this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
this.usepurposeComboBox.DisplayMember = "Name";
this.usepurposeComboBox.FormattingEnabled = true;
this.usepurposeComboBox.Location = new System.Drawing.Point(277, 53);
this.usepurposeComboBox.Name = "usepurposeComboBox";
this.usepurposeComboBox.Size = new System.Drawing.Size(218, 21);
this.usepurposeComboBox.TabIndex = 4;
this.usepurposeComboBox.ValueMember = "id";
// to do in code:
this.usepurposeBindingSource.Insert(0, new MyObject() { Name = "Choose One", ID = 0 });
// bind the data source
this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
}
The trick is to comment out the DataSource line and do it in your code, inserting one more element into your object that is from your Model
//this.usepurposeComboBox.DataSource = this.usepurposeBindingSource;
A: The simplest way to do this, is to wrap your BindingSource with some kind of "ViewModel". The new class will return a "complete" list of items - both those provided from the original binding source, as well as those "additional" items.
You can then bind the new wrapper to your combobox.
I wrote an article about this a while back... It's not my finest work, and it's probably a bit outdated, but it should get you there.
A: I resolved it on my own. I created a new unbound combobox then bind it to a datatable. Not sure if it's the best way but it works for me. Thanks for all of your suggestions. :)
private void FillCombobox()
{
using (mydatabaseEntities mydatabaseEntities = new mydatabaseEntities())
{
List<usepurpose> usepurposes = mydatabaseEntities.usepurposes.ToList();
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("Name");
dt.Rows.Add(-1, "test row");
foreach (usepurpose usepurpose in usepurposes)
{
dt.Rows.Add(usepurpose.id, usepurpose.Name);
}
usepurposeComboBox.ValueMember = dt.Columns[0].ColumnName;
usepurposeComboBox.DisplayMember = dt.Columns[1].ColumnName;
usepurposeComboBox.DataSource = dt;
}
}
A: Check out this link: http://forums.asp.net/t/1695728.aspx/1?
In asp you can add this to insert an empty line:
<asp:DropDownList ID="CustomerDropDownList" runat="server"
DataSourceID="CustomerEntityDataSource" DataTextField="CustomerId"
DataValueField="CustomerId" AppendDataBoundItems="true">
<asp:ListItem Text="Select All Customers" Value="" />
</asp:DropDownList>
Or in code behind:
DropDownList1.AppendDataBoundItems = true;
DropDownList1.Items.Add(new ListItem("Select All Customers", "-1"));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: JSON Parsing with GSON I have the following Json string.How to parse this kind of Json using Gson in Java?Any help would be appreciated.
{
"acclst":[{
"accountInfoData":[{
"userId":9,
"rid":"1-Z5S3",
"acnme":"acc_1234.",
"actpe":"Fabricator / Distributor",
"mph":"2660016354",
"euse":"Biofuels",
"com":"0",
"sta":"Active",
"stem":"BBUSER5",
"wsite":"",
"fax":"",
"zone":"",
"crted":"BBUSER4",
"statusX":1,
"partyId":0,
"address":[]
}
]
}
],
"conlst":[],
"actlst":[],
"prolst":[],
"code":"200"
}
A: your Gson getter/Setter class will be
sample.java
public class sample {
public String code="";
ArrayList<String> conlst;
ArrayList<String> actlst;
ArrayList<innerObject> prolst;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public ArrayList<String> getConlst() {
return conlst;
}
public void setConlst(ArrayList<String> conlst) {
this.conlst = conlst;
}
public ArrayList<String> getActlst() {
return actlst;
}
public void setActlst(ArrayList<String> actlst) {
this.actlst = actlst;
}
public ArrayList<innerObject> getProlst() {
return prolst;
}
public void setProlst(ArrayList<innerObject> prolst) {
this.prolst = prolst;
}
}
innerObject.java
public class innerObject {
ArrayList<String> accountInfoData;
public ArrayList<String> getAccountInfoData() {
return accountInfoData;
}
public void setAccountInfoData(ArrayList<String> accountInfoData) {
this.accountInfoData = accountInfoData;
}
}
secondInnerObject.java
public class secondInnerObject {
public String userId="";
public String rid="";
public String acme="";
public String actpe="";
public String mph="";
public String euse="";
public String com="";
public String sta="";
public String stem="";
public String wsite="";
public String fax="";
public String zone="";
public String crted="";
public String statusX="";
public String partyId="";
ArrayList<String> address;
ArrayList<String> accountInfoData;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getRid() {
return rid;
}
public void setRid(String rid) {
this.rid = rid;
}
public String getAcme() {
return acme;
}
public void setAcme(String acme) {
this.acme = acme;
}
public String getActpe() {
return actpe;
}
public void setActpe(String actpe) {
this.actpe = actpe;
}
public String getMph() {
return mph;
}
public void setMph(String mph) {
this.mph = mph;
}
public String getEuse() {
return euse;
}
public void setEuse(String euse) {
this.euse = euse;
}
public String getCom() {
return com;
}
public void setCom(String com) {
this.com = com;
}
public String getSta() {
return sta;
}
public void setSta(String sta) {
this.sta = sta;
}
public String getStem() {
return stem;
}
public void setStem(String stem) {
this.stem = stem;
}
public String getWsite() {
return wsite;
}
public void setWsite(String wsite) {
this.wsite = wsite;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getZone() {
return zone;
}
public void setZone(String zone) {
this.zone = zone;
}
public String getCrted() {
return crted;
}
public void setCrted(String crted) {
this.crted = crted;
}
public String getStatusX() {
return statusX;
}
public void setStatusX(String statusX) {
this.statusX = statusX;
}
public String getPartyId() {
return partyId;
}
public void setPartyId(String partyId) {
this.partyId = partyId;
}
public ArrayList<String> getAddress() {
return address;
}
public void setAddress(ArrayList<String> address) {
this.address = address;
}
public ArrayList<String> getAccountInfoData() {
return accountInfoData;
}
public void setAccountInfoData(ArrayList<String> accountInfoData) {
this.accountInfoData = accountInfoData;
}
}
to fetch
String json= "your_json_string";
Gson gson= new Gson();
sample objSample=gson.fromJson(json,sample.getClass());
thats it
A: You have to use JSONObject to parse this json in android.
Take a look at the following link.
http://developer.android.com/reference/org/json/JSONObject.html
A: Android already contains the required JSON libraries. You can use a valid string or a file for input. Here is code and explanation taken from here:
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
public class JsonParser extends Activity {
private JSONObject jObject;
private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";//write your JSON String here
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
parse();
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse() throws Exception {
jObject = new JSONObject(jString);
JSONObject menuObject = jObject.getJSONObject("menu");
String attributeId = menuObject.getString("id");
System.out.println(attributeId);
String attributeValue = menuObject.getString("value");
System.out.println(attributeValue);
JSONObject popupObject = menuObject.getJSONObject("popup");
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
for (int i = 0; i < 3; i++) {
System.out.println(menuitemArray.getJSONObject(i)
.getString("value").toString());
System.out.println(menuitemArray.getJSONObject(i).getString(
"onclick").toString());
}
}
}
A: Here you have a tutorial which answers your needs - Android + Gson
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Converting screen coords to world coords I'm working on a conversion matrix for a map application I'm currently writing.
I have a point in screen coordinates and the points in the target coordinate space, and for some stupid reason I cannot seem to figure out how to find the conversion matrix the converts the points in my screen coordinates to the world coordinates.
For example:
Coordinate (1005.758, 673.661) should be converted to (786382.6, 2961730.3)
and coordinate (1010.240, 665.217) should be converted to (786488.3, 2961837). I'm using WPF so that's why the screen coordinates are actually double and not int.
A: With two coordinates you can extract scaling factor and translation (if the map is using these two operations only).
Scaling in the first dimension is given by
s1 = (786382.6 - 786488.3) / (1005.758 - 1010.24) => s1 ~ 23.583
and in the second via
s2 = (2961730.3 - 2961837) / (673.661 - 665.217) => s2 ~ -12.636
while the corresponding offsets are
o1 = 786382.6 - s1 * 1005.758 => o1 ~ 762663.586
and
o2 = 2961730.3 - s2 * 673.661 => o2 ~ 2970242.809
Thus your transformation is given by
(x, y) -> (o1+s1*x, o2+s2*y) = (762663.586+23.583*x, 2970242.809-12.636*y)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Sublime Text 2 - How to open a file from open folders using the command pallet? I want to open a file using some kind of fuzzy searching, and I'm pretty sure I've seen this functionality inside Sublime Text, but for some reason I can't find any mention of this anywhere.
I want to open the command pallet and be able to type a file name in there, and if the file is close, It will open the file for me, if it's open, it will activate it's window and group.
Is this possible?
A: I see you already found ctrl+p, but the original announcement of this feature has some good information on usage so I thought I'd post it.
The biggest change here is that the Ctrl+P dialog has been reworked into a more general "Goto Anything" popup. From this, you can:
Type, to search through files (open files, recently closed files, and files in open folders)
@foo, to search through symbols in the current file
:foo, to go to the given line number
#foo, to do a fuzzy search in the current file for foo
These can be combined: "foo@bar" will search for the file that best matches "foo", and go to the symbol in that file that best matches "bar". "foo:100" would go to line 100 of the same file. You can use this to preview a location in another file, then hit escape to go back to where you where.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: HierarchicalDataTemplate for very complex layout Im making a herbal database program and I am having troubles setting up HierarchicalDataTemplates for my main data class.
Tree layout wanted:
*
*Glossary
*
*Category1
*
*Letter (Reduces overall list size)
*
*Entry
*
*Note1
*Note2
*Herbs
*
*Botanical Name
*
*Alphabetical
*
*Letter (Reduces overall list size)
*
*Entry
*By Family
*
*Family
*
*Entry
*Common Name
*
*Letter (Reduces overall list size)
*
*Entry
NOTE: All entries have notes
NOTE2: Letter is a letter of the alphabet for sorting
Ex:
*
*a
*
*apple
*b
*
*bus
Main Class:
Public Class MainSystem
Public herbs As New Dictionary(Of Integer, herbEntry)
Public glossary As New Dictionary(Of Integer, glossaryEntry)
End Class
GlossaryEntry:
Public Class glossaryEntry
Public Property ID As Integer
Public Property Words As List(Of String) 'Each word is in the format: Catagory/word
Public Property Notes As SortedDictionary(Of String, String)
End Class
HerbEntry:
Public Class herbEntry
Public ID As Integer
Public Property commonName As List(Of String)
Public Property botanicalName As List(Of String)
Public Property PlantID As PlantID
End Class
EDIT: Thanks to the link from @AngelWPF I have got the tree displaying my object. But, currently the tree looks like this:
*
*Herbs
*
*Common Name
*
*CommonName item from entry
*Another CommonName item from entry
*Common Name
*
*CommonName item from entry
*Another CommonName item from entry
How can I make this change to match my hierarchy?
XAML:
<UserControl.Resources>
<HierarchicalDataTemplate DataType="{x:Type my:herbEntry}">
<TreeViewItem Header="Common Name" ItemsSource="{Binding commonName}">
</TreeViewItem>
</HierarchicalDataTemplate>
</UserControl.Resources>
<Grid>
<TreeView HorizontalAlignment="Stretch" Name="TreeView1" VerticalAlignment="Stretch">
<TreeViewItem Header="Herbs" ItemsSource="{Binding herbs.Values}"/>
</TreeView>
</Grid>
A: This example may guide you to assign different item templates at different levels for each type of bound item ...
Having HierarchicalDataTemplates in a TreeView
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Referring to a value in a dropdown list in javascript I am building validation for my forms. I have covered the input text fields with the folowing code:
function validateForm_id()
{
var ctrl = document.forms["form1"]["id"];
var x=ctrl.value;
if (x==null || x=="") {
document.getElementById('id').style.backgroundColor="#FFD4D4";
document.getElementById("id").style.borderColor="#FF7A7A";
document.all.id.innerText = "password required";
I would like to validate the value from my select drop down boxes. The values are:
-- Select Title --
Mr
Mrs
Ms
I would like the user to not be able to submit if -- Title -- is the value from the box.
how do i refer to the first value of the dropdownbox in the if (x==null || x=="") of the above code? Here is my dropdown:
<select name="title" onKeydown="Javascript: if (event.keyCode==13) post();" onFocus="validation_title()" onBlur="return validateForm_title()" id="title">
<option>- Title -</option>
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Other</option>
</select> <div align="center" id="title" style="font-size:small; color:#FF0000;"><script type="text/javascript">document.all.title.innerText = " ";</script></div>
A: You can use the selectedIndex property of <select> to check out that the first index is never selected.
if (ctrl.selectedIndex == 0) { alert('The Title field is required'); }
A: var select = document.getElementById('mySelectID');
alert(select.options[0].value); //first option's value
alert(select.value); // currently selected value
To get option's text use
alert(select.options[select.selectedIndex].text);
A: var opts = yourSelectObj.options;
then loop on options.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632555",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: HTTP post and wininet I implement sending POST request by using the wininet library. I tried to use the different flags both in the HttpOpenRequest and in the PostInitWinInetHandle functions. The generated request contains the Cache-Control: no cache header always.
Does HTTP protocol allows sending POST request without this header? If so how can I eliminate adding this header to a request?
A: Don't use the flag INTERNET_FLAG_PRAGMA_NOCACHE.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to filter anchor tags that were received from the jquery .each() function I have a div that contains allot of anchor tags.
Some of them have a img as the in side of the tag.
I need to get all of the "a" that have regular text in them not a image tag or any other HTML tag.
How can this be done with jquery.
To get them all i just do:
$(element).find('a').each(function () {
...........
});
But how do i filter them using the .text() function or any thing else.
Thank you
A: You can use the not and has selectors
$(element).find('a').filter(':not(:has(*))').each(function() {
});
That says "find a elements, then filter that selection down to those that don't have child elements". :has(*) means "select elements that have any child elements", so :not(:has(*)) means "select elements that don't have any child elements".
You can combine the two selectors:
$(element).find('a:not(:has(*))').each...
However, this means that querySelectorAll won't work, so the selection will be considerably slower.
Live example at jsbin
A: You can use the .filter method to filter the matched set of elements to contain only those with text:
$("#example").find('a').filter(function () {
return $(this).text();
}).each(function() {
//Do stuff
});
Here's a working example.
A slight problem with the above may be the fact that $(this).text() will evaluate to true if there is any text node present within the a element. That includes a single empty space. To prevent that, you may want to trim the text:
$.trim($(this).text());
A: Try this simple and easy
$(element).find('a').not(":has('img')").each(function () {
...........
});
A: An idea: in the each block make the check this way:
$(element).find('a').each(function () {
if($(this).text() == $(this).html())
{
...........
}
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632563",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to display korean text on Textview? I want to display Korean text in my TextView. It should display proper Korean language but instead it's displaying junk chars. Any one know how to fix this?
Thanks in advance.
A: Android use a Unicode font, so it can display Korean character normally.
You can try change your text encoding of your project because its not android problem.
A: what you need is to load a korean font to the TextView, like Batang, BatangChe, Dotum..
This is similar question to yours: Display all Unicode chars in TextView
A: You require a True Type font(ttf) file to support the language it seems. copy and paste the korean font file into your assets folder and try this code.
TextView text = (TextView) findViewById(R.id.textView1);
Typeface font=Typeface.createFromAsset(activity.getAssets(), "fonts/yourfontname.ttf");
holder.text.setTypeface(font);
holder.text.setText(your_variable);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632568",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Linking Eclipe projects together using 'Deployment Assembly' and 'Build Path' options I have a simple java project with this basic structure:
*
*IncludeMe
*
*src
*deploy
*siteSpecific
-> site1
-> site2
-> etc...
I also have another project which I check out as a Dynamic Web project.
I add it to a tomcat7 instance and run it locally on my machine.
*
*MainWebApp
*
*src
*deploy
*WebContent
-> resources
-> templates
-> etc...
What I need is to include the 'siteSpecific' folder from the 'IncludeMe' project under the 'WebContent' directory in the 'MainWebApp' project.
So if I make a change to files under 'IncludeMe->siteSpecific', they are automatically picked up and applied by my MainWebApp under 'MainWebApp->siteSpecific' i.e. I do bot want to have to manually copy the contents between the two separate projects.
I currently do the following with no luck:
- Open 'properties' of 'IncludeMe' and go to 'Deployment Assembly'
- Select 'Add' and choose the 'SiteSpecific' folder.
- Source then reads '/siteSpecific' and I adjust the deploy path to be 'siteSpecific'
- Open 'properties' of 'MainWebApp' and go to 'Java Build Path'
- Go to 'projects' tab and add the 'IncludeMe' project.
I'm using Eclipse Indigo 3.7 by the way.
Any help appreciated
Thanks
A: This is a bit hacky solution but the only one I found when I needed something like this.
The trick is to link external source folder and then use it in "deployment assembly"
Do the following:
*
*Right click on Your webapplication project (MainWebApp)
*Build path
*Link source
*Variables (Here we will add variable that points to our external project, relative to our current project)
*New (add something like: "${PROJECT_LOC}..\IncludeMe" in "Location" and some name for new variable)
*OK
*Extend (You should extend variable You've created on prev. step).
*Pick right folder and press OK.
*Next.
*Add exclusion pattern to prevent eclipse from building anything from that folder.
*Finish
After this dancing You should be able to see linked folder in "deployment assembly"...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632578",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Sitecore Import language file feature - does it create language versions? Can anyone tell me what happens if I export a language file, rename all the language nodes to a different language (e.g. from en-US to en-GB) and then import it?
Are new language versions of the relevant items created? Or is content only imported if the language version exists?
Edit: corrected typo in title
A: Yes, the new language versions are created. However, the language item itself is not created (if it doesn't exist before). Hence, if you run a Database Clenup afterwards, for instance, it will remove these item versions.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to add style on html tag on android heres my code:
String tempStr = "The <b>quick</b> brown fox";
tvView.setText(Html.fromHtml(tempStr), BufferType.SPANNABLE);
What i want is to add a color to the tag. Tnx in advanced.
A: Hi you can use like this. you can set any style which is use in css:
String html = "<html><head><title></title> "
+ "<style type=\"text/css\"> "
+ "body {background-image:url('file:///android_res/drawable/background.png'); background-repeat: repeat-y; font-family:"
+ Fontname
+ "; } "
+ "</style> "
+ "</head><body ><div>"
+ "<p><FONT COLOR=\"#f7bd79\" >" + yourstring
+ "</FONT></p></div> </body></html>";
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Facebook like box won't work with Facebook connect I have both like box and connect on the same page and I am trying to get the html5 or xfbml code of the like box to work with Facebook connect but it won't. Only the iframe code will work but the thing is I can't customize anything in iframe. Any advice?
A: Have you got:
xmlns:fb="http://www.facebook.com/2008/fbml"
In your html open tag at the top of you page?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632585",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Memory does not go down when I press GoBack When GoBack I call function Dispose() in
private void Dispose()
{
ImageBrush brushRoot = LayoutRoot.Background as ImageBrush;
if (brushRoot != null)
{
((BitmapImage)brushRoot.ImageSource).UriSource = null;
brushRoot.ImageSource = null;
LayoutRoot.Background = null;
}
gridHeader_hotNews.Children.Clear();
gridHeader_hotNews = null;
if (grid_Two.Background as ImageBrush != null)
{
((BitmapImage)(grid_Two.Background as ImageBrush).ImageSource).UriSource = null;
(grid_Two.Background as ImageBrush).ImageSource = null;
grid_Two.Background = null;
}
if (btn_Two.Background as ImageBrush != null)
{
((BitmapImage)(btn_Two.Background as ImageBrush).ImageSource).UriSource = null;
(btn_Two.Background as ImageBrush).ImageSource = null;
btn_Two.Click -= new RoutedEventHandler(btn_Two_Click);
btn_Two.Background = null;
}
btn_Two = null;
grid_Two.Children.Clear();
grid_Two = null;
grid_Content.Children.Clear();
grid_Content = null;
if (grid_footer.Background as ImageBrush != null)
{
((BitmapImage)(grid_footer.Background as ImageBrush).ImageSource).UriSource = null;
(grid_footer.Background as ImageBrush).ImageSource = null;
grid_footer.Background = null;
}
if (btnspeaker.Background as ImageBrush != null)
{
((BitmapImage)(btnspeaker.Background as ImageBrush).ImageSource).UriSource = null;
(btnspeaker.Background as ImageBrush).ImageSource = null;
btnspeaker.Background = null;
}
btnspeaker = null;
grid_footer.Children.Clear();
grid_footer = null;
LayoutRoot.Children.Clear();
LayoutRoot = null;
GC.SuppressFinalize(this);
GC.WaitForPendingFinalizers();
}
but is still uses 3 to 5 MB. How do I recover the original memory when I call the GoBack event?
Please help me, I want memory released when back I Page or I Dispose of the Object.
A: The garbage collector only runs when it is required to run, so it won't necessarily run as soon as you run Dispose.
You can force the GC to collect by calling GC.Collect(); but this will probably have an effect on your apps performance. This is because when the GC runs it stops all executing threads in your application and checks each object in the heap to see if it is still referenced or in use. While the garbage collector is fast there will be an overhead to calling the GC repeatedly.
As the other people commenting have said, it's best to let the GC manage itself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632587",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting realtime output from ffmpeg to be used in progress bar (PyQt4, stdout) I've looked at a number of questions but still can't quite figure this out. I'm using PyQt, and am hoping to run ffmpeg -i file.mp4 file.avi and get the output as it streams so I can create a progress bar.
I've looked at these questions:
Can ffmpeg show a progress bar?
catching stdout in realtime from subprocess
I'm able to see the output of a rsync command, using this code:
import subprocess, time, os, sys
cmd = "rsync -vaz -P source/ dest/"
p, line = True, 'start'
p = subprocess.Popen(cmd,
shell=True,
bufsize=64,
stdin=subprocess.PIPE,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
for line in p.stdout:
print("OUTPUT>>> " + str(line.rstrip()))
p.stdout.flush()
But when I change the command to ffmpeg -i file.mp4 file.avi I receive no output. I'm guessing this has something to do with stdout / output buffering, but I'm stuck as to how to read the line that looks like
frame= 51 fps= 27 q=31.0 Lsize= 769kB time=2.04 bitrate=3092.8kbits/s
Which I could use to figure out progress.
Can someone show me an example of how to get this info from ffmpeg into python, with or without the use of PyQt (if possible)
EDIT:
I ended up going with jlp's solution, my code looked like this:
#!/usr/bin/python
import pexpect
cmd = 'ffmpeg -i file.MTS file.avi'
thread = pexpect.spawn(cmd)
print "started %s" % cmd
cpl = thread.compile_pattern_list([
pexpect.EOF,
"frame= *\d+",
'(.+)'
])
while True:
i = thread.expect_list(cpl, timeout=None)
if i == 0: # EOF
print "the sub process exited"
break
elif i == 1:
frame_number = thread.match.group(0)
print frame_number
thread.close
elif i == 2:
#unknown_line = thread.match.group(0)
#print unknown_line
pass
Which gives this output:
started ffmpeg -i file.MTS file.avi
frame= 13
frame= 31
frame= 48
frame= 64
frame= 80
frame= 97
frame= 115
frame= 133
frame= 152
frame= 170
frame= 188
frame= 205
frame= 220
frame= 226
the sub process exited
Perfect!
A: *
*Calling from the shell is generally not required.
*I know from experince that part of the ffmpeg output comes on stderr, not stdout.
If all you want to do is print the output line, like in your example above, then simply this will do:
import subprocess
cmd = 'ffmpeg -i file.mp4 file.avi'
args = cmd.split()
p = subprocess.Popen(args)
Note that the line of ffmpeg chat is terminated with \r, so it will overwrite in the same line! I think this means you can't iterate over the lines in p.stderr, as you do with your rsync example. To build your own progress bar, then, you may need to handle the reading yourself, this should get you started:
p = subprocess.Popen(args, stderr=subprocess.PIPE)
while True:
chatter = p.stderr.read(1024)
print("OUTPUT>>> " + chatter.rstrip())
A: In this specific case for capturing ffmpeg's status output (which goes to STDERR), this SO question solved it for me: FFMPEG and Pythons subprocess
The trick is to add universal_newlines=True to the subprocess.Popen() call, because ffmpeg's output is in fact unbuffered but comes with newline-characters.
cmd = "ffmpeg -i in.mp4 -y out.avi"
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,universal_newlines=True)
for line in process.stdout:
print(line)
Also note that in this code sample the STDERR status output is directly redirected to subprocess.STDOUT
A: This answers didn't worked for me :/ Here is the way I did it.
Its from my project KoalaBeatzHunter.
Enjoy!
def convertMp4ToMp3(mp4f, mp3f, odir, kbps, callback=None, efsize=None):
"""
mp4f: mp4 file
mp3f: mp3 file
odir: output directory
kbps: quality in kbps, ex: 320000
callback: callback() to recieve progress
efsize: estimated file size, if there is will callback() with %
Important:
communicate() blocks until the child process returns, so the rest of the lines
in your loop will only get executed after the child process has finished running.
Reading from stderr will block too, unless you read character by character like here.
"""
cmdf = "ffmpeg -i "+ odir+mp4f +" -f mp3 -ab "+ str(kbps) +" -vn "+ odir+mp3f
lineAfterCarriage = ''
print deleteFile(odir + mp3f)
child = subprocess.Popen(cmdf, shell=True, stderr=subprocess.PIPE)
while True:
char = child.stderr.read(1)
if char == '' and child.poll() != None:
break
if char != '':
# simple print to console
# sys.stdout.write(char)
# sys.stdout.flush()
lineAfterCarriage += char
if char == '\r':
if callback:
size = int(extractFFmpegFileSize(lineAfterCarriage)[0])
# kb to bytes
size *= 1024
if efsize:
callback(size, efsize)
lineAfterCarriage = ''
Next, you need 3 more functions to implement it.
def executeShellCommand(cmd):
p = Popen(cmd , shell=True, stdout=PIPE, stderr=PIPE)
out, err = p.communicate()
return out.rstrip(), err.rstrip(), p.returncode
def getFFmpegFileDurationInSeconds(filename):
cmd = "ffmpeg -i "+ filename +" 2>&1 | grep 'Duration' | cut -d ' ' -f 4 | sed s/,//"
time = executeShellCommand(cmd)[0]
h = int(time[0:2])
m = int(time[3:5])
s = int(time[6:8])
ms = int(time[9:11])
ts = (h * 60 * 60) + (m * 60) + s + (ms/60)
return ts
def estimateFFmpegMp4toMp3NewFileSizeInBytes(duration, kbps):
"""
* Very close but not exact.
duration: current file duration in seconds
kbps: quality in kbps, ex: 320000
Ex:
estim.: 12,200,000
real: 12,215,118
"""
return ((kbps * duration) / 8)
And finally you do:
# get new mp3 estimated size
secs = utls.getFFmpegFileDurationInSeconds(filename)
efsize = utls.estimateFFmpegMp4toMp3NewFileSizeInBytes(secs, 320000)
print efsize
utls.convertMp4ToMp3("AwesomeKoalaBeat.mp4", "AwesomeKoalaBeat.mp3",
"../../tmp/", 320000, utls.callbackPrint, efsize)
Hope this will help!
A: The only way I've found to get dynamic feedback/output from a child process is to use something like pexpect:
#! /usr/bin/python
import pexpect
cmd = "foo.sh"
thread = pexpect.spawn(cmd)
print "started %s" % cmd
cpl = thread.compile_pattern_list([pexpect.EOF,
'waited (\d+)'])
while True:
i = thread.expect_list(cpl, timeout=None)
if i == 0: # EOF
print "the sub process exited"
break
elif i == 1:
waited_time = thread.match.group(1)
print "the sub process waited %d seconds" % int(waited_time)
thread.close()
the called sub process foo.sh just waits a random amount of time between 10 and 20 seconds, here's the code for it:
#! /bin/sh
n=5
while [ $n -gt 0 ]; do
ns=`date +%N`
p=`expr $ns % 10 + 10`
sleep $p
echo waited $p
n=`expr $n - 1`
done
You'll want to use some regular expression that matches the output you're getting from ffmpeg and does some kind of calculation on it to show the progress bar, but this will at least get you the unbuffered output from ffmpeg.
A: I wrote a dedicated package that gives you a generator function for ffmpeg progress in Python: ffmpeg-progress-yield.
Simply run:
pip3 install ffmpeg-progress-yield
Then, simply do:
from ffmpeg_progress_yield import FfmpegProgress
cmd = [
"ffmpeg", "-i", "test/test.mp4", "-c:v", "libx264", "-vf", "scale=1920x1080", "-preset", "fast", "-f", "null", "/dev/null",
]
ff = FfmpegProgress(cmd)
for progress in ff.run_command_with_progress():
print(f"{progress}/100")
Note that this only works for input files where the duration is known in advance.
A: If you have the duration (Which you can also get from the FFMPEG output) you can calculate the progress by reading the elapsed time (time) output when encoding.
A simple example:
pipe = subprocess.Popen(
cmd,
stderr=subprocess.PIPE,
close_fds=True
)
fcntl.fcntl(
pipe.stderr.fileno(),
fcntl.F_SETFL,
fcntl.fcntl(pipe.stderr.fileno(), fcntl.F_GETFL) | os.O_NONBLOCK,
)
while True:
readx = select.select([pipe.stderr.fileno()], [], [])[0]
if readx:
chunk = pipe.stderr.read()
if not chunk:
break
result = re.search(r'\stime=(?P<time>\S+) ', chunk)
elapsed_time = float(result.groupdict()['time'])
# Assuming you have the duration in seconds
progress = (elapsed_time / duration) * 100
# Do something with progress here
callback(progress)
time.sleep(10)
A: You can also do it pretty clearly with PyQt4's QProcess (as asked in the original question) by connecting a slot from the QProcess to a QTextEdit or whatever. I'm still pretty new to python and pyqt but here's how I just managed to do it:
import sys
from PyQt4 import QtCore, QtGui
class ffmpegBatch(QtGui.QWidget):
def __init__(self):
super(ffmpegBatch, self).__init__()
self.initUI()
def initUI(self):
layout = QtGui.QVBoxLayout()
self.edit = QtGui.QTextEdit()
self.edit.setGeometry(300, 300, 300, 300)
run = QtGui.QPushButton("Run process")
layout.addWidget(self.edit)
layout.addWidget(run)
self.setLayout(layout)
run.clicked.connect(self.run)
def run(self):
# your commandline whatnot here, I just used this for demonstration
cmd = "systeminfo"
proc = QtCore.QProcess(self)
proc.setProcessChannelMode(proc.MergedChannels)
proc.start(cmd)
proc.readyReadStandardOutput.connect(lambda: self.readStdOutput(proc))
def readStdOutput(self, proc):
self.edit.append(QtCore.QString(proc.readAllStandardOutput()))
def main():
app = QtGui.QApplication(sys.argv)
ex = ffmpegBatch()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632589",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
} |
Q: how to optimize code for automatic Mapping? I would like to use something like AutoMapper for the following code instead of manual mapping.
I have two tables User and Role and both mapped with RoleID. now problem is if i am getting records from Users then it will gives me only RoleID instead of RoleName. so i tried to get result with custom class and mapped each entities with for loop (Manually).
Can anybody help to optimize this manual code to automatic. because i have more then 15 tables with relations.
// M O D E L
public class RoleModel : IRoleModel
{
public Guid RoleID { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
}
public class UserModel : IUserModel
{
public Guid UserID { get; set; }
public Guid RoleID { get; set; }
public string UserName { get; set; }
}
public class UserRoleModel
{
public Guid UserID { get; set; }
public string UserName { get; set; }
public string Description { get; set; }
public Guid RoleID { get; set; }
public string RoleName { get; set; }
}
// C O N T R O L L E R
public class UsersController : Controller
{
private IUserService _UserService;
public UsersController()
: this(new UserService())
{
}
public UsersController(IUserService UserService)
{
_UserService = UserService;
}
public ActionResult Index()
{
IList<UserRoleModel> users = _UserService.GetUsersWithRole();
return View(users);
}
public ActionResult Create()
{
return View();
}
}
// S E R V I C E
public class UserService : ServiceBase<IUserService, User>, IUserService
{
private IUserRepository _UserRepository;
public UserService()
: this(new UserRepository())
{
}
public UserService(IUserRepository UserRepository)
{
_UserRepository = UserRepository ?? new UserRepository();
}
public IList<UserRoleModel> GetUsersWithRole()
{
IList<User> users = _UserRepository.GetAll();
IList<UserRoleModel> userswithrol = new List<UserRoleModel>();
/* I would like to use AUTO MAPPER instead of MANUAL MAPPING*/
foreach (User u in users)
{
UserRoleModel ur = new UserRoleModel();
ur.UserID = u.UserID;
ur.UserName = u.UserName;
ur.Description = u.Description;
ur.RoleID = u.RoleID.Value;
ur.RoleName = u.Role.RoleName;
userswithrol.Add(ur);
}
/**/
return userswithrol;
}
private IList<UserModel> GetAll()
{
IEnumerable<User> alliance;
if (whereCondition != null)
alliance = _UserRepository.GetAll(whereCondition);
else
alliance = _UserRepository.GetAll();
UserListModel model = new UserListModel();
model.UserList = new List<UserModel>();
AutoMapper.Mapper.CreateMap<User, UserModel>().ForMember(dest => dest.UserID, opt => opt.MapFrom(src => src.UserID));
model.UserList = AutoMapper.Mapper.Map(alliance, model.UserList);
return model.UserList;
}
}
Any answer would be appreciated!
Thanks,
Imdadhusen
A: I have solved this question using following solution:
public IList<UserRoleModel> GetUsersWithRole()
{
IList<User> users = _UserRepository.GetAll();
IList<UserRoleModel> userswithrol = new List<UserRoleModel>();
AutoMapper.Mapper.CreateMap<User, UserRoleModel>()
.ForMember(d => d.UserID, o => o.MapFrom(s => s.UserID))
.ForMember(d => d.RoleName, o => o.MapFrom(s => s.Role.RoleName));
userswithrol = AutoMapper.Mapper.Map(users, userswithrol);
return userswithrol;
}
Note: i have just added single line of code to achieve desired output
.ForMember(d => d.RoleName, o => o.MapFrom(s => s.Role.RoleName))
Thanks,
Imdadhusen
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632595",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: The best way to read SQL Query using .NET and Oracle How can I get the result of a SQL query calculation?
Say, there are two cases"
CASE 1
RETURN "Process ok"
CASE 2
RETURN "Process failed"
This will be returned from the stored procedure.
Which is the best way to read this on .net, C# (Windows Forms)?
A: it's up to you to use DataReader if you think you can get multiple records, or an ExecuteScalar if you only get a single value, no records and no multiple columns, simply a string or an int...
here how to call a stored procedure and get a reader then read its first column:
using(var conn = new OracleConnection("Data Source=oracledb;User Id=UserID;Password=Password;"))
{
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "storedProcedurename";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(...);
conn.Open();
OracleDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
var yourResult = dr[0].ToString();
}
}
A: It depends on if you are invoking a stored procedure or if you are trying to get a record set back.
As for stored procedures it can either assign values to out or inout parameters or generate a record set. For the former you need to specify the parameter kind using the Direction property. As for the latter, everything works as a normal query except that you need to set command.CommandType to CommandType.StoredProcedure.
A typical SQL query looks like:
using (var cmd = connection.CreateCommand())
{
cmd.CommandText = "SELECT something FROM YourTable";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine(reader["something"]);
}
}
}
As for the database connection I do recommend that you use DbProviderFactory to generate it to get as generic code as possible: http://www.davidhayden.com/blog/dave/archive/2007/10/08/CreatingDataAccessLayerUsingDbProviderFactoriesDbProviderFactory.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Emulate limited resource device android I am trying to find a NullPointerException that I get when in my app the phone release memory. I was testing on a Samsung G3, but now that I have change for a GS2 which has more RAM memory, the variable is still there when I minimaze/maximize.
Is there any way to simulate my old phone and his limited RAM memory? A bit ironic,but now I miss it...In the SDK emulators I can set SD card size, but not the RAM, which I guess is the key problem here.
A: There is a program on the android market called CPU Master. You can set CPU speed so then you can test your program as in a phone with limited resources.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632611",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Pass parameters from form submission to specified route in Syfmony2 I have a route in my routing.yml which is as follows:
pattern: /admin/clients/{clientid}/projects/{projectid}/review/{id}/comments
defaults: { _controller: ShoutAdminBundle:Project:revcomm }
requirements:
_method: POST
Now, on a page (the comments page) I have a form where the user will enter a comment and then submit it to that page. Then the user clicks submit, they will be brought back to the same page but their comment will have been submitted to the database and then displayed.
My Form code looks like this:
<form action="{{ path('ShoutAdminBundle_adminprojectreviewcommentssuccess') }}" method="post" {{ form_enctype(form) }} class="blogger">
{{ form_errors(form) }}
<p class="comments">
{{ form_label(form.from, 'Your Name*', { 'attr': {'class': 'title'} }) }}
{{ form_errors(form.from) }}
{{ form_widget(form.from, { 'attr': {'class': 'textfield'}}) }}
</p>
<p class="comments">
{{ form_label(form.comment, 'Your Comment*', { 'attr': {'class': 'title'} }) }}
{{ form_errors(form.comment) }}
{{ form_widget(form.comment, { 'attr': {'class': 'textfield'}}) }}
</p>
<p class="comments_save">
<input type="submit" value="Post Your Comment" id="savebutton" class="savebutton" />
</p>
{{ form_rest(form) }}
</form>
Now. When the page is rendered I get the following error:
An exception has been thrown during the rendering of a template ("The
"ShoutAdminBundle_route" route has some missing mandatory parameters
("id", "projectid").") in
"ShoutAdminBundle:Default:projectreviewcomments.html.twig" at line 54.
How do I pass the variables {clientid}, {projectid} and {id} to the page? These variable are declared in the page already, it's a question of how do I include them in the form submission?
Cheers
A: You can pass them via your controller by using an associative array:
class ProjectController extends Controller
{
public function revcommAction($clientid, $projectid, $id)
{
// ...
$params = array(
'clientid' => $clientid,
'projectid' => $projectid,
'id' => $id
);
return $this->render('ShoutAdminBundle:Default:projectreviewcomments.html.twig', $params);
}
}
To render a link (or a path for the form action) to this controller in a template, you can use path() for relative and url() for absolute links. The second argument takes in any arguments required to construct the link, for example:
<a href="{{ path('my_route_name', {'clientid': clientid, ...}) }}"></a>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Click event not registered in IE, jQuery on div (jsfiddle) I've got html that looks like this:
<h3>Sample</h3>
<div class="skjemaHjelp" id="sample"><div><h3>3</h3><p>Content goes here</p></div></div>
<input type="text" class="inputWide" name="formSample" id="formSample" value="" />
The class skjemaHjelp is posisioned on the right side of the input-field and styled with a help-icon. The content within .skjemaHjelp div is hidden.
My jQuery looks like this:
$('.skjemaHjelp, .skjemaHjelpU').click(function () {
alert('debug');
}):
The alert-box appears in every browser, except IE. For some reason the event does not fire. I have no idea why. Are there any workarounds?
JSFiddle
http://jsfiddle.net/wJEPV/11/
Thomas
A: Assuming you're testing with IE lower than version 9 (or IE9 in a different Document Mode), the only problem with your jsFiddle is that the console object is not defined.
If you remove console.log('loaded');, it works in all versions of IE.
In earlier versions of IE, the console object is only defined when you open the Developer Tools (hit F12).
Alternatively, you can add something like this to make it always safe to use console.*:
// make it safe to use console.log always
(function(b){function c(){}for(var d="assert,clear,count,debug,dir,dirxml,error,exception,firebug,group,groupCollapsed,groupEnd,info,log,memoryProfile,memoryProfileEnd,profile,profileEnd,table,time,timeEnd,timeStamp,trace,warn".split(","),a;a=d.pop();){b[a]=b[a]||c}})((function(){try
{console.log();return window.console;}catch(err){return window.console={};}})());
(snippet taken from http://html5boilerplate.com/)
A: Add a tabindex="0" property to your div. This will make it fire the click event.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Netbeans disabled everything & became a simple text editor when I interupted the plugin upgrade process I switched off Netbeans while the plugins upgrade was in progress & then it has disabled everything. How do I get back everything that was available before? I've tried updating once again but it says:
Your IDE is up to date!
Probably it searches only for the few things remaining. It has become like a simple text editor :(
I don't want to lose my settings anyhow.. Using netbeans 7
EDIT:
I see that the plugins are still installed but they have been deactivated. When I try to activate them, it fails, giving out following message:
Activation failed: Not all requested modules can be enabled:
[StandardModule:org.netbeans.modules.ant.kit jarFile: C:\Program
Files\NetBeans 7.0\java\modules\org-netbeans-modules-ant-kit.jar,
StandardModule:org.netbeans.modules.form.kit jarFile: C:\Program
Files\NetBeans 7.0\java\modules\org-netbeans-modules-form-kit.jar,
StandardModule:org.netbeans.modules.versioning.system.cvss jarFile:
C:\Program Files\NetBeans
7.0\ide\modules\org-netbeans-modules-versioning-system-cvss.jar, StandardModule:org.netbeans.modules.hudson jarFile: C:\Program
Files\NetBeans 7.0\ide\modules\org-netbeans-modules-hudson.jar,
StandardModule:org.netbeans.modules.websvc.restkit jarFile: C:\Program
Files\NetBeans
7.0\enterprise\modules\org-netbeans-modules-websvc-restkit.jar, StandardModule:org.netbeans.modules.core.kit jarFile: C:\Program
Files\NetBeans 7.0\platform\modules\org-netbeans-modules-core-kit.jar,
StandardModule:org.netbeans.modules.web.primefaces jarFile: C:\Program
Files\NetBeans
7.0\enterprise\modules\org-netbeans-modules-web-primefaces.jar, StandardModule:org.netbeans.modules.apisupport.kit jarFile: C:\Program
Files\NetBeans
7.0\apisupport\modules\org-netbeans-modules-apisupport-kit.jar, StandardModule:org.netbeans.modules.subversion jarFile: C:\Program
Files\NetBeans 7.0\ide\modules\org-netbeans-modules-subversion.jar,
StandardModule:org.netbeans.modules.localhistory jarFile: C:\Program
Files\NetBeans 7.0\ide\modules\org-netbeans-modules-localhistory.jar,
StandardModule:org.netbeans.modules.spring.beans jarFile: C:\Program
Files\NetBeans 7.0\java\modules\org-netbeans-modules-spring-beans.jar,
StandardModule:org.netbeans.modules.j2ee.persistence.kit jarFile:
C:\Program Files\NetBeans
7.0\java\modules\org-netbeans-modules-j2ee-persistence-kit.jar, StandardModule:org.netbeans.modules.hibernate jarFile: C:\Program
Files\NetBeans 7.0\java\modules\org-netbeans-modules-hibernate.jar,
StandardModule:org.netbeans.modules.web.jsf.kit jarFile: C:\Program
Files\NetBeans
7.0\enterprise\modules\org-netbeans-modules-web-jsf-kit.jar, StandardModule:org.netbeans.modules.mercurial jarFile: C:\Program
Files\NetBeans 7.0\ide\modules\org-netbeans-modules-mercurial.jar,
StandardModule:org.netbeans.modules.debugger.jpda.ui jarFile:
C:\Program Files\NetBeans
7.0\java\modules\org-netbeans-modules-debugger-jpda-ui.jar, StandardModule:org.netbeans.modules.maven.kit jarFile: C:\Program
Files\NetBeans 7.0\java\modules\org-netbeans-modules-maven-kit.jar,
StandardModule:org.netbeans.modules.bugzilla jarFile: C:\Program
Files\NetBeans 7.0\ide\modules\org-netbeans-modules-bugzilla.jar,
StandardModule:org.netbeans.modules.web.kit jarFile: C:\Program
Files\NetBeans
7.0\enterprise\modules\org-netbeans-modules-web-kit.jar, StandardModule:org.netbeans.modules.java.kit jarFile: C:\Program
Files\NetBeans 7.0\java\modules\org-netbeans-modules-java-kit.jar,
StandardModule:org.netbeans.modules.ide.branding.kit jarFile:
C:\Program Files\NetBeans
7.0\nb\modules\org-netbeans-modules-ide-branding-kit.jar, StandardModule:org.netbeans.modules.spellchecker.kit jarFile:
C:\Program Files\NetBeans
7.0\ide\modules\org-netbeans-modules-spellchecker-kit.jar, StandardModule:org.netbeans.modules.web.struts jarFile: C:\Program
Files\NetBeans
7.0\enterprise\modules\org-netbeans-modules-web-struts.jar, StandardModule:org.netbeans.modules.websvc.saas.kit jarFile:
C:\Program Files\NetBeans
7.0\websvccommon\modules\org-netbeans-modules-websvc-saas-kit.jar, StandardModule:org.netbeans.modules.db.kit jarFile: C:\Program
Files\NetBeans 7.0\ide\modules\org-netbeans-modules-db-kit.jar,
StandardModule:org.netbeans.modules.profiler jarFile: C:\Program
Files\NetBeans 7.0\profiler\modules\org-netbeans-modules-profiler.jar,
StandardModule:org.netbeans.modules.websvc.kit jarFile: C:\Program
Files\NetBeans
7.0\enterprise\modules\org-netbeans-modules-websvc-kit.jar, StandardModule:org.netbeans.modules.ide.kit jarFile: C:\Program
Files\NetBeans 7.0\ide\modules\org-netbeans-modules-ide-kit.jar,
StandardModule:org.netbeans.modules.spring.webmvc jarFile: C:\Program
Files\NetBeans
7.0\enterprise\modules\org-netbeans-modules-spring-webmvc.jar, StandardModule:org.netbeans.modules.j2ee.kit jarFile: C:\Program
Files\NetBeans
7.0\enterprise\modules\org-netbeans-modules-j2ee-kit.jar]
A: The simplest way to fix this is to re-install NetBeans. I don't believe that your settings have been corrupted. So, in order to keep your settings, before you uninstall you'll need to export your settings.
*
*Open Options Dialog: Tools > Options
*Click Export button
*Choose a location and file name to use for the zip file
*Choose a category(s) to export
Note, that If a category is not enabled this means that you have not made any changes in that category.
If you have libraries defined and would like to save the configuration, you need to copy your build.properties file which is located in your .netbeans directory as exporting alone will not save this configuration (due to the fact that these settings should be able to be relocated on another machine and the libraries are specific to your machine). In Windows, your .netbeans directory is located in your user directory. For example, on my machine (Windows 7) this location is C:\Users\Jonathan\.netbeans.
After you've re-installed, import your settings back into the IDE and then replace the build.properties file.
A: I had the same problem, after trying some thinks the following two steps solve the problem:
*
*Locate the java folder, using this question
*Run the netbeans from its folder, specifying the jdkhome with the result of the previous step:
~/netbeans-X.X/bin/netbeans --jdkhome /usr/lib/jvm/java-7-openjdk-amd64/
A: I had the same problem after upgrading from java 7 to java 8. After wasting a few minutes, I discovered that netbeans wasn't seeing the right jdkhome. I solved the problem in two steps:
*
*In the netbeans installation folder, open the file netbeans.conf which is under etc directory. As for my case /home/his-kenya/netbeans-8.1/etc/netbeans.conf
*Set netbeans_jdkhome to point to the absolute location of your jdk. This should be on line 57 if the file hasn't been edited before. As for my case netbeans_jdkhome="/usr/lib/jvm/jdk1.8.0/"
Restart the IDE.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Control rs232 windows terminal program from python I am testing a piece of hardware which hosts an ftp server. I connect to the server in order to configure the hardware in question.
My test environment is written in Python 3.
To start the ftp server, I need to launch a special proprietary terminal application on my pc. I must use this software as far as I know and I have no help files for it. I do however know how to use it to launch the ftp server and that's all I need it for.
When I start this app, I go to the menu and open a dialog where I select the com port/speed the hardware is connected to. I then enter the command to launch the ftp server in a console like window within the application. I am then prompted for the admin code for the hardware, which I enter. When I'm finished configuring the device, I issue a command to restart the hardware's software.
In order for me to fully automate my tests, I need to remove the manual starting of this ftp server for each test.
As far as I know, I have two options:
*
*Windows GUI automation
*Save the stream of data sent on the com port when using this application.
I've tried to find an GUI automater but pywinauto isn't supporting Python 3. Any other options here which I should look at?
Any suggestions on how I can monitor the com port in question and save the traffic on it?
Thanks,
Barry
A: Have you looked at pySerial? It's been a few years since I've used it but it was quite good at handling RS-232 communications and it looks like it's compatible with Python 3.x.
A: Sikuli might provide the kind of GUI automation you need.
A: I was also able to solve this using WScript, but pySerial was the preferred solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Updating the version and dumping shared preferences into database I developed an android app ver 1.0 in which i stored the user data in shared preferences.
Now I am developing ver 2.0 and I have the following questions about updating it
1.How to detect if version 1.0 is already installed? I mean if it is a pure install(direct 2.0 install) or update from 1.0
2.If it is detected as 1.0 I want to dump the shared preferences values into database. Will the shared preferences be overwritten during update? How to prevent this? If they are not overwritten I want to write an activity which loads the values and dumps them into db
*
*What parameter should i set so that market gives notification that update is available. Should i set that in android manifest with same keystore?
Please kindly help me out
Thanking You,
ChinniKrishna Kothapalli
A: The Android Documentation has a part explaining how to update your apps.
Basically you increase the number of your android:versionCode in the manifest. You should also change the android:versionName field so your users can see it's a different version.
As for your problem with dumping preferences into a database: The preferences allow you to use a default value if a certain preference is not found (when the downloads a fresh install).
I'm not sure if there is a way of detecting wether your application has been installed or not, except if you have something like a database already in your earlier version, then you could just check if it exists or not. Might not be the best practice to solve this tough.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to set non-selectable default text on QComboBox? Using a regular QComboBox populated with items, if currentIndex is set to -1, the widget is empty. It would be very useful to instead have an initial descriptive text visible in the combo box(e.g. "--Select Country--", "--Choose Topic--", etc.) which is not shown in the dropdown list.
I couldn't find anything in the documentation, nor any previous questions with answers.
A: One way you can do something similar is to set a placeholder:
comboBox->setPlaceholderText(QStringLiteral("--Select Country--"));
comboBox->setCurrentIndex(-1);
This way you have a default that cannot be selected.
A: It doesn't appear that case was anticipated in the Combo Box API. But with the underlying model flexibility it seems you should be able to add your --Select Country-- as a first "legitimate" item, and then keep it from being user selectable:
QStandardItemModel* model =
qobject_cast<QStandardItemModel*>(comboBox->model());
QModelIndex firstIndex = model->index(0, comboBox->modelColumn(),
comboBox->rootModelIndex());
QStandardItem* firstItem = model->itemFromIndex(firstIndex);
firstItem->setSelectable(false);
Depending on what precise behavior you want, you might want to use setEnabled instead. Or I'd personally prefer it if it was just a different color item that I could set it back to:
Qt, How do I change the text color of one item of a QComboBox? (C++)
(I don't like it when I click on something and then get trapped to where I can't get back where I was, even if it's a nothing-selected-yet-state!)
A: Leaving my solution here from PyQt5. Create a proxy model and shift all the rows down one, and return a default value at row 0.
class NullRowProxyModel(QAbstractProxyModel):
"""Creates an empty row at the top for null selections on combo boxes
"""
def __init__(self, src, text='---', parent=None):
super(NullRowProxyModel, self).__init__(parent)
self._text = text
self.setSourceModel(src)
def mapToSource(self, proxyIndex: QModelIndex) -> QModelIndex:
if self.sourceModel():
return self.sourceModel().index(proxyIndex.row()-1, proxyIndex.column())
else:
return QModelIndex()
def mapFromSource(self, sourceIndex: QModelIndex) -> QModelIndex:
return self.index(sourceIndex.row()+1, sourceIndex.column())
def data(self, proxyIndex: QModelIndex, role=Qt.DisplayRole) -> typing.Any:
if proxyIndex.row() == 0 and role == Qt.DisplayRole:
return self._text
elif proxyIndex.row() == 0 and role == Qt.EditRole:
return None
else:
return super(NullRowProxyModel, self).data(proxyIndex, role)
def index(self, row: int, column: int, parent: QModelIndex = ...) -> QModelIndex:
return self.createIndex(row, column)
def parent(self, child: QModelIndex) -> QModelIndex:
return QModelIndex()
def rowCount(self, parent: QModelIndex = ...) -> int:
return self.sourceModel().rowCount()+1 if self.sourceModel() else 0
def columnCount(self, parent: QModelIndex = ...) -> int:
return self.sourceModel().columnCount() if self.sourceModel() else 0
def headerData(self, section: int, orientation: Qt.Orientation, role: int = ...) -> typing.Any:
if not self.sourceModel():
return None
if orientation == Qt.Vertical:
return self.sourceModel().headerData(section-1, orientation, role)
else:
return self.sourceModel().headerData(section, orientation, role)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: slideshow and overflow I can't make a div with an overflow to work properly..
the table inside the div with overflow has the same width as the div?!
http://jsfiddle.net/bRbyr/
div.slideshow_inner {
margin:12px 20px 0px 15px;
width:340px;
height:440px;
overflow:hidden;
background:blue;
}
#slideshow_film > tbody > tr > td {
width:340px;
background:red;
}
<div class="slideshow_inner">
<table id="slideshow_film">
<tr>
<td>PIC 1</td>
<td>PIC 2</td>
</tr>
</table>
</div>
A: You can either:
*
*Set width: 200% (number of pictures * 100) on #slideshow_film if you know the number of pictures beforehand:
http://jsfiddle.net/thirtydot/bRbyr/3/
*Or, you can stop using a table and use divs with display: inline-block and then white-space: nowrap on the parent:
http://jsfiddle.net/thirtydot/bRbyr/4/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Hiding TaskBar from a process (c#) In my application, I want to hide the windows TaskBar and StartMenuButton when my process is started and want to restore it when it exits.
I can do this using:
IntPtr startButtonHwnd = FindWindowEx(IntPtr.Zero, IntPtr.Zero, (IntPtr)0xC017, null);
IntPtr taskBarHwnd = FindWindow("Shell_TrayWnd", "");
ShowWindow(taskBarHwnd, 0);
ShowWindow(startButtonHwnd, 0);
and this is working fine for me.
Now I see a case where, if my process is crashed for some reason or is FORCIBLY killed by user, I won't be able to restore the TaskBar.
Is there any method of restoring it for these TWO (crash and killed) cases?
I am also interacting with Windows Gadget and I show a Gadget window when some button is clicked in my application, so I can not use properties like Form.TopMost = true & Screen.PrimaryScreen.Bounds
Thanks,
Vikram
A: You can cater for most crashes by putting the restore code in a global exception handler. You can do this by setting up an unhandled exception handler
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
ShowWindow(taskBarHwnd, 0);
ShowWindow(startButtonHwnd, 0);
}
This won't cater for the case where the program is killed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dependencies between PHPUnit tests I'm writing a PHPUnit test case for an API (so not exactly a unit test) and I'm thinking about having a test that all other tests will depend on.
The tests in the test case make API requests. Most of these requests require a user. The test in question will create that user that the other tests will use.
Would that be a horrible idea?
A: I think that the best way for unit tests is to eliminate the dependencies first.
*
*You can abstract the end point with your own local version that will return predictible results. This way you can test that your requests are correct.
*You can abstract the data providers (database, filesitem, etc...) with your stubs that will also return predictible data (username, etc..).
After that you just test your request and see they are correct..
The second part is to actualy test the data providers, with different tests, so you know that the good username will be given.
And then you can test the API connectivity, etc..
EDIT. If you have dependencies in your code, and it's difficult to abstract the providers or the end point web service, you may need to adjust your code so that it will accept references to those objects as parameters. Than in your tests you change the objects passed with your own stub objects. In production you pass the correct references, so that you will not need to change your code for testing.
I hope i have been clear. If not, ask me and i can explain better, maybe i did not understand your question well
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to disable a Gallery's item? I have a gallery where I have implement a custom adapter extending the BaseAdapter. For some items, I want them to be disabled, and not clickable as well.
Overriding the isEnabled(int) method doesn't work. I am still able to click on the disabled items, and then, the gallery centers this item inside it.
Any ideas?
A: This following is the relevant source code of gallery widget
public boolean onSingleTapUp(MotionEvent e) {
if (mDownTouchPosition >= 0) {
// An item tap should make it selected, so scroll to this child.
scrollToChild(mDownTouchPosition - mFirstPosition);
// Also pass the click so the client knows, if it wants to.
if (mShouldCallbackOnUnselectedItemClick || mDownTouchPosition == mSelectedPosition) {
performItemClick(mDownTouchView, mDownTouchPosition, mAdapter
.getItemId(mDownTouchPosition));
}
return true;
}
return false;
}
As you can see, the gallery scrolls to the tapped child item before performing the click on it.
So the only way you can truly disable an item is by extending Gallery and overriding onSingleTapUp(MotionEvent e) in it.
@Override
public boolean onSingleTapUp(MotionEvent e) {
int itemPosition = pointToPosition((int) e.getX(), (int) e.getY());
if (item at itemPosition is disabled) {
// Do nothing.
return true;
}
return super.onSingleTapUp(e);
}
Try and let me know.
A: Try the below code where you can handle the click event for specific positions. Also you can disable the specific items.
public class SplashActivity extends Activity{
private Activity _activity;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Gallery g = new Gallery(this);
g.setAdapter(new ImageAdapter(this));
setContentView(g);
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
private Integer[] mImageIds = {
R.drawable.menu1,
R.drawable.menu2,
R.drawable.menu3,
R.drawable.menu4,
R.drawable.menu1,
R.drawable.menu2,
R.drawable.menu3,
R.drawable.menu4
};
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageResource(mImageIds[position]);
i.setLayoutParams(new Gallery.LayoutParams(150, 100));
i.setScaleType(ImageView.ScaleType.FIT_XY);
i.setBackgroundResource(mGalleryItemBackground);
if(position!=0){
i.setEnabled(false);
i.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(SplashActivity.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
return i;
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding Windows system sound Playing a system sounds is simple. However, when looking at the ControlPanel->Sounds->Sounds, I see some programs like Itunes and TortoiseSVN have added custom sounds. How to achieve that? I was not able to find anything.
Thanks,
/Patrick
A: Custom sounds are defined in registry under HKEY_CURRENT_USER\AppEvents. You will find EventLabels and Schemes there linked together and referencing media flies for certain events. AFAIK there it no API to manage those, so you have to work with registry directly if you want to add your own sounds.
Playing custom events will still be simple, as you already noticed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to keep text inserted in a html after a wrong submission? Suppose I have a form like this:
<form action="page.php" method="post">
Section1: <input name="section1" type="text"></br>
Section2: <input name="section2" type="text"></br>
Text:</br>
<textarea name="post_text" cols="100" rows="20"></textarea>
<input name="submit" type="submit" value="Submit">
</form>
Usually if I wish to save content inserted in a field of the form I would use this statement:
Section1: <input name="section1" type="text" vale="value="<?php echo $_POST['section1']; ?>""></br>
This way if I make a mistake in submission (error control code is not posted) the values inserted will be kept, and there is no need to reinsert them.
However using it in the textarea tag it will not produce the desired result.
Any ideas on how to do?
Thanks in advance!
A: Don't forget about htmlspecialchars(). This should help: https://developer.mozilla.org/en/HTML/Element/textarea
<textarea name="post_text" cols="100" rows="20"><?php echo htmlspecialchars($_POST['post_text']);?></textarea>
A: You could use the same approach, but put the echo between the opening and closing <textarea></textarea> tags, as the textarea doesn't have a 'value' (as such) it has textual content:
<textarea name="post_text" cols="100" rows="20"><?php echo $_POST['textareaContent']; ?></textarea>
A: Use the $_POST variable like this.
<textarea name="post_text" cols="100" rows="20"><?= isset($_POST['post_text'])?$_POST['post_text']:'' ?></textarea>
the inline conditional checks if the $_POST['post_text'] is set to remove the NOTICE warning
A: You would put it inside the <textarea> element like so:
<textarea name="post_text" cols="100" rows="20"><?php echo $_POST['post_text']; ?></textarea>
However, calling the $_POST element directly is not best practice. You should rather do something like this:
<textarea name="post_text" cols="100" rows="20">
<?php echo $var = isset($_POST['post_text']) ? $_POST['post_text'] : ''; ?>
</textarea>
This stops an E_NOTICE error from being reported upon the first page-load.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SVN - User responsible for line in source file I pretty stuck with situation in which I need to get user responsible for specific file, line and revision.
E.g. I have as input: source name, line number and revision. As output I need get user name.
I not so familiar with SVN and looking into documentation might take time (which I don't have).
In Clear Case it can be achieved by running this command:
cleartool annotate -nhe -fmt %u \t file_name.cpp
A: svn blame
is what you are looking for
http://svnbook.red-bean.com/en/1.0/re02.html
A: svn ann -r revision_number source_name
Then go to line number in svn output
#svn help ann
blame (praise, annotate, ann): Output the content of specified files or
URLs with revision and author information in-line.
usage: blame TARGET[@REV]...
If specified, REV determines in which revision the target is first
looked up.
Valid options:
-r [--revision] ARG : ARG (some commands also take ARG1:ARG2 range)
A revision argument can be one of:
NUMBER revision number
'{' DATE '}' revision at start of the date
'HEAD' latest in repository
'BASE' base rev of item's working copy
'COMMITTED' last commit at or before BASE
'PREV' revision just before COMMITTED
-v [--verbose] : print extra information
-g [--use-merge-history] : use/display additional information from merge
history
--incremental : give output suitable for concatenation
--xml : output in XML
-x [--extensions] ARG : Default: '-u'. When Subversion is invoking an
external diff program, ARG is simply passed along
to the program. But when Subversion is using its
default internal diff implementation, or when
Subversion is displaying blame annotations, ARG
could be any of the following:
-u (--unified):
Output 3 lines of unified context.
-b (--ignore-space-change):
Ignore changes in the amount of white space.
-w (--ignore-all-space):
Ignore all white space.
--ignore-eol-style:
Ignore changes in EOL style
-p (--show-c-function):
Show C function name in diff output.
--force : force operation to run
Global options:
--username ARG : specify a username ARG
--password ARG : specify a password ARG
--no-auth-cache : do not cache authentication tokens
--non-interactive : do no interactive prompting
--config-dir ARG : read user configuration files from directory ARG
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: div buttons not working in internet explorer I'm having trouble making the div buttons on this simple slideshow to work. I've used jQuery and I've tried to stay away from things that don't work in IE (e.g. split).
The IE debugger shows that the div with the id "next" is properly placed, and i've found no errors in my javascript. Still, the div doesn't have the click event binded and the css style of cursor: pointer isn't applied.
How should I solve this problem?
Many thanks.
A: Shadow Wizard's comment was spot on. After realizing that this is a z-index bug, i've checked the squish-the-internet-explorer-z-index-bug link for clues but that didn't work for me so, since i was under time pressure, i've decided to replace the <img>tag with a div and set background on it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632666",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cannot access pdf file from raw resources I created an android pdf reader using MuPdf library. My problem is when I change the uri to access the pdf file from the raw resources, Uri uri = Uri.parse("android.resource/[package]/" + R.raw.[pdf]), i get a java.lang.RuntimeException error. But when i change the uri to access the pdf file from the sd card, Uri uri = Uri.parse("file:///sdcard/[pdf]") , i will have no error and it reads and displays the pdf file successfully. My main goal is to read and display a pdf file from the resources, not from the sd card. Do you have any idea on how to solve this?
A: Do this, it works for me :)
Uri uri = Uri.parse("android.resource://com.xxx.appname/raw/pdfId");
A: Does not work for me!
String path="android.resource://com.artifex.mupdfdemo/raw/"
+ String.valueOf(R.raw.example_katalog);
results in
08-05 15:26:50.748: E/libmupdf(18977): Failed: Cannot open document: '/raw/2131034112'
Is there a working solution for this problem?
A: Try this
Uri uri = Uri.parse("android.resource://"+getPackageName()+"/raw/" + "pdfname");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(getContentResolver().openInputStream(uri)));
...
} catch ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How could I use a different strategy for just one commit in a rebase? Given this:
master A---B---G---H---I
\
branch C---D---E---F
Is there anyway to get to the following, but using -X theirs only for the C commit?
master A---B---G---H---I
\
branch C'--D'--E'--F'
(I've created a branch for migrating a big solution from VS2008 to VS2010. The first commit on the branch was the one that changed all the project files. Now I would like to update the branch to get the latest changes, but without having to manually merge any conflicts arising from tool-generated code)
A: This obvious rebasing step, pulled straight from the manuals doesn't work?
git checkout branch
git rebase master
A: You could try to:
*
*merge first C to master, using one the the merge --strategy=theirs detailed in this SO answer.
*then git rebase master (which shouldn't repeat commit C, since it has already been merged and is identical to the C of branch).
A: guess, you can use cherry-pick to apply one commit anywhere you want:
git checkout master
git cherry-pick -x C
this will apply C patch to master. then you can rebase your branch on master, because it will contain C inside
git checkout master
git rebase master
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to upload an image using jQuery / AJAX in an ASP.NET MVC website? I'm trying to find a decent way of allowing users to upload a profile photo on an edit profile page.
I've tried out Uploadify but this doesn't appear to work under some of the more recent Google Chrome browser releases.
Ideally, I just want to offer the user the ability to replace a placeholder profile image with an image of their own, via a simple upload button (preferably ajax), and once an image has been upload, to show a 'delete' button to remove the uploaded photo and re-instate the default placeholder image.
Are there any other alternatives that play nicely across all the main browsers and integrate easily into an MVC application?
A: To upload with jQuery only with HTML 5, and not all browser are able to this.
You can do something like this.
You need to have a IFRAME that 'll be use to make the post with the file.
Like this:
<iframe id="targetUpload" name="targetUpload"></iframe>
In the form you set the target to the iframe.
<form target="targetUpload" name="file" runat="server" method="post" id="file" enctype="multipart/form-data" action="@Url.Content("~/Controller/Upload")">
And a submit button
<input type="Submit" value="Upload">
This is a way to upload files without refresh the page.
You can treat the files before upload with jquery. (File type, size, etc...)
And in yout controller you recive the files:
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
//Save the file in the server path
string savePath = Server.MapPath("~/Upload/");
string fileName = file.FileName;
savePath += fileName;
file.SaveAs(savePath);
}
return RedirectToAction("Index");
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Image download from browser I have a problem downloading an image from a web browser. I want to download the image directly, but instead it's opened in the browser. I'm using asp.net.
My HTML code:
<a href ="http://example.com/file/image.jpg" target="_blank" /> Download </a>
A: What you need to do here is to modify the HTTP headers to in a way that requests the browser to show the "File Dialog" box for your image instead of simply displaying it on screen.
To do this you need to modify the Content-Disposition header and set it to attachment. To do this in ASP.NET you can do the following:
Response.Clear()
Response.AppendHeader("Content-Disposition", "attachment; filename=somefilename")
but make sure you do this before you respond with the file.
You might also want to change the following:
Response.ContentType = "image/jpeg"
This will allow the browser to regonise and display the image icon in the File Dialog box. To finally send the file you would then call:
Response.TransmitFile(Server.MapPath("/myimage.jpg"));
Response.End();
However please realise all you are doing here is modifying what the server requests of the browser - it is not bound in anyway carry it out.
A: Try the following method (assuming you're using c#)
Response.ContentType = "image/jpg";
Response.AppendHeader("Content-Disposition", "attachment; filename=myimage.jpg");
Response.TransmitFile(Server.MapPath("/images/image.jpg"));
Response.End();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: IE8 Opacity Issue I understand that there has been countless of question posted here regarding opacity issues on IE. I have gone through almost everyone of them and have tried almost every available method that I have managed to source to but nothing worked.
The strangest thing is that the opacity issue is an isolated case, occurring only on IE8; IE7 had no issues with it whatsoever. Before I proceed to speak more about the problem I'm facing, let me show you a sample of my markup in a single page HTML site that I am developing:
This is the CSS controlling the opacity for the DIVs in question:
#home, #services, #freeport, #about-us, #advantage, #contact{
opacity:0;
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
width:400px;
zoom:1;
}
And this is the JQUERY I have used to control their opacity settings:
$(document).ready(function(){ //fades in the menu div first followed by the home div
(function _loop( nodelist ) {
$( nodelist.shift() ).fadeTo( 2400, 1, function() {
_loop( nodelist );
});
}( ["#menu", "#home"] ));
$("#about-us-button").click(function(){ //upon clicking the home button, fades in the home div and fades out the rest of the divs
$("#about-us").fadeTo(900, 1);
$("#home, #freeport, #advantage, #services, #contact").fadeTo(1000, 0);
});
});
NOTE: I have only shown how the #about-us div fades in upon clicking the #about-us-button; the rest of the sections work the same way. Also left out the HTML because it's pretty straight forward - DIV container holding some text, that's it.
So applying the CSS styles mentioned above, I have managed to get the DIVs to appear at the correct instances in all the browsers (including IE7) except IE8.
What puzzles me most is that filter works in IE7, but -ms-filter which is supposedly IE8 specific failed to work. I've read about the HasLayout issue and applied all the methods to no avail. I have also made sure that -ms-filter came before filter but that didn't work either.
I resorted to also making IE8 emulate IE7 with the meta tag method, but unfortunately, that failed as well.
It should be noted that I have marked this up as HTML5 and after running into this issue, I have marked it down to XHTML 1.0 Transitional and HTML 4.0, but nothing worked - not even the IE8 as IE7 method.
Anyone has any idea what could be done to resolve this? Thanks in advance guys!
A: I ran into a similar issue not too long ago. I don't remember the precise details, but I believe what happened was that jQuery would set an opacity value at the element level, constantly changing it as it faded in--and then once the fade was complete would leave the attribute there, but blank, overriding the CSS file opacity. You should be able to doublecheck this with Firebug or the Element Inspector in Chrome.
I believe this is what I used to fix the error, forcing jQuery to clean up that attribute when it was done so the opacity attribute specified in my CSS file could actually take effect. Of course, tweak it to fit properly in your code.
$("#darkbg, #popup-movie-panel").fadeIn(300, function(){
if(jQuery.browser.msie) {
this.style.removeAttribute('filter');
}
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632686",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to rewrite a hardware linux driver for android use recently, i am doing a school project on a beagleboard which has android 2.2 ported.the beagleboard is like this.
I have to connect a sensor called phidgets 1056 to the board.
However, the drivers provider only got linux driver for the board.
the linux driver is available here.
Is it possible to rewrite the source code in the linux driver so that android can use them???
If it is, how can i make it ?
I really need help now, so thanks
A: The Android OS is just another version of Linux. If the drivers are flexible enough all you would have to do is include them in the Android libs. For custom Android libs check this out If they aren't flexible enough you will have to at the least compile the source code if you have access to it then deploy it on the Android OS.
Try this site Custom KO and to create an Android image..
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Mono.Math.BigInteger is inaccessible due to its protection level So I'm working on a program in C# using ideone and I'm working with Mono for the first time. I'm trying to use the BigInteger class (Mono.Math.BigInteger) but I keep getting errors. Here's me code below. What is going on and how do I fix it? Thanks.
using System;
using Mono.Math;
public class TFIB
{
public static int Main()
{
const int FIB_SEQUENCE_SIZE = 300;
BigInteger[] FibonacciSequence = new BigInteger[FIB_SEQUENCE_SIZE];
// Calculate Fibonacci Sequence
FibonacciSequence[0] = 0;
FibonacciSequence[1] = 1;
for (int i = 2; i < FIB_SEQUENCE_SIZE; i++)
{
FibonacciSequence[i] = FibonacciSequence[i - 1] + FibonacciSequence[i - 2];
}
while (true)
{
string[] tokenInput = Console.ReadLine().Split(' ');
Mono.Math.BigInteger lowerBound = Mono.Math.BigInteger.Parse(tokenInput[0]);
BigInteger upperBound = BigInteger.Parse(tokenInput[1]);
if (lowerBound == 0 && upperBound == 0)
{
break; // ending sequence found
}
else
{
// find the number of fibonacci sequences
int numbersInRange = 0;
for (int i = 0; i < FIB_SEQUENCE_SIZE; i++)
{
if (FibonacciSequence[i] >= lowerBound)
{
if (FibonacciSequence[i] <= upperBound)
{
numbersInRange++;
}
else
{
continue; // there is nothing more to find
}
}
}
Console.WriteLine(numbersInRange);
}
}
return 0;
}
}
These are the errors I'm getting:
prog.cs(9,13): error CS0122: Mono.Math.BigInteger' is inaccessible due to its protection level
/usr/lib/mono/2.0/mscorlib.dll (Location of the symbol related to previous error)
prog.cs(9,23): error CS0122:Mono.Math.BigInteger[]' is inaccessible due to its protection level
/usr/lib/mono/2.0/mscorlib.dll (Location of the symbol related to previous error)
prog.cs(23,27): error CS0122: Mono.Math.BigInteger' is inaccessible due to its protection level
/usr/lib/mono/2.0/mscorlib.dll (Location of the symbol related to previous error)
prog.cs(24,17): error CS0122:Mono.Math.BigInteger' is inaccessible due to its protection level
/usr/lib/mono/2.0/mscorlib.dll (Location of the symbol related to previous error)
Compilation failed: 4 error(s), 0 warnings
A: Mono.Math.BigInteger is in the Mono.Security.dll, are you sure you are referencing the right assembly? The compilation errors you are getting suggest you aren't.
While BigInteger is used (internally) inside mscorlib.dll, you can't reference it from there.
Alternatively, there's the 4.0 System.Numerics.BigInteger implementation that you can use by changing your using to System.Numerics and referencing System.Numerics.dll, but it doesn't look as optimized as the Mono.Math one, at least for now.
Unfortunately, Ideone does not seem to allow customizing assembly references, which means that you won't be able to compile either solution at all. You can only file a bug with Ideone.com.
A: Try targeting the .NET 4.0 framework (using dmcs)
Also, from this page:
Yes, but then see this:
http://blogs.msdn.com/bclteam/archive/2007/04/20/visual-studio-code-
name-orcas-beta-1-has-been-released-inbar-gazit.aspx
In particular:
some good and constructive feedback from customers and partners that
are interested in extended numerical types. We have learned that there
are some potential improvements that we can make to this type to better
serve their needs. As such, we decided to remove BigInteger from the
Beta 1 release of Orcas so that we can address these issues and
concerns. -- Jon Skeet"
A: Given that you can't reference the assembly, just add BigInteger.cs to your project directly. Source can be found here: https://github.com/mono/mono/blob/master/mcs/class/Mono.Security/Mono.Math/BigInteger.cs
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632692",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: what is a non-destructive version of set in lisp? I would like to be able to say (defvar x y) and have it bind to the symbol bound to x instead of x, but defvar will only bind it to the symbol x, which is too bad. How can I do this without defaulting to adding it a a property of the symbol?
A: You can use the symbol-value accessor:
CL-USER> (defvar *sym* 'abc)
*SYM*
CL-USER> (setf (symbol-value *sym*) 100)
100
CL-USER> abc ;non-ANSI-portable, since ABC is undeclared
100
Note that this sets the symbol's value cell, which is the same as its dynamic binding, so in order to portably access it, you either need to use symbol-value all the time or (either locally or globally) declare the variable special. You can do this locally like this:
CL-USER> (locally (declare (special abc))
(+ abc 3))
103
or globally by using defvar (which isn't recommended for non-earmuffed symbols):
CL-USER> (defvar abc)
ABC
(I know of no CL implementation that actually requires this, though. You're usually safe assuming that undeclared variables are assumed special by default.)
A: In addition to Matthias' answer:
You could also use set
T1> (defparameter *symbol* 'foo)
*SYMBOL*
T1> (set *symbol* 100)
100
since (set symbol value) == (setf (symbol-value symbol) value), i.e. in contrast to setq and setf, set evaluates its first argument. (setq could be read as "set quoted") set is marked deprecated in the Hyperspec, but since I don't really expect the next CL standard anytime soon, it should be safe to use.
Also, I don't think you'd have to use symbol-value or any special declarations in order to portably access it -- At least for all practical purposes. (While one could maybe argue that, technically, since one cannot rely on the modified symbol even being locally special, maybe the variable wouldn't be evaluated via symbol-value, but see the referenced Naggum post below, and Matthias' last sentence.)
It is true, that setq, setf, set et al. are only guaranteed to modify bindings for conforming implementations. When used at toplevel, the symbol-value will be modified, but you can't rely on any global special declaration (or anything else) taking place (cf. Naggum). But usually, implementations will at least make evaluating the new variable use the symbol-value slot. This doesn't mean that one has to use symbol-value or local/global special declarations in order to access the symbol-value, but it does mean, that a new binding of the same symbol won't be automatically special, as it would be the case with variables introduced via defparameter and friends.
So, while usually, with global special variables:
T1> (let ((*symbol* 'bar))
(symbol-value '*symbol*))
BAR
A new binding to a non global special will itself not be special:
T1> (let ((foo 101)) ; this new binding is lexical
(symbol-value 'foo)) ; so symbol-value refers to the outer special
100
T1> (let ((foo 101))
foo) ; evaluation of foo's new lexical binding
101 ; doesn't look at the `symbol-value`. lexical
; bindings are mere addresses at runtime.
And that's also where the local special declaration could be used in order to reference the outer, (not globally) special binding of foo:
T1> (let ((foo 101))
foo) ; our new lexical binding
101
T1> (let ((foo 101))
(locally (declare (special foo))
foo)) ; the outer special binding
100
T1> (let ((foo 101))
(setq foo 102) ; modify the new lexical binding
foo)
102
T1> foo ; doesn't modify the outer special binding
100
T1> (let ((foo 101))
(locally (declare (special foo))
(setq foo 102) ; modify the outer special binding
foo))
102
T1> foo
102
As far as I understand, the undefined part, or at least the one where you should expect portability problems, is whether such toplevel modifications might declare something (globally) special or not. The behavior I would expect is what I have shown here, but if the variable will be declared globally special or not (or maybe even introduce a toplevel lexical variable?) as long as it is at least made locally special, one won't need local declarations or symbol-value to access it.
Also, you should consider if you really need what you've asked for. It's likely that what you want to do could be solved in a more idiomatic (at least for modern Lispers) way, and relying on undefined behavior would not be considered good style by most for anything but REPL use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Infopath 2010 get culture from hosting environment I am looking into localizing the labels of an InfoPath 2010 form with code-behind that will be hosted in SharePoint as a browser form and get the current culture (based on the SharePoint variations) programatically in the InfoPath form. How do I do this?
A: You can get culture by using the SPWeb's Locale Property. You will have to reference the Microsoft.SharePoint.dll in your InfoPath project to get this to work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java, configure enterprise application and web application with spring: should they share the spring context? I have an event-driven application based on spring-integration.
The application is made up of 4 modules: domain (model objects), persistence (daos), core (biz logic based on spring-integration) services (MDB).
Every module is a maven project. The application is packaged in a EAR and deployed on weblogic.
The spring context is shared among all the modules.
Now I have to develop a web-application to expose a subset of the domain: so my controllers should use some daos and some domain objects.
What is the best practice to handle this problem? Should the web application share all the ear spring context?
Or is better to create a "ad hoc" web application spring context where I redefine all what I need? (e.g. daos).
A: Seems like you would benefit from a functional layering, e.g. instead of
|- persistence (daos)
|- domain (model objects)
|- core (biz logic based on spring-integration)
|- services (MDB)
You could layer your application in a functional way. Let's say your app does trading:
|- broker
|- product
|- underlying
|- option
|- future
|- forward
|- ..
|- feed
|- valuation
|- ...
Under broker you would have broker-persistence, broker-service, etc.. Of course the business domain of your app is probably different, and this is a naive example, but it illustrates the point.
This way you can still include everything in your EAR, with a lot greater flexibility on what can be included/imported into you webapp.
For example, you can even create a broker.war separate from a product.war. Which also means that you can redeploy a broker.war without bringing down the product.war. You may not need it in your business domain, but it is a nice ability to have, which can only be reached when things are layered according to the business need/area, rather than a tech stack.
By the way no need to complicate things with EAR just for MDBs, you can use Spring's Message Driven POJOs which will be simply controlled by a Spring container.
A: Normally, you create a specific WebApplicationContext for each DispatcherServlet in which you put all web related stuff, e.g. controllers, handlermapping, viewresolvers, etc. The rest of your application context(s) e.g. services, daos, etc, is / are configured in a root WebApplicationContext that is shared by all servlets.
Example web.xml:
<web-app ...>
<!-- Definition of the root web application context and shared by all servlets -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dao-config.xml,/WEB-INF/other-config.xml</param-value>
</context-param>
<!-- Must be added to enable the configs above -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Servlet specific application context that inherits bean definitions from the root application context. By convention, it is located in in /WEB-INF/[servlet-name]-servlet.xml -->
<servlet>
<servlet-name>yourservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>yourservlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
Scroll down to the picture "Context hierarchy in Spring Web MVC" in the Spring MVC Reference Documentation for overview and more details.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ads.getCampaignStats - Managing advertisements requires the extended permission ads_management, and a participating API key I'm trying to get out some statistics from my campaigns using the ads.getCampaignStats graph api call but I get this error :
"error_code": 294,
"error_msg": "Managing advertisements requires the extended permission ads_management, and a participating API key"
I'm using the facebook php api v3.1.1. This is the code that perfom the login authentication :
define('FACEBOOK_APP_ID', 'xxxxx');
define('FACEBOOK_SECRET', 'xxxxxxxxxxxxx');
// Remember to copy files from the SDK's src/ directory to a
// directory in your application on the server, such as php-sdk/
require_once('src/facebook.php');
$config = array(
'appId' => FACEBOOK_APP_ID,
'secret' => FACEBOOK_SECRET,
);
$facebook = new Facebook($config);
$user_id = $facebook->getUser();
if($user_id) {
try {
$result = $facebook->api(array(
"method" => "ads.getCampaignStats",
"account_id" => "xxxxxx",
"ext_perm" => "ads_management",
"campaign_ids" => json_encode(array("xxxxxxxxxx")),
"time_ranges" => "[\"time_start\":1284102000,\"time_stop\":1284447600]"));
var_dump($result);
} catch(FacebookApiException $e) {
// If the user is logged out, you can have a
// user ID even though the access token is invalid.
// In this case, we'll get an exception, so we'll
// just ask the user to login again here.
$login_url = $facebook->getLoginUrl(array(
'scope' => 'ads_management'));
echo 'Please <a href="' . $login_url . '">login.</a>';
error_log($e->getType());
error_log($e->getMessage());
}
} else {
// No user, print a link for the user to login
$login_url = $facebook->getLoginUrl(array(
'scope' => 'ads_management'
));
echo 'Please <a href="' . $login_url . '">login.</a>';
}
The same thing happen if I'm using the test consol given by facebook on the link below : ads.getCampaignStats - test console.
Any ideas? what I'm doing wrong? Any help will be really appreciated.
Thanks to all.
A: you have to give permissions to an account with ads api access.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Delay is not working Why this is not working
$('#upload-title').css({ background: '#ffffff' }).delay(800).css({ background: '#00FF72' });
I want that my #upload-title. Is white for 0.5 sec. Thanks for help
A: The delay method delays things in the effects queue, and css is not an effects method.
You can add the css call to the queue using the queue method:
$('#upload-title').css({ background: '#ffffff' }).delay(500).queue(function(){
$(this).css({ background: '#00FF72' });
});
Demo: http://jsfiddle.net/Guffa/BxJ3Z/
A: .delay() works with animations, use jquery .animate() instead http://api.jquery.com/animate/
A: You'll need to use a timeout, delay is meant for use with animations:
$('#upload-title').css({
background : '#eeeeff'
});
setTimeout(function() {
$('#upload-title').css({
background : '#00FF72'
});
}, 800);
A: Jsfiddle
$(function() {
setTimeout(
function() {
$('#upload-title').css({
background: '#00FF72'
});
}, 500
);
})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632706",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: wxTheApp problems: Undeclared identifier using msvc10 Which header file to include for this pointer ? I want to make a simple dialogue box with two buttons "Hello world" and "Close". But for OnClose function I typed wxTheApp->Exit() inside it, and my msvc10 compiler says ,"undeclared identifier: wxTheApp". I included wx\app.h in the program also, but now although it is compiling that part fine, it is showing 100's of errors in the obj files of the files i included in the project. One such error is
HelloframeGUI.obj : error LNK2001: unresolved external symbol "public: virtual enum wxLayoutDirection __cdecl wxWindow::GetLayoutDirection(void)const " (?GetLayoutDirection@wxWindow@@UEBA?AW4wxLayoutDirection@@XZ)
Can anyone help please ?
#include "HelloframeGUI.h"
#include "wx/msgdlg.h"
#include "wx/app.h"
HelloframeGUI::HelloframeGUI( wxWindow* parent )
:
Helloframe( parent )
{
}
void HelloframeGUI::OnShowMessage( wxCommandEvent& event )
{
wxMessageBox( wxT("wxFormBuilder Tutorial") );// TODO: Implement OnShowMessage
}
void HelloframeGUI::OnClose( wxCommandEvent& event )
{
wxTheApp->Exit();// TODO: Implement OnClose
}
A: It looks like wxTheApp problem is solved. Anyway, I usually use wxGetApp() for this: wxGetApp().Close(). wxGetApp requires including of application h-file (should be part of your project). Regadring linker errors, this is the list of minimal required wxWidgets libraries:
#ifdef _DEBUG
#pragma comment (lib, "wxmsw28ud_core.lib")
#pragma comment (lib, "wxbase28ud.lib")
#else
#pragma comment (lib, "wxmsw28u_core.lib")
#pragma comment (lib, "wxbase28u.lib")
#endif
#pragma comment (lib, "comctl32.lib")
#pragma comment (lib, "rpcrt4.lib")
Add it to one of .cpp files. If your project is not Unicode, remove "u" from the library names.
A: Here is a detailed tutorial on building a wxWidgets application with Microsoft Visual C++.
http://wiki.wxwidgets.org/Microsoft_Visual_C%2B%2B_Guide
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to add domain restriction to REST CAS In our project we're using jasig CAS solution. Recently we've added RESTful interface. To be 100% secure I want to provide restriction on URLs. Only trusted URLs should be able to send requests to this API.
What is the best approach, does CAS support such requirement? So far I thought about:
*
*Some firewall/server configuration
*Create a Filter with lists of trusted URLs
A: it depends on your requirement, suppose your server has more than one application and you want restriction on selected application then go through
Create a Filter with lists of trusted URLs
Or
You are sure that there is always only and only one application is available in your server then go through
Some firewall/server configuration
A: Actually, domain restriction is hard to maintenance in real-business-world. So better way is to choose different way to allow access for trusted services. Preferred way is for example: digital signature.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: OutofMemoryException in vb.net I have a desktop application in vb.net 2003. Here when we load the main screen we find an unhandled exception showing out of memory, but we are able to continue working off the form and retrieving data. It works fine, but the image is not getting loaded.
In the main screen we have a background image loaded, one of the images is animated. Please can anyone help. Thanks in advance.
A: If you are loading an image via Image.FromFile, the MSDN documentation says that an OOM exception is thrown for attempts to load an invalid image file or for images whose pixel formats are not supported by GDI+.
Since you mention that you are able to carry on running your application, but the image is not showing, this sounds like a possible culprit.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Clojure look up performance vector vs set I have a small collection of sorted items less than 50 I frequently check if a particular item is in the collection or not,
this,
(time
(let [a [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]]
(dotimes [i 100000]
(filter (fn [[k]] (= k 15)) a))))
takes 10 ms if I use a set however,
(time
(let [a (sorted-set 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)]
(dotimes [i 100000]
(a 15))))
It always takes at least twice as much. What I do not understand is, set is supposed to be optimized for look ups why is filter faster?
A: filter is a lazy function. Try adding first in order to force the evaluation of the lazy sequence generated by the filter function. There is also a minor error in your anonymous function:
(time
(let [a [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]]
(dotimes [i 100000]
(first (filter (fn [k] (= k 15)) a)))))
"Elapsed time: 126.659769 msecs"
sorted set:
(time
(let [a (sorted-set 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15)]
(dotimes [i 100000]
(a 15))))
"Elapsed time: 19.467465 msecs"
Hope that makes sence.
A: Filter is lazy. Since you're not evaluating the result of (filter (fn [[k]] (= k 15)) a) it doesn't really do anything but make a lazy sequence.
In fact, (fn [[k]] (= k 15)) isn't even correct but you don't see that because it's not evaluated.
(let [a [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]]
(filter (fn [[k]] (= k 15)) a))
=> java.lang.UnsupportedOperationException: nth not supported on this type: Integer
[Thrown class java.lang.RuntimeException]
You want something like
(time
(let [a [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]]
(dotimes [i 100000]
(some (fn [k] (= k 15)) a))))
"Elapsed time: 173.689 msecs"
nil
Instead of the incorrect:
(time
(let [a [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]]
(dotimes [i 100000]
(filter (fn [[k]] (= k 15)) a))))
"Elapsed time: 33.852 msecs"
nil
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Transport Layer Security in the .NET framework I've been asked a question by the boss and actually I can't find any sort of coherent / comprehensive answer out there!
So I turn to you, the wise and all-knowing collective of StackOverflow :)
The question of the day is "Does .NET support transport layer security version 1.1 or 1.2?" Google is next to useless on this issue and the documentation out there is severely lacking.
Any help on this would be greatly appreciated.
Thank you,
Clint
A: TLS 1.1 and 1.2 support has been added to Windows 7 and my understanding is that .NET relies on Windows' SChannel for TLS support. So I think the answer to your question is "depends on the OS".
Now you should remember, that most sites are powered by older versions of OpenSSL and other libraries which not just didn't support TLS 1.1 and 1.2, but closed connection immediately if they received indication of TLS 1.1 support from the client. In other words, if you enable TLS 1.1 support in your client, you won't be able to connect to some of servers.
Upd: Forgot to mention that you can use third-party SSL/TLS implementation (eg. the one in our SecureBlackbox product) to get TLS 1.x support in your .NET application.
A: here some places where you can start to document yourself:
Transport Security with Certificate Authentication
This topic discusses using X.509 certificates for server and client
authentication when using transport security. For more information
about X.509 certificates see X.509 Public Key Certificates.
Certificates must be issued by a certificate authority, which is often
a third-party issuer of certificates. On a Windows Server domain,
Active Directory Certificate Services can be used to issue
certificates to client computers on the domain. For more information
see Windows 2008 R2 Certificate Services. In this scenario, the
service is hosted under Internet Information Services (IIS) which is
configured with Secure Sockets Layer (SSL). The service is configured
with an SSL (X.509) certificate to allow clients to verify the
identity of the server. The client is also configured with an X.509
certificate that allows the service to verify the identity of the
client. The server’s certificate must be trusted by the client and the
client’s certificate must be trusted by the server. The actual
mechanics of how the service and client verifies each other’s identity
is beyond the scope of this topic. For more information see Digital
Signature on Wikipedia.
SslStream Class
... If the server requires client authentication, the client must
specify one or more certificates for authentication. If the client has
more than one certificate, the client can provide a
LocalCertificateSelectionCallback delegate to select the correct
certificate for the server. The client's certificates must be located
in the current user's "My" certificate store. Client authentication
via certificates is not supported for the Ssl2 (SSL version 2)
protocol. ...
A: It can support either; the support comes from the underlying IIS, not .NET.
For details on how to enable TLS 1.2, see here: http://support.microsoft.com/kb/245030. Note that currently only a few browsers support it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to display a "waiting page" while a CGI is running? I have a cgi script that takes long time (30 sec) to generate the results before printing out the html. I want to show an intermediary page that says "Loading, please wait..." with an animated GIF before displaying the results.
Thanks
A: Fork the process and keep a reference to it in a session. Then poll the script periodically for a status update.
There is a more detailed explanation with code examples that was originally published in Linux Magazine. Perl Monks has further discussion.
You could use JavaScript (and XMLHttpRequest) to do your polling instead of reloading the whole page (do remember to build on things that work though).
A: Simple solution: Make static html page, with your loading text and gif, and with an JS script loading your CGI script with XHR. It is very simple with libs like jQuery and its ajax helper functions like load.
A: Thanks guys for the help, this what I did:
<script type="text/javascript">
var ray={
ajax:function(st)
{
this.show('load');
},
show:function(el)
{
this.getID(el).style.display='';
},
getID:function(el)
{
return document.getElementById(el);
}
}
</script>
<style type="text/css">
#load{
position:absolute;
z-index:1;
border:3px double #999;
background:#f7f7f7;
width:300px;
height:300px;
margin-top:-150px;
margin-left:-150px;
top:50%;
left:50%;
text-align:center;
line-height:300px;
font-family:"Trebuchet MS", verdana, arial,tahoma;
font-size:18pt;
}
</style>
<div id="load" style="display:none;">Loading... Please wait<br/><img src="images/loading.gif"></div>
<form action="http://localhost/cgi-bin/test.cgi" method="get" onsubmit="return ray.ajax()">
<input type="text" value="Test" name="q">
<input type="submit" value="Search">
</form>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632717",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: data type conversion into SSIS? I have created one SSIS package from flat file I'm getting one price value.
But in derived table I'm converting the values into (DT_DECIMAL) as I need to insert it into database.
My problem is value 12345.6754. I want to take only 2 digits after the decimal, i.e., I want 12345.67.
For that I tried (DT_DECIMAL,2)MYCOLUMN and (DT_NUMERIC,10,2) MYCOLUMN too, but then also it is giving me 12345.6754 :(
please help
A: In a Derived Column Transformation I'd look at using an appropriate String Functions and Other Functions (SSIS Expression) to manipulate the value. In this case, it sounds like you want toRound
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Actionscript 3 - parsing XML values I have the following XML:
<document>
<homeitems>
<homeitem>
<itemURL>URL1.html</itemURL>
</homeitem>
<homeitem>
<itemURL>URL2.html</itemURL>
</homeitem>
<homeitem>
<itemURL>URL3.html</itemURL>
<itemImage>image3.jpg</itemImage>
</homeitem>
</homeitems>
</document>
And the following code that parses it:
var XMLData:XML = new XML(LoaderMax.getContent("xmlDoc")); // loads XML
var numitems = XMLData.homeitems.homeitem.length();
for (var i=0;i<numitems;i++) {
if ((XMLData.homeitems.homeitem[i].itemImage) && (XMLData.homeitems.homeitem[i].itemImage!=="")) {
trace("Loading image "+XMLData.homeitems.homeitem[i].itemImage);
}
}
Trace result:
Loading image
Loading image
Loading image image3.jpg
WHY?!?!? Shouldn't it skip the items that don't have images? Am I stupid?
A: You can see that your test if (XMLData.homeitems.homeitem[i].itemImage) evaluate to true (just do a trace(Boolean(XMLData.homeitems.homeitem[i].itemImage) you will see true).
Also don't compare a node to a String use the toString method of the node or cast it explicitely to a String (i.e. String(XMLData.homeitems.homeitem[i].itemImage)!="" or XMLData.homeitems.homeitem[i].itemImage.toString()!="" )
There is multiple way todo it :
You can test if the node is undefined :
if (XMLData.homeitems.homeitem[i].itemImage != undefined)
Use hasOwnProperty method :
if (XMLData.homeitems.homeitem[i].hasOwnProperty('itemImage'))
And you can also cast your itemImage to a String and see if it's != "" :
if (String(XMLData.homeitems.homeitem[i].itemImage) != "")
Using e4x and foreach you can have a cleaner code for your loop :
for each(var homeItem:XML in XMLData.homeitems.homeitem) {
var itemImage:String = String(homeItem.itemImage)
if (itemImage!="") {
trace("Loading image "+itemImage);
}
}
A: It's enough if you compare with != not !==
if ((XMLData.homeitems.homeitem[i].itemImage) && (XMLData.homeitems.homeitem[i].itemImage!="")) {
/* do somethong here */
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632727",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to remove CustomListViewItem Hy !
My Code:
i just want to remove a item in a listview. But that code doesn't work for me.
public boolean onItemLongClick(final AdapterView<?> arg0, final View arg1,
final int arg2, long arg3) {
final Pizza pizza = (Pizza)arg0.getItemAtPosition(arg2);
AlertDialog.Builder builder = new AlertDialog.Builder(Main.this);
builder.setMessage("Are you sure you to delete " + pizza.title + "?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// ListView lv2 = (ListView)arg1;
arg0.removeView(arg0.getChildAt(arg2));
arg0.removeViewAt(arg2);
myDB = Main.this.openOrCreateDatabase(MY_DB_NAME, MODE_PRIVATE, null);
myDB.execSQL("DELETE FROM+"+MY_DB_TABLE+ "WHERE ID="+pizza.id);
}
})
;
AlertDialog alert = builder.create();
alert.show();
return false;
}
});
Error:
10-03 08:25:12.445: ERROR/AndroidRuntime(391): java.lang.UnsupportedOperationException: removeViewAt(int) is not supported in AdapterView
A: I guess, you must have a call to the ListView Adapter
adapter.notifyDataSetChanged();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632730",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: FCK Editor customization When we click on the anchor tag of fckeditor, we will obtain one pop up asking the anchor name.
I need to get same functionality for adding the footnote in my application.
Is it possible to customize the fckeditor in this way. Here I need to add one toolbar item 'say footnoe'. when we click on that appear a pop up.
where the anchor section code is written in fckeditor?
A: Are you talking about FCK editor or the Ckeditor?
You can extend CKeditor via plugins. Here is a tutorial http://www.voofie.com/content/2/ckeditor-plugin-development/
anchor code is in '\ckeditor\plugins\link\dialogs\anchor.js' (compressed)
source is in 'ckeditor\_source\plugins\link'.
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632736",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android send a image and save url
Possible Duplicate:
Send post data in android
How to send a image via http post along with the form data i.e image name etc
to a specified url .. which is the url of a aspx.
A: Check this code for Sending Image with Title,Caption,Name etc,
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("You Link");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("name", new StringBody("Name"));
reqEntity.addPart("Id", new StringBody("ID"));
reqEntity.addPart("title",new StringBody("TITLE"));
reqEntity.addPart("caption", new StringBody("Caption"));
try{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
reqEntity.addPart("picture", bab);
}
catch(Exception e){
//Log.v("Exception in Image", ""+e);
reqEntity.addPart("picture", new StringBody(""));
}
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
Where bitmap is the Image Bitmap.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632737",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: trouble traversing the DOM I have some HTML that looks likes this,
<dl class="dropdown">
<dt><span>Gender</span><a href="">Go</a></dt>
<dd class="shadow_50">
<ul>
<li><a href="#"><span class="option">male</span><span class="value">1</span></a></li>
<li><a href="#"><span class="option">female</span><span class="value">2</span></a></li>
</ul>
</dd>
</dl>
The DD is set to be hidden when the GO link is clicked I have some code that slides the DD down or up. However my question is that when I have more than one instance if these in a page, one click opens all the DD on the page, how can I target the DD that is closest to click,
I have tried the following,
$(".dropdown dt a").click(function(e) {
$(this).closest("dd").slideToggle(defaults.speed);
e.preventDefault();
});
and also this,
$(".dropdown dt a").click(function(e) {
$(this).next("dd").slideToggle(defaults.speed);
e.preventDefault();
});
I have had no success yet though.
A: You have the right idea, but the methods you've tried do not function quite the way you're expecting. The easiest option will probably be to go up to the parent and then find the appropriate element:
$(this).parent().next().slideToggle(defaults.speed);
Your attempts failed for the following reasons:
.closest traverses the DOM (it looks upwards, so it checks the parent, then all further ancestors until a match is found). In your case, the required element is not an ancestor of this, so that won't work.
.next gets the following sibling of the currently matched element. In your case, there isn't a following sibling as the a is the last element in the dt.
Note that if your DOM structure is likely to change you may want to use closest to reach the dl element, and then use .find to find the dd (see @Nicola Peluchetti's answer).
A: Have you tried:
$(".dropdown dt a").click(function(e) {
$(this).closest("dl").find("dd").slideToggle(defaults.speed);
e.preventDefault();
});
Youc't use next() because your link has only a SPAN as a sibling and you can't use closest because it just walks up the tree
A: Try;
$(this).parent().siblings("dd").slideToggle(defaults.speed);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Add to collection existing identificator I have Customer with Orders collection. I have some orders identificators which I need to add to new Customer instance like this:
var customer = new Customer();
customer.Orders.Add(new Order() { Id = 1 });
customer.Orders.Add(new Order() { Id = 2 });
customer.Orders.Add(new Order() { Id = 3 });
Is it possible without retrieveing approapriate Order instances?
A: Yes it is possible but you must do it in correct order. The simplest way is:
var order1 = new Order { Id = 1 };
context.Orders.Attach(order1); // Now context knows the order and it tracks it as unchanged
var customer = new Customer();
context.Customers.AddObject(customer); // Now context knows the customer and it tracks it as a new
customer.Orders.Add(order1); // Now context knows about new relation between new customer and existing order
If you do it as you showed in your example you will call:
context.Customers.AddObject(customer);
and context will track customer and all related orders as a new one so you will have to manually change state of all orders to unchanged to avoid duplicate inserts:
foreach (var order in customer.Orders)
{
if (order.Id != 0)
{
context.ObjectStateManager.ChangeObjectState(order, EntityState.Unchagned);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632743",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: view Blackberry log In Android through Logcat we can see application debug output and logs. In Blackberry is there any thing like Logcat? If not then where we can see its debug output.
A: In RIM API SDK there is EventLogger class. Use it for logging purposes.
A: above answer is good even though you can use system.out.println(string what you want to see in log list );
and you can see the output in blackberry simulator output console
for example,
try{
}catch(Exception e){
System.out.println(e.getMessage());
}
when ever exception will come at that time you can see the exception details in the blackberry simulator output console
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632746",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I make one central message for my jquery validate custom function? I'm using the jquery validate plugin to validate my form. I need to validate that 1 field of a section is filled in. This is the code I used:
http://blog.rebeccamurphey.com/2009/04/15/jquery-validation-indicate-that-at-least-one-element-in-a-group-is-required/
So, I have a few form fields with a "required_group" class, and the following lines of code in my document.ready function:
jQuery.validator.addMethod('required_group', function(value, element){
var $module = $(element).parents('div.panel');
return $module.find('.required_group:filled').length;
},
"Please fill out at least one of these fields");
jQuery.validator.addClassRules('required_group', {'required_group':true});
This works the way it's supposed to. But - I find it a bit messy to have the "Please fill out at least one of these fields" message show up by every field in the group. I'd prefer to have one message at the top of the group. How can I accomplish this using the validate plugin? Is there any way to customize where I want the message to display?
A: Use the showErrors option to define your own message displaying function. From the documentation:
showErrors Callback Default: None, uses built-in message disply.
A custom message display handler. Gets the map of errors as the first
argument and and array of errors as the second, called in the context
of the validator object. The arguments contain only those elements
currently validated, which can be a single element when doing
validation onblur/keyup. You can trigger (in addition to your own
messages) the default behaviour by calling this.defaultShowErrors().
Edit: here is a fiddle that does more or less what you need.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: internet connectivity status using SCNetwork leaks Trying to build up simple function to get internet status, but getting leaks every time I call this function:
+ (BOOL) connectionStatus
{
BOOL retVal = NO;
const char *hostName = [@"google.com"
cStringUsingEncoding:NSASCIIStringEncoding];
SCNetworkReachabilityRef reach = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, hostName); // Attempt to ping google.com
SCNetworkConnectionFlags flags;
SCNetworkReachabilityGetFlags(reach, &flags); // Store reachability flags in the variable, flags.
if(kSCNetworkReachabilityFlagsReachable & flags) {
// Can be reached using current connection.
}
if(kSCNetworkReachabilityFlagsConnectionAutomatic & flags) {
// Can be reached using current connection, but a connection must be established. (Any traffic to the specific node will initiate the connection)
}
if(kSCNetworkReachabilityFlagsIsWWAN & flags) {
// Can be reached via the carrier network
} else {
// Cannot be reached using the carrier network
}
if((kSCNetworkReachabilityFlagsReachable & flags) && !(kSCNetworkReachabilityFlagsIsWWAN & flags)) {
// Cannot be reached using the carrier network, but it can be reached. (Therefore the device is using wifi)
retVal = YES;
} else if (kSCNetworkReachabilityFlagsIsWWAN & flags) {
// Using the carrier network
retVal = YES;
} else {
// No connection available.
}
return retVal;
}
Instruments shows leaks and always point as responsible frame SCNetworkReachabilityGetFlags and SCNetworkReachabilityGetFlags from SystemConfiguration .
Any idea?
A: When you done with 'reach' do
CFRelease(reach);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to remove certificate from Store cleanly You can install certificate into certificate store using Wizard in certmgr.msc (Right click install)? Does anyone knows how to "cleanly" remove all the certificate by either using wizard/Code (pref.) /Script ?
I want to be able to remove everything (that I have installed earlier) from the LocalMachine and/or CurrentUser Store without leaving any residue.
Thanks
A: Old thread, but I just followed the linked post below using Win 7 and it worked nicely... Uses the Management Console.
*
*Start -> Run -> mmc.exe
*Click File -> "Add/Remove Snap-in"
*Select Certificates, click Add
*Select "Computer account", click Next.
*Select "Local computer", click Finish
*Click OK, which should bring you back to the MMC
*In left pane, expand Certificates (Local Computer)
*Do what you will with the listed certificates...
Source:
http://windowssecrets.com/top-story/certificate-cleanup-for-most-personal-computers/
A: You can try certmgr.exe. The following command removes a certificate with a cn of 'commoncertname ' from the local user personal\certificates store.
.\certmgr.exe -del -n commoncertname -c -s -r currentuser my
You can find more information about certmgr.exe here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa376553%28v=vs.85%29.aspx
UPDATE
Duh! I can't believe I didn't try this! You can remove certificates with the following:
Get-ChildItem Cert:\CurrentUser\My | Where-Object {$_.Subject -eq 'CN=certCN'} | Remove-Item
A: You could try the X509Store and releated classes in the .Net Framework to delete a certificate from the certificate store. The following code example deletes a certificate from the current user's My store:
// Use other store locations if your certificate is not in the current user store.
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite | OpenFlags.IncludeArchived);
// You could also use a more specific find type such as X509FindType.FindByThumbprint
X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySubjectName, "yoursubjectname", false);
foreach (var cert in col)
{
Console.Out.WriteLine(cert.SubjectName.Name);
// Remove the certificate
store.Remove(cert);
}
store.Close();
BEGIN EDIT:
Based on the comments in the comment section I've updated my answer with a code sample showing how to remove a certificate and all certificates in the chain:
X509Certificate2Collection col = store.Certificates.Find(X509FindType.FindBySubjectName, "yoursubjectname", false);
X509Chain ch = new X509Chain();
ch.Build(col[0]);
X509Certificate2Collection allCertsInChain = new X509Certificate2Collection();
foreach (X509ChainElement el in ch.ChainElements)
{
allCertsInChain.Add(el.Certificate);
}
store.RemoveRange(allCertsInChain);
END EDIT
Hope, this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Join 1 or 2 tables using the Max Command Can someone help me join these to tables and extract the PRODUCT_ID, PRODUCT_CODE, PRODUCT_NAME and the LAST_ORDER_DATE as not had much experience with SQL only MYSQL.
I'm not sure if I even need the second table or is it possible to use MAX in in just the ODBC_ORDER_LINE_ALL.
Table 1
Name: ODBC_ORDER_LINE_ALL
ORDER_LINE_ID
ORDER_LINE_DATE
ORDER_LINE_PRODUCT_ID
ORDER_LINE_PRODUCT_CODE
ORDER_LINE_PRODUCT_NAME
Table 2
Name: ODBC_PRODUCT_ALL
PRODUCT_ID
PRODUCT_CODE
PRODUCT_NAME
Thanks in advance.
Roy
A: Have you tried simple grouping like :
SELECT ORDER_LINE_PRODUCT_ID,ORDER_LINE_PRODUCT_CODE,ORDER_LINE_PRODUCT_NAME, MAX(ORDER_LINE_DATE)
FROM ODBC_ORDER_LINE_ALL
GROUP BY ORDER_LINE_PRODUCT_ID,ORDER_LINE_PRODUCT_CODE,ORDER_LINE_PRODUCT_NAME
A: You don't require the second table.
With your current implementation the query would be
SELECT ORDER_LINE_PRODUCT_ID,
ORDER_LINE_PRODUCT_CODE,
ORDER_LINE_PRODUCT_NAME,
MAX(ORDER_LINE_DATE)
FROM ODBC_ORDER_LINE_ALL
GROUP BY ORDER_LINE_PRODUCT_ID
However, you need to normalize your first table.
Assuming that your product id, product code and product name in your order line table reference the same values in the product table,
(And that a single product id corresponds to only one product code and name),
Your table structure for Table 1: ODBC_ORDER_LINE_ALL should be
ORDER_LINE_ID
ORDER_LINE_DATE
Foreign key (ORDER_LINE_PRODUCT_ID) references ODBC_PRODUCT_ALL(PRODUCT_ID)
In this case the query would be
SELECT ORDER_LINE_PRODUCT_ID, PRODUCT_CODE, PRODUCT_NAME, MAX(ORDER_LINE_DATE),
FROM ODBC_ORDER_LINE_ALL
JOIN ODBC_PRODUCT_ALL
ON ORDER_LINE_PRODUCT_ID = PRODUCT_ID
GROUP BY ORDER_LINE_PRODUCT_ID
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Will changing the upper case to lower case can shorten the length of string? Will changing the upper case to lower case can shorten the length of string?
void lower(char *s)
{
int i;
for (i=0;i<strlen(s);i++)
if(s[i])>='A' && s[i]<='Z')
s[i]-=('A'-'a');
}
A: No, it shouldn't.
Some other things to note:
*
*You're calculating strlen on each iteration of the loop, try saving it to a variable
*You assume the string is properly null-terminated; you will overrun if it's not
A: Since you are working in ASCII, no, you're obviously doing 1-on-1 replacement. Should you ever change the code to support UTF-8: Maybe.
A: If you just replace one character for another, as you do, then the resulting string will still have the same size. Type char is always defined to be one byte in C or C++.
A: Changing the case of a string could change the length, if it is done
correctly. In German, for example, the two character string "SS" will
become the single character string "ß" in certain contexts (but not in
others, e.g.: "STRASSE" -> "Straße", but "GASSE"->"Gasse"). Changing
case correctly is decidedly non-trivial however, and very locale
specific. And there's no real support for it in the standard.
The code you post won't change the length, but then, it's far from
correctly: depending on the encoding, it may change some non-alphabetic
characters as well (the alphabet is not always contiguous), and it will
definitely fail to convert some alphabetic characters, e.g. 'Ä', 'Ö' and
'Ü' in Swedish.
A: This code doesn't change the length of the string. However there are problems with the code: Calculating strlen() with every iteration, which is redundant.
Store the result in the a variable and use it in the loop
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Can I use custom xml namespace in ePub 3.0? An error comes out by epub which uses custom namespaces in ePubChecker.
Is using custom namespaces in ePub 3.0 forbidden?
example code:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/1999/xhtml">
<html xmlns="http://www.w3.org/TR/xhtml11" xmlns:customns="http://example.com">
<head></head>
<body><customns:customtag></customns:customtag></body>
</html>
ERROR:
/Untitled.epub/OPS/page0.html(5,27): element "customns:customtag" not
allowed here; expected the element end-tag, text or element "a",
"abbr", "address", "area", "article", "aside", "audio", "b", "bdi",
"bdo", "blockquote", "br", "button", "canvas", "cite", "code",
"command", "datalist", "del", "details", "dfn", "div", "dl", "em",
"embed", "fieldset", "figure", "footer", "form", "h1", "h2", "h3",
"h4", "h5", "h6", "header", "hgroup", "hr", "i", "iframe", "img",
"input", "ins", "kbd", "keygen", "label", "map", "mark", "menu",
"meter", "nav", "ns1:switch", "ns1:trigger", "ns2:math", "ns3:svg",
"object", "ol", "output", "p", "pre", "progress", "q", "ruby", "s",
"samp", "script", "section", "select", "small", "span", "strong",
"style", "sub", "sup", "table", "textarea", "time", "u", "ul", "var",
"video" or "wbr" (with xmlns:ns1="http://www.idpf.org/2007/ops"
xmlns:ns2="http://www.w3.org/1998/Math/MathML"
xmlns:ns3="http://www.w3.org/2000/svg")
A: I've tried it with a Sony PRS-650. I didn't expect but it worked. The reader showed the text between the opening and closing tags.
As far as I see Epub 2.0.1 supports namespaces and Epub 3.0 draft does not remove this feature. XHTMLs are XMLs, so it could be fine but unless it's absolutely necessary I wouldn't use this feature. Maybe the firmware of other devices isn't so well tested and won't show the book.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7632766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Subsets and Splits