text
stringlengths 8
267k
| meta
dict |
---|---|
Q: How to "svn export" a remote branch on github? I do not need any history, I just want the files from the said branch to be downloaded locally .
This is for a deploy script
Usage: ./deploy.sh remote_branch_name
the script checks out an arbitrary branch from a remote github repository and copies the files to a server.
I figured I could use git clone without history:
git clone --depth 1 your_repo_url
But how can I specify a branch to checkout?
A: You can use the -b flag with clone:
--branch <name>
-b <name>
Instead of pointing the newly created HEAD to the branch pointed to
by the cloned repository's HEAD, point to branch instead. In a
non-bare repository, this is the branch that will be checked out.
You might also want to explore the downloads that github provides for your repo.
On github, download links are available like so:
https://github.com/username/reponame/zipball/branch
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: use p6 web service in .net There are a lot of web services installed on Primavera P6.
WSDL: ActivityCodeAssignment.wsdl
Primary Key Field: A multi-part key comprised of the following elements:
ActivityObjectId
ActivityCodeTypeObjectId
Target Namespace: http://xmlns.oracle.com/Primavera/P6/WS/ActivityCodeAssignment/V1
Default Transport URLs:
http://<hostname>:<port number>/p6ws/services/ActivityCodeAssignment?wsdl
https://<hostname>:<port number>/p6ws/services/ActivityCodeAssignment?wsdl
But if I input this on the web brower:
http://my-machine:7005/p6ws/services/ActivityCodeAssignment?wsdl
It shows, "No service was found."
If I try to Add Service Reference in Visual Studio, it says.
There was an error downloading 'http://my-machine:7005/p6ws/services/ActivityCodeAssignment?wsdl'.
The request failed with HTTP status 404: Not Found.
Metadata contains a reference that cannot be resolved: 'http://my-machine:7005/p6ws/services/ActivityCodeAssignment?wsdl'.
There was no endpoint listening at http://my-machine:7005/p6ws/services/ActivityCodeAssignment?wsdl that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.
The remote server returned an error: (404) Not Found.
If the service is defined in the current solution, try building the solution and adding the service reference again.
Is P6 using some different web service?
A: On my machine, running Oracle database, Weblogic server with P6 version 8.1 Web Services, the URL for this is:
http://<hostname>:<port number>/p6ws/services/ActivityCodeAssignmentService?wsdl
Note the word "Service" tacked onto the end.
A: Not sure which version of P6 you are using.
Firstly, please check the root web service URL is working or not:
[http://hostname:port/p6ws]
If not, you may need to check your P6 Web Services is installed and deployed correctly or not.
This is P6 Web Services Administrator’s Guide for version 7.0:
http://docs.oracle.com/cd/E16281_01/Technical_Documentation/Web_Services/wsadmin.pdf
If you can access the root web services and other endpoint such as ActivityService [http://host:port/p6ws/services/ActivityService?wsdl] rather than ActivityCodeAssignmentService, but you want to use it, you may need to build your own WS Stubs with following steps:
*
*Create a Class Library project in .NET with the name P6WSStubs
*Change the Root Namespace to Primavera
*Add a reference to Microsoft WSE 3.0.
*Add the following Web Reference Ws.P6.ActivityCodeAssignment - [http://hostname:port/p6ws/services/ActivityCodeAssignmentService?wsdl]
*Build the P6WSStubs.dll
Hope it will help you,
Yogi
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Avoid login (JAAS) every time I change path (and it generates a new session) I've configured my Java EE app to use declarative security with JAAS (I've even implemented a custom LoginModule). The problem is that every time I change the url path (e.g. from http://mysite/restricted to http://mysite/restricted/configs), the system asks me to login again!!!!
After searching a little I found out that a new Session is being created every time I change the directory (there are cookies for each path). So I guess that the authentication is done for the session (seems obvious). But... how do I solve this? I need subdirectories to apply security by linking them with roles (role X can access /restricted/some-function/*). Also, I need that some roles (e.g. Manager) have access to all subdirectories without needing to login everytime.
What am I missing?
A: You should set the path of your cookies to /.
For Tomcat: http://tomcat.apache.org/tomcat-7.0-doc/config/context.html (Search for sessionCookiePath.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614391",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: EJB - external lib or inside JSF project? I'm packaging my app as WAR archive. What are pros/cons of these two approaches:
*
*Keep EJB (beans, entities etc) as separate project and include into WAR as lib (*.jar file - WEB-INF/lib) during build?
*Keep everything (ejb-s, jsf beans etc) in one project, so after build all would go to WEB_INF/classes
Is there any performance/security difference?
I'm using GlassFish 3.1.1 WebProfile
A: There is really no performance/security difference for JARs in /WEB-INF/lib versus classes in /WEB-INF/classes. They end up in the same context and classloader anyway. Perhaps extracting the JAR and loading its classes into memory needs a few milliseconds more, but that's totally negligible.
Only maintainability and reusability is different here. When you put EJBs in a separate project, then you can more easily reuse them for other WARs and purposes without the need to copypaste classes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How can I tell Visual Studio/Microsoft's C compiler to allow variable declarations after the first statement? I have code that compiles on the GNUARM compiler, but Visual Studio 2010 issues errors. The issue involves declaring variables after the first statement in a C language file:
main.c
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i = 6;
i = i + 1;
printf("Value of i is: %d\n", i);
int j = i * 10; // <-- This is what Visual Studio 2010 complains about.
printf("Value of j is: %d\n", j);
return EXIT_SUCCESS;
}
The following code compiles without errors:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i = 6;
int j; // <-- Declaration is now here, valid according to K&R rules.
i = i + 1;
printf("Value of i is: %d\n", i);
j = i * 10; // <-- Moved declaration of j to above.
printf("Value of j is: %d\n", j);
return EXIT_SUCCESS;
}
I'm using default settings for creating a Win32 console project. When I set "Compile as" property to "Compile as C++ (/TP)", I get compilation errors in some Visual Studio header files. (Right click on project, choose Properties → Configuration Properties → C/C++ → Advanced).
How do I tell Visual Studio 2010 to allow variable declarations after the first statement, like C++ or the current C language standard?
A: You don't. Visual C++ does not support C99.
You'll need to compile as C++ (and update your code accordingly) or follow the rules of C89.
(I don't know what errors you get when compiling with /TP; I can compile your example successfully with /TP if I add #include <stdlib.h> for EXIT_SUCCESS; if you provide more details, I or someone else may be able to help.)
A: As of Visual Studio 2013, the Visual C++ compiler supports C99 style variable declarations. More details can be found in:
http://blogs.msdn.com/b/vcblog/archive/2013/06/28/c-11-14-stl-features-fixes-and-breaking-changes-in-vs-2013.aspx
A: I made the same test with the default Visual Studio 2010 project, with the C file and /TP switch, and got the precompiled headers error. It can be removed by renaming stdafx.cpp to stdafx.c, or disabling precompiled headers for the whole project or for specific C files.
I didn't find any other problems. However, this effectively converts C language to C++, which is not your intention, I think. C allows, however, to define a variable in the beginning of every {} block.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: How to deal with System.Drawing.Color <--> System.Windows.Media.Color ambiguous reference I'm using System.Drawing to fill rectangles and draw lines and stuff. The System.Drawing.Color object only has a list of pre-defined colors, and I want to assign my own colors using RGB. So I've added the System.Windows.Media namespace, and now all references to "Color" say they're a ambiguous references.
I understand why. But I am wondering if there is a better solution than doing this
System.Windows.Media.Color colorVariableName;
wherever I reference a Color variable.
A: You're able to alias your usings at the top, so you can say something like
using MediaColor = System.Windows.Media.Color
And you'll be able to say
MediaColor colorVariableName
A: With System.Drawing.Color, you can do
Color c = Color.FromArgb(255,255,255);
to initialize color from your own R, G and B values and maybe you can skip System.Windows.Media.Color
A: Use Color.FromArgb(r, g, b)) to convert from rgb to System.Color. r,g, and b are ints
A: The other option would be to alias one of the namespaces in the using clause like so:
using System.Windows.Media = med;
Then you can access the colours with:
med.Blue
Also if it's just that particular class that you're interested in you can give that an alias in the using clause also.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Nested set INSERT operation for SQLite I am trying to implement the nested-set model for a sqlite database.
So far I have implemented getting leaf nodes, finding subordinates etc.
I am using this tutorial as a reference
However, I am stuck at inserting a new node.
Here's the code from the site
LOCK TABLE nested_category WRITE;
SELECT @myRight := rgt FROM nested_category
WHERE name = 'TELEVISIONS';
UPDATE nested_category SET rgt = rgt + 2 WHERE rgt > @myRight;
UPDATE nested_category SET lft = lft + 2 WHERE lft > @myRight;
INSERT INTO nested_category(name, lft, rgt) VALUES('GAME CONSOLES', @myRight + 1, @myRight + 2);
UNLOCK TABLES;
I know that there's no lock table in sqlite.. my problem here is that I need to pass the result of the first query to the next one. Here it's done by using a user-created variable by @. I couldn't figure out how to do it in SQLite.
Thanks in advance.
A: An ideea is to replace the variable myRight with the query that generated it.
That is to move the code into pure SQL.
UPDATE nested_category SET rgt = rgt + 2
WHERE rgt > (SELECT rgt
FROM nested_category
WHERE name = 'TELEVISIONS');
UPDATE nested_category SET lft = lft + 2
WHERE lft > (SELECT rgt
FROM nested_category
WHERE name = 'TELEVISIONS');
INSERT INTO nested_category(name, lft, rgt)
SELECT 'GAME CONSOLES', rgt + 1, rgt + 2
FROM nested_category
WHERE name = 'TELEVISIONS' ;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How do i access camera video from phonegap? Phonegap's documentation suggests that there is a single method to access the camera, camera.getPicture().
Now I would like to access the video feed and draw something on top. Is this possible?
A: I made a PhoneGap Plugin for iOS to capture video streaming into a canvas or image:
https://github.com/daraosn/Cordova-CanvasCamera
It's not the best way to do it (if you can, do it natively). I wouldn't recommend it for production apps yet, but it works good so far in development.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Hibernate updating a single column I am confused as to the stance Hibernate takes when it determines which column information to persist. Some places I read online says it will only update dirty fields, some people say that it is also database dependant (ie. Using hibernate with Oracle 9 will persist all fields of an object, even if only 1 is dirty).
Is there a correct way to handle this if you only want column xxx to change? Or should that simply be abstracted to a different table? Lastly, is any of this affected whether you use Session#get or Session#load?
A: Use dynammic-update Hibernate mapping attribute:
<class ... dynamic-update="true">
Source: Hibernate – dynamic-update attribute example.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614406",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: It's possible know when the HttpURLConnection was established? I'm using the HttpURLConnection to open connections to web pages. I call the connect() method to open the connection.
I not found an isConnected() method.
I need to know when the connection was established with the server. I need this because I tryinf to found a fast way to open multiple connections. One object open connections and another do some processing with the connections that established the communication with the server.
I want to let the processor always busy.
A: Not sure why you would need that information.
You should not care since once you call connect() you can start retrieving the response e.g.
int responseCode = connection.getResponseCode();//Get HTTP status code
Assuming of course you have send all your request to the output stream.
The HttpURLConnection under the hood knows if it is already connected to the server and the implementation reuses the connection (transparent to you).
Now, having said that to answer your question, I think that the only way to know if the HttpURLConnection's state is connected to the server, is to call openConnection() a second time in the same HttpURLConnection object.
If it is already connected it will throw a relevant exception complaining that it is already connected something like: IllegalStateException("Already connected");.
At that point you know that the HttpURLConnection is connected
A: httpURLConnection con = new httpURLConnection(some URL object);
con.getHeaderField(httpURLConnection.HTTP_CREATED );
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: when and how should i call IDisposable Interface? asp.net MVC 3 i was just googling it and could find anything that give me a good example of how to implement and what are the best scenarios when i should call the IDisposable interface
please if someone could post the example and the explain it that would be a great help and could give me a good start..
thanks in advance..
A: Your controllers that use EF should include a dispose method
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
See Ensuring that Database Connections Are Not Left Open
When you use the MVC scaffolding, it creates the dispose method for you. See also Controller.Dispose Method (Boolean)
The ASP.NET MVC framework calls Dispose when the request has completed processing. Developers typically do not have to call Dispose. If you derive a class from Controller and the derived class uses unmanaged memory, managed operating-system resources (such as files), or COM objects, you should implement Dispose to clean up these resources. You should also call the Dispose method of the base class. The Dispose method leaves the Controller instance in an unusable state. After you call Dispose, you must release all references to the Controller instance so that the garbage collector can reclaim the memory that the Controller instance was occupying.
For more information, see Cleaning Up Unmanaged Resources and Implementing a Dispose Method.
A: The IDisposable interface is meant to be used by classes that also access un-managed resources. This gives the class a chance to clean up those un-managed resources as soon as possible.
The MSDN Page for the IDisposable Interface actually provides a good example as to what this means.
A: Since you tagged MVC Ill reply specific to mvc controllers. If you aren't using any resources you need to dispose (ie resources that support a Dispose method and you aren't disposing then already in a code method) then you should implement IDisposable and call dispose in your objects there. It's quite rare you need to do this though and generally will see it if using an ObjectContext or DbContext entity framework class in your controller. However I prefer creating and disposing any objects in the same method.
Note however the discussion here where its mentioned to essentially keep this responsibility of the caller implementing IDisposable (ie your controller implementing it) to a dependency injection framework calling the dispose for you automatically.
Ensuring IDisposable call on objects created in the controller and handed off to view
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is my output file empty in this simple program using std::fstream? I am trying to understand how to read information form an input file and write that data into an output file. I understand how to read from a file and dispaly its contents, but I DONT understand how to write to a file or display its contents. My program runs fine but when I check my output txt file, there is nothing in it! What could I be doing wrong?
input file contains 3.1415 2.718 1.414.
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
int main()
{
float fValue;
fstream inputFile;
ofstream outputFile;
inputFile.open("C:\\Users\\David\\Desktop\\inputFile.txt");
outputFile.open("C:\\Users\\David\\Desktop\\outputfile.txt");
cout << fixed << showpoint;
cout << setprecision(3);
cout << "Items in input-file:\t " << "Items in out-put File: " << endl;
inputFile >> fValue; // gets the fiest value from the input
while (inputFile) // single loop that reads(from inputfile) and writes(to outputfile) each number at a time.
{
cout << fValue << endl; // simply prints the numbers for checking.
outputFile << fValue << ", "; // writes to the output as it reads numbers from the input.
inputFile >> fValue; // checks next input value in the file
}
outputFile.close();
inputFile.close();
int pause;
cin >> pause;
return 0;
}
A: On windows, it's likely that you have the output file open with something like notepad and your C++ program is not opening the file for output. If it can't open the file, the ofstream::open function will silently fail. You need to check the status of outputFile after you attempt to open it. Something like
outputFile.open("C:\\Users\\David\\Desktop\\outputfile.txt");
if (!outputFile) {
cerr << "can't open output file" << endl;
}
If the status of outputFile is not ok, then you can do
outputfile << "foobar";
and
outputfile.flush();
till the cows come home and you still won't get any output.
A: As David N. mentioned, fstreams do not throw by default when the file fails to open, or the stream gets into a bad state at some point during writing. You can make them throw on error by setting the ofstream::exceptions flag to 'ofstream::failbit | ofstream::badbit'. You can find more information about the exception mask here:
http://www.cplusplus.com/reference/iostream/ios/exceptions/
It is good practice to set the exception mask for failure, because a) it avoids race conditions and b) requires errors to be dealt with and c) allows automatic stack unwinding which is often convenient in larger programs.
Secondly, in this loop:
while (inputFile)
{
...
}
The condition that you should be checking is inputFile.eof(). However, I would suggest that you do this "The C++ Way":
#include <iostream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
float fValue;
ifstream inputFile;
ofstream outputFile;
inputFile.open("input");
outputFile.open("output");
// EDIT: this is optional, but recommended
inputFile.exceptions(ifstream::badbit | ifstream::failbit);
outputFile.exceptions(ofstream::badbit | ofstream::failbit);
copy(istream_iterator<double>(inputFile)
, istream_iterator<double>()
, ostream_iterator<double>(outputFile, ", "));
/*
// EDIT: you can also check the status manually, but it looks more like C code:
if(inputFile.bad() || outputFile.bad())
return 1;
*/
outputFile.close();
inputFile.close();
cin.ignore();
return 0;
}
Notice the use of iterators and the std::copy() algorithm rather than reading directly from the stream. If you want to print out the contents of a file directly to std::cout, then you can do this:
copy(istream_iterator<char>(file), istream_iterator<char>(), ostream_iterator<char>(cout));
Note that by default istream_iterators will skip whitespace, so you have to set file >> noskipws in order to prevent this.
HTH!
Gred
A: You need to close the output file for the buffer to be flushed to the file prior to your application exiting.
A: The code looks like it should save something to the file. The logic is all wrong, but something ought to be there. Check the states of your streams.
cout << fixed << showpoint;
cout << setprecision(3);
cout << "Items in input-file:\t " << "outputFile: " << endl;
while (inputFile >> fValue)
{
cout << fValue << endl; // this confirms that the above code read from my text file.
outputFile << fValue << '\n'
if (!outputFile) {
cout << "Error saving to file.\n";
break;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Android Gallery - Replace Bitmap in ImageView after scrolling stopped I've programmed a zoomable gallery with several images.
*
*The images can be zoomed.
*Zoomed images can be dragged.
*If the image is not zoomed, the gallery can be scrolled.
The layout consists of a LinearLayout with a TextView (the name of the gallery) and the Gallery itself.
An item in the gallery consists of a RelativeLayout containing a FrameLayout with the ImageView in it (I read I need the FrameLayout for zooming) and a TextView to show the zoom state of the image.
I've used a custom View.OnTouchListener to implement the zooming.
Now I was trying to replace the image in the ImageView after the gallery has stopped scrolling with a high res picture so the user can zoom in much better/further.
I did this with the OnItemSelectedListener and setCallbackDuringFling to false.
Even this works fine if you fling the screen fast.
But if you keep your finger on the display and move it slowly to the edge, the OnItemSelectedListener is fired before the next item reached the center and the scrolling animation stops. Instead the gallery jumps like it looses touch contact and centers the next item in the gallery immediately. Also the OnItemSelectedListener is called more than once on the same item when moving the finger slowly (I avoid this problem by saving the position of the last selected item).
So (long story short) I was looking for a callback/listener to the "scrolling/snap-to-grid" effect of the Gallery. I also tried an AnimationListener, but the gallery returns null when i call getAnimation on it.
I'm desperate here... can anyone help?
A: Problem solved: I'm now using the android.support.v4.view.ViewPager with the custom callbacks in the OnPageChangeListener:
*
*onPageSelected
*onPageScrollStateChanged
*onPageScrolled
A: I recommend a slight change to your method. For your Gallery, override onScroll(MotionEvent, MotionEvent, float, float) and onFling(MotionEvent, MotionEvent, float, float) have them return their super but on MotionEvent.ACTION_DOWN || MotionEvent.ACTION_UP set a moving flag to true || false respectively.
Now in the BaseAdapter for your Gallery in the getView(int, View, ViewGroup) method when you are returning your image view return the low res ImageView if the moving flag is true else return the high res.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: ASP.NET MVC Routing - Keeping up with parameters through redirects I am working on my first real ASP.NET MVC project and I need a little advice.
So, let's say that my app has an admin section where you can create companies, departments, and users within each department.
Company -> Department -> User
Right now my urls are looking like this:
Companies/Index
Departments/Index?companyId=1
Users/Index?companyId=1&departmentId=2
It's getting complicated because if I have to redirect from the user list back to the department list, I have to do something like:
return RedirectToAction("Index", "Departments", new { companyId = model.CompanyId });
As things get more nested, I have to start passing more and more parameters so that the controller actions have the context that they need.
Is there a better way to structure the routes for controllers that have "nested" functionality like this? Should they look more like:
Companies/{id}/Departments/{id}/Users ?
Is there a good article that someone could link me to that can provide some advice for best practices when it comes to this?
A: You just need to add more routes on your Global.aspx which maps Urls to actions
with more specific routes at the top.
You can have something like:
routes.MapRoute("user","Users/Index/{companyId}{departmentId}", new {controller="",action=""})
routes.MapRoute("department","Departments/Index/{companyId}",new { controller="",action=""})
routes.MapRoute("company","Companies/Index",new { controller="",action=""})
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how can i know when i reach end of a datareader? cmd.CommandText = "select name from Tbl_Shahr_No";
SqlDataReader reader = null;
reader = cmd.ExecuteReader();
reader.Read();
while(reader.HasRows)
{
ddl.Items.add(reader["name"].tostring());
reader.read()
}
i wrote this code but problem is that while statement is true all times!
how can i read all of reader information with a while or repeater ring?
A: The simplest idea is to simply let Read() be the loop condition.
while (reader.Read())
{
// grab data
}
A: Use the .Read() method in your while.
It advances the SqlDataReader to the next record.
Returns true if there are more rows; otherwise false.
while(reader.Read())
{
ddl.Items.add(reader["name"].ToString());
}
Alternatively, data-bind your dropdownlist to your SqlDataReader, and don't bother iterating it manually.
ddl.DataSource = reader;
ddl.DataTextField = "name";
ddl.DataValueField = "name";
ddl.DataBind();
A: IDataReader.Read() returns a bool. Use it as the condition for your while-loop:
reader = cmd.ExecuteReader();
while(reader.Read())
{
ddl.Items.add(reader["name"].tostring());
}
A: When reader.Read() returns false then there are no more rows so by using
while(reader.Read())
{
//do some thing here
}
it will loop until there are no more rows!
But if the datareader has more then one dataset use the following
while(reader.Read())
{
//First dataset
//do some thing here
}
reader.NextResult();
while(reader.Read())
{
//Second dataset
//do some thing here
}
......
A: while (reader.read())
{
// do your thing here for each row read
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: AJAX/jQuery/Javascript - Access a page in an external domain The question is quite simple, the answer may not be. :)
How to make an AJAX request (preferably with 'jQuery'), to an external domain, ie a web address (for example) completely different from the server which is the site you requested this page.
What I want is to get a html page outside of the server, and display it on my page.
I also accept suggestions from other way, without using AJAX, for example, to accomplish that.
Thank you, now.
A: If you're trying to take HTML from that domain and inject it into your page, just put it in an iframe.
If you're trying to access some sort of API, you'll want to use JSONP. Here's a good writeup of how it works: http://devlog.info/2010/03/10/cross-domain-ajax/
Note that JSONP will require some changes to server side code. If it's a popular API designed for this thing, it probably already supports it.
A: Perhaps this can help:
-> http://www.ajax-cross-domain.com/
A: Besides JSONP the other way this is commonly worked around is by setting up a "proxy" file on your server in php/python/ruby/some-server-language. Your "proxy" script will take a url optionally some parameters and perform a curl on that domain.
So a data flow example would be:
1) ajax call originates from client accessing yourdomain.com. The ajax request points to yourdomain.com/proxy.php passing the url as a post or get variable.
2) the PHP script takes the url and performs a curl, gets whatever data is returned by the call and echos or dies or returns that data in some other method.
3) Data is given to the calling ajax on yourdomain.com, you can now make use of said data.
Though, it does sound from your description that you just want an iframe :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Chat Server with Java & Netty I want to implement a Chat Server with Java and Netty. My question is: should I make all the work in Netty's connection handler?
For "all the work" I mean for example: to do the login ( so with mysql connection ), eventually to send message, to log informations..
A: I think a more robust design would be to make a system that works without Netty and then use Netty's connection handler to go between the two. This way, if you decide to move away from Netty in the future, you can do so with minimal rewiring.
A: If you put all that functionality into interface-based POJOs, rather than a Netty connection handler, you'll find it easier to test it without having to fire up Netty.
Once you have all those objects working and tested, then give them to a connection handler and let them do the work. The connection handler just orchestrates your POJOs to fulfill its requests.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614422",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Registry Editing: How to calculate DWord Hex Values I'm trying to make some registry edits and I'm not sure I understand how specific dword values are calculated.
Here are two examples:
[HKEY_CURRENT_USER\ControlPanel\Volume]
"Volume"=dword:0xFFFFFFFF ; 0=off, 0xFFFFFFFF=maximum
"Refresh"=dword:493E0 ; every 5 minutes
For the volume, how would I calculate what the range of options are if 0xFFFFFFFF is the max? And for "Refresh", if 493E0 is every 5 minutes, how do I figure out what every minute, or every day or every hour would be?
This is a Motorola Symbol MK4000 WinCE 5.0 device.
A: Volume is splt in 2. The low word is left and the high word is right. 0xffff on a channel corresponds to 100% or "max". 50% is 0x7fff and so on. Remember that is also rarely linear, so 50% volume doesn't mean 50% as loud.
EDIT
To clarify a bit further, the volume is split into two channels. I'll assume that you want the same volume on each.
The general formula is [left value] | ([right value << 16])
Here are examples:
For 100%, a value of 0xFFFF on both channels is what you want.
Value = 0xFFFFFFFF == 0xFFFF | (0xFFFF << 16)
For 50%, a value of 0x7FFF on both channels (0xffff / 2) is what you want.
Value = 0x7FFF7FFF == 0x7FFF | (0x7FFF << 16)
For 25%, a value of 0x3FFF on both channels (0x7fff / 2) is what you want.
Value = 0x3FFF3FFF == 0x3FFF | (0x3FFF << 16)
A: If you put the windows calculator into scientific mode, you can convert between HEX and regular DECIMAL easily.
http://scripts.sil.org/cms/scripts/page.php?item_id=HextoDecConversion
EDIT:
The number 0x493E0 is 300000, which I imagine is the number of MILLISECONDS, divide that by 1000 to get the number of seconds (300), divide that by 60 to get the number of minutes (5).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614427",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Notification opens activity, back button pressed, main activity is opened? The best way I can describe my problem is like this:
*
*A notification is created at boot (with a BroadcastReceiver).
*My app main activity is opened and the home button is pressed (the app is still running in the background until the system closes it).
*I pull down the status bar and press on the notification previously created at boot.
*Some activity, different from the main one, is started.
*I press the back button and the main activity is displayed.
How can I prevent that last step? What I want with the back button is to go back where I was, which is the home screen (the desktop with all the widgets and app icons). My app's main activity was supposed to be running on the background, why was it called with the back button?
In case it's relevant, my code to create a notification goes like this:
public void createNotification(int notifyId, int iconId, String contentTitle, String contentText) {
Intent intent = new Intent(mContext, NewNoteActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(AgendaNotesAdapter.KEY_ROW_ID, (long)notifyId);
PendingIntent contentIntent = PendingIntent.getActivity(mContext, notifyId, intent, 0);
Notification notification = new Notification(iconId, contentTitle, 0);
notification.setLatestEventInfo(mContext, contentTitle, contentText, contentIntent);
mNotificationManager.notify(notifyId, notification);
I tried to add a couple of more flags combinations to intent but neither of them solved my problem... Suggestions?
A: Had the same problem.
What worked for me was setting in the manifest the following attribute to the activity launched by the notification:
android:taskAffinity=""
This essentially separates the affinity of the notification activity from the main activity and so the OS doesn't feel the need to "return" to the main activity, but simply returns to whatever was there before e.g. the "desktop".
A: Your problem is in following steps as I know from your question is
1.Create notification after boot complete
2.Main activity will call on start up
3.you pressed home button so main activity will be stopped but will not destroy
4.You click on notification from status bar so your application will be resume so that you have already main activity in your back stack and notification will create new activity like you mentioned in your question NewNoteActivity activity will be push on back stack.SO at this step you have two activities in back stack
5.you pressed back button so that last activity will be destroy and your main activity will be resume But you want to go to homepage screen.
So the Your problem is in following steps as I know from your question is
1.Create notification after boot complete
2.Main activity will call on start up
3.you pressed home button so main activity will be stopped but will not destroy
4.You click on notification from status bar so your application will be resume so that you have already main activity in your back stack and notification will create new activity like you mentioned in your question NewNoteActivity activity will be push on back stack.SO at this step you have two activities in back stack
5.you pressed back button so that last activity will be destroy and your main activity will be resume But you want to open homepage activity when you pressed on back button from NewNoteActivity activity.
So the solution is that when you pressed back button from your NewNoteActivityactivity you start main activity again with Intent.FLAG_ACTIVITY_CLEAR_TOP flag so that your main activity will recreate and will receive onNewIntent() method so there you can get flag and you can finish main activity
for example
@Override
public void onBackPressed() {
Intent i = new Intent(this, Main.class);
i.putExtra("exit", true);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
super.onBackPressed();
}
Now you have to implement onNewIntent() method in your Main activity
On back button pressed from NewNoteActivity activity your Main activity will call onNewIntent() method so in this method you have to fetch flag variable which is passed from NewNoteActivity activity.If you get flag and if it is true then just finish the Main activity so that you will get Home screen.
EDIT
You are saying that you have any of the activity from A,B,or C is opened and you pressed back button so that this activity will be closed.If you have only one activity in stack at that time your application will be closed means you will get home screen.But if you have more than one activity and you pressed back button you have at least one activity in stack and now you click on notification so that this will open a new activity associated with your notification so that this activity will be pushed on that on back stack.Now if you pressed back button your last activity which is associated with your notification will be closed if you have not modify onBackPressed() method in that activity and then it will check back stack if any activity in back stack so that activity will be resumed or if there is no activity in back stack then your application will be closed and you will get home screen
A: I use this solution in my apps.
Override onBackPressed (in your activity routed from notification) and check if your app is in stack or not. if not then start your root activity. User can always navigate from your root activity. This is what I do in my apps
@Override
public void onBackPressed() {
if (isTaskRoot()) {
Intent intent = new Intent(this,YourMainActivity.class);
startActivity(intent);
super.onBackPressed();
}else {
super.onBackPressed();
}
}
A: For whose who still might need answer. It looks like this is what you want to achieve:
When you start an Activity from a notification, you must preserve the user's expected navigation experience. Clicking Back should take the user back through the application's normal work flow to the Home screen, and clicking Recents should show the Activity as a separate task.
http://developer.android.com/guide/topics/ui/notifiers/notifications.html#NotificationResponse
Your situation is - Setting up a regular activity PendingIntent
See full steps in the link. Basically you need to:
1. Define Activity hierarchy in AndroidManifest.xml
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ResultActivity"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity"/>
</activity>
2. Create a back stack based on the Intent that starts the Activity:
...
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(resultIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
...
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(id, builder.build());
A: It works for me. try this:
notifyIntent.setAction(Intent.ACTION_MAIN);
notifyIntent.addCategory(Intent.CATEGORY_LAUNCHER);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614429",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Different column types on INNER JOIN So I got two tables that I'll reference with a INNER JOIN. In one side the column type is Number(3, 0) and in the other is Varchar(150). Seeing that I CAN'T change the data types, I have to Cast it on the join. But, on the table that the column is varchar the string always have 3 digits like '001', '010' or even '100' and so on...
My solution is use Case on the join like this:
INNER JOIN TAB1 ON TAB1.VARCHAR_COL = Cast(Case...), AS Varchar(150)
The Case have to format the number to a string with the tree digits prefixed, like mentioned above.
If data comes like '1', Case have to format as '001', if comes like '10', it will change to '010'...
Help me with the Case.
Edit: The varchar column have some values that aren't numbers, so casting it show an error.
A: Doesn't seem like any need for CASE at all.
TAB1.VARCHAR_COL = TO_CHAR( TAB2.NUMBER_COL, '000' )
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I change the Android Manifest to launch an Application instead of an Activity? I would like my program to extend the Application class to and launch from it's Overridden onCreate() method, rather than from an Activity class. How do I change the manifest to launch an application?
I only know how to launch activities like this:
<activity
android:name=".TestActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
How can I tell Android that it needs to launch from an Application instead?
A: First of all check the use of Application Class
Application class is used to declare Global variables and other stuffs but it doesn't have any UI.
To declare Application class you just need to add android:name attribute in your application tag in the AndroidManifest file
<application android:icon="@drawable/icon" android:label="@string/app_name" android:name=".myApplication_class_name">
A: You can't. Android does not work this way. Activities are a main UI component. If you want to show UI to user you must use activities.
http://developer.android.com/guide/topics/fundamentals.html#Components
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: can we declare a public variable in asp using vb I have a established connection to my database using
adoCon.Open "Driver={SQL Server}; Server=" & host_name & "; Database=" & db_name & "; Uid=" & user_name & "; Pwd=" & password
Now i want to use this connection on all the pages of my website. How to do that? Is there anyway to make adoCon variable public so that it can be accessible from all the pages.
Thanks
A: Is it Classic ASP you're talking about?
Use the global.asa file to create an application object, such as:
Sub Application_OnStart
Application("some name") = "Your connection string"
End Sub
Then you can reuse it in all your pages, such as:
Dim rsObj,cnObj, sSQL
Set cnObj = Server.CreateObject ("ADODB.Connection")
cnObj.Open Application("some name")
Set rsObj=Server.CreateObject("adodb.recordset")
sSQL="your sql string"
With rsObj
.Open sSQL, cnObj
If Not( .BOF or.EOF ) Then
[do some stuff]
End If
.Close
End With
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Border-image not working for QWidget I have a class derived from QWidget. When I try to use the style-sheet to set the border-image, it appears to ignore it. I am using QT 4.4 and it looks like the QWidget should support border-image. Is there something I would need to do in the paint event to get it to display, or something else I am missing?
Also, is it possible to define a series of images for the border, using border-top-left-image and the rest?
A: Try subclassing QFrame instead of QWidget. I've never seen a border* style sheet work on a plain QWidget.
A: You need to provide a paint event for your QWidget-derived-widget to make sure it loads the stylesheet.
void MyWidget::paintEvent(QPaintEvent * event)
{
QStyleOption option;
option.init(this);
QPainter painter(this);
style()->drawPrimitive(QStyle::PE_Widget, &option, &painter, this);
QWidget::paintEvent(event);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Confusion when comparing StartDate and EndDate in asp.net I am a bit confused when comparing StartDate and EndDate in my asp.net app.
EndDate: 10/1/2011
StartDate: 9/30/2011
The if statement below returns true, based on the date values above.
If strEndDate < strStartDate Then
I would think the If statement shoudl return false. The concept is supposed to be that if EndDate is earlier than StartDate, display an error message.
A: I'm assuming that since your variables are called strEndDate and strStartDate that they're strings, not DateTimes. Since they're strings, and since '1' < '9' (the first characters in the strings), strEndDate is indeed "less than" strStartDate.
Convert the values to DateTime before comparing:
If DateTime.Parse(strEndDate) < DateTime.Parse(strStartDate) Then
'...
End If
A: If those are DateTime variables, that code should evaluate to true. If not, you should convert them to DateTime.
DateTime start = DateTime.Parse(strStartDate);
DateTime close = DateTime.Parse(strEndDate);
if (close > start)
//do something
You can also compare them like this:
if ((close - start).TotalDays > 0)
//do something
As Rick Schott pointed out, you can also use DateTime.Compare
A: You should be using DateTime.Compare.
Dim date1 As Date = DateTime.Parse(strStartDate)
Dim date2 As Date = DateTime.Parse(strEndDate)
Dim result As Integer = DateTime.Compare(date1, date2)
Dim relationship As String
If result < 0 Then
relationship = "is earlier than"
ElseIf result = 0 Then
relationship = "is the same time as"
Else
relationship = "is later than"
End If
Console.WriteLine("{0} {1} {2}", date1, relationship, date2)
' The example displays the following output:
' 8/1/2009 12:00:00 AM is earlier than 8/1/2009 12:00:00 PM
A: Don't compare them as strings, compare them as dates.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: EE layout logic We are a church with four different locations: let’s call them North, South, East and West. Now, each of these locations has ‘Ministries:’ Let’s call them Man, Boy, Woman, Girl.
Here’s where the problem lies, not all of the locations have all of the same ‘Ministries.’ Basically, I’m setting the backend up in EE to where ‘Ministries’ is a channel, and I created a category group called ‘Locations’ that holds North, South, East and West as categories. I then set up a static template for North, South, East and West so that the URL will look like site.com/north/ministries/man, etc… My problem is I can’t figure out how to get category linking to work. For example, under my North template page, I make a call to show all entries that hold the ‘Man’ category. The only problem is that I’m not sure where I can send the link for ‘Man’ once the user clicks it. For instance, whatever URL the user clicks on from the category needs to know that the category was sent from the ‘North’ location because the content for each ‘Ministry’ is different depending on which location it’s in. Any idea’s would be hugely appreciated.
Thanks!
A: @rjb and @Stephanie, thanks for your comments. I finally decided that using the Multi-Site Manager to turn each campus into it's own 'site' in a sub-folder of the main site was the practical way to go, since each campus is likely going to have a large amount of unique content in the future.
Since they're separated by 'site' now, it's super easy using categories to relate content, since it's all going to be properly related now. Thanks again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Animate only views that are on-screen So I want to have transition between my app's views that consist of a special animation. In a nutshell, said animation fades out every single subview of the page you are on, one after another, before continuing to the next. The obvious problem is, if I use an UIScrollView at some point, my animation would just fade out the contents of the entire scrollview, which would take way too long, and not just the ones you see on-screen. Which brings me to my question:
Is it possible to get all the subviews of an UIView that are currently visible on-screen?
Thanks in advance
A: You could check which views are on the visible area of the scroll view with something like this:
CGRect visibleArea = CGRectMake(scrollView.contentOffset.x, scrollView.contentOffset.y, scrollView.view.frame.size.width, scrollView.view.frame.size.height);
NSMutableArray *visibleViews = [[NSMutableArray alloc] init];
for(UIView *view in scrollView.subviews){
if(CGRectIntersectsRect(visibleArea, view.frame)
[visibleViews addObject:view];
}
The result would be that you'd have an array (visibleViews) with all the views which's rects intersect with the visible rect of the scroll view. You could then animate only the views in said array.
PS. I didn't test that code, but it should give you the general idea.
A: Loop through all of the subviews in an animation and remove them from the superview, and before commitAnimations, and then change VC:
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:1.0f];
for (UIView *view in self.view.subviews) {
[view removeFromSuperview];
}
[UIView commitAnimations];
[self.navigationController performSelector:@selector(pushViewController:) withObject:viewControllerToSwitchTo afterDelay:1.0f];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why doesn't a properies code block get hit when stepping though C# code? I'm trying to understand how Properties work. I've found that stepping though sample code can be very helpful. But When I step through a small program with a simple class and Property, the Property never gets hit. Which makes me wonder if its even being used. With the code below I can see that the private variables of the class are touched but nothing else. I'm confused. Plus if anyone has found a site or video that was their "ah hah" moment for understanding class properties I'd love to see it.
using System;
public class Customer
{
private int m_id = -1;
public int ID
{
get
{
return m_id;
}
set
{
m_id = value;
}
}
private string m_name = string.Empty;
public string Name
{
get
{
return m_name;
}
set
{
m_name = value;
}
}
}
public class CustomerManagerWithProperties
{
public static void Main()
{
Customer cust = new Customer();
cust.ID = 1;
cust.Name = "Amelio Rosales";
Console.WriteLine(
"ID: {0}, Name: {1}",
cust.ID,
cust.Name);
Console.ReadKey();
}
}
Thanks!
A: You have to modify the default debugger settings to step into properties (Tools|Options ->Debugging->General):
A: You should check your settings in Visual Studio, in: Tools -> Options -> Debugging, there is the option:
Step over properties and operators (Managed only)
Make sure this is unchecked.
A: In Visual Studio 2010, the default is to step over properties. You can change this behavior in the Tools -> Options -> General -> Step over properties and operators (Managed only).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614473",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Passing array in function I have an array that is read like this:
MyArray(0)='test'
MyArray(1)='test2'
MyArray(2)='test3'
How do I pass this through a function?
Function(MyArray(all_arrays))
What do I put for all_arrays?
A: MyArray(0)='test'
MyArray(1)='test2
MyArray(2)='test3'
AcceptArray MyArray
Private Function AcceptArray(myArray())
'Code here
End Function
You look to want to pass a string before the array.
So, change the Function to :
Private Function AcceptArray(param1, myArray)
'Code here
'Don't forget to return value of string type.
End Function
And you call this function like this:
returnValue = AcceptArray("MyString", MyArray)
If you do not need to return a value you should use a Sub.
A: Looks like you need to define you function as such:
Function <FunctionName>(byref <list Name>)
then when you call it in your code use
<FunctionName>(MyArray)
found here:
http://www.herongyang.com/VBScript/Function-Procedure-Pass-Array-as-Argument.html
passing by referrence using just the array name allows you to pass in the entire array to the function
A: A simple example...
Dim MyArray(2)
MyArray(0) = "Test"
MyArray(1) = "Test2"
MyArray(2) = "Test3"
ProcessArray MyArray
' -------------------------------------
' ProcessArray
' -------------------------------------
Sub ProcessArray(ArrayToProcess())
For i = 0 To 2
WScript.Echo ArrayToProcess(i)
Next
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to scrape the 'More' portion of the Quora profile page? To determine the list of all topics on Quora, I decided to start from scraping the profile page with many topics followed, e.g. http://www.quora.com/Charlie-Cheever/topics. I scraped the topics from this page, but now I need to scrape the topics from the Ajax page which is loaded when you click on 'More' button at the bottom of the page. I'm trying to find the javascript function executed upon clicking on 'More' button, but no luck yet. Here are three snippets from the html page which may be relevant:
<div class=\"pager_next action_button\" id=\"__w2_mEaYKRZ_more\">More</div>
{\"more_button\": \"mEaYKRZ\"}
\"dPs6zd5\": {\"more_button\": \"more_button\"}
new(PagedListMoreButton)(\"mEaYKRZ\",\"more_button\",{},\"live:ld_c5OMje_9424:cls:a.view.paged_list:PagedListMoreButton:/TW7WZFZNft72w\",{})
Does anyone of you guys know the name of javascript function executed when clicking on 'More' button? Any help would be appreciated :)
The Python script (followed this tutorial) at this point looks like this:
#just prints topics followed by Charlie Cheevers from the 1st page
#!/usr/bin/python
import httplib2,time,re
from BeautifulSoup import BeautifulSoup
SCRAPING_CONN = httplib2.Http(".cache")
def fetch(url,method="GET"):
return SCRAPING_CONN.request(url,method)
def extractTopic(s):
d = {}
d['url'] = "http://www.quora.com" + s['href']
d['topicName'] = s.findChildren()[0].string
return d
def fetch_stories():
page = fetch(u"http://www.quora.com/Charlie-Cheever/topics")
soup = BeautifulSoup(page[1])
stories = soup.findAll('a', 'topic_name')
topics = [extractTopic(s) for s in stories]
for t in topics:
print u"%s, %s\n" % (t['topicName'],t['url'])
stories = fetch_stories()
A: You can see it in your browser's dom inspector under Event Listeners. It's an anonymous function and looks like this:
function (){return typeof d!=="undefined"&&!d.event.triggered?d.event.handle.apply(l.elem,arguments):b}
This looks like a difficult website to scrape, you might consider using selenium.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Connecting remote Oracle Database server from a Perl script running on Unix, without Oracle client I have a Unix machine which I need to connect to a remote Oracle database server though Perl/Shell script. I have searched online but did not find a thorough information on whether it's possible to connect the Unix machine with the Oracle DB server without installing an Oracle client.
A: I suppose that you don't want / have the opportunity of installing the Oracle Client (that's the better choice). If you don't mind the performance and use Java as a bridge, you can take a look at DBD::JDBC module. It has a server you need to start from the command line with Java.
From the documentation: the DBD::JDBC server is a Java application intended to be run from the command line. It may be installed, along with whatever JDBC driver you wish to use (i.e classes12.jar), on any host capable of accessing the database you wish to use via JDBC.
Perl applications using DBD::JDBC will open a socket connection to this server. You will need to know the hostname and port where this server is running. You can install the server at the same machine you are running the Perl script, or other if you want.
I use this solution at scenarios like yours, where I cannot install the Oracle Client and I don't have high performance requirements in database access.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to place an android animation on top of the phonegap web view? I'm new to phonegap / java. Because CSS Animation/Javascript animation is slow in Android, I am trying to create a Phonegap plugin that will place a native android animation on 'top' of the webview Phonegap uses.
Example: A clock background in the asset HTML, and a 'handRotation' plugin that will put an a native android animation of rotating hands on top of the webview.
If this is not clear let me know. I will continue trying to see if this is possible, and post my findings here, but any assistance is appreciated!
***UPDATE
I figured it out.
So given you have gotten through the Phonegap Plugin tutorial and you're sitting at your class that extends Plugin, here is what I did:
public PluginResult execute(String arg0, JSONArray arg1, String arg2) {
// TODO Auto-generated method stub
new Thread(new Runnable(){
public void run(){
final SampleView hands = new SampleView(webView.getContext());
webView.post(new Runnable(){
public void run(){
webView.addView(hands, new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.FILL_PARENT
));
}
});
}
}).start();
return new PluginResult(Status.OK, webView.getId());
}
*The thread/runnable stuff is from the 2nd example in the Android UI Thread Ref (any edits to the webView must be ran by the UI Thread)
** The magic door was knowing about the webView variable in the Plugin class, which refers back to the Phonegap webview. I found out about this only after peaking into the class.
***The SampleView is a view that contains a rotationAnimation. Here is the code for reference:
public static class SampleView extends View {
private AnimateDrawable mDrawable;
public SampleView(Context context) {
super(context);
setFocusable(true);
setFocusableInTouchMode(true);
Drawable dr = context.getResources().getDrawable(R.drawable.handtrim);
dr.setBounds(0, 0, dr.getIntrinsicWidth(), dr.getIntrinsicHeight());
Log.v("test", "test");
RotateAnimation an = new RotateAnimation(0f, 360f, 13f, 133f);
an.setDuration(2000);
an.setRepeatCount(-1);
an.setInterpolator(getContext(), android.R.anim.linear_interpolator);
an.initialize(10, 10, 10, 10);
mDrawable = new AnimateDrawable(dr, an);
an.startNow();
}
@Override protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.TRANSPARENT);
int w = canvas.getWidth();
int h = canvas.getHeight();
int cx = w / 2;
int cy = h / 2 - mDrawable.getIntrinsicHeight();
canvas.translate(cx, cy);
mDrawable.draw(canvas);
invalidate();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Create vhost conf I want to configure a vhost for php so that my open base dir restriciton is overwritten but it does not use my vhost.conf.
My php.ini always shows open_basedir /var/www/vhosts/domain/httpdocs/:/tmp/ |||| no value last value is global but local has a value. I want to overwrite this with the following vhost.conf which is lying under /var/www/vhosts/domain/conf
<Directory /srv/www/vhosts/domain/httpdocs>
AllowOverride All
php_admin_value open_basedir none
</Directory>
Its not a subdomain.
ls -al
-rwxrwxrwx 1 root psaserv 295 2011-09-30 19:43 vhost.conf
Steps to reproduce:
login as root
cd /var/www/vhosts/domain/conf
touch vhost.conf
added content
/usr/local/psa/admin/sbin/websrvmng --reconfigure-vhost --vhost-name=domain
/etc/init.d/apache2 restart
no change :(
I am using ubuntu with plesk.
A: Did you include your new conf file in httd.conf?
Try adding this line to the end of httpd.conf:
Include /var/www/vhosts/domain/conf/vhost.conf
and then restart apache
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614484",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Java / SSL Server Socket I am writing an application that will accept LDAP queries via port 636, do some non ldap stuff, and then hand back an ldap looking response.
I'm a bit new to Java but have managed this much - I created a self signed cert, imported it into the keystore.
When attempting to make a connection I get the following error -
main, handling exception:
javax.net.ssl.SSLHandshakeException: Received fatal alert: unknown_ca
Argh... I've included the debug information at the bottom.. My application does find the cert in the keystore - Thanks for any help.
System.setProperty("javax.net.debug", "ssl");
System.setProperty("javax.net.ssl.keyStore", "C:\\openssl\\certs\\laptop.ks");
System.setProperty("javax.net.ssl.keyStorePassword", "somepassword");
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
System.setProperty("javax.net.ssl.trustStore", "C:\\openssl\\certs\\laptop.ks");
int port = 636;
ServerSocketFactory ssocketFactory = SSLServerSocketFactory.getDefault();
ServerSocket ssocket;
ssocket = ssocketFactory.createServerSocket(port);
// Listen for connections
while (true)
{
Socket socket = ssocket.accept();
InputStream in = socket.getInputStream();
// do stuff
socket.close();
}
///// DEBUG OUT when program is run
keyStore is : C:\openssl\certs\laptop.ks
keyStore type is : jks
keyStore provider is :
init keystore
init keymanager of type SunX509
***
found key for : mylaptop
chain [0] = [
[
Version: V1
Subject: CN=Donny Shrum, OU=HPC, O=FSU, L=Tallahassee, ST=FL, C=US
Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5
Key: Sun RSA public key, 1024 bits
modulus: <SNIP>
public exponent: 65537
Validity: [From: Fri Sep 30 09:55:27 EDT 2011,
To: Sat Sep 29 09:55:27 EDT 2012]
Issuer: CN=Donny Shrum, OU=HPC, O=FSU, L=Tallahassee, ST=FL, C=US
SerialNumber: [ 03]
]
Algorithm: [SHA1withRSA]
Signature: <snip>
]
***
trustStore is: C:\openssl\certs\laptop.ks
trustStore type is : jks
trustStore provider is :
init truststore
adding as trusted cert:
Subject: CN=Donny Shrum, OU=HPC, O=FSU, L=Tallahassee, ST=FL, C=US
Issuer: CN=Donny Shrum, OU=HPC, O=FSU, L=Tallahassee, ST=FL, C=US
Algorithm: RSA; Serial number: 0x3
Valid from Fri Sep 30 09:55:27 EDT 2011 until Sat Sep 29 09:55:27 EDT 2012
adding as trusted cert:
Subject: CN=Donny Shrum, OU=HPC, O=FSU, L=Tallahassee, ST=FL, C=US
Issuer: CN=Donny Shrum, OU=HPC, O=FSU, L=Tallahassee, ST=FL, C=US
Algorithm: RSA; Serial number: 0xb85a831528797e79
Valid from Fri Sep 30 09:53:23 EDT 2011 until Sat Sep 29 09:53:23 EDT 2012
trigger seeding of SecureRandom
done seeding SecureRandom
Allow unsafe renegotiation: true
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
matching alias: mylaptop
main, called closeSocket()
Allow unsafe renegotiation: true
Allow legacy hello messages: true
Is initial handshake: true
Is secure renegotiation: false
main, READ: SSL v2, contentType = Handshake, translated length = 65
*** ClientHello, TLSv1
Cipher Suites: <snip>
***
Cipher suite: SSL_RSA_WITH_RC4_128_MD5
*** Certificate chain
chain [0] = [
[
Version: V1
Subject: CN=Donny Shrum, OU=HPC, O=FSU, L=Tallahassee, ST=FL, C=US
Signature Algorithm: SHA1withRSA, OID = 1.2.840.113549.1.1.5
Key: Sun RSA public key, 1024 bits
modulus: <snip>
public exponent: 65537
Validity: [From: Fri Sep 30 09:55:27 EDT 2011,
To: Sat Sep 29 09:55:27 EDT 2012]
Issuer: CN=Donny Shrum, OU=HPC, O=FSU, L=Tallahassee, ST=FL, C=US
SerialNumber: [ 03]
]
Algorithm: [SHA1withRSA]
Signature:
]
***
*** ServerHelloDone
main, WRITE: TLSv1 Handshake, length = 662
main, READ: TLSv1 Alert, length = 2
main, RECV TLSv1 ALERT: fatal, unknown_ca
main, called closeSocket()
A: I wish I had a definitive answer, but the SO questions here and here seem to indicate a problem with the way the certificate was generated or imported. The first suggests regenerating without any extensions enabled. The second suggests ensuring the cert you import has the entire chain (which may not be applicable for your self-signed cert).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Telerik RADGrid and sorting I'm using the RADGridView for WPF to display some data. It is pulled dynamically from DB so I don't know column names or the type of data contained in each cell. I want to let the user sort the data on each column when it double-clicks on a column header.
For some reason the grid doesn't sort. This is what I have so far.
private void SetEventHandlers()
{
if (_grid != null)
{
_grid.AddHandler(GridViewCellBase.CellDoubleClickEvent, new EventHandler<RadRoutedEventArgs>(OnCellDoubleClick), true);
}
}
private void OnCellDoubleClick(object sender, RoutedEventArgs e)
{
GridViewCellBase cell = e.OriginalSource as GridViewCellBase;
if (cell != null && cell is GridViewHeaderCell)
{
SetSorting(cell);
}
}
private void SetSorting(GridViewCellBase cell)
{
GridViewColumn column = cell.Column;
SortingState nextState = GetNextSortingState(column.SortingState);
_grid.SortDescriptors.Clear();
if (nextState == SortingState.None)
{
column.SortingState = SortingState.None;
}
else
{
_grid.SortDescriptors.Add(CreateColumnDescriptor(column, nextState));
column.SortingState = nextState;
}
}
EDIT:
private ColumnSortDescriptor CreateColumnDescriptor(GridViewColumn column, SortingState sortingState)
{
ColumnSortDescriptor descriptor = new ColumnSortDescriptor();
descriptor.Column = column;
if (sortingState == SortingState.Ascending)
{
descriptor.SortDirection = ListSortDirection.Ascending;
}
else
{
descriptor.SortDirection = ListSortDirection.Descending;
}
return descriptor;
}
A: It turned out than my RadGrid data was binded to an ObservableCollection. Sorting functionality of the grid itself did not work. Sorting the ObservableCollection was the solution. I ended up sorting the ObservableCollection using linq.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to make a android ListView with a ImageView and TextView in Each Line?
Possible Duplicate:
Can I have a List view and images icon with textview on the Android
How to make a android ListView with a ImageView and TextView in Each Line?
I am working on a Android app that is going to have a screen with a ListView on it and its going to need a ImageView and a TextView on each line... can someone please help me out with some clues and samples
A: You will need to teach your ListAdapter how to do that. This may be by subclassing it and overriding getView(), if this is an ArrayAdapter. You can design your own custom rows and use those, pouring in the data for the ImageView and TextView as the rows get loaded.
Here is a free excerpt from one of my books that goes through the process. Here is the source code to the sample projects profiled in that chapter.
A: In short, you should use a ListActivity. You'll be able to set the layout xml for each row.
Take a look at this
tutorial:
What you need to do is the same, but adapt it to have an ImageView in addition to a textview.
A: As mentioned, you will need to extend an adapter and use it in your ListActivity. Make an XML file with a TextView and an ImageView (using LinearLayout or any other layout). You can add IDs to TextView and ImageView so you can change them according to the position in the list.
Here is a code example that creates three rows and sets the text in them to a, b, c.
public class MyActivity extends ListActivity {
private String[] data = {"a","b","c"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new MyAdapter(this, R.layout.rowxml, data));
}
private class MyAdapter extends ArrayAdapter<String> {
public MyAdapter(Context c, int i, String[] s) {
super(c, i, s);
}
@Override
public View getView(int position, View v, ViewGroup parent) {
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.rowxml, null);
}
TextView tw = (TextView) v.findViewById(R.id.text);
if (tw != null) tw.setText(data[position]);
// You can do something similar with the ImageView
return v;
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614489",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Order numbers with Lua I'm trying to make something to find the median, mode, mean, and range of a set of data. Mean is easy to find using the programming; but median, mode, and range require the numbers to be in order (from least to greatest).
Also, I'm trying to assemble it so it returns the data I would need to make a box and whisker plot. (Not all, just the basic).
Right now I'm simply working on this:
Order the numbers into a table (that a function will return)
QWERTYUIOP[]\
Okay, here's the main question:
How would I do this?
This is what I'm running on:
function Order_Numbers(Data_Set, Greatest_Integer, Least_Integer)
local Ordered = {} --Give a place for the numbers to go
for i=Least_Integer, Greatest_Integer do --Start from the lowest value, continue to highest.
table.insert(Ordered, Data_Set[i])
end
return Ordered
end
But it doesn't work!
Anyone have ideas?
A: Have you considered using table.sort? It even allows you to provide a function to do the comparison.
A: If you can sort in place, use table.sort(Data_Set).
A: The Lua distribution includes sort.lua which has a simple implementation of quick sort; slightly simplified, the core is as follows:
function qsort(vec, low, high)
if low < high then
local middle = partition(vec, low, high)
qsort(vec, low, middle-1)
qsort(vec, middle+1, high)
end
end
-> http://lua-users.org/wiki/LazySort
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: MGSplitViewController with all github patches? I am interested in using MGSplitViewController but it seems that is has current bugs, especially when used in a tabbarController. I see that there are quite a few submitted patches on github for this. Is there a way to pull the files with all those patches? Or does someone have a branch that they are updating with all the new patches?
Thanks so much.
A: The article "Quickly applying GitHub pull " details how to apply a pull request (which is at its core a patch)
See the patch and apply section of the Send Pull Request GitHub help
Another approach that’s a bit quicker in one-off cases is to use git-am.
Every pull request has a .patch URL where you can grab a textual patch file to feed into the git-am command:
In your case:
$ git checkout master
$ curl https://github.com/mattgemmell/MGSplitViewController/pull/43.patch | git am
$ git push origin master
Since you can list pull requests through the GitHub api, you can combine that in order to quickly apply all current pending pull requests.
A: I created an answer for a similar question.
I use git-pull-request to get the list of open pull requests with <number>, <user> and <branch>.
This can also be gathered manually at the web page of every request.
Then I pull the corresponding github branches directly.
# pull request <number>
git pull https://github.com/<user>/MGSplitViewController <branch>
See Merging a pull request from the github help.
I don't like applying patches with https://github.com/<user>/<repo>/pull/<number>.patchwhen I have the repositories at hand.
Especially since commit hashes can change using git am, which would "mess up" the github network view.
See should-git-apply-or-git-am-come-up-with-the-same-hash
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614494",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get only from second TR to last from table i have a variable $response and in it i have object of a table
the table has ID
i'm trying to have the variable only with the TR (no TABLE tag or /Table tag) and the TD content
i have tried:
$response = $response.find('#gGridView1');
$response = $response.find('tr').slice(1);
and
$response = $response.find('#gGridView1');
$response = $response.find('tr:first').remove();
i have fixed my first quesiton
the answer is:
$response = $response.find('#gGridView1');
$response.find('tr:first').remove();
in addition, what would be the way without each or loop to have every TD in the table that is the second column to have a specific width of 100px?
A: I believe you are looking for the nth-child selector:
http://api.jquery.com/nth-child-selector/
So for example, something like:
$response.find('td:nth-child(2)').css('width','100px');
A: To get every tr that is not the first, just select everyone that is not the first:
$response = $response.find("#table tr:not(:first)");
For the second td of every tr use the nth-child selector:
$response = $response.find("#table tr td:nth-child(2)");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614496",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Powershell regex for connectionStrings? For some reason I'm having a brutal time parsing the connection string in the web.config file.
I've already gotten connectionString but I'm trying to get all the values such as the
*
*Data Source
*Initial Catalog
*Username
*etc...
The connection string looks like:
Data Source=db.sample.com;user
id=sample-user;password=sample-password;Initial
Catalog=sample-catalog;
A: Use System.Data.Common.DbConnectionStringBuilder
$sb = New-Object System.Data.Common.DbConnectionStringBuilder
# Attempting to set the ConnectionString property directly won't work, see below
$sb.set_ConnectionString('Data Source=db.sample.com;user id=sample-user;password=sample-password;Initial Catalog=sample-catalog;')
$sb
Output:
Key Value
--- -----
data source db.sample.com
user id sample-user
password sample-password
initial catalog sample-catalog
See also for more details: DbConnectionStringBuilder does not parse when used in PowerShell
(That is why this funny syntax $sb.set_ConnectionString(...) is used instead of $sb.ConnectionString = ...).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Adding an array to a Class (rails) I'd like to make one of the attributes of my class an array. The class is "Course" and the attribute is Course.evals.
I tried using "serialize," ala http://duanesbrain.blogspot.com/2007/04/ruby-on-rails-persist-array-to-database.html, but for some reason it's not working. Here's my relevant code:
class Course < ActiveRecord::Base
serialize :evals
end
But then when I go into the console, this happens:
ruby-1.9.2-p290 :043 > blah = Course.find(3)
=> #<Course id: 3, evals: nil>
ruby-1.9.2-p290 :045 > blah.update_attribute :evals, "thing"
=> true
ruby-1.9.2-p290 :047 > blah.evals << "thing2"
=> "thingthing2"
ruby-1.9.2-p290 :048 > blah.save
=> true
ruby-1.9.2-p290 :050 > blah.evals
=> "thingthing2"
So blah.evals << "thing2" simply adds "thing2" to the existing "thing" string. It doesn't create a new entry in any array. Does this mean that my program isn't picking up my "serialize" command within the Model? If so, how can I fix it?
A: I believe the problem is that when you initially assign a value to the attribute, its assigned as a string. If you want to store it as an array you need to initialise the variable as an array...
> blah = Course.find(3)
> blah.update_attribute :evals, ["thing"]
As a side note, you can add an optional param to the serialize method to determine which class the attribute should have when deserializing...
class Course < ActiveRecord::Base
serialize :evals, Array
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ruby XML Replacing I have an XML file, and I need to replace the text between two tags with a new string
the tags are <<ConnectionString>ConnectionString>THE OLD TEXT<<ConnectionString>/ConnectionString>
I need to change this to <<ConnectionString>ConnectionString>MY NEW TEXT<<ConnectionString>/ConnectionString>
I can't seem to find anything online, and see that using regex is a bad idea?
Please note, that this file contains more that 1
<<ConnectionString>ConnectionString>THE OLD TEXT<<ConnectionString>/ConnectionString>
Lines!
Can someone point my in the right direction or an example?
Andrew
A: Nokogiri is great for things like this. See the Nokogiri::Node#content= method
#!/usr/bin/env ruby
require 'nokogiri'
doc = Nokogiri.XML(DATA) # create a new nokogiri object, this could be a string or IO type (anything which responds to #read)
element = doc.at('ConnectionString') # fetch our element
element.content = "MY NEW TEXT" # change the content
puts doc #=> <?xml version="1.0"?>\n<ConnectionString>MY NEW TEXT</ConnectionString>
__END__
<ConnectionString>THE OLD TEXT</ConnectionString>
A: Use nokogiri for dealing with XML files. See this for the specific task.
A: I agree in general to use nokogiri over regex in xml but in this case I think it's overkill.
xml = open(xmlfile).read.gsub /<ConnectionString>THE OLD TEXT<\/ConnectionString>/, '<ConnectionString>MY NEW TEXT</ConnectionString>'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to find all the descendants with SQL? Each entity can have one parent. I need to find all the descendants of a given entity.
Is it possible with just SQL?
I can only think in terms of a script, and it won't be as fast as sql alone.
I'm using PHP and MS SQL Server 2005, and doctrine 2 DBAL
A: For SQL Server 2005+, you can use a recursive CTE.
WITH cteRecursion AS (
SELECT PrimaryKey, 1 AS Level
FROM YourTable
WHERE PrimaryKey = @GivenEntity
UNION ALL
SELECT t.PrimaryKey, c.Level+1
FROM YourTable t
INNER JOIN cteRecursion c
ON t.ParentKey = c.PrimaryKey
)
SELECT PrimaryKey, Level
FROM cteRecursion
ORDER BY Level, PrimaryKey;
A: PHP will run one SQL statement at a time so you will need to create this list in a loop. A good alternative is to use nested sets.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JSF 2: Change rendered atribute of a component on phase listener Hy guys,
In JSF 2 How can I change the rendered atribute of a h:InputText component using a PhaseListener.
Before the jsf page be rendered I have to verify all id of the h:inputtexts, and after that I will change the atribute to be rendered or not.
Am I clear?
A: On GET requests, the view root is not created yet during the before phase of the render response and during the after phase it's too late because the response is already been rendered and sent to the client. The view root is however available for modification during the "pre render view" system event.
public class PreRenderViewListener implements SystemEventListener {
@Override
public void processEvent(SystemEvent event) throws AbortProcessingException {
UIViewRoot root = (UIViewRoot) event.getSource();
// ...
}
@Override
public boolean isListenerForSource(Object source) {
return true;
}
}
To get it to run, register it as follows in faces-config.xml:
<application>
<system-event-listener>
<system-event-listener-class>com.example.PreRenderViewListener</system-event-listener-class>
<system-event-class>javax.faces.event.PreRenderViewEvent</system-event-class>
</system-event-listener>
</application>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Can we delete the "getContext" property of HTML5 Canvas tag through script? There is a HTML5 conformance test suite with a test for prototype for HTMLCanvasElement.
This test fails for Safari, Firefox but passes for Opera on Windows 7.
The test has a script which tries to delete the getContext property of the HTMLCanvasElement, and further trying to read getContext should give undefined.
delete window.HTMLCanvasElement.prototype.getContext;
_assertSame(window.HTMLCanvasElement.prototype.getContext, undefined, "window.HTMLCanvasElement.prototype.getContext", "undefined");
This test fails for WebKit (Safari) because the getContext property has DontDelete attribute and so it does not allow the script to delete this property.
Is there any description in the HTML5 specification which says deletion of getContext property by script is valid?
A:
Is there any description in the HTML5 specification which says deletion of getContext property by script is valid?
No, nothing explicit in the spec about that. No idea why webkit is different than FF/Opera here (It is Chrome too that disallows delete), but the spec itself does not demand DontDelete for anything on the Canvas. Something else in the ECMAScript spec might.
Firefox 7 and 8 alpha do not delete window.HTMLCanvasElement.prototype.getContext though. They just return true, but getContext is still there. In other words, the test you linked to fails in the exact same place and for the same reason.
Webkit of course still allows you to overwrite whatever you want: window.HTMLCanvasElement.prototype.getContext = undefined
A: From what I understand, the configurability ([[DontDelete]] in ES3, [[Configurable]] in ES5) of getContext method is described in WebIDL — as any other CanvasRenderingContext2D methods.
Take a look at "Interface Prototype Object" section, which says:
There must exist an interface prototype object for every interface defined, regardless of whether the interface was declared with the [NoInterfaceObject] extended attribute. The interface prototype object for a particular interface has properties that correspond to the attributes and operations defined on that interface. These properties are described in more detail in sections 4.5.5 and 4.5.6 below.
And in 4.5.6, you can see:
For each unique identifier of an operation defined on the interface, there must be a corresponding property on the interface prototype object (if it is a regular operation) or the interface object (if it is a static operation), unless the effective overload set for that identifier and operation and with an argument count of 0 (for the ECMAScript language binding) has no entries.
The characteristics of such a corresponding property are as follows:
The name of the property is the identifier.
The property has attributes { [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true }.
Note the "[[Configurable]]: true" bit (emphasis mine).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Cross platform build system with IDE? I've been searching since around a year for a combination of C++ build system and IDE which brings the following features:
*
*Cross plattform build system that builds atleast on Windows, Linux and Mac OS.
*Some sort of inteligent code completion (IntelliSense of Visual Studio, that thing fromEclipse).
*Debugger integrated inside the IDE (starting debugging, setting breakpoints in the code, ...).
*No need to restart programms all over to build, or edit code.
It doesn't matter for me on which operating system the IDE runs, only important aspect is that there is a way to build on other plattforms (possibly without requiring that IDE). The closest I got to these was a combination of CMake + VisualStudio. Problem with that is, that every time you want to adjust your build process (add or delete a file) you have to restart VisualStudio and reconfigure all settings, CMake won't set for you.
A: The Qt framework uses Qmake - it has a cross platform ide QtCreator that uses the qmake .pro files.
There is also a plugin for visual studio that will convert .pro to and from visual studio projects
A: I have investigated a solution like the one you are looking for and haven't found anything satisfactory. I'm currently maintaining separate project files for each of my platforms (Visual Studio, XCode for OSX and iOS, makefiles for Linux, Android and webOS). I have found that it isn't a lot of work to keep them in sync, so I don't mind.
But in any case, here are a couple of ideas that I think are the most promising to achieve what you want:
*
*I think the CMake solution that you are using is the best, but it is true that each time you regenerate your project custom settings are lost. You may want to generate a patch file with all your settings, so that you can reapply those changes after running CMake to update your projects. This should work for settings stored in text files, so it works for .sln, .vcxproj, vcxproj.filters and vcxproj.user files.
*You may have some luck with Eclipse or Netbeans. Both are cross-platform IDEs that will allow you to work with a single project file on multiple platforms. If you have your project under source control, then you can commit the project files from your main platform, and then on other platforms you just check out the projects and make the necessary changes to the settings (directories, etc.). You just need to remember to always commit changes to the projects from the main platform, and on the other ones the local changes will stay only in your local source tree.
Option #2 above is decent, but not an option for me, as I have developed an addiction to the VS debugger, it is so much better than anything else that I would not consider any setup that does not include it.
Good luck!
A: Codeblocks also has a cross-platform build system.
Codeblocks builds itself through its Codeblocks project file.
A: Here is what I ended up doing:
*
*I stuck to CMake over qmake, since it simply seems more powerful, and is easy to install seperatly. Also both only generate Makefiles so they pretty much do the same for me.
*Since the Eclipse/VisualStudio project files created by CMake are only there for building I couldn't use them (running/debugging inside of IDE is not possible). Now I'm creating standard Makefiles and then build these with a hand mantainend Eclipse Project.
*I added a filesystem link to my source directory and code completion and debugging are working.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Tails recursive method to calculate standard deviation public class StampaInversa {
private static class NumberWithCounterAndAverage{
private int number=0;
private int counter=1;
private int average=0;
public int getNumber(){
return number;
}
public int getCounter(){
return counter;
}
public void setNumber(int number){
this.number=number;
}
public void setCounter(int counter){
this.counter+=counter;
}
public int getAverage(){
return avrage;
}
public void setAverage(int average){
this.average=average;
}
public String toString(){
return "Number: "+number+"Counter "+counter+"Average "+average;
}//toString
}//NumeroConContatore
public static void reversePrint(){
Scanner sc= new Scanner(System.in);
System.out.println("Insert number");
int x=sc.nextInt();
if(x==0) return;
reverseprint();
System.out.println(x);
}
public static int sumPrint(){
Scanner sc=new Scanner(System.in);
System.out.println("Insert number");
int x=sc.nextInt();
if(x!=0) x+=sumPrint();
return x;
}
public static NumberWithCounterAndAverage printAverage(){
Scanner sc=new Scanner(System.in);
NumberWithCounterAndAverage ncc= new NumberWithCounterAndAverage();
System.out.println("Insert number");
int x=sc.nextInt();
if(x!=0){
NumberWithCounterAndAverage nccem= printAverage();
ncc.setNumber(x+nccem.getNumber());
ncc.setCounter(+nccem.getCounter());
}
if (x!=0){
ncc.setAverage(ncc.getNumber()/(ncc.getCounter()-1));
}
return ncc;
}
public static void main(String[] args) {
NumberWithCounterAndAverage nccem= printAverage();
System.out.println(nccem.getCounter()+" "+nccem.getNumber()+" average "+nccem.getAverage());
}
}//StampaInversa
My prof. gave me an assignment: write tail recursive functions to calculate:
the sum of the number inserted from input till 0 is inserted;
the average of the number inserted till 0 is inserted;
the standard deviation of the number inserted till 0 is inserted;
The conditions to accomplish the assignment are:
No data structure allowed (arrays, arraryslist, LinkedList...), only ad hoc objects are allowed (such as the one that I have created: NumberWithCounterAndAverage)
No istance variables allowed, the variables must be own only by the functions.
The function must be recursive.
The functions in the code above work perfectly, but now I need to made a recursive function to calculate the standard deviation with the condition descripted above. Do you have any clue?
If it is still not clear how the function should be, tell me.
A: I think the idea you should be going for is to have a function which takes as arguments the current count, sum, average, etc that is needed for the calculation. This would support your requirement for no instance variables unlike what you have above.
The first call to this method would pass all zeros. Each subsequent call would read in one value and if not 0 call itself with the updated values. If zero, do the final calculation and output the results.
The answer is at this post: How to efficiently calculate a running standard deviation?
With this calculation: have the method take the sum_x, sum_x2 and count. (sum_x is the sum of the elements, sum_x2 is the sum of the squares). In the iteration where you receive 0 the results are:
sum = sum_x
average = sum_x / count
stdev = sqrt((sum_x2 / count) - (average * average))
A: To compute the standard deviation, you must, for each amount entered, square the difference between that amount and the average. You can't know the average until all elements are entered. So you'll have to compute the standard deviation while returning from the functions.
To compute the standard deviation, you will need the count, the average, and an accumulator for the sum of the squared differences. This would be your "NumberWithCounterAndAverage" class.
During the initial calls that build the stack, I would input one number per recursion, and pass count and sum variables as parameters.
A: I have solved the assignment, thanks to all of you. Here is the solution,
I have added the double standardDeviation, to the object in the code above
public static NumberWithCounterAndAverage calculateStandardDeviation(){
Scanner sc= new Scanner(System.in);
NumberWithCounterAndAverage nccem= new NumberWithCounterAndAverage();
System.out.println("Insert number");
int x= sc.nextInt();
int counter=1;
int sum=x;
nccem=calculateStandardDeviation(sum, counter);
int partialDeviationSum=((x-nccem.getAverage())*(x-nccem.getAverage()));
nccem.setDeviazioneStandard(partialDeviationSum+nccem.getStandardDeviation());
double standardDeviation= Math.sqrt(nccem.getStandardDeviation());
nccem.setStandardDeviation(standardDeviation);
return nccem;
}
public static NumberWithCounterAndAverage calculateStandardDeviation(int sum, int counter){
Scanner sc= new Scanner(System.in);
NumberWithCounterAndAverage nccem= new NumberWithCounterAndAverage();
System.out.println("Insert number");
int x= sc.nextInt();
int partialSum=0, partialCounter=0;
if(x!=0){
partialSum= x+sum;
partialCounter=1+counter;
nccem=calculateStandardDeviation(partialSum, partialCounter);
}
if(x==0){//I am at the top of the stack, I calculate the average and i go down
nccem.setAverage(sum/counter);
}
if(x!=0){
int sumPartialDeviation=((x-nccem.getAverage())*(x-nccem.getAverage()));
nccem.setStandardDeviation(sumPartialDeviation+nccem.getStandardDeviation());
}
return nccem;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614518",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Strange bug in usage of abs() I encountered recently I have C++/C mixed code which I build on
a) Visual C++ 2010 Express(Free version) on Win-7 x32.
b) Cygwin/Gcc environment installed on a Windows-7 Home premium edition x32. The gcc version 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)
c) Ubuntu 10.04 Linux- GCC version 4.4.3 (Ubuntu 4.4.3-4ubuntu5)
I have a code as below(Its a member function for my user defined class) which computes absolute value of the passed object myhalf-
myhalf::myhalfabs(myhalf a)
{
float tmp;
tmp = abs(a.value); //This abs is from math.h :- float abs(float)
return tmp;
}
This is working perfectly as desired in MS - Visual C++ 2010. abs() of -ve nos were returned correctly as +ve nos having same value.
Strangely when I built this code on b) Cygwin/gcc environment & c) Linux-gcc 4.4.3 mentioned above, I was getting junk output. So fired up gdb, and after lot of sweat and 'binary-search approach' on the code to decide where it started going wrong, I hit this piece of code as shown above :
tmp = abs(a.value);
which was behaving strangely under cygwin/gcc.
For -ve numbers abs() was returning 0(zero). WTF??
Then as a work around, avoided calling abs() from stdlib, and coded my own abs as below:
myhalf::myhalfabs(myhalf a)
{
float tmp;
unsigned int tmp_dbg;
// tmp = abs(a.value);
tmp_dbg = *(unsigned int*)(&a.value);
tmp_dbg = tmp_dbg & 0x7FFFFFFF;
tmp = *(float*)(&tmp_dbg);
return tmp;
}
This worked fine on cygwin/gcc & linux-gcc and output was as desired, And of course it worked fine on MS-Visual C++ 2010.
This is the whole Makefile for the cygwin/gcc and linux-gcc builds, I use. Just if anyone supspects something fishy there:-
OBJS= <all my obj files listed here explicitly>
HEADERS= <my header files here>
CFLAGS= -Wall
LIBS= -lm
LDFLAGS= $(LIBS)
#MDEBUG=1
ifdef MDEBUG
CFLAGS += -fmudflap
LDFLAGS += -fmudflap -lmudflap
endif
myexe: $(OBJS)
g++ $(OBJS) $(LDFLAGS) -o myexe
%.o: %.cpp $(HEADERS) Makefile
g++ $(CFLAGS) -c $<
clean:
rm -f myexe $(OBJS)
1] What is going on here? What is the root cause of this strange bug?
2] Am i using some old version of gcc on cygwin which has this issue as known bug or something?
3] Is this function float abs(float) known to be deprecated or something with a newer version superseding it?
Any pointers are useful.
A: math.h has the C version of abs which operates on ints. Use <cmath> for the C++ overloads or use fabs() for the C floating point version.
A: First, abs() takes and returns an int. You should use fabs(), which takes and returns a floating-point value.
Now, the abs() you're ending up calling is actually a GCC built-in function, which returns an int, but apparently accepts a float argument and returns 0 in that case.
A: Almost certainly what's happening is that in your MSVC case it's picking up the C++ abs float overload (which is probably being brought into the global namespace for some reason or other). And then in g++ it's NOT picking up the C++ version (which isn't implicitly imported into the global namespace) but the C version that works on and returns an int which is then truncating the output to zero.
If you #include <cmath> and use std::abs it should work fine on all your platforms.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
} |
Q: Changing values of multi dimentional arrays I have the results of a mysql query in a multi dimentional array as follows:
Array (
[0] => stdClass Object ( [name] => john doe [id] => [email protected] [userlevel] => 1 )
[1] => stdClass Object ( [name] => mary jane [id] => [email protected] [userlevel] => 5 )
[2] => stdClass Object ( [name] => joe blow [id] => [email protected] [userlevel] => 1 )
);
I would like to loop through these, check the value of the [userlevel] value and if == '5', then modify the [name] value. The idea is to give a visual indicator next to those users that are a certain userlevel.
I've tried to loop through using foreach, but I can't get it to work.
A: foreach ($array as $i => &$user) {
if ($user->userlevel == 5) {
$user->name = 'foo';
}
}
NOTE: The ampersand & is very important here.
Alternatively:
for ($i = 0, $arrayLen = count($array); $i < $arrayLen; ++$i) {
if ($array[$i]->userlevel == 5) {
$array[$i]->name = 'foo';
}
}
A: From PHP documentation site
Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.
A: What have you tried? Something like this should work.
foreach ($result as $i => $item)
{
if ($item->userlevel == 5)
$result[$i]->name = 'modified name';
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614527",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Serial Port reading causes application freezing for a while - Do I need threading? I got some code in c# for reading results of AT command compatible modem.
In case I start COM port reading whole apps freezes until data received. I suppose I should use threading but I've no idea how ?
if (!serialPort1.IsOpen)
serialPort1.Open();
serialPort1.WriteTimeout = 5000;
serialPort1.NewLine = "\r\n";
serialPort1.WriteLine("AT#MON");
serialPort1.NewLine = "\r\n";
while (true) // Loop indefinitely
{
serialPort1.NewLine = "\r\n"; // Prompt
string linee = serialPort1.ReadLine(); // Get string from port
if (System.Text.RegularExpressions.Regex.IsMatch(linee, ("^xcqa:")))
{
textBox1.AppendText(System.Environment.NewLine);
}
if (System.Text.RegularExpressions.Regex.IsMatch(linee, ("^fkss:")))
{
textBox1.AppendText(System.Environment.NewLine);
}
if (System.Text.RegularExpressions.Regex.IsMatch(linee, ("ended"))) // Check string
{
break;
}
textBox1.AppendText(linee);
}
A: Yes. You need to use multithreading. Spawning a new thread will allow other code in your application to carry on simultaneously. For this, your serial port read code would need its own thread. Read up on multithreading doc for C#.
*
*Threading Tutorial
*Threading in C#
*Introduction to Multithreading in C#
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614536",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: can't get json.NET to deserialize and show my values in c# Please help I can't get the values out after user json.NET
Here is the string that I get back from my jquery ajax call:
"[{\"roleInfo\":{\"roleIndex\":0,\"roleID\":\"c1_r0_23\",\"roleName\":\"Chief Executive\"}}, {\"roleInfo\":{\"roleIndex\":1,\"roleID\":\"c1_r1_192\",\"roleName\":\"Chief Operating Officer\"}}]"
Here is the webmethod that exists in my code behind on my aspx page:
List md1 = (List)Newtonsoft.Json.JsonConvert.DeserializeObject(sv, typeof(List));
This is my class for MappedRole:
public class MappedRole
{
public int roleIndex { get; set; }
public int roleID { get; set; }
public string roleName { get; set; }
public MappedRole(){
}
}
These are the values that I get after trying to use JsonConvert.DeserializeObject....notice that I get null and 0 values: I try to see the values while in debug mode.
?md1[0].roleID
0
?md1[0].roleName
null
?md1[0].roleIndex
0
A: Have you tried to run the JSON through the JSON Validator? I ran your sample from your question and it's not validating. Here's the url to the validator: http://jsonlint.com/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614540",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to programmatically log user in with Spring Security 3.1 What's the proper way to programmatically log a web visitor in under a particular username in Spring and Spring Security 3.1? It seems the way I was doing it under 2.5 has changed a little. I'm sure there's a much better way of doing this now.
Basically, when I create a new user, I need to also log them in at the same time.
A: This three lines of code do the work for me:
Authentication request = new UsernamePasswordAuthenticationToken( username, password );
Authentication result = authenticationManager.authenticate( request );
SecurityContextHolder.getContext().setAuthentication( result );
A: If you are interested in doing this for testing purposes you can do this:
UserDetails user = _userService.loadUserByUsername(username);
TestingAuthenticationToken token = new TestingAuthenticationToken(user,null);
SecurityContextHolder.getContext().setAuthentication(token);
Where user service is your thing that implements UserDetailsService
A: Create an Authentication (usually a UsernamePasswordAuthenticationToken) and then call
SecurityContextHolder.getContext().setAuthentication(authentication)
A: You can write a custom UsernamePasswordAuthenticationFilter that extends Spring's UsernamePasswordAuthenticationFilter.
Here is the code:
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class CustomUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, Authentication authResult) throws IOException, ServletException {
super.successfulAuthentication(request, response, authResult);
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) authResult;
WebAuthenticationDetails details = (WebAuthenticationDetails) token.getDetails();
String address = details.getRemoteAddress();
User user = (User) authResult.getPrincipal();
String userName = user.getUsername();
System.out.println("Successful login from remote address: " + address + " by username: "+ userName);
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
super.unsuccessfulAuthentication(request, response, failed);
UsernamePasswordAuthenticationToken token = (UsernamePasswordAuthenticationToken) failed.getAuthentication();
WebAuthenticationDetails details = (WebAuthenticationDetails) token.getDetails();
String address = details.getRemoteAddress();
System.out.println("Failed login try from remote address: " + address);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Facebook Canvas application using Javascript SDK Hope someone can help me out. I have a facebook canvas application. I'm using this code to authenticate
window.fbAsyncInit = function() {
FB.init({ appId: '123842974364777',
status: true,
cookie: true,
xfbml: true,
oauth: true});
this.vars = {
access_token: '',
album_id: '',
items: '',
user_id: '',
photo_path: '',
errorHandler: 'There was a problem posting your picture!<br> Please contact <a href="mailto:[email protected]">[email protected]</a>',
counter: 1
}
authenticate();
function authenticate() {
FB.getLoginStatus(function(response) {
if(response.authResponse) {
// logged and known to app
// store access token
vars.access_token = response.authResponse.accessToken;
sendUserInformation();
} else {
// not logged in or unknow to app
// prompt user to authorize app
FB.login(function(response) {
if(response.authResponse) {
// store access token
vars.access_token = response.authResponse.accessToken
sendUserInformation();
}
}, {scope: 'email,read_stream,user_birthday,user_photos,publish_stream'});
}
});
}
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
My problem is, running this code doesn't show my page in a facebook iframe. it just stays on the web domain. What I need is to get this page shown in a facebook iframe.
What do I have to add to make this happen?
Any help is appreciated!
A: Have you set your canvas url/secure url in the developer app to point to your canvas code?
This should essentially point to your domain like http://mydomain.com/mycanvasfolder where the canvas folder would have the index page you want to show.
You should be able to see a basic page without any other configuration or FB stuff.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614543",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Vim CursorLine color change in insert mode There is good snippet for changing cursor color:
if &term =~ "xterm\\|rxvt"
" use an orange cursor in insert mode
let &t_SI = "\<Esc>]12;orange\x7"
" use a red cursor otherwise
let &t_EI = "\<Esc>]12;red\x7"
silent !echo -ne "\033]12;red\007"
" reset cursor when vim exits
autocmd VimLeave * silent !echo -ne "\033]112\007"
" use \003]12;gray\007 for gnome-terminal
endif
How should I alter this that instead of cursor, CursorLine would change color for example from dark blue to blue?
My complete config is https://bitbucket.org/JackLeo/home-configs/src/5b8faf340f87/.vimrc
A: This is pretty straightforward, put the following in your .vimrc or custom colorscheme file.
set cursorline
autocmd InsertEnter * highlight CursorLine guifg=white guibg=blue ctermfg=white ctermbg=blue
autocmd InsertLeave * highlight CursorLine guifg=white guibg=darkblue ctermfg=white ctermbg=darkblue
For more information see:
*
*:help 'cursorline'
*:help :autocmd
*:help InsertEnter
*:help :highlight
N.B: You can use the same method to change the colour of the cursor without all of those if-statements and escape-sequences (and this will also work in GVim).
A: When using MacVim with 'Lokaltog/vim-powerline' you can setup your normal/visual/insert colors to match the powerline mode color. I find this extremely helpful to know what mode I'm in without reading the powerline, especially on a large screen.
Here is the code I am using, based on @Zarick-Lau's answer.
In my colors/molokai.vim file:
" Visual Mode Orange Background, Black Text
hi Visual guifg=#000000 guibg=#FD971F
" Default Colors for CursorLine
highlight CursorLine guibg=#3E3D32
highlight Cursor guibg=#A6E22E;
" Change Color when entering Insert Mode
autocmd InsertEnter * highlight CursorLine guibg=#323D3E
autocmd InsertEnter * highlight Cursor guibg=#00AAFF;
" Revert Color to default when leaving Insert Mode
autocmd InsertLeave * highlight CursorLine guibg=#3E3D32
autocmd InsertLeave * highlight Cursor guibg=#A6E22E;
Here is an example using the molokai original color scheme.
Normal
Visual
Insert
I also find it's helpful to set the OS up to visually select using the same color too. For example, I've changed my highlight color to Orange in OSX, and when I select text, it is now orange instead of blue, same as in VIM.
Example
Here the orange highlight being used in the text-box as I'm writing this Stack Overflow entry. Now all text I select in my OS matches the VIM setup.
A: Have you look in into the 'highlight' command which is a easier way to control this.
For example, to change the CursorLine,
:hi CursorLine guifg=red guibg=blue
Reference: :help highlight
To make it switch between mode.
" Enable CursorLine
set cursorline
" Default Colors for CursorLine
highlight CursorLine ctermbg=Yellow ctermfg=None
" Change Color when entering Insert Mode
autocmd InsertEnter * highlight CursorLine ctermbg=Green ctermfg=Red
" Revert Color to default when leaving Insert Mode
autocmd InsertLeave * highlight CursorLine ctermbg=Yellow ctermfg=None
I may be possible to mix termcap color with autocmd, but IMO, highlight is more easy to maintain in long term (and in case if use gVim occassionally)
A: I chose to switch CursorLine and Normal in insert mode. First get the values with :hi Normal and :hi CursorLine. Then adjust the following lines:
set cursorline
autocmd InsertEnter * highlight Normal ctermbg=7
autocmd InsertEnter * highlight CursorLine ctermbg=15
autocmd InsertLeave * highlight Normal ctermbg=15
autocmd InsertLeave * highlight CursorLine ctermbg=7
For solarized light, this looks like this. I like the "focus" effect.
A: NO COLOR in current line even if you enter or leave INSERT MODE
"set cursorline
set noshowmode
"Enable CursorLine
set nocursorline
"Default Colors for CursorLine
hi CursorLine cterm=NONE ctermbg=NONE ctermfg=NONE
"Change Color when entering Insert Mode
autocmd InsertEnter * set nocursorline
"Revert Color to default when leaving Insert Mode
autocmd InsertLeave * set nocursorline
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614546",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Find value in array for Wordpress template condition I am using MagicFields in Wordpress with a custom group for Ingredients which is duplicated. The ingredient type field is selected with a radio button.
I am trying to write a conditional statement to only show certain ingredient types (Base, Sauce, etc) so they can be shown in different lists on the page.
An example of what I'm trying to achieve is:
if (in_array('Base', $IngGroup)) {
echo "Base Ingredients";
}
elseif (in_array('Sauce', $IngGroup)) {
echo "Sauce Ingredients";
}
Here is the array output from pr($IngGroup);
Array
(
[1] => Array
(
[ingredient_type] => Array
(
[1] => Main
)
[ingredient_unit] => Array
(
[1] => g
)
[ingredient_amount] => Array
(
[1] => 300
)
[ingredient_name] => Array
(
[1] => Chicken
)
)
[2] => Array
(
[ingredient_type] => Array
(
[1] => Sauce
)
[ingredient_unit] => Array
(
[1] => g
)
[ingredient_amount] => Array
(
[1] => 220
)
[ingredient_name] => Array
(
[1] => Sauce
)
)
)
A: foreach( $IngGroup as $Ing ) {
if( $Ing[ingredient_type][1] == 'Sauce' ) {
echo "Sauce Ingredients";
} elseif ( $Ing[ingredient_type][1] == 'Base' ) {
echo "Base Ingredients";
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614554",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cannot run cshtml configured within an Area I have an Area defined in the MVC project named Account and under views in this Area I have Logon.cshtml. In web.config, I got following
<authentication mode="Forms">
<forms loginUrl="~/Areas/Account/LogOn" timeout="600" />
</authentication>
I am using Authorize attribute on my controllers but when I run the project, get following error
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Areas/Account/LogOn
Any ideas what I am doing wrong?
A: While the files are stored in a folder named Area, this does not mean that the routing to this file is /areas/account/logon.
Review the AccountAreaRegistration.cs in the Account folder. The AreaName defined in this file (most likely Account) is the initial portion of the route to the area. Also, the context.MapRoute line will have the default Route for your area.
In all likelihood, especially if you did not edit the area registration file, the correct path to put in web.config is ~/account/logon.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I repeat steps in a Specflow Scenario Outline In a nutshell, what I need is to create a Scenario Outline with a step that is repeatable without having to type it in using multiple AND's as I am currently doing below:
Scenario Outline: outline
Given I am a user
When I enter <x> as an amount
And I enter <x2> as an amount
Then the result should be <result>
Scenarios:
|x|x2|result|
|1|2 |3 |
|1|0 |1 |
However, I would like to do something like the following:
Scenario Outline: outline
Given I am a user
When I enter <Repeat: x> as an amount
Then the result should be <result>
Scenarios:
|x |result|
|1,2,3|6 |
|1,2 |3 |
Basically, I want the "I enter as an amount" to run 3 and 2 times respectively.
The closest I have found to this question is How do I re-run a cucumber scenario outline with different parameters? , but I wanted to double check before giving up and using a StepArgumentTransformation with a comma separated list or something similar.
The final answer that I went with is something more like this:
Scenario Outline: outline
Given I am a user
When I enter the following amounts
| Amount1 | Amount 2| Amount3|
| <Amt1> | <Amt2> | <Amt3> |
Then the result should be <result>
Scenarios:
|Amt1 |Amt2 |Amt3 |result|
|1 |2 |3 |6 |
There does not seem to be a good way to leave a value blank though, but this is pretty close to the solution I was looking for
A: The Examples keyword:
Scenario Outline: outline
Given I am a user
When I enter <x> as an amount
Then the result should be <result>
Examples:
|x|result|
|1|3 |
|1|1 |
Is for when you want the entire test to take different parameters. It sounds like you want to feed repeating parameters at the When step.
The easier approach that won't require implementation of a StepArgumentTransformation is to simply use a table in the when:
When I enter the following amounts
|Amount|
|2 |
|3 |
|4 |
Then simply iterate all the rows in table to get your arguments. This avoids needing to have an interim method for the transformation.
Alternatives include using more steps or by parameter parsing, so as you say, use the StepArgumentTransformation.
Of course, if you need to test multiple repeating items, you could use both StepArgumentTransformation and Examples: feeding in a comma-list of numbers:
Examples:
|x |result|
|1 |1 |
|1,2,3|6 |
A: You might be able to make use make use of an approach patrickmcgraw suggested on an answer to my question:
SpecFlow/Cucumber/Gherkin - Using tables in a scenario outline
So basically you could take the input x as a normal input string split it on a delimiter in this case ',' and then iterate over it performing your actions i.e. something like below (I haven't tested this code).
[When(@"I enter (.*) as an amount")]
public void IEnterAsAnAmount(string x)
{
var amounts = x.Split(',');
foreach (var amount in amounts)
{
// etc...
}
}
A: This works for me and looks bit more readable too:
Scenario: common scenarios goes here one time followed by scenario outline.
Given I am a user
Scenario Outline: To repeat a set of actions in the same page without logining in everytime.
When I enter <x> as an amount
Then the result should be <result>
Examples:
|x|result|
|1|2|
|2|4|
|4|8|
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614562",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How can I check if Json matches a specific C# type? My Asp.Net MVC application action is returning JSON by serializing one of several C# objects, depending on the circumstances (if an error occurred, one data type if one type of data was retrieved, etc...).
When I try to consume the JSON in a C# windows service, I am having trouble trying to figure out what type of JSON is being returned. Unfortunately from what I have seen, JSON serializers (JSON.Net and whatever RestSharp uses) all have no problem creating an empty object if none of the JSON matches.
I understand why this happens, but I am confused on how to figure out if the values serialized from JSON are legit, or if none of the JSON properties matched and the serializer just created an empty object.
Does anyone know how I would determine if a match exists between JSON and the type I am trying to deserialize to?
A: I don't know exactly how to match between JSON and C# type. But if you want to check is all properties from match appropriate values in JSON you can do Json Serialization Sttributes:
Here I have C# type:
[JsonObject(ItemRequired = Required.Always)]
public class Event
{
public string DataSource { get; set; }
public string LoadId { get; set; }
public string LoadName { get; set; }
public string MonitorId { get; set; }
public string MonitorName { get; set; }
public DateTimeOffset Time { get; set; }
public decimal Value { get; set; }
}
I decorated that type with attribute [JsonObject(ItemRequired = Required.Always)] which requires from all properties to be populated with appropriate properties from JSON text.
There are three imporatnt things:
*
*If you try to deserialize JSON text which doesn't contain properties like in Event class it will throw exception.
*If JSON contains these properties, but doesn't contain values it will pass deserialization.
*If JSON text contains same properties as Event class but contains additional properties too, it will still pass deserialization.
Here is example code:
var message = @"{ 'DataSource':'SomeValue','LoadId':'100','LoadName':'TEST LOAD','MonitorId':'TEST MONITOR','MonitorName':'TEST MONITOR','Time':'2016-03-04T00:13:00','Value':0.0}";
try
{
var convertedObject = JsonConvert.DeserializeObject<Event>(message);
}
catch (Exception ex)
{
}
A: I would recommend using a try and catch block, if your deserialization will throw invalid argument exception then the string was not in proper format.
If you are using System.Web.Script.Serialization
JavaScriptSerializer sel = new JavaScriptSerializer();
try
{
return sel.Deserialize<List<YourObjectType>>(jSONString);
}
catch(System.ArgumentException e)
{
return null;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614564",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Dollar sign before self declaring anonymous function in JavaScript? What is the difference between these two:
$(function () {
// do stuff
});
AND
(function () {
// do stuff
})();
A: The first uses jQuery to bind a function to the document.ready event. The second declares and immediately executes a function.
A: one is a jquery $(document).ready function and the other is just an anonymous function that calls itself.
A: They are both anonymous functions, but (function(){})() is called immediately, and $(function(){}) is called when the document is ready.
jQuery works something like this.
window.jQuery = window.$ = function(arg) {
if (typeof arg == 'function') {
// call arg() when document is ready
} else {
// do other magics
}
}
So you're just calling the jQuery function and passing in a function, which will be called on document ready.
The 'Self-executing anonymous function' is the same as doing this.
function a(){
// do stuff
}
a();
The only difference is that you are not polluting the global namespace.
A: $(function() {}); is a jQuery shortcut for
$(document).ready(function() {
/* Handler for .ready() called. */
});
While (function() {})(); is a instantly invoked function expression, or IIFE. This means that its an expression (not a statement) and it is invoked instantly after it is created.
A: $(function () {
// It will invoked after document is ready
});
This function execution once documents get ready mean, the whole HTML should get loaded before its execution but in the second case, the function invoked instantly after it is created.
(function () {
// It will invoked instantly after it is created
})();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "41"
} |
Q: Postgres is not taking System Resources I am restoring my database to my new database in postgresql in linux 2.6.18 kernel.
My problem is restoring does not happen quickly, And even system has 90 % free resources.
It does not consume all the resource not doing the things as fastest. what can be issue ?
How can overcome this issue.. Please help me out of this problem.
Note :
I have used following things for pg_dump and restoring.
pg_dump -Fc -h 192.168.12.165 -d mydb -U mydb -f log.sql.tar.gz
pg_restore -Fc -h 192.168.12.165 -d mydb -U mydb log.sql.tar.gz
Why this system is not allowing postgres to consume all available memory and cpu resources ?
A: Postgres uses only very little system resources out of the box, so you will have to adjust the configuration settings to allow it to consume more.
There is a page on the wiki that gives you some hints on how to speed up the restoring of the database: http://wiki.postgresql.org/wiki/Bulk_Loading_and_Restores
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614576",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java getMethod throws method not found exception? I am using the getMethod(String name) function to load a method but it always throws MethodNotFoundException. If I run class.getMethods() the method I am looking for is in that result with the exact name I am using to pass to getMethod(). The method I am trying to load is a static method so I don't know if getMethod() will not work for static methods. Any help?
A: If the method you're looking for takes any arguments, you need to pass their types to getMethod() as well. A Java method's signature (the thing that uniquely defines and identifies a method) is comprised of the method name and its parameter types.
http://download.oracle.com/javase/tutorial/java/javaOO/methods.html
A: The name isn't enough. You have to specify exactly which argument types you think the method takes, otherwise the query might be ambiguous (because Java supports overloading).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614577",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Modifying the SBJson framwork for my app I am using the SBJson framework found at github(brilliant stuff) https://github.com/stig/json-framework/
with example : http://blog.zachwaugh.com/post/309924609/how-to-use-json-in-cocoaobjective-c
This twitter example works great now.
So I change my url and
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(@"%@ - %@", [status objectForKey:@"text"], [[status objectForKey:@"user"] objectForKey:@"screen_name"]);
}
to
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
NSLog(@"%@ - %@", [status objectForKey:@"text"], [[status objectForKey:@"message"] objectForKey:@"nationalad"]);
}
so my json on my page has message: and a nationalad: yet I don't get any return or or log print out. These are the only 2 things I have changed.
Any Ideas?
This is for the edit:
SBJsonParser *parser = [[SBJsonParser alloc] init];
// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.mywebpagehere.com"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];
// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
// You can retrieve individual values using objectForKey on the status NSDictionary
// This will print the tweet and username to the console
//NSLog(@"%@ - %@", [status objectForKey:@"text"], [[status objectForKey:@"message"] objectForKey:@"nationalad"]);
// NSLog(@"Message: %@", [status objectForKey:@"message"]);
}
// NSDictionary *json = [NSString JSONValue];
NSLog(@"Status: %@", statuses);
// NSArray *items = [statuses valueForKeyPath:@"data.array"];
//NSLog(@"message : %@", [[items objectAtIndex:1] objectForKey:@"message"]);
and the server page:
{
'message': "<p style=\"color:#FFFFFF;font-family:'Century Gothic',futura,'URW Gothic L',Verdana,sans-serif;\">Welcome!<\/p><p style=\"color:#FFFFFF;font-family:'Century Gothic',futura,'URW Gothic L',Verdana,sans-serif;\">Check out today's Dinner and Lunch specials below!<\/p>",
'nationalad': "<img src='http:\/\/www.mywebpage.com\/images\/national\/fullrz_3_4e81fa75ceba5_mywebpage.JPG'>"
}
A: Firstly, NSLog status and see if it is nil. If it is, then you should check the URL that you are getting the JSON from.
If the URL is nil, then correct the URL and try again.
A: That’s not valid JSON — all strings must be inside double quotation marks, including names. If you fix your server so that it outputs
{
"message": "<p style=\"color:#FFFFFF;font-family:'Century Gothic',futura,'URW Gothic L',Verdana,sans-serif;\">Welcome!<\/p><p style=\"color:#FFFFFF;font-family:'Century Gothic',futura,'URW Gothic L',Verdana,sans-serif;\">Check out today's Dinner and Lunch specials below!<\/p>",
"nationalad": "<img src='http:\/\/www.mywebpage.com\/images\/national\/fullrz_3_4e81fa75ceba5_mywebpage.JPG'>"
}
(note that both message and nationalad are inside double quotation marks), SBJSON should be able to parse your JSON string.
There’s another issue, though: your server isn’t returning an array — it’s returning a single object instead. Either fix your server code so that it returns an array of objects or, in your client code, parse a single object:
NSDictionary *status = [parser objectWithString:json_string error:nil];
Also, note that by using nil in
NSArray *statuses = [parser objectWithString:json_string error:nil];
you’re effectively telling the JSON parser not to return an error object in case there’s an error. Ignoring errors is usually a bad idea. You could do something like this:
NSError *jsonParseError;
NSArray *statuses = [parser objectWithString:json_string error:&jsonParseError];
if (!statuses) {
// there's been a parse error; look at jsonParseError
// for example:
NSLog(@"JSON parse error: %@", jsonParseError);
}
or this:
NSError *jsonParseError;
NSDictionary *status = [parser objectWithString:json_string error:&jsonParseError];
if (!status) {
// there's been a parse error; look at jsonParseError
// for example:
NSLog(@"JSON parse error: %@", jsonParseError);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: iOS - flip animation, small to large I am trying to simulate the flip animation seen in the iTunes iPad app. On the main Featured page, if you tap on one of the small posters in the New Releases list, it will flip open to show all the details of the movie.
When the poster is tapped I do this:
//...create newView
[self.view addSubview:poster]; //because the poster was previously in a scrollview
[UIView transitionWithView:self.view duration:3
options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
[poster removeFromSuperview];
[self.view addSubview:newView];
}
completion:NULL];
But... the ENTIRE view flips, instead of just the poster. And it flips vertically instead of horizontally, even though I have specified FlipFromLeft. What am I doing wrong?
EDIT: It seems that you have to use some kind of container view to do this. So I made one, added the poster to it, then created a dummy UIView for testing:
CGPoint newPoint = [self.view convertPoint:CGPointMake(poster.frame.origin.x, poster.frame.origin.y) fromView:[poster superview]];
poster.frame = CGRectMake(0, 0, poster.frame.size.width, poster.frame.size.height);
UIView *containerView = [[UIView alloc] initWithFrame:CGRectMake(newPoint.x, newPoint.y, poster.frame.size.width, poster.frame.size.height)];
[self.view addSubview:containerView];
[containerView addSubview:poster];
UIView *testView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, containerView.frame.size.width, containerView.frame.size.height)];
testView.backgroundColor = [UIColor redColor];
[UIView transitionWithView:containerView duration:3
options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
[poster removeFromSuperview];
[containerView addSubview:testView];
}
completion:NULL];
Now, the red UIView appears in place of the poster, but there is no Flipping animation at all. Why not?
A: You are telling the view to transition with self.view, so it's no wonder why the entire view is animating. Try telling the transition to animate with the posters view instead.
[UIView transitionWithView:poster.view duration:3
options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
[poster removeFromSuperview];
[self.view addSubview:newView];
}
completion:NULL];
A: I created an UIViewController (named: transitionView) with two UIImageView (named: fromImageView and toImageView). I added the transitionView to my viewController in viewDidLoad and I set alpha to 0.
I create both from the two UIView an image with this:
- (UIImage *) imageFromView: (UIView *) view {
CGFloat alpha = [view alpha];
[view setAlpha: 1.0];
CGSize pageSize = view.frame.size;
UIGraphicsBeginImageContext(pageSize);
CGContextRef resizedContext = UIGraphicsGetCurrentContext();
[view.layer renderInContext: resizedContext];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[view setAlpha: alpha];
return image;
}
and here is my flip code with resizing:
- (void) flipFromView: (UIView *) fromView toView: (UIView *) toView {
// Warning: positions is wrong when your image (or view) is in UIScrollView...
CGRect frame = CGRectMake(-8.0, 30.0, 336.0, 380.0); // resizing the fromView if the image is small...
CGFloat interval = 1.0;
[[transitionView view] setAlpha: 1.0]; //
UIImage *fromViewImage = [self imageFromView: fromView];
UIImageView *fromImageView = [transitionView fromImageView];
[fromImageView setImage: fromViewImage];
[fromImageView setFrame: [fromView frame]];
UIImage *toViewImage = [self imageFromView: toView];
UIImageView *toImageView = [transitionView toImageView];
[toImageView setImage: toViewImage];
[toImageView setFrame: frame];
[fromView setHidden: YES]; // hide original while animating
toImageView.layer.transform = CATransform3DMakeRotation(M_PI_2, 0.0, 1.0, 0.0);
[UIView animateWithDuration: interval
delay: 0.0
options: UIViewAnimationOptionCurveEaseIn
animations: ^{
[fromImageView setFrame: frame];
fromImageView.layer.transform = CATransform3DMakeRotation(M_PI_2, 0.0, 1.0, 0.0);
} completion: ^(BOOL finished) {
}
];
[UIView animateWithDuration: interval
delay: interval // wait to previous animation ending
options: UIViewAnimationOptionCurveEaseOut
animations: ^{
toImageView.layer.transform = CATransform3DMakeRotation(M_PI_2, 0.0, 0.0, 0.0);
toImageView.frame = [toView frame];
} completion: ^(BOOL finished) {
[toView setAlpha: 1.0];
[fromView setHidden: NO];
}
];
}
And sorry my bad english, I don't speak english!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How can I merge/join then sort with mongodb I have an entries collection and a domain collection like the following
entries:
{
{
entry_id:1,
title:"Title 1",
domain_id:1
},
{
entry_id:2,
title:"Title 2",
domain_id:1
},
{
entry_id:3,
title:"Title 3",
domain_id:2
}
}
domains:
{
{
domain_id:1,
domain:"Google",
rank:1
},
{
domain_id:2,
domain:"Yahoo",
rank:2
}
}
I am looking to gather all the information together and sort by the rank of the domain. Coming from a MySQL background I would normally join the entries and domains on the domain_id and sort by the rank field. One of my co-workers suggested looking into map/reduce, but after doing some reading I'm unsure how to apply that here.
A: As your co-worker said, Map/Reduce.
MongoDB is a document-based database. Probably a better pattern to follow in your scheme is to put entries inside the domains, see how much DRY it is:
{
{
domain_id:1,
domain:"Google",
rank:1,
entries: [
{
_id: dsfdsailfub3i4b23i4b234234,
title: "the title"
},
{
_id: dsfdsailfub3i4b23i4b234234,
title: "the title"
}
]
},
{
domain_id:2,
domain:"Yahoo",
rank:2
}
}
That's the easy part. you can now easily query a certain domain. Now, if you want to know how many entries each domain has you map each entry to return 1, and you reduce all those ones to find out their sum.
Here are several great answers to what exactly is Map/Reduce. Once you wrap your head around the idea it will be easy to implement it in Mongo.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614596",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Facebook meta tags scraped with locale not working My website is multi-language and I have a FB like button. I'd like to have the like posts in different languages.
According to Facebook documentation, if I use the meta tag og:locale and og:locale:alternate, the scraper would get my site info passing the parameter "locale" and the header "X-Facebook-Locale", but it's not sending neither.(https://developers.facebook.com/docs/beta/opengraph/internationalization/). So the posts end always in en_US.
Anyone having the same problem?
A: Facebook's locale handling is completely inconsistent
After wrestling with open graph locales for weeks now, I managed to post content with changing texts based on user's locale. For the links though, I'm still unable to get the expected results.
Here are my observations:
og:locale in the debugger shows by default, my actual facebook locale. Clicking on the og:locale:alternate links changes object properties as well as the interface language. I think it's by design.
The 'Raw Open Graph Document Information' section, without fb_locale appended to the input URL, shows the default data. If the fb_locale is set and in mixed case, Raw Open Graph Document Information section is changed according to the parameter.
The 'Object properties' section still shows data based on actual / selected locale.
If fb_locale is in lowercase, it returns 'Error parsing input URL, no data was scraped.'
The same thing is true for the 'locale' parameter appended to the debugger's (not the input) URL. If it's in mixed case format, Object Properties section and the interface language is changed. However, it does nothing when I pass it in lowercase (returns default/current locales)
Surprisingly, the graph api is acting inversely:
*
*when I request a re-scrape with php sdk
*
*the content is updated only when locale is passed in lowercase, but(!) in this case, the response returned doesn't have locale:locale parameter, which is set if either X-Facebook locale header or fb_locale parameter were present.
All data in the response is in default locale. However, the wall post is updated and text is displayed correctly according to my facebook locale settings.
*if the locales are passed in mixed case format - as defined is the documentation -, request returns 'unsupported post request' error.
When using php CURL function instead of the Facebook php SDK's api call, en_GB is an exception, where the response contains fb_locale and localized (english) content as well, but, the object properties / wall posts aren't updated, neither for en_GB. For other languages, 'Unspported post request' is returned.
*When I use the object's id (the id found on the bottom of the debugger page - by querying the 'comments_fbid' field from 'link_stat' table) instead of the URL:
*
*with mixed case locales, the response contains correct text and fb_locale for all locales, but none of them are updated. og:updated_time is unchanged in the debugger, but it's updated on https://graph.facebook.com/[object ID]
*with lower case locales, the result is the same as described in 1.1.
*In graph queries, the behaviour is again the opposite of the above:
When I try to query https://graph.facebook.com/[object ID]?locale=en_GB,
with mixed-case locales, it returns the expected result,
with lower-case locales, it returns the default version with no locale (only locale:alternate) tags set. :-o
Is it possible that the graph api endpoint and the debugger treats the locales differently, making it impossible to get the same reponse from both?
btw with lower case locales, I managed to have localized posts on the feed, where the text is displayed based on the uer's locale.
Now my problem is that all links are pointing to the same canonical URL without any locale-specific information, because - as Salvador said -doing so would create different objects. See my post here:
how to get the locale of a facebook user clicking on a localised object's link?
A: I got this working. The documentation is not very detailed; here are details.
Here are my Open Graph locale tags:
<meta property="og:locale" content="en_US" />
<meta property="og:locale:alternate" content="en_US" />
<meta property="og:locale:alternate" content="fr_CA" />
VERY IMPORTANT: The documentation makes it seem that og:locale should always reflect the page's "default" locale. This is not the case; doing so will prevent the scraper from retrieving other languages. og_locale must reflect the page's current locale. In other words, if the scraper (or the user) requests fr_CA content, make sure og_locale is set to fr_CA in the response.
Specify all possible locales with og:locale:alternate. This way, whether the scraper asked for en_US or fr_CA, it still knows that both exist.
Here's me asking the Facebook scraper to re-process my page:
curl -d "id=https://apps.facebook.com/everydaybarilla/&scrape=true" https://graph.facebook.com
Here's the response:
{
"url": "http://apps.facebook.com/everydaybarilla/",
"type": "website",
"title": "Barilla\u2019s Every Day, Every Way Contest",
"locale": {
"locale": "en_us",
"alternate": [
"fr_ca"
]
},
"image": [
{
"url": "http://everydaybarilla.ssl.spidermarketing.ca/assets/img/thumbnails/5.png"
},
{
"url": "http://everydaybarilla.ssl.spidermarketing.ca/assets/img/thumbnails/4.png"
},
{
"url": "http://everydaybarilla.ssl.spidermarketing.ca/assets/img/thumbnails/3.png"
},
{
"url": "http://everydaybarilla.ssl.spidermarketing.ca/assets/img/thumbnails/en-2.png"
},
{
"url": "http://everydaybarilla.ssl.spidermarketing.ca/assets/img/thumbnails/en-1.png"
}
],
"description": "Barilla Canada is whisking one lucky winner and a guest off to Italy on an 8-day Italian culinary adventure for 2 in the Barilla Every Day, Every Way Contest!",
"site_name": "Barilla\u2019s Every Day, Every Way Contest",
"updated_time": "2012-04-16T17:59:38+0000",
"id": "10150594698421968",
"application": {
"id": "317271281656427",
"name": "Barilla\u2019s Every Day, Every Way Contest",
"url": "http://www.facebook.com/apps/application.php?id=317271281656427"
}
}
The scraper correctly returns the data for the default locale, but according to the documentation, it seems that the scraper should scrape alternate locales as well; this is not the case. Clearly from the response above it sees the alternate locales, but it does not process them.
So, here's me specifically asking the Facebook scraper to process my page en français:
curl -d "id=https://apps.facebook.com/everydaybarilla/&scrape=true&locale=fr_CA" https://graph.facebook.com
This time, I correctly see two requests to my server from the scraper. The second request has both the X-Facebook-Locale header and the fb_locale URL parameter correctly set to fr_CA. And the POST correctly returns the French response:
{
"url": "http://apps.facebook.com/everydaybarilla/?fb_locale=fr_CA",
"type": "website",
"title": "Concours Tous les jours, de toutes les fa\u00e7ons de Barilla",
"locale": {
"locale": "fr_ca",
"alternate": [
"en_us",
"fr_ca"
]
},
"image": [
{
"url": "http://everydaybarilla.ssl.spidermarketing.ca/assets/img/thumbnails/5.png"
},
{
"url": "http://everydaybarilla.ssl.spidermarketing.ca/assets/img/thumbnails/4.png"
},
{
"url": "http://everydaybarilla.ssl.spidermarketing.ca/assets/img/thumbnails/3.png"
},
{
"url": "http://everydaybarilla.ssl.spidermarketing.ca/assets/img/thumbnails/fr-2.png"
},
{
"url": "http://everydaybarilla.ssl.spidermarketing.ca/assets/img/thumbnails/fr-1.png"
}
],
"description": "Un heureux gagnant et son invit\u00e9(e) partiront \u00e0 destination de l\u2019Italie pour une aventure culinaire de 8 jours pour 2 personnes (valeur au d\u00e9tail approximative de 15 000 $)!",
"site_name": "Barilla\u2019s Every Day, Every Way Contest",
"updated_time": "2012-04-16T18:11:27+0000",
"id": "10150594698421968",
"application": {
"id": "317271281656427",
"name": "Barilla\u2019s Every Day, Every Way Contest",
"url": "http://www.facebook.com/apps/application.php?id=317271281656427"
}
}
Success!
Of course, after all this effort, when I go to the French Facebook.com and post this URL, the status box is populated… with the English data. It seems Facebook's own interfaces aren't configured to request the correct locale.
So even with all this effort, nothing seems to have been accomplished (translations of my strings via the Facebook translation app aren't working either, so I guess I shouldn't be surprised).
Still, it does answer the question. Perhaps somebody else can determine why the Facebook.com interfaces don't seem to request the correct locale.
A: I had the same issues until finally getting it to work by setting all locale values in the meta tags (og:locale and og:locale:alternate) in lowercase.
Check this out:
http://developers.facebook.com/bugs/309825175774568?browse=search_5033cc14f42016961266549
After doing that and re-scraping, going to Facebook and changing the language settings to a supported locale would correctly send the X-Facebook-Locale and fb_locale, and trigger the desired results for me.
Btw: Setting the user locale to one not listed in og:locale:alternate would not send the header/get parameter.
A: What language did you specify when loading the Javascript SDK? It's easy to overlook that one.'
The default one is en_US, see the js.src line
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=127211380649475";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
A: I have the same problem.
The Like button sends to Facebook only his own attribute data-href="www.example.com/yourpage", not og meta tags values. Afterwards Fb scrapes og meta tags into yourpage, and from these creates the Wall post.
So practically the post is always in yourpage default language.
One solution to have posts in userlanguage is:
*
*Add ?lang=userlanguage to data-href url of Like button
*Give yourpage ability to get userlanguage and display meta tags og:title and og:description in the appropriate translation
(e.g. with php $_GET)
So Fb will scrape yourpage in userlanguage and will create a locale post.
Unfortunately Fb create a single object for every different url ?lang=userlanguage1, userlanguage2... and every object has his own fans list.
So every translation of yourpage will have his locale fans.
:-(
Similar question: Open Graph Localization
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: PostgreSQL: order by sum of computed values I have a table tips that is defined as follows:
CREATE TABLE tips
(
tip_id bigserial NOT NULL,
tip text NOT NULL,
author text NOT NULL,
post_date bigint NOT NULL,
likers character varying(16)[],
dislikers character varying(16)[],
likes integer NOT NULL,
dislikes integer NOT NULL,
abuse_history character varying(16)[]
);
I need to get the tips based on popularity, with the definition of popularity being:
likes - dislikes - (size(abuse_history)*5)
The query below gives me the same results regardless of the sort order (ASC/DESC).
select * from tips order by (likes - dislikes - (array_length(abuse_history,1) * 5)) ASC limit 2147483647 offset 0
EDIT
I inserted 3 records that have the following values:
1) 1 like, 0 dislikes, 0 abuse complaints
2) 0 likes, 1 dislike, 0 abuse complaints
3) 0 likes, 0 dislikes, 0 abuse...
Regardless of the sort order (ASC/DESC), I get the following order:
{3, 1, 2}
Could anyone please point me in the right direction?
A: Consider this:
SELECT array_length('{}'::character varying(16)[],1);
Output is NULL for an empty array. Also, your abuse_history can be NULL itself. So you need something like this:
SELECT *
FROM tips
ORDER BY (likes - dislikes - COALESCE(array_length(abuse_history,1) * 5, 0)) DESC;
EDIT after feedback:
Works in PostgreSQL 9.0 as shown in this demo:
CREATE TABLE tips
( tip_id bigserial NOT NULL,
tip text,
author text,
post_date bigint,
likers character varying(16)[],
dislikers character varying(16)[],
likes integer,
dislikes integer,
abuse_history character varying(16)[]
);
INSERT INTO tips (likes, dislikes, abuse_history)
VALUES(1,0, '{}')
,(1,0, '{}')
,(0,1, '{}')
,(0,0, '{}')
,(1,0, '{stinks!,reeks!,complains_a_lot}');
SELECT tip_id
, likes
, dislikes
, (likes - dislikes - COALESCE(array_upper(abuse_history,1) * 5,0)) as pop
, (likes - dislikes - array_upper(abuse_history,1) * 5) as fail_pop
FROM tips
ORDER BY (likes - dislikes - COALESCE(array_upper(abuse_history,1) * 5,0)) DESC;
Output:
tip_id | likes | dislikes | pop | fail_pop
--------+-------+----------+-----+----------
1 | 1 | 0 | 1 |
2 | 1 | 0 | 1 |
4 | 0 | 0 | 0 |
3 | 0 | 1 | -1 |
5 | 1 | 0 | -14 | -14
A: In order to debug this, put the same expression of the ORDER BY clause into the SELECT part. Then examine the results - are they really what you expect?
select *, (likes - dislikes - (array_length(abuse_history,1) * 5))
from tips
order by (likes - dislikes - (array_length(abuse_history,1) * 5)) ASC
limit 2147483647 offset 0
Oh, and BTW, strip that silly LIMIT and OFFSET thing.
A: Try this:
select t2.*
from ( select t1.*,
(likes - dislikes - (array_length(abuse_history,1) * 5)) as popularity
from tips t1) t2
order by popularity;
Edit: The above usually works (at least with Oracle). Maybe the below variation that uses the With clause will avoid the error.
WITH popularity_query as
( select t.*,
(likes - dislikes - (array_length(abuse_history, 1) * 5)) as popularity
from tips t)
select * from popularity_query order by popularity
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: Solving hid.lib "unresolved external symbol" linker errors in VC++ As the title suggests, I am having the following linker error:
error LNK2019: unresolved external symbol "unsigned char __stdcall
HidD_GetAttributes(void *,struct _HIDD_ATTRIBUTES *)"
(?HidD_GetAttributes@@YGEPAXPAU_HIDD_ATTRIBUTES@@@Z)
when calling result = HidD_GetAttributes(WriteHandle, &attributes) in my code.
This function should exist in "hid.lib" which I have added to my linker dependencies for the project. I have also included the header file "hidsdi.h" which has the function prototype for HidD_GetAttributes.
The only other thing that I thought might be problematic is that the function prototypes for "hid.lib" are split between three different headers: hidsdi.h, hidpi.h, and hidsage.h.
Any suggestions?
A: Just solved the problem. Apparently "hid.lib" was written in C which was resulting in some name mangling. Using
extern "C"
{
#include "hidsdi.h"
}
cleared everything up.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: how OS know encoding of files For example I have a file on my disk: a.txt
I opened it in Hex mode and see no other signal character in it but plain text in UTF-8.
I am wondering how OS know it is UTF-8??
Thanks,
A: The OS doesn't know. The hex editor is probably auto-detecting it. That's possible by looking out for the presence and absence of specific byte pairs, but it's not 100% reliable.
There is no general flag or property in which a file's encoding is stored. That's why you often need to specify the encoding manually when opening a text file.
One approach to mark a UTF-8 or -16 file is the BOM but that's not mandatory.
A: The OS has no concept of text file encoding. Text editors usually guess from the contents, or assume UTF-8 or default to your locale's encoding.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614609",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: improving my python script I have an interesting python script (not sure if it has been done before) It uses
import os
os.system("say %s" % say)
#and I have added;
os.system("say -v whisper %s" % say)
but now there are new voices in lion and i want to know how to get those voices and if there is a centralized list.
A: The manual doesn't doc which voices are available. But I believe the syntax is just using the name like so:
> say -v Karen Hello
I don't have access to my Mac right now but I found this list from here:
*
*American English: Jill, Samantha and Tom
*Australian English: Karen and Lee
*British English: Daniel, Emily and Serena
*South African English: Tessa
There is also other languages as well.
UPDATE:
say -v ? spits out:
MacBook-Austin:~ Austin$ say -v ?
Agnes en_US # Isn't it nice to have a computer that will talk to you?
Albert en_US # I have a frog in my throat. No, I mean a real frog!
Alex en_US # Most people recognize me by my voice.
Bad News en_US # The light you see at the end of the tunnel is the headlamp of a fast approaching train.
Bahh en_US # Do not pull the wool over my eyes.
Bells en_US # Time flies when you are having fun.
Boing en_US # Spring has sprung, fall has fell, winter's here and it's colder than usual.
Bruce en_US # I sure like being inside this fancy computer
Bubbles en_US # Pull the plug! I'm drowning!
...
If you do not see the voice you are looking for when you do a say -v ? you can install more.
A: From the say man page:
-v voice, --voice=voice
Specify the voice to be used. Default is the voice selected in
System Preferences. To obtain a list of voices installed in the
system, specify '?' as the voice name.
Most of the new voices are downloaded on demand from the Speech panel in System Preferences
A: Hopefully, this command comes with some documentation, so you could try this command in your shell to get more information:
say -h
say --help
man say
UPDATE
The man page I found says the default voice is the voice selected in System preferences. So I guess you can find all the different voices there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614610",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to integrate CSS pre-processing within Eclipse? I would like to edit SCSS files in Eclipse, preferably with syntax highlighting for .scss files.
I found these resources valuable:
*
*http://sass-lang.com/editors.html - has no editor for .scss files only .sass
*http://colorer.sourceforge.net/eclipsecolorer - has only .scss files
How can do I integrate SCSS development within the Eclipse editor?
Or, more generally, how do I integrate a CSS pre-processor into Eclipse?
A: You can use the latest Eclipse Plug-in called "Colorer" which now supports SASS files. Here it is : http://colorer.sourceforge.net/eclipsecolorer/index.html
Open "Install New software" From "Help" menu in Eclipse and Enter "http://colorer.sf.net/eclipsecolorer" into the "Work with" box to install the plug-in
A: I just figured out how to do this in Eclipse. I admit that this solution does not have 100% SASS support, the colors get a little funky when using nested css, but it's waaaaay better than looking at plain text and you don't need to install a separate editor.
You need to associate the .scss file type with the native Eclipse CSS Editor in Eclipse[Part 1]. After you do that, you need to add the .scss file type to the native CSS Editor as well so the CSS Editor will be able to open it [Part 2]. Here are the steps for eclipse (I'm running Eclipse Java EE IDE for Web Developers, Indigo):
Part 1 - Associate the .scss file type with the native Eclipse CSS Editor
*
*Go to Window > Preferences
*Drill down to General > Editors > File Associations
*In File Associations pane, click the 'Add..." button on the top right.
*For File Type:, enter *.scss and then click OK.
*Find the *.scss entry in the File Associations list and select it.
*After selecting *.scss, on the bottom pane Associated editors:, click the Add... button.
*Make sure Internal editors is selected on the top, then find and select CSS Editor and then click OK.
This associated the file type .scss with eclipses native CSS Editor. Now we have to configure the native CSS Editor to support .scss files. To do this, follow this steps:
Part 2 - Add the .scss file type to the native CSS Editor
*
*Go to Window > Preferences
*Drill down to General > Content Types
*In the Content Types pane, expand Text, then select CSS
*After CSS is selected, on the bottom File associations: pane, click the Add... button.
*For Content type:, enter *.scss and then click OK.
*Click OK to close out the Preferences window.
All done. All you need to do now is close any .scss files that you have open then re-open them and wha-la, css colors in Eclipse for .scss files!
Note: If the css colours do not appear you may have to do the following: Right click the .scss file > Open With > CSS Editor.
A: Aptana Studio provides syntax coloring support for SASS/SCSS and it’s possible to install Aptana as Plugin into Eclipse. See the following quote from the Aptana sownload site:
Installing via Eclipse
Please copy the following Update Site URL to your clipboard and then follow the steps listed below to add this URL to your Available Software Sites list. Attempting to access this URL using your web browser will return an Access Denied error.
http://download.aptana.com/studio3/plugin/install
*
*From the Help menu, select »Install New Software …« to open the Install New Software dialog.
*Paste the URL for the update site into the Work With text box, and hit the Enter (or Return) key.
*In the populated table below, check the box next to the name of the plug-in, and then click the Next button.
*Click the Next button to go to the license page.
*Choose the option to accept the terms of the license agreement, and click the Finish button.
*You may need to restart Eclipse to continue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614612",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "113"
} |
Q: Joomla form to fill and send email (the message is a composition of the fields values) I work with Joomla 1.7
I want to make a form with different text input.
Like : name, adress, age....
And with this form, i will compose a message and this message is send by email to someone.
I try my best but i can't make it.
I need to know if there's a module or plugin to make this.
Thanks to all.
A: The absolute best component for forms is Chronoforms (Chronoengine.com) - It has a 'drag & drop' type editor for creating forms and can get your forms up and going in a matter of minutes.
It's best to familiarize yourself with some of the documentation so you can see what's going on - but even if you just hop in and start playing around it's easy to see what's going on. The 'form wizard' literally walks you through the process.
I use it on every Joomla install I create!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614613",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Linux equivalent of I_PUSH This question is related to pty terminal packet mode TIOCPKT
What the linux way of enabling packet mode? I could not find I_PUSH working when passed in ioctl function.
A: TIOCPKT is exactly what you want, according to the tty_ioctl(4) man page: the argument is a pointer to an integer which is non-zero to enable packet mode, or zero to disable it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Can spork work with rake tasks? Rake tasks suffer from the same problem as running tests: the Rails bootup process takes a long time before the task is even running.
Is there a way to integrate spork and rake together?
A: You can use the irake gem which makes it possible to execute rake tasks from the console.
Add this to Gemfile:
gem 'irake'
Then bundle and start console
$ bundle install
$ rails console
...and wait for the Rails environment to load (only once). Then you can do:
rake "db:migrate"
If you want to list tasks, you can:
Rake::Task.tasks.each{|t| puts t.name }; nil
A: I discovered zeus today. It's the best thing ever, so I'm changing my answer to zeus:
https://github.com/burke/zeus
zeus rake my:special:task
A: rake test:units
testdrb -I test/ test/unit/
rake test:functionals
testdrb -I test/ test/functional/
rake test:integration
testdrb -I test/ test/integration/
A: There is no standard out of the box solution as i know.
Rake does not have --drb option and spork can't help here.
Sure, custom solution is possible. This will require extension of rake runner.
I think rake tasks run not so often as tests, that why question is not addressed yet.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: c++ how to inherit operator that returns specific type I have a class 'A' that overrides the + operator, and a subclass 'B'.
I want to inherit 'A's + operator but instead of returning type A I want to return type B.
How can I go about doing this? I tried calling the parent's operator from B and casting the result to an A object but it won't let me cast a parent to a child
Can my + operator somehow return a generic 'A' pointer or something?
A: It could - no technical reason it couldn't - it just violates some expectations when using operators. So if this is code for yourself, go for it, but if it's going to be read or used by other people, I'd reconsider for the following reasons:
*
*Expected behaviour is that operators like += and *= return a reference to the object they were called on after modifying that object. Operators like + and * return a new object (they pretty much have to, as the implication is that the object they're called on isn't changed). They don't return a pointer to a new object because:
*No one expects them to, so they won't think to delete an object they get back from an operator, which will cause memory leaks, and:
*You can't chain operators that return pointers; an expression like MyClass a = b + c + d; won't work, because the return type (MyClass*) won't match the argument type you need to pass into the operator (probably const MyClass&).
*Returning a reference to a new object lets you work around #3, and still supports polymorphism, but you're still stuck with #2, and that's the worse of the pair. The same applies to overloading the operator to take either a pointer or a reference.
Ultimately, just do whatever makes life easiest for whoever's going to be using the code - and if it's just you, you can do anything you want. Just be careful if it's going to fall into other people's hands, because they will make assumptions.
Hope this helps!
Edit: An example that returns a reference to a new object:
A& A::operator + (const A& other) const
{
A* temp = new A(); // <- This is why it's a potential memory leak
/* Do some stuff */
return *temp;
}
But, having had a little more time to think about this, I'd propose an alternative: Define an = operator for B that takes an A as its argument. Then you could do things like this:
B b1;
B b2;
B b3 = b1 + b2;
And it wouldn't matter that b1 + b2 returned an A, because it was converted back to a B during the =. If this works for you, I'd recommend it above any other method, as it lets all the operators have expected behaviours.
A: I frequently see it done in the following way:
class A {
int a;
A(int rhs) :a(rhs) {}
public:
A& operator+=(const A& rhs) {a+=rhs.a; return *this}
A operator+(const A& rhs) {return a+rhs.a;}
};
class B : public A {
int b;
public:
B(const B& rhs) :A(rhs), b(rhs.b) {}
// VVVVVVVVVVVVVVVVVV
B& operator+=(const B& rhs) {A::operator+=(rhs); b+=rhs.b; return *this;}
B operator+(const B& rhs) {return B(*this)+=rhs;}
};
A: The simplest way to solve this problem is to implement operator+ in terms of operator+=. So roughly:
A::operator+=(const A& right) { /* stuff */ }
B::operator+=(const B& right) { static_cast<A&>(*this) += right; /* stuff */ }
operator+(B left, const B& right) { return B += right; }
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614625",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to send data to a cross-server php file? While developing a native Android app using Dreamweaver's "build" functionality, I found out that I had to use Jquery's JSONP functionality to access dynamic data. The dynamic data, pulled from a mySQL database and populated into a php file, is considered "cross-server," because the web-language-created Android app resides in the Android device, while the php file resides on the web server (I think? I couldn't ajax in the data like I could when I hosted the web app.).
I can display the dynamic data from the php file easily with a JSONP scrip inject...but what if I wanted to do a user-specified filter on the data? (Send to the php file which "linkID" was clicked)
I've read that jquery's .getJSON() function can send data (currently only using it to pull data):
function jsoncallback(data){
console.log(data);
}
$.getJSON("http://crossServerPhpFile.php?jsoncallback=?",
{ linkID: "0"});
But is there a way to send a GET variable to the cross-server php file?
A: Not sure really if i understood it correctly but here is what i think you can do:
$.getJSON("http://crossServerPhpFile.php?linkId=0&jsoncallback=?");
sending the linkid directly in the url.
A: $.get("url", { linkId : "0", item2 : "data"},function(data){
alert(data.response);
});
Etc works for me with json/rest api's. Maybe im misunderstanding your question?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: After writing to a stringstream, why does extracting into a string cause that string to become bogus? I'm encountering a puzzling bug involving stringstream. I've got a object whose properties I want to dump to a file using dumpState(). This object has a number of member objects, each of which has had operator<< defined for them. Here's the code:
void dumpState(int step){
stringstream s;
s << DUMP_PATH << step;
string filename;
//s >> filename;
fstream f;
f.open("fuuuuu.csv", fstream::out);
//f.open(filename.c_str(), fstream::out);
f << numNodes << '\n';
f << nodes << '\n';
f << numEdges << '\n';
f << edges << '\n';
f.close();
}
My intention is of course to write to a file whose name is determined by step. Unfortunately, I find that the values outputted are bogus. Tracking the bug down, I found that if I comment out "s>>filename;" the values are correct.
There must be some sort of flushing problem going on, but I don't know how to fix it. Any ideas on this rather evil looking bug?
UPDATE:
I think the problem was a rather complicated error due to a mistake elsewhere in my code. After restructuring my code, the original code I posted works fine.
A: you should use an ostringstream and call s.str() to get the contents.
A: I can't reproduce your problem using g++ 4.5.2 x86_64, so I can't confirm that this is the problem, but try this:
std::stringstream s;
s << DUMP_PATH << step;
s.flush();
std::string filename;
s >> filename;
A: Among other possible problems, s >> filename; will only read up to the first whitespace.
Foo Bah has the correct solution.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614632",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to make a function template the least priority during ADL? I have a problem where I'd like to provide a generic version of a function foo which may only be applied when there is absolutely no other match for an invocation. How can I modify the following code such that last_resort::foo is a worse match for derived::type than base::foo? I'd like to find a solution which does not involve modifying the definition of bar and which would preserve the type of the argument of last_resort::foo.
#include <iostream>
namespace last_resort
{
template<typename T> void foo(T)
{
std::cout << "last_resort::foo" << std::endl;
}
}
template<typename T> void bar(T)
{
using last_resort::foo;
foo(T());
}
namespace unrelated
{
struct type {};
}
namespace base
{
struct type {};
void foo(type)
{
std::cout << "base::foo" << std::endl;
}
}
namespace derived
{
struct type : base::type {};
}
int main()
{
bar(unrelated::type()); // calls last_resort::foo
bar(base::type()); // calls base::foo
bar(derived::type()); // should call base::foo, but calls last_resort::foo instead
return 0;
}
A: This would be about as bad as it gets:
struct badParam { template <typename T> badParam(T t) { } };
namespace last_resort {
void foo(badParam, int dummy = 0, ...) {
std::cout << "last_resort::foo" << std::endl;
}
}
You've got a user-defined conversion, a defaulted parameter and an unused ellipsis.
[edit]
Slight variant, to save T I moved the user-defined conversion to the dummy parameter:
struct badParam {
badParam() { }
operator int() { return 42; }
};
namespace last_resort {
template <typename T> void foo(T t, int dummy = badParam(), ...) {
std::cout << "last_resort::foo" << std::endl;
}
}
A: You can't do much about it. Both foo functions are in the overload set. But your last_resort one is a better match simply because it does not require a conversion unlike base::foo for derived::type(). Only in the case where two candidates are "equally good" judging by the parameters and possible conversions, a non-template is preferred.
A: last_resort::foo can be removed from the overload set with disable_if. The idea is to disable last_resort::foo(T) if foo(T) is otherwise well-formed. This causes last_resort::foo(T) to be the worst match for foo:
namespace test
{
template<typename T> struct has_foo { ... };
}
namespace last_resort
{
template<typename T>
struct disable_if_has_foo
: std::enable_if<
!test::has_foo<T>::value
>
{};
template<typename T>
typename disable_if_has_foo<T>::type foo(T)
{
std::cout << "last_resort::foo" << std::endl;
}
}
The output:
$ g++ last_resort.cpp
$ ./a.out
last_resort::foo
base::foo
base::foo
This answer describes how to build a solution for checking for the existence of a function (foo) returning void.
A: You can provide an overload of bar for type derived::type after the declaration of derived::type. This can be in namespace derived or not.
void bar(derived::type)
{
foo(derived::type());
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614633",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: in python, how to match Strings based on Regular Expression and get the non-matching parts as a list? For example: I have a string "abcde2011-09-30.log", I want to check if this string matchs "(\d){4}-(\d){2}-(\d){2}" ( dont think it has correct syntax, but you get the idea). And I need to split the string into 3 parts: (abcde),(e2011-09-30), (.log). How can I do it in python? Thanks.
A: There's a split method in the re module that should work for you.
>>> s = 'abcde2011-09-30.log'
>>> re.split('(\d{4}-\d{2}-\d{2})', s)
('abcde', '2011-09-30', '.log')
If you don't actually want the date as part of the returned list, just omit the parentheses around the regular expression so that it doesn't have a capturing group:
>>> re.split('\d{4}-\d{2}-\d{2}', s)
('abcde', '.log')
Be advised that if the pattern matches more than once, i.e. if there is more than one date in the filename, then this will split on both of them. For example,
>>> s2 = 'abcde2011-09-30fghij2012-09-31.log'
>>> re.split('(\d{4}-\d{2}-\d{2})', s2)
('abcde', '2011-09-30', 'fghij', '2012-09-31', '.log')
If this is a problem, you can use the maxsplit argument to split to only split it once, on the first occurrence of the date:
>>> re.split('(\d{4}-\d{2}-\d{2})', s, 1)
('abcde', '2011-09-30', 'fghij2012-09-31.log')
A: How's this:
>>> import re
>>> a = "abcde2011-09-30.log"
>>> myregexp = re.compile(r'^(.*)(\d{4}-\d{2}-\d{2})(\.\w+)$')
>>> m = myregexp.match(a)
>>> m
<_sre.SRE_Match object at 0xb7f69480>
>>> m.groups()
('abcde', '2011-09-30', '.log')
A: (without using regex and interpreting your string as a filename:)
lets start with splitting the filename and the extension 'log':
filename, ext = os.path.splitext('abcde2011-09-30.log')
most probably, the length of the date is allways 10, allowing for:
year, month, day = [int(i) for i in filename[-10:].split('-')]
description = filename[:-10]
However, if you are not sure we can find out where the date-part of the filename starts:
for i in range(len(filename)):
if filename[i].isdigit():
break
description, date = filename[:i], filename[i:]
year, month, day = [int[c] for c in date.split('-')]
A: I don't know the exact python regex syntax but something like this should do the job:
/^(\D+?)([\d-]+)(\.log)$/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: h264 mp4 index to front command line Is there any command line tools to move an h264/mp4 index to the beginning so that flash will start playing the file quicker over the net? I am aware of the tool QTIndexSwapper however it is not command line.
Alternatively is there an ffmpeg command to place the index at the front during an encoding?
Thanks.
A: As answered a few years later;
ffmpeg -i input.mp4 -codec copy -movflags +faststart output.mp4
A: After enough poking around I managed to find a python script called qt-faststart that does it. So far so good. qt-faststart
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Modify ViewModel property value through Javascript in MVC3 Is it possible to change a property value from a ViewModel using javascript?
For example:
<script type="text/javascript">
@Model.PageNumber = 2;
</script>
A: No, JavaScript is on the client-side(unless you are using Node.js), and MVC3 Views are rendered on the server-side in the Controllers.
A: No; that page code is executed once; changing the model wouldn't do anything even if it was allowed.
If you want a view model that can change on the client-side, and have the UI automatically update in response to changes, KnockoutJS is what you're looking for. With KnockoutJS, you can have view models with properties that can be changed in javascript, and the UI will automatically update accordingly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: My CustomRoleProvider doesn't seem to be used for controlling access to the application I've set up my application to use a custom role provider by adding some lines to the Web.config file, like so:
<roleManager enabled="true" defaultProvider="AspNetSqlRoleProvider">
<providers>
<!-- <clear/>-->
<add name="CustomRoleProvider"
connectionStringName="Custom"
applicationName="Custom"
type="Authorization.CustomRoleProvider" />
</providers>
</roleManager>
I've created an empty Authorization.CustomRoleProvider class and added references to it.
Now my code has one simple test case in it, like so:
[Authorize (Roles= "Admin")]
public ActionResult Index(Model model)
As far as I can tell, none of the code I've written so far is being called (if it would, it would raise an exception on account of methods not being implemented). Am I messing something up in my configuration?
A: You should change your default provider name to match your provider name of "CustomRoleProvider":
<roleManager enabled="true" defaultProvider="CustomRoleProvider">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614640",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is an efficient method to determine the size of a type given as a binary string? First off, lets assume I have endian sorted out and know the size of the types a priori.
Here's what I am doing: I have a function bs2i(char *bitStr) that takes in a character array representing the binary of a signed char/short/int/long. The array can be of any length <= sizeof(long long).
What I want to do is take bitStr[0] and set it as the sign bit such that it won't be truncated if I do something like char val = bs2i("111"). In this case, the function should return -125, as the bits would be set as "000...00010000011." To do this, I need to know how long the final type needs to be so I can shift the msb to the proper spot.
This is what I have thus far:
size_t size = (((strlen(bitStr)-1)>>3)+1)<<3;
But I just realized that only works for chars and shorts. For instance, a string of length 17 should return size 32, but would only return 24 with this method. Is there an efficient way to determine what the proper length should be?
For reference, here is the full function:
long long bs2i(char *bitStr) {
long long val = 0l;
size_t len = (((strlen(bitStr) - 1) >> 3) + 1) << 3;
char msb = *bitStr & 1;
bitStr++;
while (*bitStr) {
val = (val << 1l) | (*bitStr & 1);
bitStr++;
}
val = (msb << len-1l) | val; /* Use MSB as sign bit */
return val;
}
Bonus points, I guess, if there's a good way to do this that doesn't require a priori knowledge of type sizes.
A: It sounds like you want to find the smallest power-of-two, multiple of 8 number of bits that would fit as many bits as there are characters in the string. If you have a maximum of 64 bits, why not just use a switch on the string length?
switch((strlen(bitStr) - 1) >> 3) {
case 0: return 8; /* strlen <= 8 */
case 1: return 16; /* strlen <= 16 */
case 2:
case 3: return 32; /* strlen <= 32 */
case 4:
case 5:
case 6:
case 7: return 64; /* strlen <= 64 */
default: return 0;
}
Alternatively, you could try this:
int reqIntSz(char *bitStr)
{
int len = strlen(bitStr);
int res = 8;
while ( len > res ) res <<= 1;
return res;
}
A: You want to round up the bit length to a power of two with a minimum of 8. Wikipedia has a decent algorithm for doing this. The essence of the algorithm is to set every bit below the highest bit, then add one.
You'll have to adjust it slightly since you don't want to round 8 to 16, but that's simple enough to figure out on your own.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Is there a function in Matlab to read your computer's audio in and store data in near real time? Would anyone know if there is a way in MATLAB to read from your computer's audio in and store the data into a pre-allocated array? If so, what is the function or the path to do so?
Thank you.
A: it's very simple. check these two links
http://www.mathworks.com/help/techdoc/ref/audiorecorder.html
http://www.mathworks.com/matlabcentral/newsreader/view_thread/162428
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614645",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: When to Use Gated Check-In? I am using TFS 2010. Currently I use Gated Check-in build on the trunk (MAIN) branch only. And, I use CI on DEV and RELEASE branches.
*
*Why not use Gated Check-in build on all the branches?
*In what scenarios, you shouldn't use Gated Check-in build on DEV and RELEASE branches?
*Is it better to always use Gated Check-in build on every branch?
A: There is not really a reason that I know of why not to do a Gated Check-in on every change you make. There is however (in general) a pre-requisite for doing Gated Check-in: your overall build time should not be longer that a few minutes, including any (unit) test you would like to have performed before the check-in is accepted. Otherwise it takes to much time for a check-in to get accepted, or worse for the developer, to get rejected. For a dev team it is also a bit more complex, or at least something to get used to.
Continuous Integration (in my opinion optimized in the form of Rolling builds) allows to have the developer check-in its code without having the uncertainty if it will be accepted or not. Important is that the dev will always have to be confronted as soon as possible with negative end results of a check-in. If you can achieve that, I like it better than Gated check-ins.
A: I prefer Gated Check-In's everywhere because it limits the pain to the developer checking-in rather than sharing that pain with the entire team when somebody (inevitably) makes a mistake.
As mentioned above, it's important to keep the Gated Check-Ins quick. I will sometimes have a Gated Checkin that runs the most important checks, then a CI build that kicks off after the Gated Checkin succeeds that runs more time-consuming checks.
A: In our very large team, we also do gated in the main branch and CI in the dev/feature branches (many of them).
Gated offers more protection for the branch but with a very large team and large code base, it can back up the queue if the whole dev team is doing changes in that branch.
CI provides protection with a little more trust in the developers also knowing that any issues will get caught quickly. It's a bit more optimistic and allows the team to move much faster which is appropriate for a dev branch.
In both cases, devs run unit tests and test the code they are changing. CI (affects the team) and Gated (consumes time in the queue) should not replace testing - there should be a plausible explanation more complex than I didn't try it.
The whole team is in feature/dev branches using CI for the majority of the cycle and in higher branches with many more folks during end game stabilization - both of those latter conditions support the case for gated.
In a large team, we also need to get the CI builds and the rolling tests to be done in parallel to find issues quicker when build times are not trivial and full test suites are also not trivial. In that scenario, folks are checking in, the CI is picking up the last batch of checkin, running a build and when a build drops another machine is picking up and running the test suites.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614650",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Intent resolution and difference between ACTION_CHOOSER and ACTION_PICK_ACTIVITY I have a question about intent resolution and the difference between Intent.ACTION_PICK_ACTIVITY and Intent.ACTION_CHOOSER (including it's convenience function version, Intent.createChooser()).
I'm writing a "package manager" app. In it I have a ListActivity that displays all packages installed on the device (populated with PackageManager.getInstalledPackages()). I also have a context menu registered on the list, one of whose items is "Launch".
Below is my code from onContextItemSelected() for handling the "Launch" context menu item.
Intent intent ;
List<ResolveInfo> ris ;
int nLauchables ;
int REQUEST_LAUNCH = 1 ; // for use in onActivityResult()
// PackageInfo pi ; // set outside this code
intent = new Intent (Intent.ACTION_MAIN) ;
intent.addCategory (Intent.CATEGORY_LAUNCHER) ;
intent.setPackage (pi.packageName) ; // limit to launchable activities in the package represented by pi
ris = getPackageManager ().queryIntentActivities (intent, 0) ; // get list of launchable activities in pi
nLaunchables = ris.size () ;
if (ris == null || nLaunchables == 0) {
// do nothing (in the real code, the "Launch" item is already disabled in this case, so this never happens)
}
else if (nLaunchables == 1) {
// only 1 launchable activity, so just start that activity
intent.setComponent (new ComponentName (ris.get (0).activityInfo.packageName, ris.get (0).activityInfo.name)) ;
startActivity (intent) ;
}
else if (nLaunchables > 1) {
// mutiple launchable activites, so let the user choose which one they want to launch
// Intent chooseIntent = new Intent (Intent.ACTION_CHOOSER) ;
// chooseIntent.putExtra (Intent.EXTRA_INTENT, intent) ;
// chooseIntent.putExtra (Intent.EXTRA_TITLE, "Select activity") ;
// startActivity (chooseIntent) ; // doesn't show all launchable activities in the package
//
// or
//
// startActivity (Intent.createChooser (intent, "Select activity") ; // doesn't show all launchable activities in the package
Intent pickIntent = new Intent (Intent.ACTION_PICK_ACTIVITY) ;
pickIntent.putExtra (Intent.EXTRA_INTENT, intent) ;
startActivityForResult (pickIntent, REQUEST_LAUNCH) ;
}
I first tried the ACTION_CHOOSER version...but it doesn't always show all launchable activities in the package. For example, Google Maps has 4 launchable activities (Latitude, Maps, Navigation and Places) that show up with ACTION_PICK_ACTIVITY but ACTION_CHOOSER only shows 2 (Latitude, Maps). The only thing I can see that is different between the activities that do show when using ACTION_CHOOSER and those that don't is that they have CATEGORY_DEFAULT in their <intent-filter>s.
Below are the parts of the documentation that I have consulted to understand what is going on:
Docs for CATEGORY_DEFAULT say, in part, "Setting this will hide from the user any activities without it set when performing an action on some data."
This seems to explain the behavior I'm seeing...but...
Docs for ACTION_CHOOSER say, in part, "...all possible activities will always be shown even if one of them is currently marked as the preferred activity." (emphasis mine)
This seems to be in conflict with the above docs for CATEGORY_DEFAULT and suggests that using ACTION_CHOOSER and ACTION_PICK_ACTIVITY should produce the same results....and...
Docs for Intents and Intent Resolution (sorry, as a new user, I'm limited to 2 links in a post, so I can't link to this...just look in the "Intent Resolution" section, "Category test" subsection), says, in part, "Android treats all implicit intents passed to startActivity() as if they contained at least one category: android.intent.category.DEFAULT" (the CATEGORY_DEFAULT constant). Therefore, activities that are willing to receive implicit intents must include android.intent.category.DEFAULT" in their intent filters. (Filters with android.intent.action.MAIN" and android.intent.category.LAUNCHER" settings are the exception. They mark activities that begin new tasks and that are represented on the launcher screen. They can include "android.intent.category.DEFAULT" in the list of categories, but don't need to.)" (emphasis mine)
Again, this seems to explicitly say that using ACTION_CHOOSER and ACTION_PICK_ACTIVITY should produce the same results.
So, is this just a case of incomplete documentation for ACTION_CHOOSER (i.e., that it doesn't mention that CATEGORY_DEFAULT activities are excluded) or is there something else going on?
Using ACTION_PICK_ACTIVITY works for me but is not ideal because of the need for calling startActivityForResult() with it (rather than just startActivity()).
A: I think your reading of those last two excerpts from the documentation is not the intended meaning. Starting with the ACTION_CHOOSER doc, "...all possible activities will always be shown even if one of them is currently marked as the preferred activity," specifically refers to preferred activities. Normally, when you use an implicit intent, and more than one activity matches, if the user has previously chosen "Always" from a previous chooser for this intent, then you'll get that activity without a chooser. If you use the ACTION_CHOOSER intent, you'll get all the activities that match, even if one has been chosen. That's all this line means: "all possible activities" means all activities that match the intent filter, taking categories into account too. It's simply another explanation of the difference between getting a chooser automatically vs. using ACTION_CHOOSER.
The other part you call out, about android.intent.action.MAIN and android.intent.category.LAUNCHER, doesn't mean that that action and category are handled specially in the intent filtering process. Don't forget that most people reading this documentation are simply writing launchable apps, and need to know what to put in their manifest to get an activity shown in the launcher. The "exception" here isn't an exception to the intent filter rules: it's an exception to the usual behaviour that implicit intents use CATEGORY_DEFAULT, and that's only an exception because launchers set this category (CATEGORY_LAUNCHER) instead of CATEGORY_DEFAULT.
In summary, the whole area of intent resolution is quite underdocumented, as you've found, but there's no inconsistency in the excerpts you've mentioned: they're just talking about slightly different things.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614652",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Opera won't recognize iframe.load I have a file that's being upload via iframe work around. I have it working in all browsers except Opera now. To first submit the form, I have
$(document).ajaxComplete(function() {
$('.aboutContentImageForm').each(function() {
var $this = $(this);
$this.find('[type=file]').change(function() {
$this.submit();
});
});
});
Then to capture the post data returned, I use
$('.aboutContentImageForm').live('submit', function() {
$('#' + $this.attr('target')).load(function() {
var responseHtml = $(this).contents().find('body'),
response = responseHtml.html();
alert(response);
});
});
And my HTML
<form action="ajax/about_content.php" method="post" enctype="multipart/form-data" class="aboutContentImageForm" target="form_image_upload_content_id_8">
<fieldset>
<input type="file" name="image_path" id="image_path_8">
</fieldset>
</form>
<iframe id="form_image_upload_content_id_8" name="form_image_upload_content_id_8"></iframe>
So my form targets the iframe, and then once the iframe is finished loading, grab the data returned.
I can confirm the iframe is getting the response data. I can see it in the frame after I hit submit. I just can't capture the event of the iframe receiving said data. Is this a bug with .load()?
Edit
after putting an alert within the load() it looks like it DOES recognize that this action is completed, but they why can't I get my response data?
A: I think you've got the right approach, but there are inconsistencies with DOM readiness in iFrames between user agents. jQuery's form plugin uses this same technique. Looking at the source code of that plugin, I can see they're having to do some dancing around to deal with this issue, and Opera is specifically mentioned.
You might want to take a look there for some ideas: https://github.com/malsup/form/blob/e77e287c8024d200909a7b4f4a1224503814e660/jquery.form.js#L409
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614658",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to use sendkeys to copy text from outside application I have a specific application (someprogram.exe) i wish to use the sendkeys command to perform CTRL + C from the application i'm bulding in vb.net. I don't need to bring the data into my app, just copy it to the windows clipboard.
Thanks in advance!
A: i would Recommand to send the message GETTEXT to handle of that control (use FindWindow api maybe to get the handle) and then set it yourself to the clipboard, to avoid copying wrong data or only the selected part of it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Loading multi-level collections without duplicates in NHibernate My question is very similar to this one (that wasn't really answered): Nhibernate: distinct results in second level Collection
I have this object model:
class EntityA
{
...
IList<EntityB> BList { get; protected set; }
...
}
class EntityB
{
... does NOT reference its parent EntityA...
IList<EntityC> CList { get; protected set; }
}
They are One-to-Many relations. EntityB and C do not have an object reference to its parent object.
I'd like to fully load the collections by performing something like the following three SQL queries to avoid to Cartesian join:
SELECT id, ... FROM EntityA;
SELECT id, idA, ... FROM EntityB;
SELECT id, idB, ... FROM EntityC;
With that, the DAL has all the information to properly fill the objects. But since EntityB is not aware of who its parent is, it has to be nHibernate who takes care of filling the collections properly.
Can it be done ??
I could do this workaround with the Cartesian Product, but it requires modifying my model to provide a collection setter and that qualifies as a patch for a technical problem with the DAL in my mind.
ICriteria criteria = session.CreateCriteria<EntityA>()
.SetFetchMode("BList", FetchMode.Join)
.SetFetchMode("BList.CList", FetchMode.Join)
.SetResultTransformer(new DistinctRootEntityResultTransformer());
IList<EntityA> listA = criteria.List<EntityA>();
foreach (EntityA objA in listA) {
objA.BList = objA.BList.Distinct().ToList();
foreach (EntityB objB in objB.BList) {
objB.CList = objB.CList.Distinct().ToList();
}
}
A: Have you tried this syntax:
var entities = session.QueryOver<EntityA>().Where(...).List();
var entityIds = entities.Select(e => e.Id).ToArray();
session.QueryOver<EntityA>()
.WhereRestrictionOn(a => a.Id)
.IsIn(entityIds)
.Fetch(e => e.BList).Eager
.List();
var bEntityIds = entities
.SelectMany(e => e.BList)
.Select(b => b.Id)
.ToArray();
session.QueryOver<EntityB>()
.WhereRestrictionOn(b => b.Id)
.IsIn(bEntityIds).Fetch(e => e.CList).Eager
.List();
This should fire the three selects that you mention. It might seem a wee bit convoluted, but it is taking advantage of the session's first level cache, which ensures that all the entities in the first collection is updated with the loaded collections as they are executed.
Also, you do not pay the penalty of whatever complex query-logic you may have in place for the second and third query. The DB should use the primary index for the second query (maybe even clustered depending on you settings) and a foreign key for the join for extremely low-cost queries.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Multithreading: how to specify responsibility of newly created thread I'm very new to multithreading and I'm getting kind of confused! Ok, so suppose I create another thread besides the main thread in my program. That thread should be responsible of updating the UI while the main thread does calculations and other stuff. My question how does that newly created thread know it's responsible for updating the UI? How do you specify that?
A: Only one thread is allowed to update the UI, and that is the main thread. You can use BackgroundWorker to do the secondary work. It can "report progress" or "complete work" and on those events pass a message back to the main thread to do the work.
A: Only the UI thread can update the UI.
If you are in another thread you'll need to pass it to the UI thread.
string newText = "New Text Here"; //Your thread
this.Invoke((MethodInvoker)delegate {
Label1.Text = newText; // UI thread
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to hide a MatrixRow in SSRS 2005 based on an expression? I was wondering if someone can tell me how I can hide a row in a matrix on an SSRS 2005 report. I have tried hiding the specific TextBoxes, but when I do that, I still get whitespace where the TextBoxes would appear, which is pretty worthless.
According to research I have done online, there is supposed to be a visibility/hidden property when I right click the row header and go to properties, but I don't see that there. Below is a link to a screenshot of what I get for the properties:
http://imageshack.us/photo/my-images/696/ssrs.jpg
Where do I find this property? When I expanded all the groups, I didn't see anything related to visibility.
Is it possible to hide this row bases on an expression? Please let me know.
Thanks
New users apparently cannot answer their own questions without waiting 8 hours. It said to use the edit function instead. I'll marked this as answered later.
I think I found what I was looking for. I got the desired result anyway. Since I hate coming to posts and seeing "Thanks, I figured it out" without any other detail...
Right Click on the Matrix, that is to say, right click on the dotted line with the resizing handles that outlines the matrix. After that click properties. This should bring up a Matrix Properties dialog box. Go the Groups tab (5th over). To change the visibility of a row/column, click the "Edit" button. This brings up another dialog box. Visibility is the 4th tab.
Hope that saves someone a headache.
A: I think I found what I was looking for. I got the desired result anyway. Since I hate coming to posts and seeing "Thanks, I figured it out" without any other detail...
Right Click on the Matrix, that is to say, right click on the dotted line with the resizing handles that outlines the matrix. After that click properties. This should bring up a Matrix Properties dialog box. Go the Groups tab (5th over). To change the visibility of a row/column, click the "Edit" button. This brings up another dialog box. Visibility is the 4th tab.
Hope that saves someone a headache.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614669",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Can a C function have multiple signatures?
Possible Duplicate:
function overloading in C
Apologies if this is a dup but if it is, I can't find it.
In C, can you define multiple functions with the same function name, but with different parameters? I come from a C# background. In C#, the following code is completely legal.
//Our first function
int MyFunction()
{
//Code here
return i;
}
int MyFunction(int passAParameter)
{
// Code using passAParameter
return i;
}
In my specific case, I would like to create a function that has one optional parameter (that is an int) at the end of the parameter list. Can this be done?
A: No. C does not support overloading.
A: No you must use a different name for each function (this is not true with C++, as it allows you to specify optional parameters)
A: No. In strict C, you cannot do overloading.
However, given that most C compilers also support C++, and C++ does support overloading, there's a good chance you can do overloading if you're using a mainstream C/C++ compiler.
But its not strictly standard or portable to pure-C environments.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Marshal structure with integer references to C# Hi I'm trying to create and marshal the following structure from C# into C++ and maintain the linked reference. I'm unsure how this structure should be defined in C#? In C++ the structure must look like below, with the const reference maintained.
// C++
struct {
int a; // my value
const int& b = a; // my reference to a
}
Does anyone know if this is possible?
Thanks.
Edit:
This is more representative of what I'm trying to accomplish, and as pointed out by @Hans it is not legal C++, but maybe someone can suggest a better path? The system_t is generated in either C++ or C# and passed to C++. My best guess: (if this is even a good design pattern) is to initialize all the references in the system_t constructor in C++. As far as marshaling from C#, it will get complicated.
struct system_t
{
float sysSampleRate = 112500.0f; // Sample rate from receivers.
// Illegal statement @Hans
struct tvg_t // tvg_t is passed to tvg processor
{
float tvgLinearGain;
const float& tvgSampleRate = sysSampleRate; // Get the rate from system.
// Illegal statement @Hans
} tvg; // Nested tvg_t in system_t.
//... Many other structures and variables ..//
};
I'd like to find the right design pattern rather than abandoning this and going to a flat structure or passing system_t to every module.
A: This should work:
[StructLayout(LayoutKind.Sequential)]
public struct MyCStruct {
public int a;
public IntPtr b;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: error accessing elements of array of std::pair I have defined an array of pairs as following:
std::pair<int,int> delta[4];
delta[0] = std::make_pair(0,1);
delta[1] = std::make_pair(1,1);
delta[2] = std::make_pair(1,0);
delta[3] = std::make_pair(1,-1);
but when I try to access the elements like:
delta[2].first
I get an error as following :
binary '[' : 'std::pair<_Ty1,_Ty2>' does not define this operator or a conversion to a type acceptable to the predefined operator
error C2228: left of '.first' must have class/struct/union
Here is the function where I access it:
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <utility>
#include <algorithm>
int who_won(std::pair<int,int> &delta,std::vector<std::vector<int>> &grid);
int main(int argc, char** argv)
{
std::fstream input;
input.open("E:\\in.txt",std::ios_base::in);
std::string line;
char ch;
std::vector<std::vector<int>> grid;
std::vector<int> row;
while(input.get(ch))
{
if(ch == '\n')
{
grid.push_back(row);
row.clear();
}
else if(ch != ',')
{
row.push_back(std::atoi(&ch));
}
}
if(row.size()>0)
grid.push_back(row);
row.clear();
std::pair<int,int> delta[4];
delta[0] = std::make_pair(0,1);
delta[1] = std::make_pair(1,1);
delta[2] = std::make_pair(1,0);
int l = grid.size();
for( int i =0; i < l; ++i)
{
//auto & v = *i;
for( int j = 0; j < l; ++j)
std::cout<<grid[i][j]<<" ";
std::cout<<"\n";
}
int winner = who_won(*delta,grid);
if( winner == 0)
{
if( std::find(grid.front().begin(),grid.front().end(),0) == grid.front().end())
std::cout<<"draw";
else
std::cout<<"play";
}
else if( winner == 1)
std::cout<<"1";
else if( winner == 2)
std::cout<<"2";
return 0;
}
int who_won(std::pair<int,int> delta[],std::vector<std::vector<int>> &grid)
{
int l = grid.size(),connect;
for(int px = 0; px < l; ++px)
{
for(int py = 0; py < l; ++py)
{
for(int i = 0;i < 4;++i)
{
connect = 0;
for(int j = 1;j < 4;++j)
{
if( grid[px + delta[i].first*j][py + delta[i].second*j] != grid[px][py])
break;
else
connect++;
}
if(connect == 4)
return grid[px][py];
}
}
}
return -1;
}
Where am I going wrong ?
A: You method signature only specifies a reference to a single std::pair instance. You would probably want your signature to look something like the following if you want to pass an array of std::pair.
int who_won(std::pair<int,int> delta[],std::vector<std::vector<int>> &grid)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614683",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Flex Timer issue The Timer in my class does not seem to fire any TIMER events at all when the interval is more than 5 seconds or after it has measured 5 seconds. I need to measure 30 seconds.
Here's my code
//class ctor
public function myClass() {
tmr=new Timer(5000, 6);
tmr.addEventListener(TimerEvent.TIMER_COMPLETE, timerComplete);
tmr.addEventListener(TimerEvent.TIMER, timerTrace);
}
private function timerComplete(e:TimerEvent):void {
trace("complete");
}
private function timerTrace(e:TimerEvent):void {
trace("tick|" + tmr.currentCount);
}
The output I get is
tick|1
When I change the interval to 1000ms and the repeatCount to 30, I get
tick|1
tick|2
tick|3
tick|4
When interval is 30000 and repeatCount is 1, I get no output
The timer never completes.
I tried using setTimeout, but the timeout of 30 seconds doesn't work there either.
How can I add a timeout of 30 seconds?
EDIT
//declare timer
public var tmr as Timer;
//external class
nyClassInstance.tmr.start();
A: If you only want to set the delay to 30 seconds you should do it like this:
_timer = new Timer(30 * 1000, 1);
_timer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
_timer.start();
Example: http://wonderfl.net/c/4duo/
package
{
import flash.display.Sprite;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.text.TextField;
import flash.utils.getTimer;
public class FlashTest extends Sprite
{
private var _timer : Timer;
private var _lastUpdate : int;
private var _debugText : TextField;
public function FlashTest()
{
_debugText = new TextField();
addChild(_debugText);
_lastUpdate = getTimer();
_timer = new Timer(6 * 1000, 6);
_timer.addEventListener(TimerEvent.TIMER, onTimerUpdate);
_timer.addEventListener(TimerEvent.TIMER_COMPLETE, onTimerComplete);
_timer.start();
_debugText.appendText("STARTED");
}
private function onTimerUpdate(event : TimerEvent) : void
{
_debugText.appendText("\n" + (getTimer() - _lastUpdate) + " - UPDATE " + _timer.currentCount);
_lastUpdate = getTimer();
}
private function onTimerComplete(event : TimerEvent) : void
{
_debugText.appendText("\nCOMPLETE");
}
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ImageMagick leaving behind temp files - is this by design or should they be automatically deleted? I've installed ImageMagick on OS X using macports (I don't think these makes any difference but just in case)
I use the following:
$im = new imagick($src . '[0]');
$im->setImageFormat('png');
header("Content-Type: image/png" );
echo $im;
and I get a nice conversion of a pdf to a png.
Every time I do that however, I end up with a file like:
magick-23Iwt3tG
in /private/var/tmp. They do not seem to delete automatically.
Do I need to delete these manually or is there an option I can set to have them automatically deleted? (I don't want to end up with tons of these files hanging around)
A: The contents of /private/var/temp can be safely deleted but are not included in the /etc/rc.cleanup and /etc/weekly scripts which remove temporary files.
You can either do it manually or there is a script here which should do it for you.
A: I think you should use Imagick::clear() or Imagick::destroy() at the end of your script, it takes care of cleaning up everything.
I know it is a bit of a late response to your question, sorry about that :).
A: You have to write your own script to delete them. For example cron, or sth.
Check this link http://www.webmasterworld.com/forum88/4135.htm
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to use the "-Property" parameter for PowerShell's "Measure-Object" cmdlet? Why does
$a = GPS AcroRd32 | Measure
$a.Count
work, when
GPS AcroRd32 | Measure -Property Count
doesn't?
The first example returns a value of 2, which is what I want, an integer.
The second example returns this:
Measure-Object : Property "Count" cannot be found in any object(s) input.
At line:1 char:23
+ GPS AcroRd32 | Measure <<<< -Property Count
+ CategoryInfo : InvalidArgument: (:) [Measure-Object], PSArgumentException
+ FullyQualifiedErrorId : GenericMeasurePropertyNotFound,Microsoft.PowerShell.Commands.MeasureObjectCommand
This Scripting Guy entry is where I learned how to use the "Count" Property in the first code sample.
The second code sample is really confusing. In this Script Center reference, the following statement works:
Import-Csv c:\scripts\test.txt | Measure-Object score -ave -max -min
It still works even if it's re-written like so:
Import-Csv c:\scripts\test.txt | Measure-Object -ave -max -min -property score
I don't have too many problems with accepting this until I consider the Measure-Object help page. The parameter definition for -Property <string[]> states:
The default is the Count (Length) property of the object.
If Count is the default, then shouldn't an explicit pass of Count work?
GPS AcroRd32 | Measure -Property Count # Fails
The following provides me the information I need, except it doesn't provide me with an integer to perform operations on, as you'll see:
PS C:\Users\Me> $a = GPS AcroRd32 | Measure
PS C:\Users\Me> $a
Count : 2
Average :
Sum :
Maximum :
Minimum :
Property :
PS C:\Users\Me> $a -is [int]
False
So, why does Dot Notation ($a.count) work, but not an explicitly written statement (GPS | Measure -Property Count)?
If I'm supposed to use Dot Notation, then I will, but I'd like to take this opportunity to learn more about how and *why PowerShell works this way, rather than just building a perfunctory understanding of PowerShell's syntax. To put it another way, I want to avoid turning into a Cargo Cult Programmer/ Code Monkey.
A: Because the COUNT property is a property of the OUTPUT object (i.e. results of Measure-Object), not the INPUT object.
The -property parameter specifies which property(ies) of the input objects are to be evaluated. None of these is COUNT unless you pass an array or arrays or something.
A: I think what you want is something like this:
gps AcroRd32 | measure-object | select -expand Count
A: One thing you need to know is that in PowerShell generally, and particulary in CmdLets you manipulate objects or collection of objects.
Example: if only one 'AcroRd32' is running Get-Process will return a [System.Diagnostics.Process], if more than one are running it will return a collection of [System.Diagnostics.Process].
In the second case you can write:
(GPS AcroRd32).count
Because a collection has a count property. The duality object collection is also valid in CmdLets parameters that most of the time supports objects or list of objects (collection built with the operator ,).
PS C:\> (gps AcroRd32) -is [object[]]
True
Just use the Get-Member cmdlet:
PS C:\> (gps AcroRd32) | Get-Member
TypeName: System.Diagnostics.Process
Name MemberType Definition
---- ---------- ----------
Handles AliasProperty Handles = Handlecount
... ...
And
PS C:\> Get-Member -InputObject (gps AcroRd32)
TypeName: System.Object[]
Name MemberType Definition
---- ---------- ----------
Count AliasProperty Count = Length
... ...
A: If you're just looking for the count you can do the following:
$a = GPS AcroRd32
$a.Count = 2
$a = GPS AcroRd32 sets $a to an array of process objects. The array has a member call, Count, that will allow you to determine the number of elements already.
The Measure-Object commandlet (with alias measure) is used to measure the average, maximum, minimum, and sum values of a property. So you could do something like $a | measure -property Handles -sum and get a count of the total number of open handles.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614695",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: htaccess rewrite hide .php and also flatten query string on one particular url I have checked various topics and nothing caught my eyes. This is what am trying to do ..
It's a small site and with only few pages all in my root /mobile folder. So I decided to modify h*p://example.com/mobile/academics.php to h*p://example.com/mobile/academics (without the trailing slash)
RewriteRule ^([^.]+)$ $1.php [NC,L] - Works fine.
But I have http://example.com/mobile/program.php?p=ams which I want to convert as http://example.com/mobile/program/ams . I tried this :
RewriteRule ^/program/([^/]+)$ program.php?p=$1 - Makes no effect. Browser keeps looking for /program/ams.php
How to have both rules coexist? I have query string only on program.php . Any help is appreciated. I am sorry if this has been answered before. I searched for quite sometime and couldn't find any.
Thanks,
Vik
A: use
RewriteRule ^/?program/([^/]+)$ program.php?p=$1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why wont this event receiver code work? We are trying to create an ItemAdded event receiver that will update Created By (Author) field in a custom SharePoint list. In this custom list we have enabled Item-Lever Permissions so that userA will only be able to see what they create. Issue is when another User (UserB) creates the item for someone else (UserA), User A will not be able to see that item.
So we want whatever is in Request By filed to be copied to Created By field. To get there, with the help of few people online, we have created the following event receiver but it does not work. Can you tell us whats wrong with it?
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
namespace createdByElevate.EventReceiver1
{
/// <summary>
/// List Item Events
/// </summary>
public class EventReceiver1 : SPItemEventReceiver
{
/// <summary>
/// An item was added.
/// </summary>
public override void ItemAdded(SPItemEventProperties properties)
{
//update base first
base.ItemAdded(properties);
string SiteUrl = properties.Web.Url;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SiteUrl))
{
SPWeb web = site.OpenWeb();
SPList List = web.Lists["listName"];
SPListItem item = List.GetItemById(properties.ListItem.ID);
item["Submit User"] = item["Requested By"];
item.Update();
}
});
}
}
}
Found the following error in ULS logs:
*
*
*
*Sandboxed code execution request failed. - Inner Exception: System.Runtime.Remoting.RemotingException: Server encountered an internal error. For more information, turn off customErrors in the server's .config file. Server stack trace: Exception rethrown
at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
at Microsoft.SharePoint.Administration.ISPUserCodeExecutionHostProxy.Execute(Type userCodeWrapperType, Guid siteCollectionId, SPUserToken userToken, String affinityBucketName, SPUserCodeExecutionContext executionContext)
at Microsoft.SharePoint.UserCode.SPUserCodeExecutionManager.Execute(Type userCodeWrapperType, SPSite site, SPUserCodeExecutionContext executionContext)
Error loading and running event receiver createdByElevate.EventReceiver1.EventReceiver1 in createdByElevate, Version=1.0.0.0, Culture=neutral, PublicKeyToken=97fddd01b051f985. Additional information is below. Server encountered an internal error. For more information, turn off customErrors in the server's .config file.
A: Your error seems to suggest that you have deployed this as a Sandboxed solution. Unfortunately you can't use elevated privileges ( SPSecurity.RunWithElevatedPrivileges ) in this type of deployment. You will either have to think of another way around this limitation or redeploy as a Farm solution.
A: Can you first verify whether both "Submit User" and "Requested By" columns are of same datatype.
I mean if they were of same Type then it will work fine.
Thanks,
-Santosh
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614701",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: SetWindowPos() not moving or resizing window I have a GUI application that is using GStreamer to capture video from capture cards, and then play the video. The audio and video streams are sent to GStreamer, and GStreamer automatically opens its own window to play the video. Once the video window is open, I need to take the video window and remove the border and set the window size and position and make my GUI window the parent of that window so that it will be "anchored" to my GUI window.
Since I know the name of the video window I am using FindWindow() to get an HWND handle to the window. I am then passing that HWND to SetWindowPos() as follows SetWindowPos(VideoWindow, GUIWindow, GUIWindowLeft, GUIWindowTop, 640, 360, SWP_SHOWWINDOW). Then I set the parent of the video window SetParent(VideoWindow, GUIWindow).
When I start my application, for a very brief moment it looks like my window is being resized and placed correctly but then the window returns to its default position (almost like it is just neglecting that SetWindowPos() was even called). Is there an obvious reason for why this happens? I am new to window manipulation so it is very possible I am making a simple mistake, but it does not make since why my window would be positioned correctly for a very brief moment but then move back to default position.
A: This is because the SWP_SHOWWINDOW or SWP_HIDEWINDOW is set, the window won't be moved or resized (see SetWindowPos documentation). Seems a little strange. Try using a different flag.
From the docs:
If the SWP_SHOWWINDOW or SWP_HIDEWINDOW flag is set, the window cannot be moved or sized.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: perl - setting up conditions to find correct key in a hash Problem:
Seeing exists argument is not a HASH or ARRAY element
Need help setting up several conditions to grab the right key.
Code: (I'm not sure also if my conditions are set up correctly. Need advice troubleshooting)
my $xml = qx(@cmdargs);
my $data = XMLin($xml);
my $size=0;
# checking for error string, if file not found then just exit
# otherwise check the hash keys for filename and get its file size
if (exists $data->{class} =~ /FileNotFound/) {
print "The directory: $Path does not exist\n";
exit;
} elsif (exists $data->{file}->{path}
and $data->{file}->{path} =~/test-out-XXXXX/) {
$size=$data->{file}->{size};
print "FILE SIZE:$size\n";
} else {
# print "Nothing to print.\n";
}
# print "$data";
print Dumper( $data );
My Data:
Data structure for xml file with FileNotFound:
$VAR1 = {
'file' => {},
'path' => '/source/feeds/customer/testA',
'class' => 'java.io.FileNotFoundException',
'message' => '/source/feeds/customer/testA: No such file or directory.'
};
Data structure for xml file found:
$VAR1 = {
'recursive' => 'no',
'version' => '0.20.202.1.1101050227',
'time' => '2011-09-30T02:49:39+0000',
'filter' => '.*',
'file' => {
'owner' => 'test_act',
'replication' => '3',
'blocksize' => '134217728',
'permission' => '-rw-------',
'path' => '/source/feeds/customer/test/test-out-00000',
'modified' => '2011-09-30T02:48:41+0000',
'size' => '135860644',
'group' => '',
'accesstime' => '2011-09-30T02:48:41+0000'
},
A: The interpreter is probably thinking you meant:
exists($data->{class}=~/FileNotFound/)
Try:
exists $data->{class} and $data->{class}=~/FileNotFound/
instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is it possible to create table-valued *methods* in a SQL CLR user-defined type? I have a CLR UDT that would benefit greatly from table-valued methods, ala xml.nodes():
-- nodes() example, for reference:
declare @xml xml = '<id>1</id><id>2</id><id>5</id><id>10</id>'
select c.value('.','int') as id from @xml.nodes('/id') t (c)
I want something similar for my UDT:
-- would return tuples (1, 4), (1, 5), (1, 6)....(1, 20)
declare @udt dbo.FancyType = '1.4:20'
select * from @udt.AsTable() t (c)
Does anyone have any experience w/ this? Any help would be greatly appreciated. I've tried a few things and they've all failed. I've looked for documentation and examples and found none.
Yes, I know I could create table-valued UDFs that take my UDT as a parameter, but I was rather hoping to bundle everything inside a single type, OO-style.
EDIT
Russell Hart found the documentation states that table-valued methods are not supported, and fixed my syntax to produce the expected runtime error (see below).
In VS2010, after creating a new UDT, I added this at the end of the struct definition:
[SqlMethod(FillRowMethodName = "GetTable_FillRow", TableDefinition = "Id INT")]
public IEnumerable GetTable()
{
ArrayList resultCollection = new ArrayList();
resultCollection.Add(1);
resultCollection.Add(2);
resultCollection.Add(3);
return resultCollection;
}
public static void GetTable_FillRow(object tableResultObj, out SqlInt32 Id)
{
Id = (int)tableResultObj;
}
This builds and deploys successfully. But then in SSMS, we get a runtime error as expected (if not word-for-word):
-- needed to alias the column in the SELECT clause, rather than after the table alias.
declare @this dbo.tvm_example = ''
select t.[Id] as [ID] from @this.GetTable() as [t]
Msg 2715, Level 16, State 3, Line 2
Column, parameter, or variable #1: Cannot find data type dbo.tvm_example.
Parameter or variable '@this' has an invalid data type.
So, it seems it is not possible after all. And even if were possible, it probably wouldn't be wise, given the restrictions on altering CLR objects in SQL Server.
That said, if anyone knows a hack to get around this particular limitation, I'll raise a new bounty accordingly.
A: You have aliased the table but not the columns. Try,
declare @this dbo.tvm_example = ''
select t.[Id] as [ID] from @this.GetTable() as [t]
According to the documentation, http://msdn.microsoft.com/en-us/library/ms131069(v=SQL.100).aspx#Y4739, this should fail on another runtime error regarding incorrect type.
The SqlMethodAttribute class inherits from the SqlFunctionAttribute class, so SqlMethodAttribute inherits the FillRowMethodName and TableDefinition fields from SqlFunctionAttribute. This implies that it is possible to write a table-valued method, which is not the case. The method compiles and the assembly deploys, but an error about the IEnumerable return type is raised at runtime with the following message: "Method, property, or field '' in class '' in assembly '' has invalid return type."
They may be avoiding supporting such a method. If you alter the assembly with method updates this can cause problems to the data in UDT columns.
An appropriate solution is to have a minimal UDT, then a seperate class of methods to accompany it. This will ensure flexibility and fully featured methods.
xml nodes method will not change so it is not subject to the same implemetation limitations.
Hope this helps Peter and good luck.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7614712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.