text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Rails 3 : How to call create action form Flex I have a rails app that records a video from the webcam. After the video file is saved on the flex server, I need to create a record on the database calling the create action on my rails app from Flex.
How can I achieve this? I need a url with params to be called. I think the
authenticity_token is necessary to post data.
Any ideas?
A: You can do POST request with ActionScript and Flex framework to your serverside action. It can be a pretty default resourse with create action.
To pass authenticity token you have 2 options: 1) external interface via JS function, 2) flashvars.
Everything else it depends on requirements. If you can explain details, I can help you, because we are working on rails+flex application more than 3 years
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How To Compare Two Strings If they are rearranged I wanted to know how can I compare two rearranged strings
E.g if String a="string" ,String b="tsrngi" ... If I compare a.equals(b), It will return false because of order of characters... I want it to return true because characters are same but only order is different.. Thanks
A: Sort them, then compare. To sort, use something like:
char[] content = unsorted.toCharArray();
java.util.Arrays.sort(content);
String sorted = new String(content);
A: I really like JRL's solution, since it's quite elegant. At the same time, I feel that because there is a solution that is an order of complexity better that I should share it. It's less elegant, but it's O(n) instead of O(n lg n).
if(str1.length() != str2.length()) return false;
Map<Character, Integer> counts = new HashMap<Character, Integer>();
for(int i = 0; i < str1.length(); i++) {
// add 1 for count for str1
if(counts.contains(str1.charAt(i)) {
counts.put(str1.charAt(i),counts.get(star1.charAt(i)) + 1);
} else {
counts.put(str1.charAt(i),1);
}
// sub 1 for count for str2
if(counts.contains(str2.charAt(i)) {
counts.put(str2.charAt(i),counts.get(str2.charAt(i)) - 1);
} else {
counts.put(str2.charAt(i),-1);
}
}
// when you're done, all values in the map should be 0. If they
// aren't all 0, you don't have equal-arranged strings.
for(Integer i : counts.values()) {
if(i.intValue() != 0) return false;
}
// we made it this far, we know it's true
return true;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Is Ruby's open dynamic class structure (duck typing) secure? I"m a newish Ruby/Rails developer with years of Java experience. This "security" question is specific to ruby - not rails - which is why it was hard to find an answer as most rails security questions deal with web stuff.
As a Java developer I've read Effective Java several times. One of the key points made in that book is to protect your data and methods in your classes from malicious users. By that I mean : make as much of your code private as possible, use immutable classes and use defensive copying when returning references to immutable objects. You can use the final keyword too.
But in Ruby, everything is open. Sure you can make a method / data private, but but as a consumer of a Ruby API, is there anything stopping me from writing my own version of the method then simply (dynamically at run time or in code) attaching it to a class in the API? Seems like all the security discussed in Effective Java doesn't apply to Ruby at all. Is this just a mindset shift from Java? Isn't this a "flaw" in Ruby or other similar languages?
A: The defense is against bad design, not intruders
Encapsulation, class-private functionality, and other recommended OO design patterns are not there to defend again malicious foreign functions and enemy classes.
Rather, the idea is simply to structure the program in a way that makes it less fragile and easier to modify.
Think of each class as a separate building. We could build a new office so that it's leaning on the next building to the north and perhaps extend some steel from the building to the west to help hold up our new structure.
The obvious result would be damage to the structural integrity of the N and W neighbors, and questionable support for the new construction. With software, bad ideas like these are not always so obvious, so we read books full of principles and recommendations to remind us.
A: In order for this to be a vector of attack, the malicious user has to be able change code that you will then run. If he can do that, it doesn't matter what language you are using: you are running his code, and he owns you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is chain of StringBuilder.append more efficient than string concatenation? According to Netbeans hint named Use chain of .append methods instead of string concatenation
Looks for string concatenation in the parameter of an invocation of the append method of StringBuilder or StringBuffer.
Is StringBuilder.append() really more efficient than strings concatenation?
Code sample
StringBuilder sb = new StringBuilder();
sb.append(filename + "/");
vs.
StringBuilder sb = new StringBuilder();
sb.append(filename).append("/");
A: You have to balance readability with functionality.
Let's say you have the following:
String str = "foo";
str += "bar";
if(baz) str += "baz";
This will create 2 string builders (where you only need 1, really) plus an additional string object for the interim. You would be more efficient if you went:
StringBuilder strBuilder = new StringBuilder("foo");
strBuilder.append("bar");
if(baz) strBuilder.append("baz");
String str = strBuilder.toString();
But as a matter of style, I think the first one looks just fine. The performance benefit of a single object creation seems very minimal to me. Now, if instead of 3 strings, you had 10, or 20, or 100, I would say the performance outweighs the style. If it was in a loop, for sure I'd use the string builder, but I think just a couple strings is fine to do the 'sloppy' way to make the code look cleaner. But... this has a very dangerous trap lurking in it! Read on below (pause to build suspense... dun dun dunnnn)
There are those who say to always use the explicit string builder. One rationale is that your code will continue to grow, and it will usually do so in the same manner as it is already (i.e. they won't take the time to refactor.) So you end up with those 10 or 20 statements each creating their own builder when you don't need to. So to prevent this from the start, they say always use an explicit builder.
So while in your example, it's not going to be particularly faster, when someone in the future decides they want a file extension on the end, or something like that, if they continue to use string concatenation instead of a StringBuilder, they're going to run into performance problems eventually.
We also need to think about the future. Let's say you were making Java code back in JDK 1.1 and you had the following method:
public String concat(String s1, String s2, String s3) {
return s1 + s2 + s3;
}
At that time, it would have been slow because StringBuilder didn't exist.
Then in JDK 1.3 you decided to make it faster by using StringBuffer (StringBuilder still doesn't exist yet). You do this:
public String concat(String s1, String s2, String s3) {
StringBuffer sb = new StringBuffer();
sb.append(s1);
sb.append(s2);
sb.append(s3);
return sb.toString();
}
It gets a lot faster. Awesome!
Now JDK 1.5 comes out, and with it comes StringBuilder (which is faster than StringBuffer) and the automatic transation of
return s1 + s2 + s3;
to
return new StringBuilder().append(s1).append(s2).append(s3).toString();
But you don't get this performance benefit because you're using StringBuffer explicitly. So by being smart, you have caused a performance hit when Java got smarter than you. So you have to keep in mind that there are things out there you won't think of.
A: None of the answers so far explicitly address the specific case that hint is for. It's not saying to always use StringBuilder#append instead of concatenation. But, if you're already using a StringBuilder, it doesn't make sense to mix in concatenation, because it creates a redundant StringBuilder (See Dirk's answer) and an unnecessary temporary String instance.
Several answers already discuss why the suggested way is more efficient, but the main point is, if you already have a StringBuilder instance, just call append on it. It's just as readable (in my opinion, and apparently whoever wrote the NetBeans hint) since you're calling append anyway, and it's a little more efficient.
A: It's only more efficient if you are using lots of concatenation and really long strings. For general-use, such as creating a filename in your example, any string concatenation is just fine and more readable.
At any rate, this part of your application is unlikely to be the performance bottleneck.
A: Theoretically, yes. Because String objects are immutable: once constructed they cannot be changed anymore. So using "+" (concatenation) basically creates a new object each time.
Practically no. The compiler is clever enough to replace all your "+" with StringBuilder appendings.
For a more detailed explanation:
http://kaioa.com/node/59
PS: Netbeans??? Come on!
A: A concat of two strings is faster using this function.
However, if you have multiple strings or different data type, you should use a StringBuilder either explicitly or implicitly. Using a + with Strings is using a StringBuilder implicitly.
A: Well, your first example is essentially translated by the compiler into something along the lines:
StringBuilder sb = new StringBuilder();
sb.append(new StringBuilder().append(filename).append("/").toString());
so yes, there is a certain inefficiency here. However, whether it really matters in your program is a different question. Aside from being questionable style (hint: subjective), it usually only matters, if you are doing this in a tight loop.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "63"
}
|
Q: NamedQueries problem with Hibernate I used NanedQueries (as follows) in my JPA project Eclipselink as persistence provider:
@Entity
@Table(name = "login")
@NamedQueries({
@NamedQuery(name = "Login.random", query = "SELECT l FROM Login l WHERE l.pk = :randomPk"),
@NamedQuery(name = "Login.max", query = "SELECT MAX(l.pk) FROM Login l")
})
But after I change Hibernate as my persistence provider, I get the following error:
java.lang.IllegalArgumentException: org.hibernate.QueryException: unexpected char: '{' [SELECT...
I use Hibernate 3.2.5 (MySQL dialect)
A: Not having your exact configuration makes this difficult. But I didn't have an issue with hibernate 3.2.5.GA
I created the following Login Domain object:
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import java.io.Serializable;
@Entity
@Table(name = "login")
@NamedQueries({
@NamedQuery(name = "Login.random", query = "select l FROM Login l WHERE l.pk = :randomPk"),
@NamedQuery(name = "Login.max", query = "select max(l.pk) from Login l")
})
public class Login implements Serializable {
private Long pk;
private String username;
public Login() {}
public Login(Long pk, String username) {
this.pk = pk;
this.username = username;
}
@Id
public Long getPk() {
return pk;
}
public void setPk(Long pk) {
this.pk = pk;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
and test class:
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import sky.sns.domain.Login;
import static org.junit.Assert.assertEquals;
public class AnnotationTest {
private static SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@BeforeClass
public static void initialise() {
sessionFactory = new AnnotationConfiguration().configure("/hibernate-annotation.cfg.xml").buildSessionFactory();
}
@Before
public void setUp() {
session = sessionFactory.getCurrentSession();
transaction = session.beginTransaction();
}
@After
public void tearDown() {
transaction.rollback();
}
@Test
public void createUser() {
Login login = new Login(1L, "foo");
session.save(login);
session.flush();
session.clear();
Login persistedLogin = (Login)session.get(Login.class, 1L);
assertEquals(login.getPk(), persistedLogin.getPk());
}
@Test
public void obtainUserByIdNamedQuery() {
Login login = new Login(1L, "foo");
session.save(login);
session.flush();
session.clear();
Login persistedLogin = (Login)session.getNamedQuery("Login.random").setLong("randomPk", 1L).uniqueResult();
assertEquals(login.getPk(), persistedLogin.getPk());
}
@Test
public void obtainMaxUserIdNamedQuery() {
Login login = new Login(1L, "foo");
session.save(login);
session.flush();
session.clear();
Long maxId = (Long)session.getNamedQuery("Login.max").uniqueResult();
assertEquals(login.getPk(), maxId);
}
}
My hibernate-annotation.hbm.xml file is as follows:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.jboss.org/dtd/hibernate/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_owner</property>
<property name="hibernate.connection.username">hibernate_owner</property>
<property name="hibernate.connection.password">hibernate</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable second-level cache. -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="hibernate.format_sql">false</property>
<property name="hibernate.use_sql_comments">false</property>
<mapping class="sky.sns.domain.Login" />
</session-factory>
</hibernate-configuration>
Can you try this in your environment and let me know how you get on
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Detecting content parsers Is there a way to detect if someone is trying to parse your content with tools like Simple Html Dom so i can properly redirect those requests via .htaccess?
A: I would guess not -- all of these kinds of libraries happen client-side, so the request to your server is just a HTTP request like any browser would make. There might be some oddities in the request headers, but any diligent programmer could mimic what a common browser does and hide behind that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is it possible to have VLC reread automatically an XSPF file between songs using Lua? First of I have no experience in Lua, just came by it while searching for an answer to my question here on StackOverflow and the internet. If there is any other method you know of that might work I'd very much appreciate hearing it.
So what I'm gearing up to do is to have a basic webpage that uses php and a Mysql database to allow users to vote up or down songs. At a specific time the top song is put as the next song/first song in an XSPF playlist XML.
And what I need to find out how (or if its possible) to have VLC reread the XSPF file between songs so that it uses the updated playlist. I have seen examples of playlist creation in VLC using Lua scripts but before I dive into how to do that I was wondering if this was at all possible?
Also if you know of any other way of putting up a similar settup without the use of one or more of these things I've just mentioned I'd also like to know.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Lambda expressions to obtain data through navigation properties, LINQToEntities I'm having a problem getting some data since I'm just starting to use LINQToEntities, Entity Framework and Lambda Expressions.
Let me explain my case:
I have a database with 4 tables as shown here:
when I generate the model from database in Visual Studio (2010) the result is this:
I searched for some info and turns out that since the table t_user_role only has the ids from its two parent tables, it gets abstracted in the model, and you have to use the navigation properties instead.
I had some problem getting the role info for a user on a given system (as the next function does)
public t_role GetRoleForUser(string userId, string sysId)
{
entities = new secfinEntities(); //context from the model
t_role userRole = entities.t_role.Where(r => r.t_user.Any(u => u.uid == userId) & r.sys_id == sysId).First();
return userRole;
}
Now I have to implement a simple search function that will look users that contain the provided string and return the user's id and name (uid, user_name) and their role's info (role_id, role_name) on a given system (the system info i have beforehand), so basically I wanna turn this next SQL Query into Lambda Expressions (keeping in mind that in the model the table t_user_role has been abstracted)
SELECT U.uid, U.user_name, R.role_id, R.role_name
FROM t_user U
INNER JOIN t_user_role UR ON U.uid = UR.uid
INNER JOIN t_role R ON UR.role_id = R.role_id
WHERE R.sys_id = @p0 -- first parameter
AND U.user_name LIKE '%' + @p1 + '%' -- second parameter
Also, I would like to store the results of that in a List of a type I have defined as follows:
public class UserRole
{
public string UserId { get; set; }
public string UserName { get; set; }
public string RoleId { get; set; }
public string RoleName { get; set; }
public UserRole(string uid, string uname, string rid, string rname)
{
UserId = uid;
UserName = uname;
RoleId = rid;
RoleName = rname;
}
}
So after explaining what I have done and what I'm trying to do first question is: how can that be done?, second: can the same be accomplished through the verbose form instead of Lambda expressions? if yes, how?
Thanks a lot in advance for your time.
A: This T-SQL:
SELECT U.uid, U.user_name, R.role_id, R.role_name
FROM t_user U
INNER JOIN t_user_role UR ON U.uid = UR.uid
INNER JOIN t_role R ON UR.role_id = R.role_id
WHERE R.sys_id = @p0 -- first parameter
AND U.user_name LIKE '%' + @p1 + '%' -- second parameter
given your model translates to this verbose syntax (including the requirement to use your new model):
var results = (from u in entities.t_user
from r in u.t_role
where r.sys_id == sysIdVariable && u.user_name.Contains(userNameVariable)
select new UserRole(u.uid, u.user_name, r.role_id, r.role_name))
I know you didn't ask for it, but a lambda version might look like:
var results = entities.t_user.Join(entities.t_role,
x => x.t_role_id,
x => x.role_id,
(u, r) => new UserRole(u.uid,
u.user_name,
r.role_id,
r.role_name))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Creating an "object" of an interface Today I had a bit of an argument with a friend who claimed that an interface object can be created. When I said that it's impossible, he showed me the following piece of code, which seemed similar to anonymous classes.Now the question is, what's the right answer?
public interface I {
public void f();
}
public class InterfaceTest {
public static void main(String []args){
new I(){
@Override
public void f() {
System.out.println("HELLO");
}
};
}
}
Can this really be called creating an interface "object"?
A: No, it is (an instance of) an anonymous class.
A: No, this is creating an instance of an anonymous class that implements the interface.
Here's the definitive answer from the Java Language Specification, section 15.9:
Both unqualified and qualified class instance creation expressions may
optionally end with a class body. Such a class instance creation
expression declares an anonymous class (§15.9.5) and creates an
instance of it.
A: This is anonymous class creation. The class of the instance created above extends java.lang.Object and implements the interface I. So, technically, the above code creates an Object object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586277",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Grid web component with paste from table I'm looking for a spreadsheet or grid type component. Specifically I need to allow a user to copy from an html table and paste into the spreadsheet. There is no need to support styling/fonts/calculations/etc.
I'm able to do this via the google docs spreadsheets, so it is possible, but I need to embed this into a java web application.
So far I've looked at:
*
*ExtJs
*SmartGWT
*jquery grid plugin
*RichFaces rich:datatable
*zk spreadsheet
and while they are all quite impressive in their own rights, none seem to allow copy from an html table and paste into the spreadsheet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is there a problem with this mysql update in a php for loop? I'm using this php code to update a table, but nothing is updating?
if(isset($Submit))
{
include('connect_mysql.php');
for($i=0;$i<$count;$i++)
{
$sql = "UPDATE $table SET cost='{$cost[$i]}', net=('{$bypiece[$i]}' + '{$cost[$i]}') WHERE serial='{$serial[$i]}'";
$result = mysql_query($dbcon, $sql);
}
}
if($result)
{
header("location:admin-index.php#office.php");
mysql_close();
}
It seems like it should work, and i have no reason why it wouldn't.
My variables are defined, and when i echo them out with an else statement everything seems to be alright. Yet the data isn't being updated, and the header isn't redirecting.
Can anyone help me find a working solution?
A: A good idea when debugging is turn on error reporting.
error_reporting(E_ALL);
ini_set('display_errors', '1');
Also see if you have any errors in your sql statement by changing
$result=mysql_query($dbcon, $sql);
to
$result=mysql_query($dbcon, $sql) or die(mysql_error());
A: Change:
net=('{$bypiece[$i]}' + '{$cost[$i]}')
To:
net=({$bypiece[$i]} + {$cost[$i]})
You should also have some error checking with the query.
if(isset($Submit)){
include('connect_mysql.php');
$count=20;
for($i=0;$i<$count;$i++){
$sql="UPDATE $table SET cost='{$cost[$i]}', net=({$bypiece[$i]} + {$cost[$i]}) WHERE serial='{$serial[$i]}'";
$result=mysql_query($dbcon, $sql) or die(mylsql_error());
}
if($result){
header("location:admin-index.php#office.php");
mysql_close();
}
}
A: What is $count set to? Your code would go nowhere in the state that it is in right now since $count isn't set to anything.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586285",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: java ScheduledExecutorService runnable exception handling I am realizing that if a exception are raised inside(or not, but should be related to) my runnable's run method, all my future tasks will not be run.
So my question is: How can I recover from such a exception (where to catch it)?
I have tried this:
ScheduledExecutorService Exception handling
If i do a while loop to catch the exception, the future tasks are still not executed. I also tried to schedule the catch, no help either.
I tried to put a huge try/catch to wrap all the code in run method but it seems to be not catching anything, and some exception are still not catches and causing all my future tasks to not run.
A: In the executor framework, you are giving control of running a job away from one main application thread to a thread pool thread. A thread submits the work through a schedule, or submit method is returned a Future object that allows it to get information through a get method. The get method will throw an executor exception whose cause is probably the exception that your code inside the runnable threw. If the main thread does not do that it will never see that exception, so it really depends on your application logic flow.
Another thing also to mention, if you try catch all, what do you mean by that if you are doing something similar to
try {
....
}
catch(Exception e) {
.... }
you are really not catching errors in your app (throwable is the father of Exception and Error) so you might have some static initializer error (an exception caught in a static block)
Again it all depends on how you want exception handling to happen you have full power,
Thank you
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Draw order of 3D-Models in XNA i'm having trouble with drawing 3D-Models in the right order in XNA.
Here are two images that describe the problem:
Pic1: http://imgur.com/wGPIk&L5AY1l
Pic2: http://imgur.com/wGPIkl&L5AY1
The ball is moving downwards and as soon as it intersects the terrain, the perspective is changing so that it looks like as if the ball is behind the terrain.
If i change the order of drawing, it will look like the ball is on top of the terrain all the time..
Can someone please explain how to solve this problem?
Thanks in advance
A: The problem is the SpriteBatch call that draws your FPS counter in the corner.
SpriteBatch changes the state of the graphics device. Whenever you're done drawing your 2D objects (in this case, your frame rate counter in the upper-left corner), you need to restore the device state.
After calling SpriteBatch.End(), add this code:
device.DepthStencilState = DepthStencilState.Default;
where device is a reference to the current GraphicsDevice that you're drawing with.
A: This looks like a ZBuffer problem. Have you checked that your Zbuffer is enabled and working? Try what David Lively said. if that works, check that you don't draw your 3D models Inside the Begin and End calls of the SpriteBatch class.
Begin readies the device for drawing 2D objects, if you try now to call 3D drawing this can't work. End makes sure that everything, set for 2D, is unset and reverted to the states before the Begin call.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Mahout : How to convert custom document in SparseVector format for using LDA I have a set of documents in which each line has certain number of Strings seperated with "\t|\t". Each String(may contain spaces in between) is a indivisible dictionary item. Now I have to use LDA to find the correletaion between these documents with respect to each dictionsr word(String in my vocab).
Please guide me how can I convert these documents to spares vector format and then how to apply LDA on them?
A: This is one of the best links that i have found that might answer your queries.
http://www.theglassicon.com/computing/machine-learning/running-lda-algorithm-mahout
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to know which exception is thrown I'm doing a review for our codebase, and there are many statements like this:
try
{
doSomething()
} catch (Exception e)
{
}
but I would like a way to know which exception is thrown by doSomething() (there's no throw statement in the implementation of doSomething) so i can catch that exception instead of just catching Exception in general, even with findBugs it gives a warning REC_CATCH_EXCEPTION.
I should mention that logging the exception or printing it to console will not help me because it takes time in this case to reproduce the error that causes the exception here.
Thanks
A: You can 1) dig through all the code in doSomething() and everything it calls to see the exception handling and what RuntimeExceptions can be thrown, or 2) take of the catch (Exception e) and wait for it to fail. This is the problem that checked exceptions attempted to overcome by making a strongly-typed declaration in method signatures about what exceptions must be handled as a result of calling the method.
A: If there's no throws statement in doSomething (e.g. doSomething() throws IOException), any exceptions that will occur will be an instance of RuntimeException. If you want to know the exact class of an exception thrown by doSomething, you can always try
try {
doSomething();
} catch (RuntimeException e){
System.out.println(e.getClass().getName());
}
Knowing which runtime exceptions can be thrown without actually running the program is difficult. Even if none of the code that doSomething() calls has an explicit throw, core java operations can always throw NullPointerException, ArrayIndexOutOfBoundsException, etc with the wrong input. Here are some ideas:
*
*Dig through manually. At least you will know some of the exceptions.
*Use reflection to find any throw statements accessible from doSomething.
*Run your test cases and log the exceptions thrown like above. Good tests will reveal the important errors that callers of doSomething should be ready for.
*Go to the people who put the catch there in the first place
In any case it's usually a good idea to catch exceptions that are as specific as possible, since you don't know exactly what went wrong when you try to deal with all cases in one clause.
A: If there is no throws clause, then the method does not throw any checked execption. The javadoc of that method might give information about any unchecked exceptions the method can throw, but it does not have to.
Why do you want to catch any exceptions in the first place?
A: Do you want to catch just compile-time exceptions or run-time exceptions as well? If you only want to catch the compile-time ones, just remove your current catch block - you'll immediately get error messages stating that certain exceptions aren't being caught. After you add one exception, you'll see error messages for others - you'll be able to finish catching all possible exceptions thrown by your code block.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Why does a number of completed tasks in Mapreduce decrease? When running hadoop jobs, I noticed that sometimes the number of completed tasks decreases and number of canceled tasks increases.
How is this possible? Why does this happen?
A: I've only experienced this when our cluster was in a strange state, so I'm not sure if this is the same issue. Basically, map tasks would complete, and then the reducers would start... and then mappers would be reprocessed.
I believe that the problem is that mapper output hangs around on that data node waiting for reducers to pick it up. If that node has issues or it dies, the JobTracker decides that it needs to rerun that task again, even if it had completed. Our issue was that the system our NameNode was on was having some non-Hadoop related issues and once those were resolves it seemed to go away.
Sorry if my experience was not relevant to your issue. Perhaps, can you post more details? Do you see any error messages? Is there anything weird in your JobTracker or NameNode logs?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why is a .get() on a filtered query returning None? I'm following the instruction from an answer, why is my object that is returned by the function None and not an entity?
class FileInfo(db.Model):
blob = blobstore.BlobReferenceProperty(required=True)
randomvalue = db.FloatProperty()
uploaded_by = db.UserProperty()
facebook_user_id = db.StringProperty()
uploaded_at = db.DateTimeProperty(required=True, auto_now_add=True)
category = db.CategoryProperty(choices=('eyes', 'nose', 'mouth',
'other'))
# snip -- shortened here
def get_random_image(self, category):
"""
fileinfos = FileInfo.all().filter('category =', category)
return fileinfos[random.randint(0, fileinfos.count() - 1)]
"""
q = FileInfo.all()
q.filter('category =', category)
q.filter('random >=', random.random())
return q.get() # why is this not working?
A: q.filter('random >=', random.random())
should be corrected in:
q.filter('randomvalue >=', random.random())
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586310",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AspectJ EDT-Checker Code Question I am currently using Alexander Potochkin's AspectJ EDTChecker code (relevant code at bottom of post).
This code (from what little I understand of AspectJ) complains on any JComponent method call or constructor call that does not occur within the Swing EDT.
However, the following only complains on the JList constructor, NOT the JFrame constructor. Can anyone tell me why? Thanks!
package testEDT;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JList;
public class TestEDT{
JList list;
final JFrame frame;
public TestEDT() {
DefaultListModel dlm = new DefaultListModel();
list = new JList(dlm);
frame = new JFrame("TestEDT");
}
public static void main(String args[]) {
TestEDT t = new TestEDT();
t.frame.setVisible(true);
}
}
Alexander Potochkin's AspectJ code:
package testEDT;
import javax.swing.*;
/**
* AspectJ code that checks for Swing component methods being executed OUTSIDE the Event-Dispatch-Thread.
*
* (For info on why this is bad, see: http://java.sun.com/products/jfc/tsc/articles/threads/threads1.html)
*
* From Alexander Potochkin's blog post here:
* http://weblogs.java.net/blog/alexfromsun/archive/2006/02/debugging_swing.html
*
*/
aspect EdtRuleChecker{
/** Flag for use */
private boolean isStressChecking = true;
/** defines any Swing method */
public pointcut anySwingMethods(JComponent c):
target(c) && call(* *(..));
/** defines thread-safe methods */
public pointcut threadSafeMethods():
call(* repaint(..)) ||
call(* revalidate()) ||
call(* invalidate()) ||
call(* getListeners(..)) ||
call(* add*Listener(..)) ||
call(* remove*Listener(..));
/** calls of any JComponent method, including subclasses */
before(JComponent c): anySwingMethods(c) &&
!threadSafeMethods() &&
!within(EdtRuleChecker) {
if ( !SwingUtilities.isEventDispatchThread() && (isStressChecking || c.isShowing())) {
System.err.println(thisJoinPoint.getSourceLocation());
System.err.println(thisJoinPoint.getSignature());
System.err.println();
}
}
/** calls of any JComponent constructor, including subclasses */
before(): call(JComponent+.new(..)) {
if (isStressChecking && !SwingUtilities.isEventDispatchThread()) {
System.err.println(thisJoinPoint.getSourceLocation());
System.err.println(thisJoinPoint.getSignature() + " *constructor*");
System.err.println();
}
}
}
A: JFrame is not a subclass of JComponent, but JList is.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: RALLY: Determine a parent User Story's release In Rally we have the following story structure:
Parent Story 1
|__ Sub Story 1
| |__ Child Story 1
| |__ Child Story 2
|
|__ Sub Story 2
|__ Child Story 3
|__ Sub Story 3
|_ Child Story 4
I want to make a view of all Parent stories and what release they are currently scheduled in. Once the Parent story has child stories it's release value is not editable because it is set in a lower story. Is there a way to determine what release the story would be completed in with only making 1 call to Rally?
Thanks!
A: If you wanted to get a list of a parent story's children to see what release they fall in
you could use the following query.
(Parent.Parent.FormattedID = ###PUT THE FORMATTED ID HERE###)
If you want to experiment in your browser you can try the following URL.
https://rally1.rallydev.com/slm/webservice/1.26/hierarchicalrequirement.js?query=(Parent.Parent.FormattedID=###PUT_THE_FORMATTED_ID_HERE###)&fetch=Release&pretty=true
If you knew that the children stories would all be in the same release you could put a &pagesize=1 and look at the release for that single returned story while saving a bit of bandwidth.
One of the weird parts about this query is that you will have to know how deep the stories you want to retrieve are from the parent you are interested in. In the case of your example your hierarchy is two deep so in the query you use the Parent.Parent of the stories I am trying to retrieve.
A: The easiest solution I have found is to do the following:
var epicLevelStories = {
key: 'epics',
type: 'hierarchicalrequirement',
fetch: 'FormattedID,Name,ObjectID,Release'
query: epicQuery,
order: 'FormattedID'
};
var epicLevel2Stories = {
key: 'epiclevel2',
placeholder: '${epics.children?fetch=Name,FormattedID,Parent,Release}'
};
var epicLevel3Stories = {
key: 'epiclevel3',
placeholder: '${epiclevel2.children?fetch=Name,FormattedID,Parent,Release}'
};
var queryArray = [epicLevelStories, epicLevel2Stories, epicLevel3Stories];
rallyDataSource.findAll(queryArray, doStuffWithResults);
Once you get a result set (epiclevel#) that has no entries you know you have reached the bottom of the tree.
I'm guessing if epiclevel3 still has stories then you could build a new query array for the next 3 levels and recursively call the same "doStuffWithResults" method. Just a thought. I haven't tested that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: jquery vs jquery mobile with page transition I'm trying to make a simple page transition effect. I came across this one for jQuery Mobile:
http://labs.gourdisgood.com/hypertransition/
Is it a bad idea to use jQuery Mobile on a regular site? All I really want is this one effect. Any ideas?
A: Not a direct answer, but some thoughts:
*
*The sample page is really designed to clone the default behavior of iOS on a handheld device. It may not be the best UX for a desktop web site.
*The sample page only works in Safari. As such, it's likely using Safari's CSS transitions. That's great if you are targetting iOS, but not so useful for a general web page.
*The page loads jQuery Mobile, though I'm not sure it's using it specifically for the transitions. Again, they are CSS3 transitions and you could certainly handle the adding/removing of classes to trigger the animations via standard jQuery
*Technically speaking, you can certainly use jQuery Mobile on any site. The drawback would be initial load time as you're loading an additional JS file.
A: You could use some of the jQuery UI effects
If you are transitioning to a different page you can pull the content via AJAX and then display it using the effect.
If you already have the content on your page and you are just simulating a page transition then the effect should be all you need.
A: Having attempted to do similar a couple months ago, I'd strongly recommend against it. Using jQuery mobile opens a whole can of worms that you probably don't want to deal with. You should try to find a similar effect for normal jQuery.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Variable TweenLite is not defined. - probably path issue? Im currently getting the following error:
"ReferenceError: Error #1065: Variable TweenLite is not defined."
I might think its because tweenlite isnt imported correctly, so some path issue - but tried a few things, and still the same.
Basically I have my main.fla, where I import a class:
path: main.fla / classes / com / myfolder / contact / ContactForm.as
AS: import classes.com.myfolder.contact.ContactForm;
In this package I try and import the tweenlite librabry with the following:
package classes.com.myfolder.contact
{
import com.greensock.TweenLite;
import com.greensock.easing.Quad;
....
}
path to tweenlite: main.fla / classes / com / greensock
Any ideas ?
A: You have two options.
*
*Set your class path to the include the 'classes' directory.
*Get rid of the classes directory and have the 'com' directory at the same level as main.fla.
I would go with #2 as it's convention to name packages after URLs, plus if someone else uses your code (or you switch computers) you won't have to set the class path all over again.
Your new layout would look like this:
main.fla
com
greensock
myfolder
contact
A: you doing it wrong! :)
if in your main src directory is classes/Class.as.
then it's package name will be: package classes.
for classes/content/Main.as.
you will be having: package classes.content
since TweenLite has a root package com, the root directory of the packages needs to be com in your main src directory:
src
|- classes
|- com
The compiler imports the clases from the main src directory, and the class package needs to be the same as the directory it is in.
if you will not prefer to work like this then you will be needing to change all packages names inside the Tweenlite from package com.greensock to classes.com.greensock. which i think is crazy.... :)
you really need to refigure your project structure.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Best/usual practices for android app directories Is there any sort of consensus on creating/using directories for storing/accessing data for android apps.
For example on windows a new application (say MyApp) would go in the "Program files" directory in a new "MyApp" directory.
I'm writing an app that allows the user to analyse photo and xml files. Is it usual to expect MyApp to just look for those files in Environment.getExternalStorageDirectory(), require the user to move the photos/xmls to Environment.getExternalStorageDirectory()/MyApp or something else? Should you always just provide a file explorer to look anywhere on the device?
I can do any of the above means of accessing but it's better to stick with the user's expectations.
Any pointer to a UI preferred practices would be useful (assuming they're widely followed).
A: To store your pictures (assuming you are using API >= 8), you should use:
getExternalFilesDir(Environment.DIRECTORY_PICTURES);
Check the documentation which contains an example.
If you want to keep your images in a separate folder you can create one named after your package name inside this one.
Otherwise, if you are using API <= 7, use getExternalFilesDir() to obtain the root of the tree from where you should start looking for images.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: xQuery substring problem I now have a full path for a file as a string like:
"/db/Liebherr/Content_Repository/Techpubs/Topics/HyraulicPowerDistribution/Released/TRN_282C_HYD_MOD_1_Drive_Shaft_Rev000.xml"
However, now I need to take out only the folder path, so it will be the above string without the last back slash content like:
"/db/Liebherr/Content_Repository/Techpubs/Topics/HyraulicPowerDistribution/Released/"
But it seems that the substring() function in xQuery only has substring(string,start,len) or substring(string,start), I am trying to figure out a way to specify the last occurence of the backslash, but no luck.
Could experts help? Thanks!
A: Try out the tokenize() function (for splitting a string into its component parts) and then re-assembling it, using everything but the last part.
let $full-path := "/db/Liebherr/Content_Repository/Techpubs/Topics/HyraulicPowerDistribution/Released/TRN_282C_HYD_MOD_1_Drive_Shaft_Rev000.xml",
$segments := tokenize($full-path,"/")[position() ne last()]
return
concat(string-join($segments,'/'),'/')
For more details on these functions, check out their reference pages:
*
*fn:tokenize()
*fn:string-join()
A: fn:replace can do the job with a regular expression:
replace("/db/Liebherr/Content_Repository/Techpubs/Topics/HyraulicPowerDistribution/Released/TRN_282C_HYD_MOD_1_Drive_Shaft_Rev000.xml",
"[^/]+$",
"")
A: The following code tokenizes, removes the last token, replaces it with an empty string, and joins back.
string-join(
(
tokenize(
"/db/Liebherr/Content_Repository/Techpubs/Topics/HyraulicPowerDistribution/Released/TRN_282C_HYD_MOD_1_Drive_Shaft_Rev000.xml",
"/"
)[position() ne last()],
""
),
"/"
)
It seems to return the desired result on try.zorba-xquery.com. Does this help?
A: This can be done even with a single XPath 2.0 (subset of XQuery) expression:
substring($fullPath,
1,
string-length($fullPath) - string-length(tokenize($fullPath, '/')[last()])
)
where $fullPath should be substituted with the actual string, such as:
"/db/Liebherr/Content_Repository/Techpubs/Topics/HyraulicPowerDistribution/Released/TRN_282C_HYD_MOD_1_Drive_Shaft_Rev000.xml"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Elisp internal variable scoping for a minor mode (setq/make-local-variable/let) I've written this little minor mode to get the TAB key to continue indenting after the major mode has performed the initial indent behaviour and/or to force indentation when the major mode thinks no indent is necessary.
It has been pointed out to me that the combination setq and make-local-variable can probably be simplified into a let scope. Given that this needs to work across multiple buffers concurrently, how would one change this to use let instead of make-local-variable?
;;; dwim-tab.el --- minor mode to force indentation when TAB would otherwise stall
; internal tracking variables
(setq dwim-tab-point-before nil)
(setq dwim-tab-point-after nil)
(defun dwim-tab ()
"Indents normally once, then switches to tab-to-tab-stop if invoked again.
Always performs tab-to-tab-stop if the first TAB press does not cause the
point to move."
(interactive)
(setq dwim-tab-point-before (point))
(if (eq dwim-tab-point-before dwim-tab-point-after) ; pressed TAB again
(tab-to-tab-stop)
(indent-for-tab-command))
(if (eq (point) dwim-tab-point-before) ; point didn't move
(tab-to-tab-stop))
(setq dwim-tab-point-after (point)))
(define-minor-mode dwim-tab-mode
"Toggle dwim-tab-mode.
With a non-nil argument, turns on dwim-tab-mode. With a nil argument, turns it
off.
When dwim-tab-mode is enabled, pressing the TAB key once will behave as normal,
but pressing it subsequent times, will continue to indent, using
tab-to-tab-stop.
If dwim-tab determines that the first TAB key press resulted in no movement of
the point, it will indent according to tab-to-tab-stop instead."
:init-value nil
:lighter " DWIM"
:keymap '(("\t" . dwim-tab))
(make-local-variable 'dwim-tab-point-before)
(make-local-variable 'dwim-tab-point-after))
(provide 'dwim-tab)
A: Does this do what you want? Look ma, no variables!
(defun tab-dwim ()
(interactive)
(when (or (eq last-command this-command)
(= (point) (progn
(indent-for-tab-command)
(point))))
(tab-to-tab-stop)))
The last-command check isn't strictly necessary assuming indent-for-tab-command won't magically start indenting again. But it's slightly more CPU efficient.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586331",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: asp.net ListView Sorting using DataBind Sort listview using column headings in the LayoutTemplate
I am able to sort a basic list view using asp:SqlDataSource and setting the list view property DataSourceID by pointing it to the asp:SqlDataSource ID. I am having an issue when sorting when not using the asp:SqlDataSource and just DataBinding from the code behind.
SqlDataSource Example:
<asp:ListView ID="ContactsListView" DataSourceID="ContactsDataSource" runat="server">
<LayoutTemplate>
<table width="640px" runat="server">
<tr class="header" align="center" runat="server">
<td>
<asp:LinkButton runat="server" ID="SortByFirstNameButton" CommandName="Sort" Text="First Name" CommandArgument="FirstName" />
</LayoutTemplate>
....
</asp:ListView>
<asp:SqlDataSource ID="ContactsDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:MainConnString %>"
SelectCommand="SELECT * FROM TableName">
</asp:SqlDataSource>
DataBind Example:
<asp:ListView ID="ContactsListView" DataSourceID="ContactsDataSource" runat="server">
<LayoutTemplate>
<table width="640px" runat="server">
<tr class="header" align="center" runat="server">
<td>
<asp:LinkButton runat="server" ID="SortByFirstNameButton" CommandName="Sort" Text="First Name" CommandArgument="FirstName" />
</LayoutTemplate>
....
</asp:ListView>
protected void Page_Load(object sender, EventArgs e)
{
String SQL = "SELECT * FROM Customer";
SqlDataAdapter da= new SqlDataAdapter(SQL, ConnStr);
DataSet ds = new DataSet();
da.Fill(ds);
ContactsListView.DataSource = ds.Tables[0];
ContactsListView.DataBind();
}
Both code samples populate the list view, but the second example data binding does not work for sorting. With the first example, the sorting just works with the added asp:LinkButton in the LayoutTemplate adding the CommandName="sort" and setting the CommandArugment="ColumnName", but it does not work with the second example.
Can anyone please explain why and how to get the sorting working using the code behind DataBind method?
Thanks!
A: I solved my issue.
I added an event to handle the sorting. The event grabs the command name (Data column) and passes it and the sorting direction into a function which will make another call to the database sort the returned results and rebind to the List View.
I had to create a view state to hold the List View Sort Direction because for some reason, the onsorting event handler kept saying that the sort direction was ascending.
Front End
<asp:ListView ID="ContactsListView" OnSorting="ContactsListView_Sorting" runat="server">
<LayoutTemplate>
<table width="640px" runat="server">
<tr class="header" align="center" runat="server">
<td>
<asp:LinkButton runat="server" ID="SortByFirstNameButton" CommandName="Sort" Text="First Name" CommandArgument="FirstName" />
</LayoutTemplate>
....
</asp:ListView>
Back End
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindContacts(string.Empty);
}
}
protected SortDirection ListViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection)ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
protected void ContactsListView_Sorting(Object sender, ListViewSortEventArgs e)
{
BindContacts(e.SortExpression + " " + ListViewSortDirection.ToString());
// Check the sort direction to set the image URL accordingly.
string imgUrl;
if (ListViewSortDirection == SortDirection.Ascending)
ListViewSortDirection = SortDirection.Descending;
else
ListViewSortDirection = SortDirection.Ascending;
}
private void BindContacts(string sortExpression)
{
sortExpression = sortExpression.Replace("Ascending", "ASC");
sortExpression = sortExpression.Replace("Descending", "DESC");
using (SqlConnection conn = new SqlConnection(_connStr))
{
conn.Open();
using (SqlDataAdapter dAd = new SqlDataAdapter("SELECT * FROM Customer", conn))
{
DataTable dTable = new DataTable();
dAd.Fill(dTable);
// Sort now
dTable.DefaultView.Sort = sortExpression;
// Bind data now
ContactsListView.DataSource = dTable;
ContactsListView.DataBind();
}
conn.Close();
}
}
A: I guess you could try to add a handler for ListView's Sorting event. There you are given the sorting column and the sort order in the event arguments. This could be easily usable to build a specific query and bind it to the list.
A: Because depending on the sort expression (which you defined in your markup) SqlDataSource will very likely do something like this (I'm not sure this is exactly what it does) for you behind the scenes:
Expression<Func<DataRow,object>> myExpression = row => row["SortExpressionYouDefinedForTheColumn"];
IEnumerable<DataRow> ex = ds.Tables[0].AsEnumerable().OrderBy(myExpression.Compile());
Or SqlDataSource may be using a DataView to sort the DataTable.
SqlDataSource can do this because by default it uses a DataSet to store the result set (or so says the documentation):
The data retrieval mode identifies how a SqlDataSource control retrieves data from the underlying database.
When the DataSourceMode property is set to the DataSet value, data is
loaded into a DataSet object and stored in memory on the server. This
enables scenarios where user interface controls, such as GridView,
offer sorting, filtering, and paging capabilities..
Since you chose to bind manually to a DataSet, you need to do the "magic" yourself; in other words, you handle the OnSort command, get the sort expression, get your data source again (however you do it, from Session or by calling the database again) and do your sort similarly to the lines shown above and rebind to your Gridview.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: PHP chmod and file_get_content permission problem In PHP, I'm grabbing remote images with:
$img = file_get_contents("http://example.com/image.jpg");
file_put_contents("../testdir/photo.jpg",$img);
I get a Permission Denied error unless testdir is set to chmod 0777. Which, I tried to do with PHP and then set it back to 0755:
chmod("../testdir/", 0777);
$img = file_get_contents("http://example.com/image.jpg");
file_put_contents("../testdir/photo.jpg",$img);
chmod("../testdir/", 0755);
but I got Operation Not Permitted Is there a safe, working alternative?
Thanks!
A: Change the owner of the directory to be the user which PHP will be running as (typically the same user the web server process - Apache, lighttpd, nginx, whatever - is running as). Then you won't get permission errors.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: NoMethodError 'exitstatus' while using Paperclip with Ruby on Rails I'm trying to use paperclip to handle file uploads in my Rails app. I'm currently running Paperclip 2.4.1 on Rails 3.0.9, running a WEBrick server on sqlite3.
The form worked fine before adding the file upload portion, but after following the quickstart instructions in the Paperclips docs (http://rdoc.info/gems/paperclip/2.4.1/file/README.md), upon form submission I get the following error:
undefined method `exitstatus' for nil:NilClass
at app/controllers/shows_controller.rb:62:in `create'
Here's the code for my model:
class Show < ActiveRecord::Base
has_many :pictures
has_attached_file :thumb,
:styles => { :thumb => "150x150>" },
:url => "/images/:id/thumb.:extension"
validates_attachment_presence :thumb
validates_presence_of :title
validates_presence_of :start_date
validates_presence_of :end_date
validates_presence_of :description
validates_presence_of :blurb
validates_presence_of :location
def self.current
where("shows.end_date > ?", Time.new).first
end
def self.thumb
image_tag self.thumb.url(:thumb)
end
end
The create method for my controller:
def create
@show = Show.create(params[:show])
respond_to do |format|
if @show.save
format.html { redirect_to(@show, :notice => 'Show was successfully created.') }
format.xml { render :xml => @show, :status => :created, :location => @show }
else
format.html { render :action => "new" }
format.xml { render :xml => @show.errors, :status => :unprocessable_entity }
end
end
(Line 62 is the @show = Show.create(params[:show] line))
My form:
<%= form_for @show, :html => {:multipart => true} do |f| %>
<% if @show.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@show.errors.count, "error") %> prohibited this show from being saved:</h2>
<ul>
<% @show.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.label :start_date %><br />
<%= f.date_select :start_date %>
</div>
<div class="field">
<%= f.label :end_date %><br />
<%= f.date_select :end_date %>
</div>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :blurb %><br />
<%= f.text_field :blurb %>
</div>
<div class="field">
<%= f.label :location %><br />
<%= f.text_field :location %>
</div>
<div class="field">
<%= f.label :thumb %><br />
<%= f.file_field :thumb %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And the full stack trace:
activesupport (3.0.9) lib/active_support/whiny_nil.rb:48:in `method_missing'
cocaine (0.2.0) lib/cocaine/command_line.rb:35:in `run'
paperclip (2.4.2) lib/paperclip.rb:102:in `run'
paperclip (2.4.2) lib/paperclip/geometry.rb:20:in `from_file'
paperclip (2.4.2) lib/paperclip/thumbnail.rb:35:in `initialize'
paperclip (2.4.2) lib/paperclip/processor.rb:33:in `new'
paperclip (2.4.2) lib/paperclip/processor.rb:33:in `make'
paperclip (2.4.2) lib/paperclip/attachment.rb:397:in `post_process_styles'
activemodel (3.0.9) lib/active_model/attribute_methods.rb:295:in `inject'
paperclip (2.4.2) lib/paperclip/attachment.rb:396:in `each'
paperclip (2.4.2) lib/paperclip/attachment.rb:396:in `inject'
paperclip (2.4.2) lib/paperclip/attachment.rb:396:in `post_process_styles'
activesupport (3.0.9) lib/active_support/ordered_hash.rb:139:in `each'
activesupport (3.0.9) lib/active_support/ordered_hash.rb:139:in `each'
paperclip (2.4.2) lib/paperclip/attachment.rb:392:in `post_process_styles'
paperclip (2.4.2) lib/paperclip/attachment.rb:386:in `post_process'
activesupport (3.0.9) lib/active_support/callbacks.rb:414:in `_run_thumb_post_process_callbacks'
activesupport (3.0.9) lib/active_support/callbacks.rb:94:in `send'
activesupport (3.0.9) lib/active_support/callbacks.rb:94:in `run_callbacks'
paperclip (2.4.2) lib/paperclip/callback_compatibility.rb:54:in `run_paperclip_callbacks'
paperclip (2.4.2) lib/paperclip/attachment.rb:385:in `post_process'
activesupport (3.0.9) lib/active_support/callbacks.rb:414:in `_run_post_process_callbacks'
activesupport (3.0.9) lib/active_support/callbacks.rb:94:in `send'
activesupport (3.0.9) lib/active_support/callbacks.rb:94:in `run_callbacks'
paperclip (2.4.2) lib/paperclip/callback_compatibility.rb:54:in `run_paperclip_callbacks'
paperclip (2.4.2) lib/paperclip/attachment.rb:384:in `post_process'
paperclip (2.4.2) lib/paperclip/attachment.rb:142:in `assign'
paperclip (2.4.2) lib/paperclip.rb:335:in `thumb='
activerecord (3.0.9) lib/active_record/base.rb:1564:in `send'
activerecord (3.0.9) lib/active_record/base.rb:1564:in `attributes='
activerecord (3.0.9) lib/active_record/base.rb:1560:in `each'
activerecord (3.0.9) lib/active_record/base.rb:1560:in `attributes='
activerecord (3.0.9) lib/active_record/base.rb:1412:in `initialize'
activerecord (3.0.9) lib/active_record/base.rb:502:in `new'
activerecord (3.0.9) lib/active_record/base.rb:502:in `create'
app/controllers/shows_controller.rb:62:in `create'
actionpack (3.0.9) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.0.9) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.0.9) lib/abstract_controller/base.rb:150:in `process_action'
actionpack (3.0.9) lib/action_controller/metal/rendering.rb:11:in `process_action'
actionpack (3.0.9) lib/abstract_controller/callbacks.rb:18:in `process_action'
activesupport (3.0.9) lib/active_support/callbacks.rb:441:in `_run__918721632__process_action__524098549__callbacks'
activesupport (3.0.9) lib/active_support/callbacks.rb:410:in `send'
activesupport (3.0.9) lib/active_support/callbacks.rb:410:in `_run_process_action_callbacks'
activesupport (3.0.9) lib/active_support/callbacks.rb:94:in `send'
activesupport (3.0.9) lib/active_support/callbacks.rb:94:in `run_callbacks'
actionpack (3.0.9) lib/abstract_controller/callbacks.rb:17:in `process_action'
actionpack (3.0.9) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
activesupport (3.0.9) lib/active_support/notifications.rb:52:in `instrument'
activesupport (3.0.9) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activesupport (3.0.9) lib/active_support/notifications.rb:52:in `instrument'
actionpack (3.0.9) lib/action_controller/metal/instrumentation.rb:29:in `process_action'
actionpack (3.0.9) lib/action_controller/metal/rescue.rb:17:in `process_action'
actionpack (3.0.9) lib/abstract_controller/base.rb:119:in `process'
actionpack (3.0.9) lib/abstract_controller/rendering.rb:41:in `process'
actionpack (3.0.9) lib/action_controller/metal.rb:138:in `dispatch'
actionpack (3.0.9) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
actionpack (3.0.9) lib/action_controller/metal.rb:178:in `action'
actionpack (3.0.9) lib/action_dispatch/routing/route_set.rb:62:in `call'
actionpack (3.0.9) lib/action_dispatch/routing/route_set.rb:62:in `dispatch'
actionpack (3.0.9) lib/action_dispatch/routing/route_set.rb:27:in `call'
rack-mount (0.6.14) lib/rack/mount/route_set.rb:148:in `call'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:93:in `recognize'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:68:in `optimized_each'
rack-mount (0.6.14) lib/rack/mount/code_generation.rb:92:in `recognize'
rack-mount (0.6.14) lib/rack/mount/route_set.rb:139:in `call'
actionpack (3.0.9) lib/action_dispatch/routing/route_set.rb:493:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/head.rb:14:in `call'
rack (1.2.3) lib/rack/methodoverride.rb:24:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/flash.rb:182:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/session/abstract_store.rb:149:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/cookies.rb:302:in `call'
activerecord (3.0.9) lib/active_record/query_cache.rb:32:in `call'
activerecord (3.0.9) lib/active_record/connection_adapters/abstract/query_cache.rb:28:in `cache'
activerecord (3.0.9) lib/active_record/query_cache.rb:12:in `cache'
activerecord (3.0.9) lib/active_record/query_cache.rb:31:in `call'
activerecord (3.0.9) lib/active_record/connection_adapters/abstract/connection_pool.rb:354:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/callbacks.rb:46:in `call'
activesupport (3.0.9) lib/active_support/callbacks.rb:416:in `_run_call_callbacks'
actionpack (3.0.9) lib/action_dispatch/middleware/callbacks.rb:44:in `call'
rack (1.2.3) lib/rack/sendfile.rb:107:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/remote_ip.rb:48:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/show_exceptions.rb:47:in `call'
railties (3.0.9) lib/rails/rack/logger.rb:13:in `call'
rack (1.2.3) lib/rack/runtime.rb:17:in `call'
activesupport (3.0.9) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.2.3) lib/rack/lock.rb:11:in `call'
rack (1.2.3) lib/rack/lock.rb:11:in `synchronize'
rack (1.2.3) lib/rack/lock.rb:11:in `call'
actionpack (3.0.9) lib/action_dispatch/middleware/static.rb:30:in `call'
railties (3.0.9) lib/rails/application.rb:168:in `call'
railties (3.0.9) lib/rails/application.rb:77:in `send'
railties (3.0.9) lib/rails/application.rb:77:in `method_missing'
railties (3.0.9) lib/rails/rack/log_tailer.rb:14:in `call'
rack (1.2.3) lib/rack/content_length.rb:13:in `call'
rack (1.2.3) lib/rack/handler/webrick.rb:52:in `service'
C:/Rails/Ruby1.8.7/lib/ruby/1.8/webrick/httpserver.rb:104:in `service'
C:/Rails/Ruby1.8.7/lib/ruby/1.8/webrick/httpserver.rb:65:in `run'
C:/Rails/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:173:in `start_thread'
C:/Rails/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:162:in `start'
C:/Rails/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:162:in `start_thread'
C:/Rails/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:95:in `start'
C:/Rails/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:92:in `each'
C:/Rails/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:92:in `start'
C:/Rails/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:23:in `start'
C:/Rails/Ruby1.8.7/lib/ruby/1.8/webrick/server.rb:82:in `start'
rack (1.2.3) lib/rack/handler/webrick.rb:13:in `run'
rack (1.2.3) lib/rack/server.rb:217:in `start'
railties (3.0.9) lib/rails/commands/server.rb:65:in `start'
railties (3.0.9) lib/rails/commands.rb:30
railties (3.0.9) lib/rails/commands.rb:27:in `tap'
railties (3.0.9) lib/rails/commands.rb:27
script/rails:6:in `require'
script/rails:6
I wasn't able to find any instance of this error elsewhere relating to paperclip; It looks like its bubbling up from within Rails somewhere; any suggestions?
A: It seems that the command, that is run with cocaine is not correct. Have you configured paperclip's command path with Paperclip.options[:command_path] = "/usr/local/bin/" and installed ImageMagick in this path?
You can find out where ImageMagick is with which convert. This should yield the path to the convert binary of ImageMagick - in my case /usr/local/bin/convert
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to bind TextBox to datasource I want to bind a textbox to a data source so that I can implement IDataErrorInfo.
How would I achieve the functionality that essentially does what
TextBoxClientRenewalDate.DataSource = contract.RenewalDate;
would do, if it existed.
A: I'm not really sure what you're looking for, but usually you would just assign the value to the Text property, like this:
TextBox1.Text = MyDataTable.Rows[0].Field<string>("SomeColumn");
I suppose you could use the DataBinder object too:
//not positive here, but it should be close
TextBox1.Text = (string)DataBinder.Eval(MyDataTable, "SomeColumn");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Changing windows 7 system language and word 2010 language using a batch file I am hoping to be able to use a simple batch file to be able to swap between english and arabic.
The idea is to modify the options in the "region and language" format from english to arabic and vice versa.
I was hoping to be able to do the same thing with office 2010 within the language tab.
I am not entirely sure if this is possible with batch files :P
The above is what I need to do everytime I want to write in arabic on the computer (majoring in arabic and islamic studies) if you have any other solutions I would be more then happy to hear them :)
Thanks :)
A: Best way I found was to use the language toolbar and avoid batch files all together :P
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586349",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I Click on a Flash object with jQuery? I have something like this:
<object id="myflash"></object>
I've tried making jQuery click the object like so:
$('#myflash').click();
But this doesn't work. Is there another way to do this?
A: Do you want to focus it, or actually click on a certain point?
You can probably use .focus() instead of .click() to focus the flash object. If you need to click on a certain spot, you should create a method in ActionScript that does what you want the click to do, and then call it. Your ActionScript will look something like this:
import flash.external.ExternalInterface;
ExternalInterface.addCallback("sendTextToFlash", getTextFromJavaScript);
function getTextFromJavaScript(str):void {
trace(str);
}
You then call the method with the name set in the addCallback call directly on the object:
flashObject.sendTextToFlash('My string');
See this page for more info and a method that will get the object or embed so that it works correctly in all browsers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586350",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C++ insert numbers until certain symbol I tried to write a code that asked me to input numbers one by one and when a certain char was inserted ( in this case 'x' ) it would stop the loop. But when I insert that char it starts spamming me with "Insert Number" . I think that the fault is that I'm trying to insert a char in an int array, but I can't think a way around it.
long int numbers[100]={0};
char h='y';
int index=0;
do
{
cout << "Insert Number : ";
cin >> numbers[index];
h=(char)numbers[index];
index++;
}
while(h!='x');
A: This happens because 'x' is not a number and cin >> numbers[index]; operation fails, without consuming that data. So the loop continues, gets the same x, fails again and everything starts all over again. You can check for result of input operation, something like this:
#include <iostream>
using namespace std;
int main ()
{
long int numbers[100]={0};
char h='y';
int index=0;
do
{
cout << "Insert Number : ";
if (cin >> numbers[index])
{
h=(char)numbers[index];
index++;
}
else
{
cout << "Hey, that was not a number! Bye." << endl;
break;
}
}
while(h!='x');
}
A: You should write a loop as:
while(cin >> numbers[index])
index++;
It will read all the integers, untill you enter some invalid input, be it 'x' or any other character. Now if you want to skip all invalid inputs and continue reading integers (which might be after invalid inputs), and want to consider only 'x' to exit from the loop, then wrap the above loop with another loop as:
char ch;
do
{
while(cin >> numbers[index])
index++;
cin.clear(); //clear the error flags, so you can use cin to continue reading
cin >> ch; //read the invalid character
} while(ch != 'x');
One piece of advice: prefer using std::vector<long int> over long int numbers[100]. What if user entered more than 100 integers, then your program will be corrupted.
A: Because you're trying to read in an integer, any character that isn't a digit can't be converted to a number and will jam up the input - you'll get an error and the bad character will not be removed from the stream. The next time you try to read you'll get the same error.
A: If you expect a number or a string, always read the input as a string, and try converting it to a number afterwards if the string isn't "x":
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
int main(int argc, char *argv[])
{
std::vector<long int> numbers;
std::string line;
while(std::getline(std::cin, line) && line != "x") {
std::istringstream input(line);
long int value;
// Check that there is only a number with nothing else after
if((input >> value) && input.get() == std::char_traits<char>::eof()) {
numbers.push_back(value);
} else {
std::cout << "Invalid Entry, please retry" << std::endl;
}
}
//...
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586354",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Confused about which Apache SVN package to use with windows i want to make svn repo on a windows machine, but when i tried to download the Apache SVN
i found lots of packages here:
http://subversion.apache.org/packages.html#windows
but i am confused which package to use
what do you guys suggest ?
A: *
*WANdisco Windows Subversion Client 1.6.17 - if you want only local or svn:// served repo and can live with console command
*VisualSVN Server - if you want Apache-served repos with easy installer and GUI-management in Server Management Console - free Standard Edition is good if you haven't to manage a lot of remote VisualSVN servers
A: If you can pay for it, go for visual SVN server (the basic edition is free though)
if you want a free one, take silkSVN or win32svn.
I used win32svn and it works like a charm. I had set up project SVN server on a windows 2003 server.
This link helped me:
http://www.inetsolution.com/turnleft/post/How-to-Setup-Subversion-2b-Apache-2b-WebSVN-on-Windows.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SEO of Pagination using rel="next" rel="prev" HTTP Headers I am trying to perform some SEO on a pagination control I have on a website.
Following the Google guidelines, I would like to add link rel=next/prev i.e. <link href="/search/results?page=2" rel="next" /> to the <head> of my search results page.
Unfortunatley, due to a design decision / limitation of MVC3 with rendering sections and defining their content within Partials, I'm unable to do this.
So my question is - can I replicate the aforementioned functionality by adding a "Link" HTTP header, i.e. Link: <http://www.example.com/search/results?page=2>; rel="next" to the response and therefore not have to add the <link> tags in the <head>?
A: This was answered by Maile Ohye.
@estrik: We support rel=”next” and rel=”prev” in the HTTP header. For example, for page=2 of an article, you could respond with the HTTP header:
Link: http://www.example.com/article?story=abc&page=1; rel="prev"
Link: http://www.example.com/article?story=abc&page=3; rel="next"
A: Referring to this post from a Google employee rel=prev/next in the HTTP header is supported by Google
A: At the moment, I'm pretty sure they aren't supporting that, as they aren't support having the rel attribute on the anchor either.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586361",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: clear part of UIImage I've been doing some research on online for a project I'm doing but so far haven't been able to quite get it working. I want to be able to slide my finger over a UIImage and delete part of it, kind of like an eraser. I'm able to draw lines on the screen but can't figure out how to do this. Any help would be greatly appreciated.
A: Can you mask the image and when you draw on it, it adds the lines to the mask (in white, rest of mask is black) and then it should make those spots transparent
http://iosdevelopertips.com/cocoa/how-to-mask-an-image.html
A: There are two parts to this problem-
a) Determining the curve along which the finger was moved
b) Drawing the curve (which is really a combination of short lines) with the white color
For part (a), have a look at UIPanGestureRecognizer. Using the touchesBegan: & touchesMoved methods, you will be notified every time the finger moves even the smallest distance, and the source and destination co-ordinates, say (x1, y1) & (x2, y2).
Part (b), As you know how to draw a line, now you need to draw a line from the source to the destination with the line's width (thickness) equal to the finger's. For that you can set the line's width using CGContextSetLineWidth.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I supress dialogs from an exe that is executed using System.Diagnostic.Process? I'm using a System.Diagnostic.Process to call another .exe. I'm creating an application which purpose is to run on a remote server. This .exe sometimes crashes and there's a message popup stopping the whole process -> [Application Name] has encountered a problem and is forced to close. I'm trying to find a way to make my c# program ignore this popup and continue executing.
A: Is fixing the error with the .exe being called not an option?
A: In that case when your process does not work properly you will see a popup thats windows default but if you want to know that process ran successfully or not then this code will work for you
Subscribe to the Process.Exited event and then check Process.ExitCode:
public void StartProcess()
{
p.StartInfo.FileName = BasePath;
p.StartInfo.Arguments = args;
p.Start();
p.Exited += new EventHandler(Process_Exited);
}
void Process_Exited(object sender, EventArgs e)
{
var p = sender as Process;
if (p.ExitCode != 0)
MessageBox.Show(string.Format("Process failed: ExitCode = {0}", p.ExitCode));
}
A: IMHO the cleanest option to run such a buggy exe is to start it giving to your process debug privileges over it (you probably have to call explicitly CreateProcess via P/Invoke with the DEBUG_PROCESS flag in the process creation flags) and then have a thread process the debug events provided by WaitForDebugEvent; whenever you get an unhandled, last-chance exception you can notify the main thread, kill the child process (thus avoiding the default Windows exception handler) and restart it if necessary, in all other cases just call ContinueDebugEvent to let the program run normally.
Notice that the pointer to the "event structure" provided by WaitForDebugEvent could be tricky to work with in C#.
edit: fortunately it seems that someone made a nice managed wrapper for the native debugging API, see here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: converted date time in json i have a model,with jason send and fill this model but
when return a filled model by data and get it in view date time converted to :"/Date(1241465400000)/"
[Serializable]
public class MyModel
{
public int Id {get;set;}
public DateTime date {get;set;}
}
[HttpPost]
public ActionResult SchedulesDropdownIndexChanged(MyModel schedule)
{
objScheduleModel = new ScheduleModel();
objScheduleModel = schedule;
......fill model here date time is ok-----------
objScheduleModel.date=Datetime.Now;
return Json(objScheduleModel);
}
here is a dropdownlist when selected index chaned fired this function
$(function () {
$("select#SchedulesDropdown").change(function (evt) {
var ScheduleModel = getScheduleDateTime();
var json = $.toJSON(ScheduleModel);
var abc;
$.ajax({
url: "/Members/DropdownIndexChanged",
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (msg) {
var o = msg.date;---------------unformated date time--------------->>> "/Date(1241465400000)/"
}
});
});
});
function getScheduleDateTime() {
var Id = $("select#SchedulesDropdown").val();
var to = $("#dateTo").val();
return (Id == "") ? null : { Id: Id, date: to };
}
A: jQuery extension to auto convert dates
This blog post might help. It's an extension that auto converts ISO as well as Asp.net dates.
I also suggest if you use this code to make the optional parameter to disable auto conversion so by default it simply converts dates. In your case (because you're not explicitly calling parseJSON) this will just convert it. And 99.9% of the time you do want auto conversion all the time.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Graphviz subgraph doesn't get visualized I'm trying to create a graph with two subgraphs in dot. The code is as follows:
digraph G {
subgraph step1 {
style=filled;
node [label="Compiler"] step1_Compiler;
node [label="Maschine"] step1_Maschine;
color=lightgrey;
}
subgraph step2 {
style=filled;
color=lightgrey;
node [label="Interpretierer"] step2_Interpretierer;
node [label="Maschine"] step2_Maschine;
label="Virtuelle Maschine";
}
"Programm (Java)" -> step1_Compiler;
step1_Compiler -> step1_Maschine;
step1_Maschine -> "Bytecode";
"Bytecode" -> step2_Interpretierer;
step2_Interpretierer -> step2_Maschine;
step2_Maschine -> "Ergebnis";
}
The result I am getting looks like the following:
I expected to see a box around both subgraphs. What am I missing here?
A: You'll have to prefix the name of your subgraphs with cluster:
subgraph clusterstep1 {
and
subgraph clusterstep2 {
in order to get the style and label.
From the graphiz documentation, section "Subgraphs and Clusters":
The third role for subgraphs directly involves how the graph will be
laid out by certain layout engines. If the name of the subgraph begins
with cluster, Graphviz notes the subgraph as a special cluster
subgraph. If supported, the layout engine will do the layout so that
the nodes belonging to the cluster are drawn together, with the entire
drawing of the cluster contained within a bounding rectangle. Note
that, for good and bad, cluster subgraphs are not part of the DOT
language, but solely a syntactic convention adhered to by certain of
the layout engines.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "78"
}
|
Q: Set autoplay on jQuery Tabs Slideshow I've just installed the jQuery Tabs slideshow plugin and would like it to autoplay. However, when I put in the autoplay option, it performs very unevenly, not at all like when the play button is pressed manually.
<script language="JavaScript">
$(function() {
$(".slidetabs").tabs(".images > div", {
// enable "cross-fading" effect
effect: 'fade',
fadeOutSpeed: "slow",
// start from the beginning after the last tab
rotate: true
// use the slideshow plugin. It accepts its own configuration
}).slideshow({autoplay:true});
});
</script>
Have I put the autoplay code in correctly? Here is the documentation. http://flowplayer.org/tools/tabs/slideshow.html Thanks!
A: Here is how mine looked
$(document).ready(function () { //this is jQuery's "on Load" event
$("#featured > ul").tabs({ fx: { opacity: 'toggle'} }).tabs("rotate", 5000, true);
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cannot get scroll bar to work PyGTK treeview First let me start off by saying I read on here a lot and I have googled around for the answer but have not been able to turn one up.
Basically I am trying to add a scroll bar to add to my vbox window. I know its simply something I am not understanding. Here is the code (please ignore the mysql statements, I haven't gotten around to cleaning them up yet
#!/usr/bin/python
import pygtk
pygtk.require('2.0')
import gtk
import os
import sys
import MySQLdb
from Tkinter import *
database_connection = MySQLdb.connect('localhost', 'root', '', 'nmap');
cursor = database_connection.cursor()
class Table_GUI:
cells = {}
columns = {}
sort_order = gtk.SORT_ASCENDING
def delete_event(self, widget, event, data=None):
return False
def destroy(self, widget, data=None):
gtk.main_quit()
def __init__(self):
# create a new window
self.window = gtk.Window(gtk.WINDOW_TOPLEVEL)
self.window.set_geometry_hints(min_width=400, min_height=200)
self.window.connect("delete_event", self.delete_event)
self.window.connect("destroy", self.destroy)
self.vbox = gtk.VBox(False, 0)
self.window.add(self.vbox)
self.vbox.show()
self.vbox.pack_start(self.scrolledwindow)
self.frm_table = gtk.Frame()
self.frm_table.set_shadow_type(gtk.SHADOW_NONE)
self.frm_table.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#fff'))
self.show_Table(oper_sys, ip_get)
self.frm_table.show()
self.vbox.pack_start(self.frm_table, True, True, 0)
self.window.show()
def show_Table(self, search_os, search_ip):
### Create the table
# List of items to display which represent IP, OS, DNS, Port number and Port description
self.liststore = gtk.ListStore(str, str, str, str, str)
if search_os != "" and search_ip !="":
#Set up the queries. If the user has activted the checkbox, we need to include the ports in the query
if ports_check == 1:
pass
#Otherwise just return the relevent data
else:
pass
elif search_os != "" and search_ip == "":
if ports_check == 1:
pass
else:
pass
elif search_os =="" and search_ip != "":
if ports_check == 1:
pass
else:
pass
#get the results and prepare to put them inside of lists
fetch_results = cursor.fetchall()
host_name_list = []
operating_list = []
ip_list = []
ports = []
#The element chosen to append to each list based on the order of retrieval in the mysql query
for individual_result in fetch_results:
ip_list.append(individual_result[0])
operating_list.append(individual_result[1])
host_name_list.append(individual_result[2])
if ports_check == 1:
ports.append(individual_result[3])
#we are going to add blanks to the files in order to help readability
#when putting this into the chart
cleaned_host =[]
cleaned_ip = []
cleaned_os_list = []
index_counter = 0
#this loop will check to see if the entry already exists in the cleaned variables. If it does, it 'omitts' them by inserting a blank line
while index_counter < len(host_name_list):
if host_name_list[index_counter] in cleaned_host:
#print "found a duplicate in HOST....OMITTING"
cleaned_host.append("")
else:
#print "adding ", host_name_list[index_counter]
cleaned_host.append(host_name_list[index_counter])
if operating_list[index_counter] in cleaned_os_list and ip_list[index_counter] in cleaned_ip:
#print "found a duplicate in OPERATING....OMITTING"
cleaned_os_list.append("")
else:
#print "adding ", operating_list[index_counter]
cleaned_os_list.append(operating_list[index_counter])
if ip_list[index_counter] in cleaned_ip:
#print "Found a duplicate in IP.... OMITTING "
cleaned_ip.append("")
else:
#print "adding ", ip_list[index_counter]
cleaned_ip.append(ip_list[index_counter])
index_counter +=1
#this section appends to the list store depending on whether the user wants to see the ports or not
counter = 0
for single_result in fetch_results:
if ports_check == 1:
self.liststore.append(
[ cleaned_ip[counter], cleaned_os_list[counter], cleaned_host[counter], single_result[4], single_result[3] ]
)
else:
self.liststore.append(
[ single_result[0], single_result[1], single_result[2], "" , "" ]
)
counter +=1
# Treeview
self.treeview = gtk.TreeView()
self.treeview.set_property("fixed-height-mode", False)
#For some reason I can't get the scrolled window to work...
self.scrolledwindow = gtk.ScrolledWindow()
self.scrolledwindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
# Columns
self.newColumn("IP Address", 0)
self.newColumn("Operating System", 1)
self.newColumn("Hostname",2)
if ports_check == 1:
self.newColumn("Ports", 3)
self.newColumn("Protocol name", 4)
self.treeview.set_model(self.liststore)
self.treeview.set_headers_clickable(True)
self.frm_table.add(self.treeview)
self.treeview.show()
#this function allows for the sorting of the columns
#Given the way this works with the ports_check == 1, this will confuse the output
def on_column_clicked(self, tc, user_data):
self.liststore.set_sort_column_id(user_data, self.sort_order)
if self.sort_order == gtk.SORT_ASCENDING:
self.sort_order = gtk.SORT_DESCENDING
else:
self.sort_order = gtk.SORT_ASCENDING
tc.set_sort_order(self.sort_order)
def newColumn(self, title, index):
self.cells[index] = gtk.CellRendererText()
self.cells[index].set_property('cell-background-gdk', gtk.gdk.color_parse("#FFF"))
self.columns[index] = gtk.TreeViewColumn(title, self.cells[index], text=index)
self.columns[index].set_resizable(True)
self.columns[index].set_reorderable(True)
self.columns[index].set_sort_indicator(True)
if(index == 0) :
self.columns[index].set_min_width(130)
if (index == 1) :
self.columns[index].set_min_width(300)
if (index == 2) :
self.columns[index].set_min_width(200)
self.columns[index].connect("clicked", self.on_column_clicked, index)
self.treeview.insert_column(self.columns[index], -1)
# The main function
def main(self):
gtk.main()
class createUI:
def pushButton(self, parent):
global ports_check, oper_sys, ip_get
ports_check = display_ports.get()
oper_sys = OS.get()
ip_get = IP.get()
gui = Table_GUI()
gui.main()
def __init__(self, parent):
#export variables from this class so they are available in other classes
global OS, IP, counter, display_ports
self.panel1 = Frame(parent.title("main window"))
self.panel1.pack()
self.frame1 = Frame(self.panel1)
#in the first frame, create the directions and the input boxes
self.OS_label = Message(self.frame1, text="Search by operating system", justify=LEFT, width=180).pack(pady=2)
OS = Entry(self.frame1)
OS.pack()
OS.focus_set()
self.IP_label = Message(self.frame1, text="Search by IP", justify=LEFT, width=180).pack(pady=3)
IP = Entry(self.frame1)
IP.pack(pady=14, padx=60)
self.frame1.pack()
self.frame5 = Frame(self.panel1)
#set the variables used by the checkboxes to an IntVar so that they can be evaluated as off or on
display_ports = IntVar()
ports_checkbutton = Checkbutton(self.frame5, text='Display Ports', onvalue = 1, offvalue = 0, variable=display_ports, width=10)
ports_checkbutton.pack(side=LEFT)
self.frame5.pack()
self.frame6 = Frame(self.panel1)
#lambda was used so that the button does not execute the addToDB class before click. addToDB requires an argument and self.database_button didn't work
self.database_button = Button(self.frame6, text="Get results!")
self.database_button.pack()
self.database_button.configure(command=lambda btn = self.database_button: self.pushButton(btn))
self.quit_button = Button(self.frame6, text="Get me outta here", command=self.panel1.quit).pack()
self.frame6.pack()
if __name__ == "__main__":
root = Tk()
ui = createUI(root)
ui.panel1.mainloop()
You will see the following in there:
# For some reason I can't get the scrolled window to work...
self.scrolledwindow = gtk.ScrolledWindow()
self.scrolledwindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
When I have attempted to attach it via
self.scrolledwindow.add_with_viewport(self.treeview)
I get the message
GtkWarning: Attempting to add a widget with type GtkTreeView to a container of type GtkFrame, but the widget is already inside a container of type GtkViewport
I went to the FAQ page but I really didn't understand what it was telling me.
If I try to set in on self.window I get:
GtkWarning: Can't set a parent on a toplevel widget
self.scrolledwindow.add_with_viewport(self.window)
That one is pretty self explanatory
If I try to add it to vbox I get:
GtkWarning: IA__gtk_scrolled_window_add_with_viewport: assertion `child->parent == NULL' failed[/quote]
I am not looking for a freebie but I am hoping that someone could help to point me in the right direction. (as you can see I am not coming with a "can you make me a program that does X" scenario)
--->New GTK only interface below<----
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygtk
import gtk
import os
import sys
import MySQLdb
database_connection = MySQLdb.connect('localhost', 'root', '', 'nmap');
cursor = database_connection.cursor()
#---------------------------------------------------------------
class Application(gtk.Window):
cells = {}
columns = {}
sort_order = gtk.SORT_ASCENDING
####################
def __init__(self):
gtk.Window.__init__( self )
self.set_title("Netowrk Scanner")
self.create_widgets()
self.connect_signals()
#self.window.show_all()
self.show_all()
gtk.main()
#####################
def create_widgets(self):
#Ask the user to search by operating system
self.vbox = gtk.VBox(spacing=10)
self.operating_system_label_hbox_1 = gtk.HBox(spacing=10)
self.label = gtk.Label("Search by Operating System :")
self.operating_system_label_hbox_1.pack_start(self.label)
#Set a check box so the user can choose to display ports
self.ports_hbox_8 = gtk.HBox(spacing=10)
self.ports_check = gtk.CheckButton("Display Ports")
self.ports_hbox_8.pack_start(self.ports_check)
self.halign_ports = gtk.Alignment(0,1,1,0)
self.halign_ports.add(self.ports_hbox_8)
self.os_entry_hbox_2 = gtk.HBox(spacing=10)
self.OS = gtk.Entry()
self.os_entry_hbox_2.pack_start(self.OS)
self.hostname_label_hbox_3 = gtk.HBox(spacing=10)
self.label = gtk.Label("Search by Hostname:")
self.hostname_label_hbox_3.pack_start(self.label)
self.hostname_entry_hbox_4 = gtk.HBox(spacing=10)
self.HOSTNAME = gtk.Entry()
self.hostname_entry_hbox_4.pack_start(self.HOSTNAME)
self.ip_label_hbox_5 = gtk.HBox(spacing=10)
self.label = gtk.Label("Search by IP:")
self.ip_label_hbox_5.pack_start(self.label)
self.ip_entry_hbox_6 = gtk.HBox(spacing=10)
self.IP = gtk.Entry()
self.ip_entry_hbox_6.pack_start(self.IP)
self.buttons_hbox_7 = gtk.HBox(spacing=10)
self.button_ok = gtk.Button("Get Results!")
self.buttons_hbox_7.pack_start(self.button_ok)
self.button_exit = gtk.Button("Get me Outta Here!")
self.buttons_hbox_7.pack_start(self.button_exit)
#The order in which you pack_start a widget is the order in which it is displayed on the screen
self.vbox.pack_start(self.operating_system_label_hbox_1)
self.vbox.pack_start(self.os_entry_hbox_2)
self.vbox.pack_start(self.hostname_label_hbox_3)
self.vbox.pack_start(self.hostname_entry_hbox_4)
self.vbox.pack_start(self.ip_label_hbox_5)
self.vbox.pack_start(self.ip_entry_hbox_6)
self.vbox.pack_start(self.halign_ports, False, False, 3)
self.vbox.pack_start(self.buttons_hbox_7)
self.add(self.vbox)
##########################
def connect_signals(self):
#Have the buttons start 'listening' for user interaction
self.button_ok.connect("clicked", self.button_click)
self.button_exit.connect("clicked", self.exit_program)
def button_click(self, clicked):
#This function gets the values of the input boxes as well as the check box
#And then passes them to the show_table function so it can get the correct results from the database
global ports_check, os, ip, hostname
os = self.OS.get_text()
ip = self.IP.get_text()
hostname = self.HOSTNAME.get_text()
ports_check = self.ports_check.get_active()
self.frm_table = gtk.Window()
self.frm_table.set_title("Network scan results")
#Change the background to white instead of grey
self.frm_table.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#fff'))
self.frm_table.show()
self.show_Table(os, ip, hostname)
############################
def show_Table(self, search_os, search_ip, search_hostname):
### Create the table
# List of items to display which represent IP, OS, DNS, Port number and Port description
self.liststore = gtk.ListStore(str, str, str, str, str)
#If the user is running a search on the hostname run these queries
if search_hostname != "":
if ports_check == True:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name, Port_Description, Open_Port FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE DNS_Name LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address ), Open_Port" % (search_hostname))
#Otherwise just return the relevent data
else:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE DNS_Name LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address )" % (search_hostname))
#If the user has specified the IP and the OS to search, run this query
if search_os != "" and search_ip !="":
#Set up the queries. If the user has activated the checkbox, we need to include the ports in the query
if ports_check == True:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name, Port_Description, Open_Port FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE OS_Name LIKE '%%%s%%' and Computer_IP_Address LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address ), Open_Port" % (search_os, search_ip))
#Otherwise just return the relevent data
else:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE OS_Name LIKE '%%%s%%' and Computer_IP_Address LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address )" % (search_os, search_ip))
#If the user has specified an OS but not an IP run this
elif search_os != "" and search_ip == "":
if ports_check == True:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name, Port_Description, Open_Port FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE OS_Name LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address ), Open_Port" % search_os)
else:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE OS_Name LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address )" % search_os)
#If the user has specified an IP but not an OS run this
elif search_os =="" and search_ip != "":
if ports_check == True:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name, Port_Description, Open_Port FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE Computer_IP_Address LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address ), Open_Port" % search_ip)
else:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE Computer_IP_Address LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address )" % search_ip)
#get the results and prepare to put them inside of lists
fetch_results = cursor.fetchall()
host_name_list = []
operating_list = []
ip_list = []
ports = []
#The element chosen to append to each list based on the order of retrieval in the mysql query
for individual_result in fetch_results:
ip_list.append(individual_result[0])
operating_list.append(individual_result[1])
host_name_list.append(individual_result[2])
if ports_check == True:
ports.append(individual_result[3])
#we are going to add blanks to the files in order to help readability
#when putting this into the chart
cleaned_host =[]
cleaned_ip = []
cleaned_os_list = []
index_counter = 0
#this loop will check to see if the entry already exists in the cleaned variables. If it does, it 'omitts' them by inserting a blank line
while index_counter < len(host_name_list):
if host_name_list[index_counter] in cleaned_host:
#print "found a duplicate in HOST....OMITTING"
cleaned_host.append("")
else:
#print "adding ", host_name_list[index_counter]
cleaned_host.append(host_name_list[index_counter])
if operating_list[index_counter] in cleaned_os_list and ip_list[index_counter] in cleaned_ip:
#print "found a duplicate in OPERATING....OMITTING"
cleaned_os_list.append("")
else:
#print "adding ", operating_list[index_counter]
cleaned_os_list.append(operating_list[index_counter])
if ip_list[index_counter] in cleaned_ip:
#print "Found a duplicate in IP.... OMITTING "
cleaned_ip.append("")
else:
#print "adding ", ip_list[index_counter]
cleaned_ip.append(ip_list[index_counter])
index_counter +=1
#this section appends to the list store depending on whether the user wants to see the ports or not
counter = 0
for single_result in fetch_results:
if ports_check == True:
self.liststore.append(
[ cleaned_ip[counter], cleaned_os_list[counter], cleaned_host[counter], single_result[4], single_result[3] ]
)
else:
self.liststore.append(
[ single_result[0], single_result[1], single_result[2], "" , "" ]
)
counter +=1
# Treeview
self.treeview = gtk.TreeView()
#In lieu of getting the scroll bar to work, force a max height requirement on creation
self.treeview.set_property('height-request', 600)
# Columns
self.newColumn("IP Address", 0)
self.newColumn("Operating System", 1)
self.newColumn("Hostname",2)
#I only want the ports columns to show if the user requests it because this calls different mysql queries
if ports_check == True:
self.newColumn("Ports", 3)
self.newColumn("Protocol name", 4)
#put the liststore inside of the tree view
self.treeview.set_model(self.liststore)
self.treeview.set_headers_clickable(True)
#Still can't get the scroll bar to work properly so leaving them commented out
#self.scrolledwindow = gtk.ScrolledWindow()
#self.scrolledwindow.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
#add the tree view to the frm_table
self.frm_table.add(self.treeview)
self.treeview.show()
##########################
def on_column_clicked(self, tc, user_data):
#This function allows the columns to be resorted upon click
self.liststore.set_sort_column_id(user_data, self.sort_order)
if self.sort_order == gtk.SORT_ASCENDING:
self.sort_order = gtk.SORT_DESCENDING
else:
self.sort_order = gtk.SORT_ASCENDING
tc.set_sort_order(self.sort_order)
###########################
def newColumn(self, title, index):
#This function cleans up code because I want these options on all of the columns
#This code block would have to be duplicated for each column otherwise...
self.cells[index] = gtk.CellRendererText()
self.cells[index].set_property('cell-background-gdk', gtk.gdk.color_parse("#FFF"))
self.columns[index] = gtk.TreeViewColumn(title, self.cells[index], text=index)
self.columns[index].set_resizable(True)
self.columns[index].set_reorderable(True)
self.columns[index].set_sort_indicator(True)
if(index == 0) :
self.columns[index].set_min_width(130)
if (index == 1) :
self.columns[index].set_min_width(300)
if (index == 2) :
self.columns[index].set_min_width(200)
self.columns[index].connect("clicked", self.on_column_clicked, index)
self.treeview.insert_column(self.columns[index], -1)
# The main function
########################
def exit_program(self, widget, callback_data=None):
gtk.main_quit()
#---------------------------------------------
if __name__ == "__main__":
app = Application()
database_connection.commit()
cursor.close()
database_connection.close()
--->end new interface<---
I am still having the same problems with the scroll bars. I suspect it is the way I am adding widgets to containers.
NOTE: I removed mysql statements from first GUI to save post space
A: The only difference with my working code is that I do NOT use "add_with_viewport" :
swH = gtk.ScrolledWindow()
swH.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
swH.add(treeviewH)
It works fine. Please try, and tell me if it's OK. If not, I will digg further.
EDIT
Try this sample, adapt it with your DB data (I cannot run your program because I do not have the db), and enjoy !
#!/usr/bin/env python
# -*- Encoding: Latin-1 -*-
import pygtk
pygtk.require('2.0')
import gtk
def window():
win = gtk.Window ()
win.set_default_size(300, 150)
win.set_position(gtk.WIN_POS_CENTER)
win.connect ('delete_event', gtk.main_quit)
cols = ['Date', 'Index', 'Program', 'Comments']
sequence = [str] * len(cols)
starStore = gtk.TreeStore( * sequence)
starView = gtk.TreeView(starStore)
starView.cell = [None] * len(cols)
tvcolumn = [None] * len(cols)
for colnum, col in enumerate(cols):
starView.cell[colnum] = gtk.CellRendererText()
tvcolumn[colnum] = gtk.TreeViewColumn(col, starView.cell[colnum])
tvcolumn[colnum].add_attribute(starView.cell[colnum], 'text', colnum)
starView.append_column(tvcolumn[colnum])
scrollTree = gtk.ScrolledWindow()
scrollTree.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
scrollTree.add(starView)
win.add(scrollTree)
data = [['2010', '123', 'P02', 'Initial'],
['2008', '456', 'P08', 'not finished'],
['2007', '456', 'P08', 'not finished'],
['2006', '456', 'P08', 'not finished'], # copy and paste a line to add, delete a line to shorten the treeview. The scollbar appears when needed.
['2005', '456', 'P08', 'not finished'],
['2004', '456', 'P08', 'not finished'],
['2001', '999', 'P999', 'A space Odissey']]
for line in data:
mother = starStore.append( None, [line[0], line[1], line[2], line[3]])
win.show_all()
gtk.main()
if __name__ == '__main__':
window()
A: Thank you so much for that!
After some playing around I was able to adapt my program with your guidance!
If anyone is interested in this I am posting the code below for completeness
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pygtk
import gtk
import os
import sys
import MySQLdb
database_connection = MySQLdb.connect('localhost', 'root', '', 'nmap');
cursor = database_connection.cursor()
class Application(gtk.Window):
cells = {}
columns = {}
sort_order = gtk.SORT_ASCENDING
####################
def __init__(self):
gtk.Window.__init__( self )
self.set_title("Netowrk Scanner")
self.set_position(gtk.WIN_POS_CENTER)
self.create_widgets()
self.connect_signals()
#self.window.show_all()
self.show_all()
gtk.main()
##################
def create_widgets(self):
#Ask the user to search by operating system
self.vbox = gtk.VBox(spacing=10)
self.operating_system_label_hbox_1 = gtk.HBox(spacing=10)
self.label = gtk.Label("Search by Operating System :")
self.operating_system_label_hbox_1.pack_start(self.label)
#Set a check box so the user can choose to display ports
self.ports_hbox_8 = gtk.HBox(spacing=10)
self.ports_check = gtk.CheckButton("Display Ports")
self.ports_hbox_8.pack_start(self.ports_check)
self.halign_ports = gtk.Alignment(0,1,1,0)
self.halign_ports.add(self.ports_hbox_8)
self.os_entry_hbox_2 = gtk.HBox(spacing=10)
self.OS = gtk.Entry()
self.os_entry_hbox_2.pack_start(self.OS)
self.hostname_label_hbox_3 = gtk.HBox(spacing=10)
self.label = gtk.Label("Search by Hostname:")
self.hostname_label_hbox_3.pack_start(self.label)
self.hostname_entry_hbox_4 = gtk.HBox(spacing=10)
self.HOSTNAME = gtk.Entry()
self.hostname_entry_hbox_4.pack_start(self.HOSTNAME)
self.ip_label_hbox_5 = gtk.HBox(spacing=10)
self.label = gtk.Label("Search by IP:")
self.ip_label_hbox_5.pack_start(self.label)
self.ip_entry_hbox_6 = gtk.HBox(spacing=10)
self.IP = gtk.Entry()
self.ip_entry_hbox_6.pack_start(self.IP)
self.buttons_hbox_7 = gtk.HBox(spacing=10)
self.button_ok = gtk.Button("Get Results!")
self.buttons_hbox_7.pack_start(self.button_ok)
self.button_exit = gtk.Button("Get me Outta Here!")
self.buttons_hbox_7.pack_start(self.button_exit)
#The order in which you pack_start a widget is the order in which it is displayed on the screen
self.vbox.pack_start(self.operating_system_label_hbox_1)
self.vbox.pack_start(self.os_entry_hbox_2)
self.vbox.pack_start(self.hostname_label_hbox_3)
self.vbox.pack_start(self.hostname_entry_hbox_4)
self.vbox.pack_start(self.ip_label_hbox_5)
self.vbox.pack_start(self.ip_entry_hbox_6)
self.vbox.pack_start(self.halign_ports, False, False, 3)
self.vbox.pack_start(self.buttons_hbox_7)
self.add(self.vbox)
##########################
def connect_signals(self):
#Have the buttons start 'listening' for user interaction
self.button_ok.connect("clicked", self.button_click)
self.button_exit.connect("clicked", self.exit_program)
########################
def button_click(self, clicked):
#This function gets the values of the input boxes as well as the check box
#And then passes them to the show_table function so it can get the correct results from the database
global ports_check, os, ip, hostname
os = self.OS.get_text()
ip = self.IP.get_text()
hostname = self.HOSTNAME.get_text()
ports_check = self.ports_check.get_active()
self.show_Table(os, ip, hostname)
##############
def show_Table(self, search_os, search_ip, search_hostname):
### Create the table
# List of items to display which represent IP, OS, DNS, Port number and Port description
# Columns
if ports_check == True:
cols = ['IP Address', 'Operating System', 'Hostname', 'Ports', 'Protocol Name']
else:
cols = ['IP Address', 'Operating System', 'Hostname']
"""
self.newColumn("IP Address", 0)
self.newColumn("Operating System", 1)
self.newColumn("Hostname",2)
#I only want the ports columns to show if the user requests it because this calls different mysql queries
if ports_check == True:
self.newColumn("Ports", 3)
self.newColumn("Protocol name", 4)
"""
sequence = [str] * len(cols)
self.treestore = gtk.TreeStore( * sequence)
self.treestore.connect("rows-reordered", self.on_column_clicked)
self.treeview = gtk.TreeView(self.treestore)
self.treeview.cell = [None] * len(cols)
self.treeview_column = [None] * len(cols)
for column_number, col in enumerate(cols):
self.treeview.cell[column_number] = gtk.CellRendererText()
self.treeview_column[column_number] = gtk.TreeViewColumn(col, self.treeview.cell[column_number])
self.treeview_column[column_number].add_attribute(self.treeview.cell[column_number], 'text', column_number)
self.treeview_column[column_number].set_resizable(True)
self.treeview_column[column_number].set_reorderable(True)
self.treeview_column[column_number].set_sort_indicator(True)
self.treeview_column[column_number].set_sort_column_id(column_number)
self.treeview.append_column(self.treeview_column[column_number])
self.scrollTree = gtk.ScrolledWindow()
self.scrollTree.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
self.scrollTree.add(self.treeview)
#If the user is running a search on the hostname run these queries
if search_hostname != "":
if ports_check == True:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name, Port_Description, Open_Port FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE DNS_Name LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address ), Open_Port" % (search_hostname))
#Otherwise just return the relevent data
else:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE DNS_Name LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address )" % (search_hostname))
#If the user has specified the IP and the OS to search, run this query
if search_os != "" and search_ip !="":
#Set up the queries. If the user has activated the checkbox, we need to include the ports in the query
if ports_check == True:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name, Port_Description, Open_Port FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE OS_Name LIKE '%%%s%%' and Computer_IP_Address LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address ), Open_Port" % (search_os, search_ip))
#Otherwise just return the relevent data
else:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE OS_Name LIKE '%%%s%%' and Computer_IP_Address LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address )" % (search_os, search_ip))
#If the user has specified an OS but not an IP run this
elif search_os != "" and search_ip == "":
if ports_check == True:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name, Port_Description, Open_Port FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE OS_Name LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address ), Open_Port" % search_os)
else:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE OS_Name LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address )" % search_os)
#If the user has specified an IP but not an OS run this
elif search_os =="" and search_ip != "":
if ports_check == True:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name, Port_Description, Open_Port FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE Computer_IP_Address LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address ), Open_Port" % search_ip)
else:
cursor.execute("SELECT DISTINCT Computer_IP_Address, OS_Name, DNS_Name FROM Computer_Ports AS CP \
JOIN Computer_Info AS CI ON ( CP.Computer_ID = CI.Computer_ID ) \
JOIN Ports_Table AS PT ON ( CP.Port_ID = PT.Port_ID ) \
JOIN OS_Table AS OS ON ( CI.Computer_ID = OS.OS_ID ) \
JOIN Port_Description AS PS ON ( PT.Open_Port = PS.Port_Number ) \
WHERE Computer_IP_Address LIKE '%%%s%%' ORDER BY inet_aton( Computer_IP_Address )" % search_ip)
#get the results and prepare to put them inside of lists
fetch_results = cursor.fetchall()
host_name_list = []
operating_list = []
ip_list = []
ports = []
#The element chosen to append to each list based on the order of retrieval in the mysql query
for individual_result in fetch_results:
ip_list.append(individual_result[0])
operating_list.append(individual_result[1])
host_name_list.append(individual_result[2])
if ports_check == True:
ports.append(individual_result[3])
#we are going to add blanks to the files in order to help readability
#when putting this into the chart
cleaned_host =[]
cleaned_ip = []
cleaned_os_list = []
index_counter = 0
#this loop will check to see if the entry already exists in the cleaned variables. If it does, it 'omitts' them by inserting a blank line
while index_counter < len(host_name_list):
if host_name_list[index_counter] in cleaned_host:
#print "found a duplicate in HOST....OMITTING"
cleaned_host.append("")
else:
#print "adding ", host_name_list[index_counter]
cleaned_host.append(host_name_list[index_counter])
if operating_list[index_counter] in cleaned_os_list and ip_list[index_counter] in cleaned_ip:
#print "found a duplicate in OPERATING....OMITTING"
cleaned_os_list.append("")
else:
#print "adding ", operating_list[index_counter]
cleaned_os_list.append(operating_list[index_counter])
if ip_list[index_counter] in cleaned_ip:
#print "Found a duplicate in IP.... OMITTING "
cleaned_ip.append("")
else:
#print "adding ", ip_list[index_counter]
cleaned_ip.append(ip_list[index_counter])
index_counter +=1
#this section appends to the list store depending on whether the user wants to see the ports or not
counter = 0
for single_result in fetch_results:
if ports_check == True:
self.treestore.append( None,
[ cleaned_ip[counter], cleaned_os_list[counter], cleaned_host[counter], single_result[4], single_result[3] ]
)
else:
self.treestore.append(None,
[ single_result[0], single_result[1], single_result[2] ]
)
counter +=1
self.frm_table = gtk.Window()
self.frm_table.set_default_size(600, 800)
self.frm_table.set_title("Network scan results")
#Change the background to white instead of grey
self.frm_table.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse('#fff'))
self.frm_table.add(self.scrollTree)
self.frm_table.show_all()
######################
def on_column_clicked(self, col1, col2, col3, col4 ):
#This function allows the columns to be resorted upon click
if self.sort_order == gtk.SORT_ASCENDING:
self.sort_order = gtk.SORT_DESCENDING
else:
self.sort_order = gtk.SORT_ASCENDING
#tc.set_sort_order(self.sort_order)
###############
def exit_program(self, widget, callback_data=None):
gtk.main_quit()
#---------------------------------------------
if __name__ == "__main__":
app = Application()
database_connection.commit()
cursor.close()
database_connection.close()
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586379",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHP/HTML check if a select already contains a particular value I am working on redesigning a somewhat poorly designed system and have run across the following issue.
I have a time field where the user can select the hour, minute, and time zone for an event. These are done with an HTML select drop down menu with several different options. My predecessor felt it necessary to enable people to select an exact minute whereas in my particular application 15 minute increments will suffice, (not to mention make the list about a million times easier to navigate through for the users).
The issue I have is this, if an event was created to occur at say 1:17 PM previously but 17 is no longer in my minute drop down menu It will display the default --select-- option. But I would prefer that in these cases the 17 appear in the menu and be selected as the default. My issue is I don't know how exactly to check if my minute value already exists in the list, and then add it if it isn't. I suppose I could be creating a PHP array in parallel with my drop down options, but I would prefer to be able to look directly at the list of options and determine if the value is already there, if so move on, if not add it to the end. Is there a way to get this kind of information from an HTML object in PHP?
A: No you can't access this information from PHP. Only thing you could do is to buffer the html you are sending and then use DOM to access the drop down. But I suggest you use a php array, just as you mentioned, and create the drop down from it.
$values = array(0,15,30,45);
if(!in_array($values, $minute)) {
$values[] = $minute;
}
// Generate select box..
[...]
A: You could use modulus (%) to work out if the value is divisible by 15 (assuming you are using the minutes 0, 15, 30 and 45 in the new list) e.g.
if($value !== 0 && $value % 15 !== 0) { // add it to the list }
A: No, short of parsing your HTML using a PHP parser and get the values, there is no good way of knowing that beforehand. The best solution for that would be to have an array with the values in your dropdown and check with that array.
Alternatively, I would suggest selecting the nearest of the new possible values to the user's previous choice. You could get it like that:
round($minute, 15) * 15; //14 will give 15, 35 will give 30, etc
A: Why don't you just create the entire object (select/option) and remove it from the webpage you have? You'd still have the HTML page. You just don't put the HTML for the select/option ahead of time. You build it in the PHP and put it on the page.
You use the PHP to decide the values that need to be in Option.
A: PHP runs during the HTML renders, if you wish to alter a <select> with PHP, that rendering must be done before the list is presented. Your best solution is to create an array and add your custom value in there.
define('DEFAULT_SELECT', array(0, 15, 30, 45));
...
$select_options = DEFAULT_SELECT;
if (!in_array($new_option, $select_options)) { array_push($new_option, $select_options)); }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ant build target to list own build targets I am brand new to Ant. I would like to have the following:
<target name="targets" description "Lists Targets">
[some Ant code/tasks]
</target
When I call ant targets I want Ant to search the current file that Ant is running for all it's targets
<target name="all" depends="doc,sca,compile,test" description="Complete build">
</target>
And output
[echo] all - Complete Build - Depends on: doc, sca, compile, test
[echo] doc - Builds documentation
[echo] compile - Compiles files
[echo] sca - Performs static code analysis
[echo] test - Runs unit tests - Depends on: compile
[echo] clean - Cleans a build
[echo] install - Performs an installation
[echo] targets - Lists Targets
In Bash or Make I'd just do a grep regular expression. The following, in Make, lists the make targets:
noop: ;
targets:
@$(MAKE) --print-data-base --question noop | \
grep -v "[A-Z]:/" | \
awk '/^[Mm]akefile:/ { next } \
/^targets:/ { next } \
/^noop:/ { next } \
/^[^.%!][-A-Za-z0-9_]*:/ { print substr($$1, 1, length($$1)-1) }' | \
sort | \
pr --omit-pagination --width=80 --columns=4
Output:
[matt@office burning-boots-website]$ make -C ~/workspace/packages/ targets
all diagnose install vca_core
clean doc platforms vca_counting_line
compile help utils vca_rules
It would be nice to have something simliar in my Ant build script! would be especially nice if Ant could do the nice alignment that pr does - or even colour the output! Can Ant do cross platform terminal colour changes?
A: You could just use ant -p (or ant -p -v to get more information). This won't list the target dependencies, but I don't see it as a problem: dependencies are not important for the end user (they just tell how the target works). What's important is what the target does, which is what should be in its description.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Problem with importing certain strings from excel sheet into mysql I am working on part of a application that needs to import data from a excel sheet into a mysql database table. The code works fine until it gets to a record in the excel sheet where one of the string values gets assigned "ABCDE All'John D Doe 999 West Lame Blvd Cullman, AL 35055". I am not certain but I believe that it has to do completely with the "'" that appears there. Which that can not change and other records from the excelsheet could contain the " ' " as well... When it gets to this record it throws this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'John D Doe','ABCDE','All'John','D','Doe','256-555-5555',' ','256-555-5555' at line 1
the code that i have around this problems is as follows:
Private Function PerFormUpdate(ByVal customer As String, ByVal bill_to As String, ByVal Contact As String, ByVal Company As String, ByVal firstName As String, ByVal mi As String, ByVal lastname As String, ByVal phone As String, ByVal altPhone As String, ByVal fax As String)
Dim _db As New schoolEntities
Dim command As MySqlCommand = _dbconn.CreateCommand()
command.CommandText = "SELECT * FROM quickbooks_imports WHERE Customer= "" & _customer& "" & Bill_to= "" & _bill_to& "" & Contact= "" & _Company& ""& First_Name= "" & _firstName& "" & M_I= "" & _mi& "" & Last_Name= "" & _lastname& "" & Phone= "" & _phone& "" & Alt_Phone= "" & _altPhone& "" & Fax= "" & _Fax& """
_dbconn.Open()
Dim _mysqlReader As MySqlDataReader = command.ExecuteReader()
_dbconn.Close()
If Not _mysqlReader.HasRows Then
Dim _UpdateItem As New quickbooks_imports
Dim updateCommand As MySqlCommand = _dbconn.CreateCommand()
_UpdateItem.Customer = customer
_UpdateItem.Bill_to = bill_to
_UpdateItem.Contact = Contact
_UpdateItem.Company = Company
_UpdateItem.First_Name = firstName
_UpdateItem.M_I = mi
_UpdateItem.Last_Name = lastname
_UpdateItem.Phone = phone
_UpdateItem.Alt_Phone = altPhone
_UpdateItem.Fax = fax
updateCommand.CommandText = "INSERT INTO quickbooks_imports(Customer,Bill_to,Contact,Company,First_Name,M_I,Last_Name,Phone,Alt_Phone,Fax) VALUES ('" & _UpdateItem.Customer & "','" & _UpdateItem.Bill_to & "','" & _UpdateItem.Contact & "','" & _UpdateItem.Company & "','" & _UpdateItem.First_Name & "','" & _UpdateItem.M_I & "','" & _UpdateItem.Last_Name & "','" & _UpdateItem.Phone & "','" & _UpdateItem.Alt_Phone & "','" & _UpdateItem.Fax & "') "
_dbconn.Open()
updateCommand.ExecuteNonQuery()
_db.SaveChanges()
The Error shows up on the ExecuteNonQuery to perform the update..
Any help would be greatly appreciated...
As per your response I switched to the params and this is the new code:
updateCommand.CommandText = "INSERT INTO quickbooks_imports (Customer,Bill_to,Contact,Company,First_Name,M_I,Last_Name,Phone,Alt_Phone,Fax) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ? )"
updateCommand.Parameters.AddWithValue("Customer", _UpdateItem.Customer)
updateCommand.Parameters.AddWithValue("Bill_to", _UpdateItem.Bill_to)
updateCommand.Parameters.AddWithValue("Contact", _UpdateItem.Contact)
updateCommand.Parameters.AddWithValue("Company", _UpdateItem.Company)
updateCommand.Parameters.AddWithValue("First_Name", _UpdateItem.First_Name)
updateCommand.Parameters.AddWithValue("M_I", _UpdateItem.M_I)
updateCommand.Parameters.AddWithValue("Last_Name", _UpdateItem.Last_Name)
updateCommand.Parameters.AddWithValue("Phone", _UpdateItem.Phone)
updateCommand.Parameters.AddWithValue("Alt_Phone", _UpdateItem.Alt_Phone)
updateCommand.Parameters.AddWithValue("Fax", _UpdateItem.Fax)
how ever its throwing a fatal exception now...
I just tried using name parameters as you mentioned in your reply and the code is as follows:
Private Function PerFormUpdate(ByVal customer As String, ByVal bill_to As String, ByVal Contact As String, ByVal Company As String, ByVal firstName As String, ByVal mi As String, ByVal lastname As String, ByVal phone As String, ByVal altPhone As String, ByVal fax As String)
Dim _db As New schoolEntities
Dim command As MySqlCommand = _dbconn.CreateCommand()
command.CommandText = "SELECT * FROM quickbooks_imports WHERE Customer= "" & _customer& "" & Bill_to= "" & _bill_to& "" & Contact= "" & _Company& ""& First_Name= "" & _firstName& "" & M_I= "" & _mi& "" & Last_Name= "" & _lastname& "" & Phone= "" & _phone& "" & Alt_Phone= "" & _altPhone& "" & Fax= "" & _Fax& """
_dbconn.Open()
Dim _mysqlReader As MySqlDataReader = command.ExecuteReader()
_dbconn.Close()
If Not _mysqlReader.HasRows Then
Dim _UpdateItem As New quickbooks_imports
Dim updateCommand As MySqlCommand = _dbconn.CreateCommand()
_UpdateItem.Customer = customer
_UpdateItem.Bill_to = bill_to
_UpdateItem.Contact = Contact
_UpdateItem.Company = Company
_UpdateItem.First_Name = firstName
_UpdateItem.M_I = mi
_UpdateItem.Last_Name = lastname
_UpdateItem.Phone = phone
_UpdateItem.Alt_Phone = altPhone
_UpdateItem.Fax = fax
updateCommand.CommandText = "INSERT INTO quickbooks_imports (Customer,Bill_to,Contact,Company,First_Name,M_I,Last_Name,Phone,Alt_Phone,Fax) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
updateCommand.Parameters.AddWithValue("@Customer", _UpdateItem.Customer)
updateCommand.Parameters.AddWithValue("@Bill_to", _UpdateItem.Bill_to)
updateCommand.Parameters.AddWithValue("@Contact", _UpdateItem.Contact)
updateCommand.Parameters.AddWithValue("@Company", _UpdateItem.Company)
updateCommand.Parameters.AddWithValue("@First_Name", _UpdateItem.First_Name)
updateCommand.Parameters.AddWithValue("@M_I", _UpdateItem.M_I)
updateCommand.Parameters.AddWithValue("@Last_Name", _UpdateItem.Last_Name)
updateCommand.Parameters.AddWithValue("@Phone", _UpdateItem.Phone)
updateCommand.Parameters.AddWithValue("@Alt_Phone", _UpdateItem.Alt_Phone)
updateCommand.Parameters.AddWithValue("@Fax", _UpdateItem.Fax)
'updateCommand.CommandText = "INSERT INTO EXCEL (id,Customer,Bill_to,Contact,Company,First_Name,M_I,Last_Name,Phone,Alt_Phone,Fax) VALUES ('" & _UpdateItem.id & "','" & _UpdateItem.Customer & "','" & _UpdateItem.Bill_to & "','" & _UpdateItem.Contact & "','" & _UpdateItem.Company & "','" & _UpdateItem.First_Name & "','" & _UpdateItem.M_I & "','" & _UpdateItem.Last_Name & "','" & _UpdateItem.Phone & "','" & _UpdateItem.Alt_Phone & "','" & _UpdateItem.Fax & "') ON DUPLICATE KEY UPDATE Customer= '" & _UpdateItem.Customer & "' Bill_to= '" & _UpdateItem.Bill_to & "' Contact= '" & _UpdateItem.Contact & "' Company= '" & _UpdateItem.Company & "' First_Name= '" & _UpdateItem.First_Name & "' M_I= '" & _UpdateItem.M_I & "' Last_Name= '" & _UpdateItem.Last_Name & "' Phone= '" & _UpdateItem.Phone & "' Alt_Phone= '" & _UpdateItem.Alt_Phone & "' Fax= '" & _UpdateItem.Fax & "'"
'updateCommand.CommandText = "INSERT INTO quickbooks_imports (Customer,Bill_to,Contact,Company,First_Name,M_I,Last_Name,Phone,Alt_Phone,Fax) VALUES ('" & _UpdateItem.Customer & "','" & _UpdateItem.Bill_to & "','" & _UpdateItem.Contact & "','" & _UpdateItem.Company & "','" & _UpdateItem.First_Name & "','" & _UpdateItem.M_I & "','" & _UpdateItem.Last_Name & "','" & _UpdateItem.Phone & "','" & _UpdateItem.Alt_Phone & "','" & _UpdateItem.Fax & "') "
_dbconn.Open()
updateCommand.ExecuteNonQuery()
_db.SaveChanges()
and I am still getting the fatal exception on the updateCommand.ExecuteNonQuery()
Fatal error encountered during command execution.
InnerException Message: "Parameter '?' must be defined."
A: You need to use parameters which will properly escape your strings for database execution.
Refer to this link. http://www.devart.com/dotconnect/mysql/docs/Parameters.html
Edit: Try using named parameters instead:
updateCommand.CommandText = "INSERT INTO quickbooks_imports (Customer,Bill_to,Contact,Company,First_Name,M_I,Last_Name,Phone,Alt_Phone,Fax) VALUES ("@Customer", "@Bill_to", "@Contact", "@Company", "@First_Name", "@M_I", "@Last_Name", "@Phone", "@Alt_Phone", "@Fax")"
updateCommand.Parameters.AddWithValue("@Customer", _UpdateItem.Customer)
updateCommand.Parameters.AddWithValue("@Bill_to", _UpdateItem.Bill_to)
updateCommand.Parameters.AddWithValue("@Contact", _UpdateItem.Contact)
updateCommand.Parameters.AddWithValue("@Company", _UpdateItem.Company)
updateCommand.Parameters.AddWithValue("@First_Name", _UpdateItem.First_Name)
updateCommand.Parameters.AddWithValue("@M_I", _UpdateItem.M_I)
updateCommand.Parameters.AddWithValue("@Last_Name", _UpdateItem.Last_Name)
updateCommand.Parameters.AddWithValue("@Phone", _UpdateItem.Phone)
updateCommand.Parameters.AddWithValue("@Alt_Phone", _UpdateItem.Alt_Phone)
updateCommand.Parameters.AddWithValue("@Fax", _UpdateItem.Fax)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Color states with Python's matplotlib/basemap I want to generate a map of the United States and color each state in using a different shade. Is there a way to do this using Python's basemap?
A: There is a nicely formated example in the Basemap repo on GitHub: fillstates.py. The shapefile (dbf | shp | shx) is also included in the examples folder.
Here is an abbreviated version of the example:
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
# create the map
map = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
# load the shapefile, use the name 'states'
map.readshapefile('st99_d00', name='states', drawbounds=True)
# collect the state names from the shapefile attributes so we can
# look up the shape obect for a state by it's name
state_names = []
for shape_dict in map.states_info:
state_names.append(shape_dict['NAME'])
ax = plt.gca() # get current axes instance
# get Texas and draw the filled polygon
seg = map.states[state_names.index('Texas')]
poly = Polygon(seg, facecolor='red',edgecolor='red')
ax.add_patch(poly)
plt.show()
Resulting plot with Texas filled red:
Note that when we load a shapefile the shapes and attributes are stored in map.states and map.states_info respectively as lists based on the name parameter used in the readshapefile call. So to look up the shape for a specific state we had to build a corresponding list of the state names from the attributes.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
}
|
Q: hg extdiff -p and %~dp0 myprogram.cmd is in PATH;
myprogram.cmd uses %~dp0 to determine the folder it is in;
I have included @echo %~dp0 into myprogram.cmd for debugging;
When I call myprogram.cmd from anywhere, it works perfectly, displaying the folder myprogram.cmd is in;
When I call hg extdiff -p myprogram.cmd, it does not work, displaying something like c:\Users\Username\AppData\Local\Temp\extdiff.3n8op2\.
Here is the related part of hgrc file:
[extensions]
hgext.extdiff =
What do I do wrong? Should not %~dp0 return drive and path of the batch file? What do I use instead? Do I have to apply some special configuration to Mercurial repository? Passing the full path of myprogram.cmd to hg extdiff -p is not an option, unless it is done automatically.
A: The %~dp0 trick is a big lie. It is not actually a magic variable, it's simply a manipulation of %0 (or whichever var you stick the ~dp in front of). It simply takes whatever string is in that variable and tells you what its drive and path components appear to be. If that string is simply a name like "myprogram", it says "well, filenames without drives and paths are assumed to be in the current directory".
So the %~dp0 trick only works if either:
a) you've launched your script by its full name or
b) you happen to be in the directory where it resides
In this case, you run:
hg extdiff -p myprogram
gets turned into the following call to Windows:
CreateProcess(NULL, "cmd.exe /c myprogram some diff args", ..., "c:/some/temp/path", ...)
which is morally equivalent to opening a shell and running:
C:\>cd c:\some\temp\path
C:\some\temp\path>myprogram some diff args
%0 is myprogram
%~dp0 is C:\some\temp\path
I recommend passing the full program name for your tool like this via your .hgrc:
[extdiff]
myprogram=c:/tools/myprogram.cmd
But be warned, this can get confused by the presence of spaces in your filename, you may need to experiment with quoting.
A: You can try using %~dp$PATH:0, but you need to always specify the extension. For example, for the following test.cmd:
rem test.cmd
@echo dp0 == %~dp0
@echo dp$PATH:0 == %~dp$PATH:0
these are two sample runs from the d:\hg folder:
$ hg extdiff -p test.cmd
dp0 == c:\Users\estefan\AppData\Local\Temp\extdiff.pamj6n\
dp$PATH:0 == k:\home\Scripts\
$ hg extdiff -p test
dp0 == c:\Users\estefan\AppData\Local\Temp\extdiff.dgp0qz\
dp$PATH:0 ==
From http://ss64.com/nt/syntax-args.html:
%~$PATH:1 Search the PATH environment variable and expand %1 to the fully qualified name of the first match found.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: LINQ query null exception when Where returns 0 rows I have the following LINQ method that works as expected except if there are No Rows Found then I get a Null Exception. I am struggling on how I modify this to return 0 if that occurs.
public static int GetLastInvoiceNumber(int empNumber)
{
using (var context = new CmoDataContext(Settings.Default.LaCrosse_CMOConnectionString))
{
context.Log = Console.Out;
IQueryable<tblGreenSheet> tGreenSheet = context.GetTable<tblGreenSheet>();
return (tGreenSheet
.Where(gs => gs.InvoiceNumber.Substring(2, 4) == empNumber.ToString())
.DefaultIfEmpty()
.Max(gs => Convert.ToInt32(gs.InvoiceNumber.Substring(6, gs.InvoiceNumber.Length)))
);
}
}
Thanks
I tried one of Jon Skeet's suggestions, below, and now I get Unsupported overload used for query operator 'DefaultIfEmpty'
public static int GetLastInvoiceNumber(int empNumber)
{
using (var context = new CmoDataContext(Settings.Default.LaCrosse_CMOConnectionString))
{
context.Log = Console.Out;
IQueryable<tblGreenSheet> tGreenSheet = context.GetTable<tblGreenSheet>();
return tGreenSheet
.Where(gs => gs.InvoiceNumber.Substring(2, 4) == empNumber.ToString())
.Select(gs => Convert.ToInt32(gs.InvoiceNumber.Substring(6, gs.InvoiceNumber.Length)))
.DefaultIfEmpty(0)
.Max();
}
}
A: You're using
.Where(...)
.DefaultIfEmpty()
which means if there are no results, pretend it's a sequence with a single null result. You're then trying to use that null result in the Max call...
You can probably change it to:
return tGreenSheet.Where(gs => ...)
.Max(gs => (int?) Convert.ToInt32(...)) ?? 0;
This uses the overload finding the maximum of int? values - and it returns an int? null if there were no values. The ?? 0 then converts that null value to 0. At least, that's the LINQ to Objects behaviour... you'll have to check whether it gives the same result for you.
Of course, you don't need to use the ?? 0 if you're happy to change the method signature to return int? instead. That would give extra information, in that the caller could then tell the difference between "no data" and "some data with a maximum value of 0":
return tGreenSheet.Where(gs => ...)
.Max(gs => (int?) Convert.ToInt32(...));
Another option is to use the overload of DefaultIfEmpty() which takes a value - like this:
return tGreenSheet.Where(gs => ...)
.Select(gs => Convert.ToInt32(...))
.DefaultIfEmpty(0)
.Max();
A: In situations like this when there may or may not be a matching item, I prefer to return an object rather than a value type. If you return a value type, you have to have some semantics about what value means "there is nothing here." I would change it to return the last invoice, then (when it is non-null) get the invoice number from the invoice. Add a method to the class to return the numeric invoice number from the string.
public static tbleGreenSheet GetLastInvoice(int empNumber)
{
using (var context = new CmoDataContext(Settings.Default.LaCrosse_CMOConnectionString))
{
context.Log = Console.Out;
return context.GetTable<tblGreenSheet>()
.Where(gs => gs.InvoiceNumber.Substring(2, 4) == empNumber.ToString())
.OrderByDescending(gs => Convert.ToInt32(gs.InvoiceNumber.Substring(6, gs.InvoiceNumber.Length)))
.FirstOrDefault();
}
}
public class tbleGreenSheet
{
....
public int NumericInvoice
{
get { return Convert.ToInt32(InvoiceNumber.Substring(6, InvoiceNumber.Length)); }
}
...
}
Used as
var invoice = Foo.GetLastInvoice( 32 );
if (invoice != null)
{
var invoiceNumber = invoice.NumericInvoice;
...do something...
}
else
{
...do something else...
}
A: I had a remarkably similar experience with IQueryable<T> and NHibernate. My solution:
public static TExpr MaxOrDefault<TItem, TExpr>(this IQueryable<TItem> query,
Expression<Func<TItem, TExpr>> expression) {
return query.OrderByDescending(expression).Select(expression).FirstOrDefault();
}
The only drawback is that you are stuck with the standard default value, instead of getting to specify one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Object oriented programming - question about design and accessing relevant data Consider you have the following code in a Timer:
It's main goal is to count down the seconds and to show it on GUI, which is Swing based.
The Timer is part of the game and is used for a decision of who is the winner by taking the user who reached a solution first.
Action updateClockAction = new AbstractAction() {
public void actionPerformed(ActionEvent e) {
JLabel secLabel = m_GameApplet.GetJpanelStartNetGame().GetJlabelSeconds();
secLabel.setFont(new java.awt.Font("Lucida Handwriting", 1, 36));
secLabel.setForeground(Color.red);
secLabel.setText(Integer.toString(m_TimerSeconds));
if (m_TimerSeconds > 0) {
m_TimerSeconds--;
} else if (m_TimerSeconds == 0) {
m_Timer.stop();
m_GameApplet.GetJpanelStartNetGame().GetJlabelSeconds().setText("0");
m_GameApplet.GetJpanelStartNetGame().GetJbuttonFinish().setVisible(false);
//Checking whether time ended for both players and no solution was recieved
if (!m_WasGameDecisived) {
System.out.println("Tie - No one had a solution in the given time");
}
}
}
};
m_Timer = new Timer(1000, updateClockAction);
Now, I have two main packages in the client implementation
A.GUI - hold all the swing Jpanels etc.
B.LogicEngine
Now in LogicEngine I have a class that is called GameManager- that should manage and store information about the game.
My Current implementation in general is like this:
I have a JpanelMainGame which is on the GUI Package
JpanelMainGame contains JPanelGameBoard which has reference(or in other word contains) an instance of GameManger, which is on different package - The LogicEngine package.
So my questions are these:
*
*Where does all of the timer definition code above should be placed?
A. In the JpanelMainGame? (JpanelMainGame should have a reference to it).
B. In GameManger as a part of a data of the game
*In each solution you give, How should I access all the label info from within the anonymous inner class? As I can only access member from the outer class with command: OuterClass.this.member.
*Any comments about current design.
Thank you very much
A: I repeat the answer I gave on another question:
I strongly discourage from organizing packages from an implementational point of view, like controllers, data, etc. I prefer grouping them by functionality, that is, feature1, feature2, etc. If a feature is reasonably complex and requires a large number of classes, then (and only then) I create subpackages like above, that is, feature1.controllers, feature1.data, etc.
A: Well not to answer questions with questions, but...
*
*How often is Timer used?
*Is Timer coded to be general use, or specific to a certain class?
If the Timer is general use, then I would say it belongs in the LogicEngine package tree somewhere. However, if Timer can only be used in a GUI element, then it belongs in the GUI package tree.
As a general rule of thumb (not to bang on the Agile drum too hard), you should only code what makes sense now but not be afraid to change it later.
Example: You are making an anonymous inner class of the type AbstractAction() in your code. This is just fine (although I shy away from anon classes) if the updateClockAction variable is used simply. But once your coding leads you to the need to cross the boundries of updateClockAction (via OuterClass.this.member) then I assert its time for a bit of refactoring: extract this inner class and make it a fully qualified class. This way, you can have the proper amount of control over the updateClockAction object's internal state (using the cstr, getters, etc)
EDIT: Added requested example
public class Testing {
private Timer timer; /* INIT this from somewhere.... */
public void myFunction() {
/* 60 Seconds */
long countDownTimeSEC = 60;
/* convert to Miliseconds */
long countDownTimeMS = 1000 * countDownTimeSEC;
/* Get ref to label */
JLabel label = m_GameApplet.GetJpanelStartNetGame().GetJlabelSeconds();
/* Set once */
label.setFont(new java.awt.Font("Lucida Handwriting", 1, 36));
label.setForeground(Color.red);
/* Set initial time */
label.setText(Long.toString(countDownTimeSEC));
/* Get ref to button */
JButton button = m_GameApplet.GetJpanelStartNetGame().GetJbuttonFinish();
/* Set up post Count Down list */
ArrayList<AbstractAction> actsWhenComplete = new ArrayList<AbstractAction>();
/* instantiate countdown object */
CountDownClockAction cdca = new CountDownClockAction(label, countDownTimeMS, actsWhenComplete);
this.timer = new Timer(1000, cdca);
/* Now that we have a timer, add the post Count Down action(s) to the post Count Down list */
actsWhenComplete.add(new CountDownFinishAction(label, button, this.timer));
/* Finally, kick off the timer */
this.timer.start();
}
public static class CountDownClockAction extends AbstractAction {
private static final long serialVersionUID = 1L;
private final JLabel labelToUpdate;
private final long startMS;
private long currentMS;
private long timeMark;
private final ArrayList<AbstractAction> actionsToExeWhenComplete;
private boolean actionsExedFlag;
public CountDownClockAction(
final JLabel labelToUpdate,
final long startMS,
ArrayList<AbstractAction> actionsToExeWhenComplete
) {
super();
this.labelToUpdate = labelToUpdate;
this.startMS = startMS;
this.currentMS = startMS;
this.timeMark = 0;
this.actionsExedFlag = false;
this.actionsToExeWhenComplete = actionsToExeWhenComplete;
}
@Override
public void actionPerformed(final ActionEvent e) {
/* First time firing */
if (this.timeMark == 0)
this.timeMark = System.currentTimeMillis();
/* Although the Timer object was set to 1000ms intervals,
* the UpdateClockAction doesn't know this, nor should it
* since > or < 1000ms intervals could happen to do the fact that
* the JVM nor the OS have perfectly accurate timing, nor do they
* have instantaneous code execution properties.
* So, we should see what the *real* time diff is...
*/
long timeDelta = System.currentTimeMillis() - this.timeMark;
/* Allow for the label to be null */
if (this.labelToUpdate != null)
labelToUpdate.setText(Long.toString((long)(currentMS / 1000)));
if (currentMS > 0) {
currentMS -= timeDelta;
} else if (currentMS <= 0 && this.actionsExedFlag == false) {
/* Ensure actions only fired once */
this.actionsExedFlag = true;
/* Allow for the label to be null */
if (this.actionsToExeWhenComplete != null)
for (AbstractAction aa: this.actionsToExeWhenComplete)
aa.actionPerformed(e);
}
/* Finally, update timeMark for next calls */
this.timeMark = System.currentTimeMillis();
}
}
public static class CountDownFinishAction extends AbstractAction {
private final JLabel labelToUpdate;
private final JButton buttonToUpdate;
private final Timer timerToStop;
public CountDownFinishAction(
JLabel labelToUpdate,
JButton buttonToUpdate,
Timer timerToStop
) {
super();
this.labelToUpdate = labelToUpdate;
this.buttonToUpdate = buttonToUpdate;
this.timerToStop = timerToStop;
}
@Override
public void actionPerformed(final ActionEvent e) {
/* Perform actions, allowing for items to be null */
if (this.labelToUpdate != null)
this.labelToUpdate.setText("0");
if (this.buttonToUpdate != null)
this.buttonToUpdate.setVisible(false);
if (this.timerToStop != null)
this.timerToStop.stop();
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586394",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: REGEX - php preg_replace : How to replace part of a string based on a "." (period) character
only if it appears after/before/between a word(s),
not when it is before/between any number(s).
Example:
This is a text string.
-Should be able to replace the "string." with "string ."
(note the Space between the end of the word and the period)
Example 2
This is another text string. 2.0 times longer.
-Should be able to replace "string." with "string ."
(note the Space between the end of the word and the period)
-Should Not replace "2.0" with "2 . 0"
It should only do the replacement if the "." appears at the end/start of a word.
Yes - I've tried various bits of regex.
But everything I do results in either nothing happening,
or the numbers are fine, but I take the last letter from the word preceeding the "."
(thus instead of "string." I end up with "strin g.")
Yes - I've looked through numerous posts here - I have seen Nothing that deals with the desire, nor the "strange" problem of grabbing the char before the ".".
A: You can use a lookbehind (?<=REXP)
preg_replace("/(?<=[a-z])\./i", "XXX", "2.0 test. abc") // <- "2.0 testXXX abc"
which will only match if the text before matches the corresponding regex (in this case [a-z]). You may use a lookahead (?=REXP) in the same way to test text after the match.
Note: There is also a negative lookbehind (?<!REXP) and a negative lookahead (?!REXP) available which will reject matches if the REXP does not match before or after.
A: $input = "This is another text string. 2.0 times longer.";
echo preg_replace("/(^\.|\s\.|\.\s|\.$)/", " $1", $input);
http://ideone.com/xJQzQ
A: I'm not too good with the regex, but this is what I would do to accomplish the task with basic PHP. Basically explode the entire string by it's . values, look at each variable to see if the last character is a letter or number and add a space if it's a number, then puts the variable back together.
<?
$string = "This is another text string. 2.0 times longer.";
print("$string<br>");
$string = explode(".",$string);
$stringcount = count($string);
for($i=0;$i<$stringcount;$i++){
if(is_numeric(substr($string[$i],-1))){
$string[$i] = $string[$i] . " ";
}
}
$newstring = implode('.',$string);
print("$newstring<br>");
?>
A: It should only do the replacement if the "." appears at the end/start of a word.
search: /([a-z](?=\.)|\.(?=[a-z]))/
replace: "$1 "
modifiers: ig (case insensitive, globally)
Test in Perl:
use strict;
use warnings;
my $samp = '
This is another text string. 2.0 times longer.
I may get a string of "this and that.that and this.this 2.34 then that 78.01."
';
$samp =~ s/([a-z](?=\.)|\.(?=[a-z]))/$1 /ig;
print "$samp";
Input:
This is another text string. 2.0 times longer.
I may get a string of "this and that.that and this.this 2.34 then that 78.01."
Output:
This is another text string . 2.0 times longer .
I may get a string of "this and that . that and this . this 2.34 then that 78.01."
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I display excel data with the .xlsx exstension in my windows application using data grid view? I have an excel file that I would like to load into my form and display there. Is there any way to do this? Sorry I am fairly new at visual studio as well as visual basic. If anybody could help me out with this it would be great thanks.
A: There are several options - all involve some additional library:
*
*OpenXML 2.0 (free library from MS) can be used to read/modify the content of an .xlsx so you can display it anyway you want (for example in a data grid view)
*some (commercial) 3rd-party libraries come with grid controls allowing you to display excel files in your application (be it Winforms/WPF/ASP.NET...) like SpreadsheetGear, Aspose.Cells etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586396",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Summing two dataframes based on common value I have a dataframe that looks like
day.of.week count
1 0 3
2 3 1
3 4 1
4 5 1
5 6 3
and another like
day.of.week count
1 0 17
2 1 6
3 2 1
4 3 1
5 4 5
6 5 1
7 6 13
I want to add the values from df1 to df2 based on day.of.week. I was trying to use ddply
total=ddply(merge(total, subtotal, all.x=TRUE,all.y=TRUE),
.(day.of.week), summarize, count=sum(count))
which almost works, but merge combines rows that have a shared value. For instance in the example above for day.of.week=5. Rather than being merged to two records each with count one, it is instead merged to one record of count one, so instead of total count of two I get a total count of one.
day.of.week count
1 0 3
2 0 17
3 1 6
4 2 1
5 3 1
6 4 1
7 4 5
8 5 1
9 6 3
10 6 13
A: There is no need to merge. You can simply do
ddply(rbind(d1, d2), .(day.of.week), summarize, sum_count = sum(count))
I have assumed that both data frames have identical column names day.of.week and count
A: In addition to the suggestion Ben gave you about using merge, you could also do this simply using subsetting:
d1 <- read.table(textConnection(" day.of.week count
1 0 3
2 3 1
3 4 1
4 5 1
5 6 3"),sep="",header = TRUE)
d2 <- read.table(textConnection(" day.of.week count1
1 0 17
2 1 6
3 2 1
4 3 1
5 4 5
6 5 1
7 6 13"),sep = "",header = TRUE)
d2[match(d1[,1],d2[,1]),2] <- d2[match(d1[,1],d2[,1]),2] + d1[,2]
> d2
day.of.week count1
1 0 20
2 1 6
3 2 1
4 3 2
5 4 6
6 5 2
7 6 16
This assumes no repeated day.of.week rows, since match will return only the first match.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Apple Push Notification Error (aps-environment) I have registered the app on iTunes connect. When I run the app on the device I get the following APNS error.
Error Domain=NSCocoaErrorDomain Code=3000 "no valid 'aps-environment' entitlement string found for application" UserInfo=0x19e890 {NSLocalizedDescription=no valid 'aps-environment' entitlement string found for application}
I have used the same AppID and bundle identifier in the xCode project as well as the iTunes connect.
Also, I forgot to mention that the App is registered under a Enterprise developer profile and I am running it under my personal developer profile.
A: You have either not enabled Push Notifications in the Provisioning Portal, or you are not signing your app with the correct certificate that was created when you did enable Push Notifications.
A: Having the same problem, I ended up removing my Provisioning Profiles, on the provisioning portal clicked Edit and then Generate to have them freshly generated, then downloaded the needed Provisioning profiles and double-checked Code Signing Identity (in Build Settings).
Code Signing Identity looks like this: http://i.stack.imgur.com/2l2hd.png
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Error on serializing XML Hi I am getting this error, when serializing to XML
Unable to generate a temporary class (result=1).
error CS0030: Cannot convert type 'XYZ.ProducerChannel[][]' to 'XYZ.ProducerChannel[]'
error CS0029: Cannot implicitly convert type 'XYZ.ProducerChannel[]' to 'XYZ.ProducerChannel[][]'
Can someone help me with whats going on?
Depending classes:
/// <remarks/>
[System.Xml.Serialization.XmlArrayItemAttribute("CarrierAppointment", typeof(ProducerChannel[]), IsNullable=false)]
[System.Xml.Serialization.XmlArrayItemAttribute("DistributionChannelInfo", typeof(ProducerChannel), IsNullable=false, NestingLevel=1)]
public ProducerChannel[][][] Producer
{
get
{
return this.producerField;
}
set
{
this.producerField = value;
}
}
Usage:
var producer = new InitialPurchaseOrder.ProducerChannel{DistributionChannelName = division};
bdParty.Producer = new InitialPurchaseOrder.ProducerChannel[][][]// {{},{},{producer}};
{new InitialPurchaseOrder.ProducerChannel[][]
{new InitialPurchaseOrder.ProducerChannel[]{producer}}};
Error Line:
var serializer = new System.Xml.Serialization.XmlSerializer(txLife.GetType());
Related XSD:
<xs:element name="Policy" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="Annuity" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:sequence>
<xs:element name="QualPlanType" minOccurs="0" maxOccurs="unbounded">
<xs:complexType>
<xs:attribute name="tc" form="unqualified" type="xs:string" />
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
Please let me know how to fix this.
Thanks,
A: Sounds like a bug in xsd.exe I have stumbled upon a few times now, it doesn't handle arrays of arrays correctly.
If that's the case you have to modify the generated classes so that the XmlSerializer can work with it.
Either the attributes or the type of the Producer property is not correct.
If you had posted the relevant section of the XML schema I could say it for certain, but try to change the type of the Producer property from ProducerChannel[][][] to ProducerChannel[][].
If you can modify the XML schema maybe this link can help without the need to modify the C# classes after generating them.
A: I think the error message is pretty clear. You have the property as ProducerChannel[][] (or ProducerChannel[][][]), but your XmlArrayItem attribute is trying to serialize it as ProducerChannel[].
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586403",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Excel - How to reformat nested table? I have exported excel table like that
but i need another format like that:
00008BN07 item1 subitem1 2,000 6 872,320
00008LN02A item2 subitem1 2,000 10 099,340
.....
020876071 item5 subitem1 1,000 294,260
020876071 item5 subitem2 2,000 294,260
020876071 item5 subitem3 3,000 294,260
How I can reformat first table to second view? Mbe some simple vba script?
Thanks!
A: If the columns are A, B, and C, for name, item, and subitem respectively, try this code.
It makes not claims to try to be optimized.
When it has run, sort on column C, and delete all the junk that does not contain "SubItem" in column C.
Sub FillTable()
Dim lRowCurr As Long
Dim lRowColA As Long
Dim lRowColB As Long
lRowCurr = Cells(Rows.Count, 3).End(xlUp).Row
Do
If InStr(1, Cells(lRowCurr, 3), "subitem") Then
lRowColA = Cells(lRowCurr, 1).End(xlUp).Row
lRowColB = Cells(lRowColA, 2).End(xlDown).Row
Cells(lRowCurr, 1) = Cells(lRowColA, 1)
Cells(lRowCurr, 2) = Cells(lRowColB, 2)
End If
lRowCurr = lRowCurr - 1
Loop While lRowCurr > 0
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Easiest path for Microsoft Web API to generate WSDL Web API, unlike some of the older Microsoft web service technologies, does not generate WSDL documentation automatically.
What's the easiest way for it to automatically generate (or quickly manually generate) the WSDL associated with each service call?
A: Web API is technology to create REST services and REST services don't use WSDL so there is no way for your service to generate one. WSDL 1.1 supported by MS and WCF even doesn't offer ability to describe REST services.
WSDL 2.0 or WADL offers REST service description but MS and WCF supports neither of them and these standards were not broader accepted and supported yet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Couple Obj C issues including an error So basically in this code I placed below there is a couple things I would like to accomplish. 1) In that first one I would like the Text Field to close after done is pressed, but it is not doing so. (Found that code on other forums). 2)On that first button when it is pressed down I would like it to send a time to be saved for when the button is released. 3) On release of that button I would like it to calculate the time between the two times along with some other calculations later.
Problem that I am mainly getting here is the error from the NSTimeInterval. It keeps telling me that NSTimeInterval is incompatiable with type NSTimeInterval. So a double is incompatible with a double??? (I have also tried it with NSTimeInterval *timePassed in the .h and just trying to set timePassed = to it and it doesn't work either. Similar error happens.
#import "MphViewController.h"
@implementation MphViewController
@synthesize speed, distance;
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
-(IBAction)triggerDown:(id)sender{
timeStart = [NSDate date];
}
-(IBAction)triggerUp:(id)sender{
NSInteger *dist;
NSString *display;
NSTimeInterval *timePassed = [timeStart timeIntervalSinceNow];
if ([distance.text length]== 0) {
display = @"Please enter a distance";
}
else{
dist = atoi(distance.text);
display = [[NSString alloc] initWithFormat:@"%d MPH",dist];
}
speed.text = display;
[display release];
}
Also if you have a chance to glance at the else statement. I'm not sure if that will work (seeing is after I enter a distance I still cant get rid of the numberpad). Id like to pass mph once it is calculated into that to be displayed on the screen. Very confused with how parsing is done on obj c. Anyways thanks for any and all help.
As for the textField part. My textField that it is assigned to is distance. Should that Bool be written differently to have distance in it or is that just the way it is supposed to be written?
A: You are denoting primitive types as pointers where they do not need to be. Remove the star (*) from the NSInteger and NSTimerIntervaldeclaration. The if check looks fine but instead of atoi just use:
dist = [distance.text integerValue];
Edit:
Notice a couple of memory management issues.
1 . Make sure you properly retain/release the date then later release it in dealloc.
-(IBAction)triggerDown:(id)sender{
[timeStart release];
timeStart = [[NSDate alloc] init];
}
2 . Your if statement will result in trying to release an NSString literal which likely will not crash but is incorrect memory management. Just use an autoreleased string and remove the [display release];
...
else{
dist = [distance.text integerValue];
display = [NSString stringWithFormat:@"%d MPH",dist];
}
speed.text = display;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Axis 2 Client not receiving a thrown exception from an Axis 2 Webservice An Axis 2 client (wsdl2java generated code) invoking an Axis 2 Webservice is not receiving a RuntimeException thrown from a Service. The invoked method is a void method.
The Axis 2 version I'm using for both client and server is 1.6.1.
When I run the following test it completes successfully and no Exception is received:
@Test
public void testMyService() throws RemoteException {
String target = "http://localhost:8080/services/MyService";
MyServiceStub myServiceStub = new MyServiceStub(target);
myServiceStub.doSomething();
}
MyService.java:
package com.afirme.webservice.service;
@Service
public class MyService {
public void doSomething() {
throw new IllegalArgumentException("Just testing!");
}
}
services.xml:
<serviceGroup>
<service name="MyService">
<description>
My Service
</description>
<messageReceivers>
<messageReceiver
mep="http://www.w3.org/2004/08/wsdl/in-only"
class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver"/>
<messageReceiver
mep="http://www.w3.org/2004/08/wsdl/in-out"
class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</messageReceivers>
<parameter name="ServiceObjectSupplier">org.apache.axis2.extensions.spring.receivers.SpringServletContextObjectSupplier</parameter>
<parameter name="SpringBeanName">myService</parameter>
</service>
</serviceGroup>
A: This operation is an in only one. So you won't receive any soap faults from that. If you want to throw faults your operation must be an in-out one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586417",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: using enums or static string variable in java got a question around which one is better to use. Java5 Enums or static string.
I always get the data in form of Strings.
So for example,
private static final String LOAD_DRUGS = "load drugs";
or use Java5 enums
public enum LoadType
{
LOAD_DRUGS("load drugs");
}
In my code, I always receive "load drugs" kind of strings. I use if else statements to see what to do next based on it. But I am tending to use java5 enums and use switch case, but I always have to get the enum based of the string value I get.
So what are the pro's and con's of both ways??
Thanks!!
A: This answer is probably overkill. Maybe there's a badge for that. Anyway, it could be useful in a situation in which you have a lot of enumeration values and have to deal with a Strings as being the means by which another system sends information to you. That is exactly what I have (something north of 50), so I used this construct so that I could generate a mapping just once of the Strings reported by the db and the enums I used internally, and then not think about it after -- toString and fromString do all the work:
package com.stevej;
import com.google.common.collect.HashBiMap;
public enum TestEnum {
ALPHA("Alpha"), BETA("Beta"), GAMMA("Gamma");
private static HashBiMap<TestEnum, String> stringMapping = HashBiMap
.create(TestEnum.values().length);
private String stringValue = null;
TestEnum(String stringValue) {
this.stringValue = stringValue;
}
String getStringValue() {
return this.stringValue;
}
@Override
public String toString() {
return stringMapping.get(this);
}
public static TestEnum fromString(String string) {
return stringMapping.inverse().get(string);
}
static {
for (TestEnum e : TestEnum.values()) {
stringMapping.put(e, e.getStringValue());
}
}
}
Here's a quick test to show the data switching back and forth:
package com.stevej;
public class StackOverflowMain {
public static void main(String[] args) {
System.out.println(">> " + TestEnum.ALPHA);
System.out.println(">> " + TestEnum.BETA);
System.out.println(">> " + TestEnum.GAMMA);
TestEnum a = TestEnum.fromString("Alpha");
TestEnum b = TestEnum.fromString("Beta");
TestEnum c = TestEnum.fromString("Gamma");
System.out.println(">> " + a);
System.out.println(">> " + b);
System.out.println(">> " + c);
}
}
The output shows the use of the mixed case values instead of the uppercase, showing my strings are being used:
>> Alpha
>> Beta
>> Gamma
>> Alpha
>> Beta
>> Gamma
Note that I am using the Google Guava library so I can take advantage of the BiMap.
A: you can try a simple substitution for turn the string into an enum
switch(MyEnum.valueOf(text.replace(' ', '_')) {
case load_strings:
You can use toUpperCase() if you want it in upper case.
You should do what you think is the simplest and clearest.
A: Generally you should use Enums to store a set of values that are related in some way. They all should have a similar "is a" relationship. It should not be used to simply store a set of constant strings that are not related.
Of course, if you have a switch statement over a set of string values then that suggests that those string values are related and should be grouped as an Enum and use enum's mechanism to use a switch.
The enum type's valueOf method will allow you to convert from a String to the enum type if the passed string is equal to the name value. If this is not the case, you could implement your own valueOf that uses a stored string field rather than the name. You could store the fields in a private static Map for the conversion.
A: Because enum is typed.
Static String is not typed.
public enum Something{
CAT("cat");
private String animal;
private Something(String animal){
this.animal = animal;
}
public String getAnimal(){
return this.animal;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: JQUERY: (selector).load(url id), loads every second click I wanted to not reload the page every click of a sub-gallery.
So I decided to .load the content in to the wrapper div of the page.
The content works and does change on first click without a refresh, but the second click does a reload and so on alternately..
I'm guessing the script doesn't know about the new content?
I used Jquery's .bind on the click event, the click event always fires without a page refresh. I tested this by commenting out the .load line and using a alert("wonga!");
It's the .load that causes the page refresh on the second click, not sure why though.
If anyone has any suggestions or advice about this, I will be most grateful.
$('#gallery_subgalleries a').bind('click', function() {
$('.content_loader').load("index.cfm?subgallery_id=" + $(this).attr('rel') + "&gallery_id=" + $(this).attr('gallery_id') + " " + ".content_loader");
return false;
});
The script executes at the bottom of the page:
<div class="content_loader">
<!--- page content --->
<div id="gallery_subgalleries">
<a href="" gallery_id="" rel="">sub gallery name</a>
</div>
<!--- page content --->
</div>
<script>is here</script>
I am unable to show the page source at this time..
Thanks for any help.
A: When you bring in new content, the new link element it contains won't fire the load() call. The reason for this is that the new link element didn't exist when you did the original bind().
There are two ways around this.
You can either rebind the new links everytime you do a load i.e. rerun the snippet you have above.
The other better way is to use event delegation, which uses another element to listen for the clicks and doesn't require any rebinding. It's also super neat, you would only have to make one change to your code:
$('#gallery_subgalleries a').live('click', function() {
$('.content_loader').load("index.cfm?subgallery_id=" + $(this).attr('rel') + "&gallery_id=" + $(this).attr('gallery_id') + " " + ".content_loader");
return false;
});
Note the change from bind to live.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to access the object I would like to access the the _news items in a loop. But don't know how to get this done.
My Game.m looks like
#import "Game.h"
@implementation Game
@synthesize homename = _homename;
@synthesize guestname = _guestname;
@synthesize date = _date;
@synthesize gametype = _gametype;
@synthesize news = _news;
@synthesize gameId = _gameId;
-(NSString*)description{
return [NSString stringWithFormat:@"%@ gegen %@ (%@)", self.homename, self.guestname, self.gametype];
}
@end
My Game.h looks like
#import <Foundation/Foundation.h>
#import <RestKit/RestKit.h>
#import "News.h"
@interface Game : NSObject {
NSString* _homename;
NSString* _guestname;
NSString* _date;
NSString* _gametype;
NSNumber* _gameId;
// News* news;
@public
NSArray* _news;
}
@property (nonatomic, retain) NSString* homename;
@property (nonatomic, retain) NSString* guestname;
@property (nonatomic, retain) NSString* date;
@property (nonatomic, retain) NSString* gametype;
//@property (nonatomic, retain) News* news;
@property (nonatomic, retain) NSArray* news;
@property (nonatomic, retain) NSNumber* gameId;
@end
My News.h looks like
#import <Foundation/Foundation.h>
#import <RestKit/RestKit.h>
@interface News : NSObject {
NSString* _minute;
NSString* _title;
NSString* _bodytext;
NSString* _player;
}
@property (nonatomic, retain) NSString* minute;
@property (nonatomic, retain) NSString* title;
@property (nonatomic, retain) NSString* bodytext;
@property (nonatomic, retain) NSString* player;
@end
My news.m looks like
#import "News.h"
@implementation News
@synthesize player = _player;
@synthesize title = _title;
@synthesize bodytext = _bodytext;
@synthesize minute = _minute;
@end
And the code where I want to access the variable looks like:
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
NSLog(@"Loaded statuses: %@", objects);
HeaderText.text = [NSString stringWithFormat:@"%@", objects ];
// for(News* n in _news) NSLog([n _bodytext]);
// for (id object in objects) {
// NSLog(@"News = %@", object );
// }
}
The NSLog with objects looks good for the game. The next thing is that I want to do something like (above is more pseudo code than real code because I don't know how to do it right):
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
NSLog(@"Loaded statuses: %@", objects);
HeaderText.text = [NSString stringWithFormat:@"%@", objects ];
// loop all
for (id object in objects) {
news = objects.news;
for (id mynews in news) {
NSLog(@"News minute = %@", news.minute );
NSLog(@"News title = %@", news.title );
NSLog(@"News bodytext = %@", news.bodytext );
NSLog(@"News player = %@", news.player );
}
}
}
How to do the getter/setter methods right (so that I can use it here)?
Sorry for the surely stupid question but I don't get the point with it.
A: Two things:
1stly, is the _news object a private variable, without having a property declaration (getters and setters for e.g.)? The '_variableName' format is usually used to denote private variables.
2ndly, if it is not a private variable, do all the items within the _news array belong to the same class?
If so, you can do a
for (NewsObject *theNewsObject in _news)
{
//code here
}
The for(id randomObject in array) is useful when you don't know what type of object is in the array or if the objects contained in the array are of different types.
Now, again, all the objects inside the NewsObject ought to be public properties that can be accessed by other classes (they should have getters and setters).
Hope this helps. :)
EDIT FOR UPDATED QUESTION
So, if I'm getting your question correctly, you have a Game object, which has an array of News object inside it.
So, in your Game.h
NSString* _homename;
NSString* _guestname;
NSString* _date;
NSString* _gametype;
NSNumber* _gameId;
NSArray * _newsObjects; //declare it as NSMutableArray if you need to mutate it
Now, where you declare your properties;
@property(nonatomic, retain)NSArray *newsObjects
Synthesize it like you normally would in the Game.m file
You are creating the getters/setters automatically by using the @synthesize directive. It creates the getters and setters for you.
Again, from your code, it looks like the NSArray of objects that are passed through the method
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects
consist of Game objects.
So, to access the News object from within the array of Game objects, import News.h and Game.h in the class where this method is being executed, and do the following:
- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects:(NSArray*)objects {
NSLog(@"Loaded statuses: %@", objects);
// loop all
for (Game *gameObject in objects) {
NSArray *newsObjectArray = [gameObject newsObjects] //or gameObject.newsObject
for (News *mynews in newsObjectArray) {
NSLog(@"News minute = %@", mynews.minute );
NSLog(@"News title = %@", mynews.title );
NSLog(@"News bodytext = %@", mynews.bodytext );
NSLog(@"News player = %@", mynews.player );
}
}
}
What I found in your code that there was code that was being executed which was not declared in any part of the example that you posted.
What the code above will do is it will look through the Game object array (called objects).
Then, for each gameObject within that array, it will loop through the array of newsObject for that gameObject.
Hope this helps. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to display a MapView and a StreetView simultaneously? I want to display a MapView that may be used to select a point to be displayed by StreetView in a separate area. I know that the API disallows multiple MapViews in a single process.
How can I cause StreetView to display in a different area than that which displays MapView?
I have been able to grab a static streetview without any problems, but I want to have dynamic StreetView and MapView.
aTdHvAaNnKcSe (THANKS in ADVANCE)
A: You can load 360 degree panoramic Google street-view in your WebView.
Try following activity in which both google-street-view and google-map can be navigated simultaneously in single Activity :
public class StreetViewActivity extends Activity {
private WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mappingWidgets();
}
private void mappingWidgets() {
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setSupportZoom(false);
// If you want to load it from assets (you can customize it if you want)
//Uri uri = Uri.parse("file:///android_asset/streetviewscript.html");
// If you want to load it directly
Uri uri = Uri.parse("https://google-developers.appspot.com/maps/documentation/javascript/examples/full/streetview-simple");
webView.loadUrl(uri.toString());
}
}
You can place this as static HTML page in assets folder of your application and then you can modify it's java-script according to your needs using Google street-view API.
Here I am posting sample streetviewscript.html that you can put in assets folder of your application and customize it according to your needs :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Street View Layer</title>
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script>
<script>
function initialize() {
var fenway = new google.maps.LatLng(42.345573,-71.098326);
var mapOptions = {
center: fenway,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById('map_canvas'), mapOptions);
var panoramaOptions = {
position: fenway,
pov: {
heading: 34,
pitch: 10,
zoom: 1
}
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'),panoramaOptions);
map.setStreetView(panorama);
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 800px; height: 800px"></div>
<div id="pano" style="position:absolute; left:810px; top: 8px; width: 800px; height: 800px;"></div>
</body>
</html>
Edit : For simultaneously navigating two street views, load following HTML from assets :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Google Maps JavaScript API v3 Example: Street View Events</title>
<STYLE type="text/css">
body, html { height:100%; padding:0; margin:0;}
#pano { float:left }
#pano1 { float:right }
</STYLE>
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var cafe = new google.maps.LatLng(37.869085,-122.254775);
var heading_value = 270;
var pitch_value = 0;
var zoom_value = 1;
function initialize() {
var panoramaOptions = {
position: cafe,
pov: {
heading: heading_value,
pitch: pitch_value,
zoom: zoom_value
},
visible: true
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById('pano'), panoramaOptions);
var panorama2 = new google.maps.StreetViewPanorama(document.getElementById('pano1'), panoramaOptions);
google.maps.event.addListener(panorama, 'pano_changed', function() {
var panoCell = document.getElementById('pano_cell');
panoCell.innerHTML = panorama.getPano();
panorama2.setPano(panorama.getPano());
});
google.maps.event.addListener(panorama, 'links_changed', function() {
var linksTable = document.getElementById('links_table');
while(linksTable.hasChildNodes()) {
linksTable.removeChild(linksTable.lastChild);
};
var links = panorama.getLinks();
panorama2.setLinks(panorama.getLinks());
for (var i in links) {
var row = document.createElement('tr');
linksTable.appendChild(row);
var labelCell = document.createElement('td');
labelCell.innerHTML = '<b>Link: ' + i + '</b>';
var valueCell = document.createElement('td');
valueCell.innerHTML = links[i].description;
linksTable.appendChild(labelCell);
linksTable.appendChild(valueCell);
}
});
google.maps.event.addListener(panorama, 'position_changed', function() {
var positionCell = document.getElementById('position_cell');
positionCell.firstChild.nodeValue = panorama.getPosition();
panorama2.setPosition(panorama.getPosition());
});
google.maps.event.addListener(panorama, 'pov_changed', function() {
var headingCell = document.getElementById('heading_cell');
var pitchCell = document.getElementById('pitch_cell');
headingCell.firstChild.nodeValue = panorama.getPov().heading;
panorama2.setPov(panorama.getPov());
pitchCell.firstChild.nodeValue = panorama.getPov().pitch;
});
}
</script>
</head>
<body onload="initialize()">
<div style="width:100%; height :100%; background-color:Lime;">
<div id="pano" style="width:50%; height:100%; background-color:Blue;">
</div>
<div id="pano1" style="width:50%; height:100%; background-color:Gray;">
</div>
</div>
<div id="panoInfo" style="width: 425px; height: 240 px;float:left; display: none;">
<table>
<tr>
<td><b>Position</b></td><td id="position_cell"> </td>
</tr>
<tr>
<td><b>POV Heading</b></td><td id="heading_cell">270</td>
</tr>
<tr>
<td><b>POV Pitch</b></td><td id="pitch_cell">0.0</td>
</tr>
<tr>
<td><b>Pano ID</b></td><td id="pano_cell"> </td>
</tr>
<table id="links_table"></table>
</table>
</div>
</body>
</html>
A:
How can I cause StreetView to display in a different area than that which displays MapView?
Street View is only available on the device as its own activity (from its own application) and therefore cannot be displayed alongside any of your own widgets.
A: On Android have a look at the sample Street View Panorama and Map available at https://developers.google.com/maps/documentation/android/code-samples. But i am not sure if it will also do for custom street views.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Smarty 3 and spl_autoload_register I know I need to use spl_autoload_register with Smarty 3. I am registering my autoload function after smarty initializes. But smarty is trying to use my own autoload function instead of the smartyAutoload defined function. Causing an error because it obviously cant find the smarty files using my autoload. Here is the code with everything else cut out to show how it is layed out currently.
I'm sure it is just an order placement issue or something.
<?php
class application {
// include smarty
require_once(SMARTY_DIR.'Smarty.class.php');
// init controller class which initializes smarty
$controller = new Controller();
}
function autoLoader($class) {
// determine what type class it is and call from that directory
$dir = strtolower(strstr($class, '_', true));
$name = substr( strtolower( strstr($class, '_') ), 1 );
switch($dir) {
case 'component':
break;
default:
require_once(LIB_PATH.DS.$name.'.class.php');
break;
}
}
spl_autoload_register("autoLoader");
?>
A: You can make your autoloader compatbile (that's what spl_autoload_register is actually for) by only require a file if it's one of your classes.
You can do this by checking the class name against a namespace or a whitelist or with is_file (store the whitelist in the file-system):
default:
$path = LIB_PATH.DS.$name.'.class.php';
if (is_file($path)) require_once($path);
break;
A: I don't know if it's relevant to you, but I tracked my problem down to a file called smarty_internal_templatecompilerbase.php, function callTagCompiler().
My code (inside a *.tpl file) calls a smarty plugin function. My plugin-function is called Load_PO, meaning that the Smarty engine then searches for a class named Smarty_Internal_Compile_Load_PO.
Of course, neither the Smarty auto-loader, nor my custom auto-loader finds this template. The problem, in fact, was that my auto-loader errors when a file is not found.
The problem can be resolved in 2 ways:
*
*Change my auto-loader to ignore searches if (substr($class_name,0,24) = 'Smarty_Internal_Compile_')
*Modify file smarty_internal_templatecompilerbase.php, and change function callTagCompiler() as shown below
Change the code
class_exists ($class_name)
To
class_exists ($class_name, false)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: SQL Grouping, combining 2 rows to one cell I have some sql which is grouping data to summarize it.
Its basically a list of locations, items and quantities.
SELECT ItemCode, SUM(Qty) AS Qty
FROM Putaway
GROUP BY ItemCode
Which is working as expected, giving a summary of the results.
ItemCode - Qty
AAAA - 1
BBBB - 2
CCCC - 3
But I have been asked to give a list of locations for each of the items as well.
So basically I want to Generate the results to be like:
ItemCode - Qty - Locations
AAAA - 1 - A1
BBBB - 2 - B1, B2
CCCC - 3 - B5, B6, B7
If I do the obvious - and just Add [Location] to the SELECT and Group By
Then its giving me 2 rows for BBBB, 3 for CCCC etc. (Exactly as it should be, but not how I want it)
So, since there are multiple rows for each item in the table - how can I summarize it and combine the rows [Location]'s field into 1 field.
I am hoping for a simple SQL solution to avoid me having to write some sort of webpage to do it.
I hope this makes sense.
A: Provided that you're using SQL Server 2005 or newer, you can use FOR XML to do this bit for you:
create table Putaway (
ItemCode varchar(4),
Qty int,
Location varchar(3)
)
insert into Putaway
values ('AAAA', 1, 'A1'),
('BBBB', 1, 'B1'),
('BBBB', 1, 'B2'),
('CCCC', 1, 'B5'),
('CCCC', 1, 'B6'),
('CCCC', 1, 'B7')
SELECT ItemCode, SUM(Qty) AS Qty,
( SELECT x.Location + ', '
FROM Putaway x
WHERE p.ItemCode = x.ItemCode
ORDER BY x.Location
FOR XML PATH ('')
) as Locations
FROM Putaway p
GROUP BY ItemCode
Unfortunately, this results in an extra comma at the end, but you can easily trim that out in your GUI or by making it a sub-select.
A: SELECT p1.ItemCode, SUM(p1.Qty) AS Qty, (SELECT p2.location + ',' as 'data()' from putaway as p2 WHERE p1.itemcode LIKE p2.itemcode FOR xml path('')) AS Locations
FROM Putaway as p1
GROUP BY p1.itemcode;
A: This will not have extra comma at the end
SELECT ItemCode, SUM(Qty) AS Qty,
Replace( ( SELECT x.Location as [data()]
FROM Putaway x
WHERE p.ItemCode = x.ItemCode
ORDER BY x.Location
FOR XML PATH ('')) , ' ', ',') as Locations
FROM Putaway p
GROUP BY ItemCode
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to remove SVN history from java files? I have various projects that had files with SVN history in them. I recently moved those projects to a Mercurial repository so now that history within the file is useless. Is there a way to remove those which is not by hand?
Here's an example:
/*
* $Rev:x$
* $LastChangedDate:x$
* $LastChangedBy:x$
*/
Where x is a value in the files. I assume some sort of regex would help. Any idea?
Edit:
This is the working answer:
<target name="remove-svn-history">
<replaceregexp byline="false" match="\A/\*.*?\*/" replace="">
<fileset dir="src" includes="**/*.java"/>
</replaceregexp>
</target>
A: Assuming that's at the beginning of the file, you could match it with the following regex:
\A/\*.*?\*/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C# Pluggable Architecture, Consideration for a dissertation I am beginning a Software Engineering dissertation in which I have a dental practice as a client who I will be developing software for. The client has issues of requirements and the current software is constantly upgraded through patches.
Im trying to argue the idea that the underlying requirements are bad, and to develop a new piece of software that is able to mould to meet changes. I also want the software to be generic so it could be deployed to various dental practices who could customize it to toggle particular features on.
The idea I have is to consider each feature as a plugin. This way the application should simply host the enabled plugins and they could be toggled on/off, and upgraded invidually without the need of a hard change to the application.
I would appreciate if you could help me with the following questions I have:
Is this a good approach?
Is there a .NET framework already that caters for this well?
Are there any significant problems I should be aware of?
Sorry for the big intro guys, and I appreciate any response I get at all.
Many thanks
Mike
A: The Managed Extensibility Framework is built into .NET 4.0, and is available from CodePlex as a dll for earlier versions.
A: I know MEF as MS recomended framework for pluggable aplications, but maybe some IoC framework can helps you also. Recommended by MS is Unity (developed under Microsoft Patterns and Praciticies) unity on codeplex
A: I have used HTML, WinForms, ASPX, WPF, WCF, Web service, Silverlight, PRISM, MEF for applications in the last few years and my personal choices (given no restraints on a new project) would be:
*
*WPF or Silverlight (Update: I would swing more towards WPF, now that Silverlight is no longer broadly supported)
*WCF services
*A modular framework like PRISM (which now includes MEF)
PRISM is the biggest gain as the components you build really are loosely coupled and modules can be developed independently without developers breaking each other's code.
A: For something specific like a dental practice hopefully you will be able to build a layer on top of general purpose plugin frameworks.
The plug-ins, and their container, should be specialized for the domain. The best way to identify what that that specialization should be is to enumerate several plug-ins that would be appropriate for this software, recognize what is common amongst them and abstract/represent them in your framework.
I know this is not very concrete but hopefully somewhat useful.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Cannot get FlexiGrid for CodeIgniter to work I'm trying to use FlexiGrid plugin with CodeIgniter, but when the page displays the grid shows, but there are no records, and there is a little message saying that you should wait while it's processing, which never goes away...
I'm using one of my own databases, so I modified parts of the code to use fields in my database (id, username, email).
Flexigrid controller:
<?php
class Flexigrid extends CI_Controller
{
/* function Flexigrid ()
{
parent::Controller();
$this->load->helper('flexigrid');
}
*/
function __construct()
{
parent::__construct();
$this->load->helper('flexigrid');
}
function index()
{
//ver lib
/*
* 0 - display name
* 1 - width
* 2 - sortable
* 3 - align
* 4 - searchable (2 -> yes and default, 1 -> yes, 0 -> no.)
*/
$colModel['id'] = array('id', 40, TRUE, 'center', 2);
$colModel['username'] = array('username', 40, TRUE, 'center', 0);
$colModel['email'] = array('email', 180, TRUE, 'left', 1);
/*
* Aditional Parameters
*/
$gridParams = array(
'width' => 'auto',
'height' => 400,
'rp' => 15,
'rpOptions' => '[10,15,20,25,40]',
'pagestat' => 'Displaying: {from} to {to} of {total} items.',
'blockOpacity' => 0.5,
'title' => 'Hello',
'showTableToggleBtn' => true
);
/*
* 0 - display name
* 1 - bclass
* 2 - onpress
*/
$buttons[] = array('Delete', 'delete', 'test');
$buttons[] = array('separator');
$buttons[] = array('Select All', 'add', 'test');
$buttons[] = array('DeSelect All', 'delete', 'test');
$buttons[] = array('separator');
//Build js
//View helpers/flexigrid_helper.php for more information about the params on this function
$grid_js = build_grid_js('flex1', site_url("/ajax"), $colModel, 'id', 'asc', $gridParams, $buttons);
$data['js_grid'] = $grid_js;
$data['version'] = "0.36";
$data['download_file'] = "Flexigrid_CI_v0.36.rar";
$this->load->view('flexigrid', $data);
}
function example()
{
$data['version'] = "0.36";
$data['download_file'] = "Flexigrid_CI_v0.36.rar";
$this->load->view('example', $data);
}
}
?>
Flexigrid view (only changes in head to correct paths to css and js):
<head>
<title>Flexigrid Implemented in CodeIgniter</title>
<link href="<?=$this->config->item('base_url');?>assets/flexigrid/css/style.css" rel="stylesheet" type="text/css"/>
<link href="<?=$this->config->item('base_url');?>assets/flexigrid/css/flexigrid.css" rel="stylesheet"
type="text/css"/>
<script type="text/javascript" src="<?=base_url()?>assets/scripts/jquery-1.5.1.min.js"></script>
<script type="text/javascript"
src="<?=$this->config->item('base_url');?>assets/flexigrid/js/jquery.pack.js"></script>
<script type="text/javascript"
src="<?=$this->config->item('base_url');?>assets/flexigrid/js/flexigrid.pack.js"></script>
</head>
ajax_model:
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
* Eye View Design CMS module Ajax Model
*
* PHP version 5
*
* @category CodeIgniter
* @package EVD CMS
* @author Frederico Carvalho
* @copyright 2008 Mentes 100Limites
* @version 0.1
*/
class Ajax_model extends CI_Model
{
/**
* Instanciar o CI
*/
/* public function Ajax_model()
{
parent::Model();
$this->CI =& get_instance();
}*/
function __construct()
{
parent::__construct();
$this->CI =& get_instance();
}
public function get_countries()
{
//Select table name
$table_name = "users";
//Build contents query
$this->db->select('id,username,email')->from($table_name);
$this->CI->flexigrid->build_query();
//Get contents
$return['records'] = $this->db->get();
//Build count query
$this->db->select('count(id) as record_count')->from($table_name);
$this->CI->flexigrid->build_query(FALSE);
$record_count = $this->db->get();
$row = $record_count->row();
//Get Record Count
$return['record_count'] = $row->record_count;
//Return all
return $return;
}
/**
* Remove country
* @param int country id
* @return boolean
*/
public function delete_country($country_id)
{
$delete_country = $this->db->query('DELETE FROM country WHERE id=' . $country_id);
return TRUE;
}
}
?>
Ajax controller (had to use the non-JSon extension code, so the other part is commented out, according to the instructions on the FlexiGrid web site. Also, I was a bit puzzled when modifying the $recorde_item array, because the example had id twice at the beginning. I thought this must be a mistake, but tried adding a second id row too, didn't help either):
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Ajax extends CI_Controller
{
/* function Ajax ()
{
parent::Controller();
$this->load->model('ajax_model');
$this->load->library('flexigrid');
}*/
function __construct()
{
parent::__construct();
$this->load->model('ajax_model');
$this->load->library('flexigrid');
}
function index()
{
//List of all fields that can be sortable. This is Optional.
//This prevents that a user sorts by a column that we dont want him to access, or that doesnt exist, preventing errors.
$valid_fields = array('id', 'username', 'email');
$this->flexigrid->validate_post('id', 'asc', $valid_fields);
//Get "countries"
$records = $this->ajax_model->get_countries();
//Init json build
if ($this->flexigrid->init_json_build($records['record_count'])) {
//Add records
foreach ($records['records']->result() as $row)
{
$record_item = array($row->id,
$row->username,
$row->email
);
$this->flexigrid->json_add_item($record_item);
}
//Last item added, close up.
$this->flexigrid->json_add_item();
}
//Print please
$this->output->set_header($this->config->item('json_header'));
$this->output->set_output($this->flexigrid->json_build);
/*$this->output->set_header($this->config->item('json_header'));*/
/*
* Json build WITH json_encode. If you do not have this function please read
* http://flexigrid.eyeviewdesign.com/index.php/flexigrid/example#s3 to know how to use the alternative
*/
/* foreach ($records['records']->result() as $row)
{
$record_items[] = array($row->id,
$row->id,
$row->iso,
$row->name,
'<span style=\'color:#ff4400\'>' . addslashes($row->printable_name) . '</span>',
$row->iso3,
$row->numcode,
'<a href=\'#\'><img border=\'0\' src=\'' . $this->config->item('base_url') . 'public/images/close.png\'></a> '
);
}
//Print please
$this->output->set_output($this->flexigrid->json_build($records['record_count'], $record_items));*/
}
//Delete Country
function deletec()
{
$countries_ids_post_array = split(",", $this->input->post('items'));
foreach ($countries_ids_post_array as $index => $country_id)
if (is_numeric($country_id) && $country_id > 1)
$this->ajax_model->delete_country($country_id);
$error = "Selected countries (id's: " . $this->input->post('items') . ") deleted with success";
$this->output->set_header($this->config->item('ajax_header'));
$this->output->set_output($error);
}
}
?>
Well, that should be it. I also had to change the "extends Controller" etc to "extends CI_Controller" since the code in the example seems to be for an older version of CodeIgniter.
But again, it doesn't work. I only get an empty grid. The database table does definitely have the fields I mentioned. I can't find any typos myself at least. It's also my default database in CodeIgniter, and I have no trouble connecting to it in other cases. And it is autoloaded, so I'm guessing that should work automatically, right? I shouldn't have to connect to the database manually here, since it uses the $db variable...
Any ideas then why it isn't working?
A: Not sure if you still need this help or not, and i'm not sure i'm the best to teach as i'm still new to PHP and don't know the most "secure" practices, however, the following is what I was able to do with flexgrid and may help future users, or spark a more "secure" idea from a more advanced user. Without further adieu, my solution:
In the javasript grabbing the and using the json is EASY, check it:
keep in mind i tried to keep this very generic & removed all possible personal values ... it think
var flexset = {
url: 'https://www.yourSite.com/index.php/yourController/yourDBFunc',
dataType: 'json',
colModel : [
{display: 'A Column', name: 'a_col', width: 80, sortable: true, align: 'center'}, // where name=the name of the column in the database
{display: 'Another Column', name: 'another_col', width: 110, sortable: false, align: 'center'}
],
buttons : [ {name: "aButton", onpress: someFunction} ],
searchitems : [
{display: 'A Column (some more info if you want)', name: 'a_col', isdefault: true}, // where name=the name of the column in the database
{display: 'Quantity', name: 'charge'}
],
sortname: "a_col", // the name of the column in the database
sortorder: "desc", // desc or asc
usepager: true,
title: 'Some grid title',
useRp: true,
rp: 20,
showTableToggleBtn: true,
resizable: true,
width: "100%",
height: "400px",
singleSelect: true,
onSuccess: function() {
// do some work each time grid is loaded/refreshed, for instance, manipulate certain cells to have specific bgcolor based on content
console.log('onSuccess:\t\t', this, gridData);
console.log('Your inner table:\t', gridData.bDiv);
// you can get specific cells by searching from an attribute called "abbr" on each cell,
// it will = the same "name" you used when setting up the column that cell belongs too
console.log($(gridData.bDiv).find("td[abbr=transactionType]"));
}
}
$("#yourGrid").flexigrid(flexset);
In php, it gets a little harder as i use 2 functions, one public and one private. The private one actually makes the DB query while the public one is accessed by flexigrid to get the resulting data as json_encoded.
The Public Function
public function getJSONData() {
// to ensure its being pulled from a logged user,
// i always set at least one "where" var by hand,
// in this case, i am going to set the where to
// look for all rows containing this user's id,
// so i quickly grab the session var for the current id
$userID = $this->session->userdata('userID');
// should easily be greater than false in this case unless maybe it's id is 0?
// in any case, this is not the exact var i check, but same exact concept and my stuff works
if ($userID) {
// Return JSON data
$data = array();
// first i check post for a page number and go ahead and set the page
// this will be usful later in setting up the page query
$data['page'] = floatval(($this->input->post('page', TRUE))) ? floatval($this->input->post('page', TRUE)) : 1;
$value = array(
'select' => '*',
'where' => array( 'ownerID' => $userID ), // here you see my preset where clause, not absolutly necesary but useful, with some slight manipulation, you could easily redo this how you like
'orderBy' => array( 'a_col' => 'desc' ) // here i set a default orderby in case it's not provided by the post
);
// Get all other POSSIBLE posted data and save it to $value for passing to private func
if ($this->input->post('qtype', TRUE) && $this->input->post('query', TRUE)) $value['where'][$this->input->post('qtype', TRUE)] = $this->input->post('query', TRUE);
if ($this->input->post('sortname', TRUE) && $this->input->post('sortorder', TRUE)) $value['orderBy'] = array( $this->input->post('sortname', TRUE) => $this->input->post('sortorder', TRUE) );
if ($this->input->post('rp', TRUE)) $value['limit'] = array( $this->input->post('rp', TRUE) => (($data['page'] - 1) * floatval($this->input->post('rp', TRUE))) );
// call private function to get the desired data from db
$results = $this->getDBData($value);
// set return data's total count
$data['total'] = $results["total"]["absolute"];
// now we clearly define our "ROWS" for the return data to display in our final grid output
$data['rows'] = array();
foreach($results["rows"] as $k => $v) {
$data['rows'][] = array(
"id" => $v["id"],
"cell" => array( // keep in mind the order of these result here need match the order of the cols you set in the flexset options
$v["a_col"],
$v["another_col"]
)
);
};
// finally, json encode the data to be returned
$data = json_encode($data);
echo($data); // and echo the data to our ajax caller
};
}
The Private Funtion should be pretty self-explanitory
private function getDBData($val) {
$data = array( 'options'=>array(), 'rows'=>array(), 'total'=>array( 'absolute'=>0, 'offset'=>0 ) );
if (array_key_exists("from", $val)) {
$select = (array_key_exists("select", $val)) ? $val["select"] : "*";
$from = $val["from"]; // cannot be changed
$where = array(); // (col => value)
$orderBy = array(); // (name => direction)
$limit = array(); // "totalLimit" or (start => offset)
$limitType = "array";
$total = 0;
if (array_key_exists("where", $val)) if (gettype($val["where"]) === "array") $where = $val["where"];
if (array_key_exists("orderBy", $val)) if (gettype($val["orderBy"]) === "array") $orderBy = $val["orderBy"];
if (array_key_exists("limit", $val)) {
if (gettype($val["limit"]) === "array" || gettype($val["limit"]) === "integer" || gettype($val["limit"]) === "string") {
$limit = $val["limit"];
$limitType = gettype($val["limit"]);
};
};
$options = array( 'select'=>$select, 'from'=>$from, 'where'=>$where, 'orderBy'=>$orderBy, 'limit'=>$limit, 'limitType'=>$limitType );
$this->db->select($select);
$this->db->from($from);
if (count($where) > 0) $this->db->where($where);
if (count($orderBy) > 0) {
foreach ($orderBy as $k => $v) {
$this->db->order_by($k, $v);
};
};
if (gettype($limit) === "array") {
foreach ($limit as $k => $v) {
$this->db->limit($k, $v);
};
}
elseif (gettype($limit) === "integer" || gettype($limit) === "string") {
$this->db->limit($limit);
};
$records = $this->db->get();
$results = $records->result_array();
if (count($where) > 0) {
$total = $this->db->get_where($from, $where)->num_rows;
}
else {
$total = $this->db->get($from)->num_rows;
};
$data["options"] = $options;
$data["rows"] = $results;
$data["total"]["absolute"] = $total;
$data["total"]["offset"] = $records->num_rows;
};
return($data);
}
A: I Implemented Flexigrid with Codeigniter 2.1.0. You can download the code from my blog. Flexigrid in Codeigniter 2.1.0 and you can check the tutorial at Flexigrid Tutorial
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to link two or more projects in Eclipse? I am trying to develop my application in different Eclipse Java projects where each will contain a certain feature. Then I want to combine them in one complete Java project.
However, I have a problem when linking the sources.
The sub-projects can correctly refer to parent-project classes but some of the source files that are accessed by the parent projects cannot be identified in the sub-projects.
I have a workspace/ParentProject/src/main/resources/file, where in the ParentProject I am accessing with "src\main\resources\" from within Java.
However, at runtime the ChildProject throws an exception that they cannot access the file : 'file:/E:/Eclipse%20workspace/ChildProject/src/main/resources/file'
So, when using a method of the ParentProject from the ChildProject, the classpath is somewhat transfered to the ChildProject. My question is how to resolve this.
I hope I made it clear what the problem is and will be really appreciative for any help.
Regards,
Petar
Btw: It is explained there How to link project in eclipse but I still have the error, that the child project cannot access resources accessed by the parent project.
A: Right click the Parent project and click properties. Then click Java Build Path on the left hand side. Next click the projects tab. Make sure the Child project is selected as a required project, if it is not Add the Child project.
You should also do this for the Parent Project.
A: Although I am not entirely sure what you need to do, it sounds to me that you are trying to create circular dependencies, which is an anti-pattern. You want to avoid creating dependencies where project a depends on project b, but project b also depends on project a. If you provide more details on your use case and what you are trying to create I will be happy to provide some guidance as to how you could structure your dependencies.
Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can we create SSMS 2008 R2 addin using Visual Studio 2010 I tried couple of times to create a SSMS 2008 R2 addin in VS2010, following below block but always I am unsuccessful. Any inputs?
http://blogs.microsoft.co.il/blogs/shair/archive/2008/07/28/how-to-create-sql-server-management-studio-addin.aspx
Tnx.
A: Here is your answer and I can guarantee it is working
http://connectionbuttons.codeplex.com/discussions/351805#post834896
see my comment on compiling in VS2008 and not in VS 2010..that shldn't be a problem logically but not sure y it is a problem
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586457",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ruby on Rails: Update to a gem clobbering my model's pre-existing attribute, options? A gem I've been using adds methods to models. It recently updated its method names such that one of the method names is now the same as one of my model's pre-existing database attributes.
Are there any workarounds to this problem other than renaming the column in my database and updating all of my code if I wish to stay up-to-date with the gem?
In case it is helpful, to make this more concrete, the gem is PaperTrail, which adds version tracking to models. My model had a pre-existing attribute in the database called version_name, which the latest version of PaperTrail just added as a class_attribute version_name that is used by PaperTrail to define the name of another method.
A: Not that familiar with PaperTrail (though I've been meaning to look into it). Assuming PaperTrail doesn't have a config option to change the name of *version_name*, you could probably get around it this way in your model:
class Thingy
def version_name_attr
attributes['version_name']
end
def version_name_attr=(val)
attributes['version_name'] = val
end
end
Just use *version_name_attr* whenever you want to access your attribute, and *verson_name* when you want the PaperTrail method.
Something like this is a bit cleaner, but might break things if PaperTrail uses *version_name* internally.
class Thingy
alias_method :paper_trail_version_name, :version_name
def version_name
attributes['version_name']
end
end
In this case, use *paper_trail_version_name* when you want the PaperTrail method. Access to your attribute would remain as you expect it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: System colour for inactive selected items in a listview? Is there any system colour that define the background of a listview item when the control has no focus and the selection is not hidden? I'm not able to find it if so.
EDIT: I think it is the one listed in .Net as MenuBar (or ControlFace, or Control), but it would be nice if someone could confirm it.
A: I have always used the SystemColors.Control color for that and it's never not matched.
If using VisualStyles, you can try rendering it yourself:
var vsr = new VisualStyleRenderer(
VisualStyleElement.ListView.Item.SelectedNotFocus);
vsr.DrawBackground(e.Graphics, rect);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586465",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I handle forms authentication timeout exceptions in ASP.NET? If the session has expired and the user clicks on a link to another webform, the asp.net authentication automatically redirect the user to the login page.
However, there are cases when the user does not click on links to other webforms. For example: edit link in gridviews, when using AutoCompleteExtender with textboxes and the application attempts to get the information, and basically, in every case when a postback is done and the event is not automatically handled by the asp.net authentication.
What is the best way to handle these exceptions?
UPDATE: I have just modified the question title: forms authentication timeout, instead of the initial session timeout. Thanks for making me aware of this difference.
UPDATE: I have just created a new question with the specific problem I am facing: How to handle exception due to expired authentication ticket using UpdatePanel?. Surprisingly, I have not found much information about it. I would really appreciate your help.
A: This is why many systems include timers on the page to give approximate timeout times. This is tough with interactive pages. You really need to hook ajax functions and look at the return status code, which is a bit difficult.
One alternative is to use code based on the following which runs early in the page lifecycle and perform an ajax redirect to a login page. Otherwise you are stuck trying to intercept the return code from ajax and in asp.net where the ajax is done 'for you' (ie not a more manual method like jQuery) you lose this ease of detection.
http://www.eggheadcafe.com/tutorials/aspnet/7262426f-3c65-4c90-b49c-106470f1d22a/build-an-aspnet-session-timeout-redirect-control.aspx
for a quick hack you can try it directly in pre_init
http://forums.asp.net/t/1193501.aspx
Edit
what is wanted are for forms auth timeouts, not session timeouts. Forms auth timeouts operate on a different scale than session timeouts. Session timeouts update with every request. Forms auth tickets aren't actually updated until half of the time goes by. So if you have timeouts set to an hour and send in one request 25 minutes into it, the session is reset to an hour timeout, the forms auth ticket isnt touched and expires in 35 minutes! To work around this, sync up the session timeout and the forms auth ticket. This way you can still just check session timeouts. If you don't like this then still - do the below and sync up the timeouts and then parse the auth ticket and read its timeout. You can do that using FormsAuthentication.Decrypt - see:
Read form authentication cookie from asp.net code behind
Note that this code requires that upon login you set some session value - in this case its "UniqueUserId". Also change the login page path below to fit yours.
protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
//Only access session state if it is available
if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
{
//If we are authenticated AND we dont have a session here.. redirect to login page.
HttpCookie authenticationCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
if (authenticationCookie != null)
{
FormsAuthenticationTicket authenticationTicket = FormsAuthentication.Decrypt(authenticationCookie.Value);
if (!authenticationTicket.Expired)
{
if (Session["UniqueUserId"] == null)
{
//This means for some reason the session expired before the authentication ticket. Force a login.
FormsAuthentication.SignOut();
Response.Redirect("Login.aspx", true);
return;
}
}
}
}
}
A: If you're using Forms Authentication, the user will be redirected to the login page when the Forms Authentication ticket expires, which is not the same as the Session expiring.
You could consider increasing the Forms Authentication timeout if appropriate. Even to the extent of using a persistent cookie. But if it does expire, there's no real alternative to redirecting to the login page - anything else would be insecure.
One way to deal with Session timeouts is to use Session as a cache - and persist anything important to a backing store such as a database. Then check before accessing anything in Session and refresh if necessary:
MyType MyObject
{
get
{
MyType myObject = Session["MySessionKey"] as MyType
if (myObject == null)
{
myObject = ... get data from a backing store
Session["MySessionKey"] = myObject;
}
return myObject;
}
set
{
Session["MySessionKey"] = value;
... and persist it to backing store if appropriate
}
}
A: If you're using a master page or a base page, I would add some logic to one of the events in the page lifecycle to check whether the session is new:
protected void Page_Load(object sender, EventArgs e)
{
if (Session.IsNewSession)
{
//do whatever you need to do
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: jQuery Address plugin - How to get link clicked on in $.address.change() I am trying to use the Address plugin from http://www.asual.com/jquery/address/ and I really need to be able to access the link or object that was clicked on that triggers the $.address.change function.
So basically, I have a link that looks like this:
<a href="#" class="active" rel="address:/show-my-activity">Activity</a>
And then I have the $.address.change function that looks like this:
<script language="javascript">
$.address.internalChange(function (e) {
// this is where I need to get the obj of what was clicked to trigger it
// find out what the e.value is, and do the ajax needed
});
</script>
I have already looped through all the properties of "e" but I can't find anything that references me back to the object that was clicked. Here is what comes back from the "e" variable...
undefinedtype value :change
timeStamp value :1317227369056
jQuery1317227368799 value :true
value value :/show-my-activity
path value :/show-my-activity
pathNames value :show-my-activity
parameterNames value :
parameters value :[object Object]
queryString value :
result value :undefined
target value :[object Object]
currentTarget value :[object Object]
handler value :function (e) {
var str;
var obj = e;
for (prop in obj) {
str += prop + " value :" + obj[prop] + "\n";
}
alert(str);
if (e.value === "/showMyActivity") {
}
}
data value :undefined
handleObj value :[object Object]
preventDefault value :function () {
this.isDefaultPrevented = Z;
var a = this.originalEvent;
if (a) {
a.preventDefault && a.preventDefault();
a.returnValue = false;
}
}
stopPropagation value :function () {
this.isPropagationStopped = Z;
var a = this.originalEvent;
if (a) {
a.stopPropagation && a.stopPropagation();
a.cancelBubble = true;
}
}
stopImmediatePropagation value :function () {
this.isImmediatePropagationStopped = Z;
this.stopPropagation();
}
isDefaultPrevented value :function Y() {
return false;
}
isPropagationStopped value :function Y() {
return false;
}
isImmediatePropagationStopped value :function Y() {
return false;
}
Any help would be greatly appreciated.
A: Looking at the documentation here http://www.asual.com/jquery/address/docs/
You can do this in your link's click event.
$('a').click(function() {
$.address.value($(this).attr('href'));
});
Then grab it with event.value.
Edit: I updated the above solution with what I think might be helpful. Alternatively you can have a global variable that you assign your object to within its click event. Then you can use that variable within your other function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Doesn't IQueryable.Expression = Expression.Constant(this); cause an infinite loop? Expression trees represent code in a tree-like data structure, where each node is an expression. In Linq they are used by linq providers to convert them into native language of a target process.
I know very little of expression trees, but I've been reading the following code where author uses Expression.Constant(this) to describe the initial query. Thus according to author Expression.Constant(this) should enable provider to retrieve the initial sequence of elements for someQuery.
But to my understanding this should instead cause an infinite loop, since expression tree in someQuery.Expression is describing someQuery object and not the details of the query itself ( or to put it differently, if target platform is SQL DB, Expression.Constant(this) doesn't describe in non-sql terms which rows or tables a query should retrieve from a DB ). And thus when provider looks into someQuery.Expression, it will only find description D of someQuery object.And if it further inspects the details of D.Expression property, it again finds the description of someQuery object and so on – thus infinite loop:
public class Query<T> : IQueryable<T>...
{
QueryProvider provider;
Expression expression;
public Query(QueryProvider provider) {
this.provider = provider;
this.expression = Expression.Constant(this);
}
...
}
Query<string> someQuery = new Query<string>();
thank you
A: I'd expect the provider to have knowledge of the query type and know that when it hit a constant expression of type Query<T>, it had hit a leaf, effectively. Sooner or later, the provider has to get to something describing "the whole table" or an equivalent. Of course the Query<T> would need the information about which table etc, but in a full example I'd expect it to have that information.
(Out of interest, am I the author in question? I wrote something very similar in C# in Depth...)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: android: SQLite query with between condition problem I have a table with schema like this:
db.execSQL("CREATE TABLE TBL_REMINDERS (" //
+ "FLD_YEAR INTEGER, " //
+ "FLD_MON INTEGER, " //
+ "FLD_DATE INTEGER, " //
+ "FLD_HOUR INTEGER, " //
+ "FLD_MIN INTEGER, " //
+ "FLD_EVENT TEXT" //
+ ")" //
where the FLD_MON field is in range [1,12], and FLD_DATE [1,31], FLD_HOUR [0,23], FLD_MIN [0,59]
and a rawQuery against the table as below returns no result set:
public List<Reminder> getRemindersBetween(int y1, int m1, int d1, int h1, int min1, int y2, int m2, int d2, int h2,
int min2) {
String sql = "SELECT FLD_YEAR, FLD_MON, FLD_DATE, FLD_HOUR, FLD_MIN, FLD_EVENT FROM TBL_REMINDERS "//
+ "WHERE (100000000 * FLD_YEAR + 1000000 * FLD_MON + 10000 * FLD_DATE + 100 * FLD_HOUR + FLD_MIN BETWEEN ? AND ?) " //
+ "ORDER BY FLD_YEAR, FLD_MON, FLD_DATE, FLD_HOUR, FLD_MIN, FLD_EVENT ";
SQLiteDatabase db = null;
Cursor cur = null;
try {
db = new CalendarDBOpenHelper(context).getReadableDatabase();
cur = db.rawQuery(sql, new String[] { "" + (100000000 * y1 + 1000000 * m1 + 10000 * d1 + 100 * h1 + min1),//
"" + (100000000 * y2 + 1000000 * m2 + 10000 * d2 + 100 * h2 + min2 - 1) //
});
List<Reminder> list = new ArrayList<Reminder>();
while (cur.moveToNext()) {
int year = cur.getInt(0);
int mon = cur.getInt(1);
int date = cur.getInt(2);
int hour = cur.getInt(3);
int min = cur.getInt(4);
String event = cur.getString(5);
list.add(new Reminder(year, mon, date, hour, min, event));
}
return list;
} finally {
if (null != cur) {
try {
cur.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (null != db) {
try {
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
while another rawQuery as below works fine:
public List<Reminder> getRemindersOfDate(int y, int m, int d) {
String sql = "SELECT FLD_HOUR, FLD_MIN, FLD_EVENT FROM TBL_REMINDERS "//
+ "WHERE FLD_YEAR=? AND FLD_MON=? AND FLD_DATE=? " //
+ "ORDER BY FLD_HOUR, FLD_MIN, FLD_EVENT";
SQLiteDatabase db = null;
Cursor cur = null;
try {
db = new CalendarDBOpenHelper(context).getReadableDatabase();
cur = db.rawQuery(sql, new String[] { "" + y, "" + m, "" + d });
List<Reminder> reminders = new ArrayList<Reminder>();
while (cur.moveToNext()) {
int hour = cur.getInt(0);
int min = cur.getInt(1);
String event = cur.getString(2);
reminders.add(new Reminder(y, m, d, hour, min, event));
}
return reminders;
} finally {
if (null != cur) {
try {
cur.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (null != db) {
try {
db.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} // finally
}
I guess it's the `between ... and ...' condition that is making trouble since that's the only difference between the two SQL queries. but I'm not sure
EDIT:
things are getting interesting. I'm sure now that the problem is caused by having an expression in the where clause. In the second method above, if i modify
+ "WHERE FLD_YEAR=? AND FLD_MON=? AND FLD_DATE=? " //
to
+ "WHERE 10 * FLD_YEAR=? AND FLD_MON=? AND FLD_DATE=? " //
as well as
cur = db.rawQuery(sql, new String[] { "" + (10 * y), "" + m, "" + d });
then I get nothing
A: Okay first of all: They are definitely not the same.
The first returns matching entries in a certain timespan.
The second returns entries where month, year and date have the given values.
Edit
Try to use braces for the expression, so (10 * FLD_YEAR)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586474",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Google Reader-esque optimizing of WebViews on Android I have an app that displays the html of a blog post in a WebView. The images, however, are rather large and do not fit to the screen. When viewing the post in the Android Google Reader app, however, all of the images have their width reduced to fit the screen.
The Android Google Reader will also parse out all embedded Youtube and Vimeo embeds and replace them with thumbnails with links so the dedicated Youtube player can play the video instead.
How would I go about doing this? I've tried using Jsoup to match all the images in a post and alter their width, but I don't know how to go about modifying the Youtube video embeds.
A: For converting embed Youtube videos to thumbnails you can do it with mobitube.js code from Mobilize.js project:
https://github.com/mobilizejs/mobilize.js/blob/master/js/mobitube.js
Also I believe Google Reader simply resizes the images using CSS overrides.
Mobilize.js has also tools for rewriting image tags and perform "de-float" operation for them:
https://github.com/mobilizejs/mobilize.js/blob/master/js/mobilize.js#L2005
More about defloat algo:
http://webandmobile.mfabrik.com/docs/web-and-mobile/user-manual/resizing
If you want to resize images on the server-side this is a third party solution:
http://adaptive-images.com/
... though writing your own image resize proxy server from the scratch is not that challenging.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Anonymous method inside hash assignment Is there anything like this possible in Ruby:
hash = { :foo => 'bar', :bar => lambda{ condition ? return 'value1' : return 'value2'}}
That actual code doesn't work (clearly), and I know I could just do the logic before the hash assignment, but it would be nice to work inside the assignment like this. Is such a thing possible?
A: You don't need a lambda for that, just this should work:
hash = {
:foo => 'bar',
:bar => condition ? 'value1' : 'value2'
}
A: Or if you want to use a function result on hash,
hash= {
:foo=> 'foooooo',
:bar=> lambda {
if condition
value1
else
value2
end
}.call
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to printf a long typed value using input size modifier? This is basically what I am trying to do
// ... some code, calculations, what have you ...
long timeToAdd = returnTimeToAddInLongFormat();
// lets output the long type now, and yes i need the width and precision.
System.out.printf("Time to add: %13.10ld", timeToAdd);
I've read most of the google searches around the topic and think I understand how to do it conceptually, but the JRE keeps throwing me a UnknownFormatConversionException and telling me my input size modifier l doesnt work.
Is there another way to do this, or did I miss something small?
A: Java treats all integer values as d, there is no ld. Even byte and BigInteger is a d type. It also assumes integers have no decimal places. If you want to show 10 zeros, you can convert to double first and use f
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: Doctrine andWhere orWhere doesn't seem to bind more than one parameter I have a query like this:
$name = "field1";
$name2 = "field2";
$value = "searchTerm";
$query->select('*')->
from("TableName")->
where($name . " = ?", array($value))->
andWhere($name2 . " = ?", array($value));
I was suprised to see that when this executes the query generates MS SQL Error 102 (syntax error) because the query sent to sql server looks like this:
SELECT * FROM TableName WHERE field1 = 'searchTerm' AND field2 = ?
The question mark was taken literally in each additional condition added to the query! :o
Perhaps I am doing something wrong and someone can set me straight here.
A: Whew! I found the answer!
For whatever reason doctrine does not use PDO's prepared statement functionality for SQL server. Connection/Mssql.php substitutes any parameters within the query string and passes an empty array to Connection::execute. This would be fine:
*
*If the prepared statements didn't work (maybe they didn't work in sql 2000 when the connection driver was first written?) :/
*If the substitution actually successfully substituted more than one value! :o
The fix is easy:
in Connection/Mssql.php on line 314 change the execute function below:
public function execute($query, array $params = array())
{
if(! empty($params)) {
$query = $this->replaceBoundParamsWithInlineValuesInQuery($query, $params);
}
return parent::execute($query, array());
}
to:
public function execute($query, array $params = array())
{
return parent::execute($query, $params);
}
You could just as easily remove the overridden function.
Don't forget to make the same changes to exec which appears just below the execute function in the same code file.
Also, you may wish to test this before using it with versions of SQL server earlier than 2005 as I have not tested this solution with that version.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586487",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Upgrade procedures for CodeIgniter and WordPress applications on Debian Linux, PHP, Apache, and MySQL I'm a programmer that recently moved to a company where I need to start thinking about keeping software libraries and a Debian Linux LAMP stack on their current versions.
Before I jump in I'm curious on how others usually do this with the least amount of frustration. :)
We run applications that use CodeIgniter and others that use WordPress. Is it best to upgrade these before upgrading the Debian LAMP stack or the other way around?
In addition, what do others consider "best practices" on how often to upgrade? My first thought would to do this annually.
Thanks!
Jason
A: In my company we have a production and a test environment, we usually upgrade the test server first, after that, we run test cases, and if the test cases went OK, within a couple of days we patch the production server, if the test cases fails, we try to fix them.
I don't have experience in codeigniter and wordpress, we use QCubed and other frameworks, first if a new release is out, we check requirements, then upgrade these first, and then the LAMP stack update comes after, all this in the test server. It really depends on the requirements of the software which updates first.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586497",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adding new attributes in existing coredata model I am a newbie to coredata never worked with it, right now, I am working on a project on which some work has already been done by the previous developer. Coredata is being used in saving data in the project, Now I need to add some new attributes in the existing coredata models but when I added the attribute (I added @property in the .h file and @dynamic in the .m), the setAttribute is working fine (though idk if it's getting written or not) but when I try to read the attribute the application gets crashed. I don't know much about the coredata, I tried a few blogs they're suggesting to use .xcdatamodel but in my case when I try to open this file the Xcode gets crashed. Now I am very much stuck in here. Kindly help me in this regard, right now I just need a pin point solution to just get through this situation. Thanks in advance for your consideration.
A: Yep, you need to blow away your old database file first. Do this whenever you make any model changes. On the simulator, select iOS Simulator -> Reset Content and Settings.
If it's on your device, delete the app completely.
Then, try again. This time the backing persistent store will be recreated according to your new model. You'll be good to go.
A: You should try to use Xcode 4 instead of Xcode 3.2.5
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to add namespaces in web.config file? I am using VS 2008 and C# but when I added namespace in web.config file, that namespace is not imported or included in code behind or aspx
I have also read this question but not get the required answer.
web.config code
<configuration>
<system.web>
<pages>
<namespaces>
<add namespace="System.Data" />
<add namespace="System.Text"/>
</namespaces>
</pages>
</system.web>
</configuration>
A: You need to put them in the correct <system.web> section. e.g.:
<configuration>
<system.web>
<pages>
<namespaces>
<add namespace="System.Data" />
<add namespace="System.Text"/>
</namespaces>
</pages>
</system.web>
</configuration>
and put them in the correct web.config
i.e. the second web.config file is the Views folder and is specific to views. These settings do not go in the root web.config.
The purpose of these settings is to make the libraries available to the ASPX pages (e.g. for Intellisense) and it is not used for the code-behind. You still need to have using statements in your actual code as that is just plain c# programming.
A: The purpose of the namespace section is to get around having to do the import in the .aspx page. Code behind in C# still requires you to have the using statements at the top of your .cs file.
There is no way to get around this.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: How to delete a referenced object using FluentNHibernate (ye olde "deleted object would be resaved by cascade") The error I'm getting is common, but the scenario I haven't found any answers that speak to my scenario:
Entities:
School
Teacher
Student
Mappings:
School: mapping.HasMany(x => x.Students).Cascade.AllDeleteOrphan();
Student:
mapping.References(x => x.Teacher).Not.Nullable().Cascade.SaveUpdate();
mapping.References(x => x.School).Not.Nullable().Cascade.SaveUpdate();
Teacher:
mapping.References(x => x.School).Not.Nullable().Cascade.SaveUpdate();
mapping.HasMany(x => x.Students).Cascade.All().Inverse();
Scenario: Student is linked to a School that has no other Students or Teachers. If I want to link the student to a different school, I'd like to delete the orphaned school.
if (oldSchool.Students.Count == 1 && oldSchool.Teachers.Count == 0)
{
//delete it
//oldSchool.Students.Remove(student);
student.School = null;
_schoolRepository.Delete(oldSchool);
}
What happens here is that, when I go to save "student", I get the dreaded "deleted object would be resaved by cascade" error.
As always, any help greatly appreciated.
A: What's the rest of your mappings look like? What's the inverse setting between the School and the Student?
Try mapping.HasMany(x => x.Students).Cascade.AllDeleteOrphan().Inverse().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Python | accessing dll using ctypes I'm trying to access some functions in a dll (nss3.dll) that ships with Firefox web browser. To handle this task I have used ctypes in Python. The problem is that it fails at the initial point which is when loading the dll in to the memory.
This is the code snippet that I have to do so.
>>> from ctypes import *
>>> windll.LoadLibrary("E:\\nss3.dll")
The exception I'm getting is
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
windll.LoadLibrary("E:\\nss3.dll")
File "C:\Python26\lib\ctypes\__init__.py", line 431, in LoadLibrary
return self._dlltype(name)
File "C:\Python26\lib\ctypes\__init__.py", line 353, in __init__
self._handle = _dlopen(self._name, mode)
WindowsError: [Error 126] The specified module could not be found
I also tried loading it from the Firefox installation path assuming that there maybe dependencies.
>>> windll.LoadLibrary("F:\\Softwares\\Mozilla Firefox\\nss3.dll")
But I'm getting the same exception as mentioned above.
Thanks.
A: I just had a similar problem with ctypes.CDLL, and I got it to work changing the current directory to the library directory and loading the library only by name (I guess putting the directory in the system path would work too)
So, instead of
CDLL('C:/library/path/library.dll')
I did
os.chdir('C:/library/path')
CDLL('library')
A: nss3.dll is linked to the following DLLs, which are all located in the Firefox directory: nssutil3.dll, plc4.dll, plds4.dll, nspr4.dll, and mozcrt19.dll. The system library loader looks for these files in the DLL search path of the process, which includes the application directory, system directories, the current directory, and each of the directories listed in the PATH environment variable.
The simplest solution is to change the current directory to the DLL Firefox directory. However, that's not thread safe, so I wouldn't rely on it in general. Another option is to append the Firefox directory to the PATH environment variable, which is what I suggested in my original version of this answer. However, that's not much better than modifying the current directory.
Newer versions of Windows (NT 6.0+ with update KB2533623) allow the DLL search path to be updated in a thread-safe manner via SetDefaultDllDirectories, AddDllDirectory, and RemoveDllDirectory. But that approach would be over the top here.
In this case, for the sake of both simplicity and compatibility with older versions of Windows, it suffices to call LoadLibraryEx with the flag LOAD_WITH_ALTERED_SEARCH_PATH. You need to load the DLL using an absolute path, else the behavior is undefined. For convenience we can subclass ctypes.CDLL and ctypes.WinDLL to call LoadLibraryEx instead of LoadLibrary.
import os
import ctypes
if os.name == 'nt':
from ctypes import wintypes
kernel32 = ctypes.WinDLL('kernel32', use_last_error=True)
def check_bool(result, func, args):
if not result:
raise ctypes.WinError(ctypes.get_last_error())
return args
kernel32.LoadLibraryExW.errcheck = check_bool
kernel32.LoadLibraryExW.restype = wintypes.HMODULE
kernel32.LoadLibraryExW.argtypes = (wintypes.LPCWSTR,
wintypes.HANDLE,
wintypes.DWORD)
class CDLLEx(ctypes.CDLL):
def __init__(self, name, mode=0, handle=None,
use_errno=True, use_last_error=False):
if os.name == 'nt' and handle is None:
handle = kernel32.LoadLibraryExW(name, None, mode)
super(CDLLEx, self).__init__(name, mode, handle,
use_errno, use_last_error)
class WinDLLEx(ctypes.WinDLL):
def __init__(self, name, mode=0, handle=None,
use_errno=False, use_last_error=True):
if os.name == 'nt' and handle is None:
handle = kernel32.LoadLibraryExW(name, None, mode)
super(WinDLLEx, self).__init__(name, mode, handle,
use_errno, use_last_error)
Here are all of the available LoadLibraryEx flags:
DONT_RESOLVE_DLL_REFERENCES = 0x00000001
LOAD_LIBRARY_AS_DATAFILE = 0x00000002
LOAD_WITH_ALTERED_SEARCH_PATH = 0x00000008
LOAD_IGNORE_CODE_AUTHZ_LEVEL = 0x00000010 # NT 6.1
LOAD_LIBRARY_AS_IMAGE_RESOURCE = 0x00000020 # NT 6.0
LOAD_LIBRARY_AS_DATAFILE_EXCLUSIVE = 0x00000040 # NT 6.0
# These cannot be combined with LOAD_WITH_ALTERED_SEARCH_PATH.
# Install update KB2533623 for NT 6.0 & 6.1.
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR = 0x00000100
LOAD_LIBRARY_SEARCH_APPLICATION_DIR = 0x00000200
LOAD_LIBRARY_SEARCH_USER_DIRS = 0x00000400
LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800
LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000
For example:
firefox_path = r'F:\Softwares\Mozilla Firefox'
nss3 = CDLLEx(os.path.join(firefox_path, 'nss3.dll'),
LOAD_WITH_ALTERED_SEARCH_PATH)
nss3.NSS_GetVersion.restype = c_char_p
>>> nss3.NSS_GetVersion()
'3.13.5.0 Basic ECC'
A: Note that the ctypes module works with C extensions; if you want to write code in C++, you might do as follows (the C code is the same):
Your dll.c source: (you can use C++ code with .cpp extension without any problem)
#include <math.h>
#ifdef __cplusplus
extern "C" {
#endif
__declspec(dllexport) double _sin(double x)
{
return sin(x)
}
#ifdef __cplusplus
}
#endif
Command prompt with Administrator authentication:
With C source:
C:\Windows\system32>cl /LD "your_source_path\dll.c" /I "c:\Python33 \include" "c:\Python33\libs\python33.lib" /link/out:dll.dll
With C++ source:
C:\Windows\system32>cl /LD "your_source_path\dll.cpp" /I "c:\Python33 \include" "c:\Python33\libs\python33.lib" /link/out:dll.dll
Compiler generates DLL file:
Microsoft (R) C/C++ Optimizing Compiler Version 17.00.50727.1 for x86
Copyright (C) Microsoft Corporation. All rights reserved.
dll.c // or dll.cpp
Microsoft (R) Incremental Linker Version 11.00.50727.1
Copyright (C) Microsoft Corporation. All rights reserved.
/out:dll.dll
/dll
/implib:dll.lib
/out:dll.dll
dll.obj
c:\Python33\libs\python33.lib
Creating library dll.lib and object dll.exp
Your Python module:
import ctypes
dll = ctypes.CDLL('your_dll_path')
dll._sin.argtypes = [ctypes.c_double]
dll._sin.restype = ctypes.c_double
print(dll._sin(34))
# return 0.5290826861200238
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586504",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: JQuery .load() not loading classes I'm trying to load a few div's using JQuery .load(), one of those being the div containing the links from where to load from. Here's the code:
$(".category").click(function(e){
e.preventDefault();
var link = $(this).attr("href");
$('#right_options').load(link+' #right_options');
$('#center_content_title').load(link+' #center_content_title');
$('#center_content').load(link+' #center_content');
});
The first time works great but the second time instead of loading using jquery it loads the entire page by following the link, not detecting the click, the class or something.
Where's the problem on loading like this?
A: Do any of those three load calls change the a element, i.e., the $(".category") element? If so, then the binding done through the call to .click is removed when the element changes. If that is the case, you'll need to use .live("click", ... instead of the click method. Or in other words, you would replace this:
$(".category").click(function(e){
with this:
$(".category").live("click", function(e) {
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is wrong with my mySQL query? Left Join/Inner Join Basically this script exports all of the orders in our little system to a CSV file. There are 4 separate tables that are joined to complete this. SEorder, SEtracking, SE_user, users_orders.
Here is the error:
<div id="Error">An error occurred in script '/home/sites/mywebsite.com/web/administration/allorders.php' on line 81:
<br />Undefined index: UserLast
Here is my database query:
//Make the query-select all orders
$query2 ="SELECT DISTINCT o.OrderID, Basket, Title, FirstName, LastName, Suffix, Company, Address1, Address2, City, State, Zip, GiftCard, GiftCardMsg, t.Tracking, u.UserFirst, u.UserLast AS doo ".
"FROM SEorder o ".
"LEFT JOIN SEtracking t ON (o.OrderID = t.OrderID) ".
"INNER JOIN users_orders uo ON (uo.OrderID = o.OrderID) ".
"INNER JOIN SEuser u ON (u.UserID = uo.UserID) ".
"AND Submitted='Y' ".
"ORDER BY OrderDate ASC";
and here is my php to grab the data. this is line 81 that is throwing the error:
$username = $row['UserFirst'] . " " . $row['UserLast'];
I am positive that the table SEuser exists, has the column UserLast, and that column has data in it. I am not completely versed on JOIN's though so am I missing something here? I did not create this script, just troubleshooting. Thanks!
A: It looks like you aliased the UserLast column as doo.
A: because you have queried the UserLast as doo
so use the doo index not UserLast
A: u.UserLast AS doo
Your PHP should say $row['doo']
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Customizable multiple Mootools file uploader Can you recommend me customizable file uploader on top of Mootools? It whould be greate, if I can bind to 'addFile', 'uploadFile', 'uploadAllFiles' events, customize CSS and templates.
Other important is that we want to make image transloading by URL, but we do not want to hack libraries at many places.
A: Not for moo tools but worth mentioning would be plupload…
http://www.plupload.com/
Being standalone, you'll be able to update it way easier and i guess for a javascript file uploader, it's worth the extra kbs !
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is the output cache on an Asp.Net page limited to session per user? Just wondering If I set a page up to use the cache for 30 seconds is this only served to the same user that accessed the page first time round or is it configurable?
A: You can cache on a per-user basis, but generally the ApplicationCache is best used for - you guessed it - application-wide data. E.g. the contents of an autosuggest list could be cached to avoid reading it from the DB for every request.
Output caching is similar and you can set the duration, etc. in Page directives.
It's a potentially big topic, but I'd take a look here to start off.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586514",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: OutputCache.VaryByHeader is not generating a Vary header in the response I have this action method:
[OutputCache(Duration = 2,
Location = OutputCacheLocation.Any,
VaryByHeader = "Accept-Charset")]
public ActionResult Index()
{
return View();
}
And the generated response is:
Cache-Control:public, max-age=2
Content-Length:5164
Content-Type:text/html; charset=utf-8
Date:Wed, 28 Sep 2011 16:30:33 GMT
Expires:Wed, 28 Sep 2011 16:30:35 GMT
Last-Modified:Wed, 28 Sep 2011 16:30:33 GMT
Server:Microsoft-IIS/7.5
Vary:*
X-AspNet-Version:4.0.30319
X-AspNetMvc-Version:3.0
X-Powered-By:ASP.NET
Why is the Vary header showing an asterisk instead of Accept-Charset ?
OutputCacheAttribute does have effect on the response, actually, the Expires and Cache-Control:max-age=n headers depends on the Duration argument, and the Cache-Control:public/private/no-cache depends on the Location argument.
I have created a wrapper for OutputCacheAttribute to see what is going on:
public class CustomOutputCacheAttribute:OutputCacheAttribute
{
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
base.OnResultExecuted(filterContext);
Dictionary<String, String> headers = new Dictionary<string, string>();
foreach (var header in filterContext.HttpContext.Response.Headers.AllKeys)
headers.Add(header, filterContext.HttpContext.Response.Headers[header]);
Debugger.Break();
}
}
The headers are not shown in the break, so probably what OutputCacheAttribute does is configure HttpContext.Current.Response.Cache.
I can see how filterContext.HttpContext.Response.Cache.VaryByHeaders.UserCharSet is true, and for example filterContext.HttpContext.Response.Cache.VaryByHeaders.AcceptTypes is false, but the Vary header always says *.
I am wondering if the only possible values are the four ones listed as properties of filterContext.HttpContext.Response.Cache.VaryByHeaders, could it be?
Cheers.
A: The solution is use Response.Cache.SetOmitVaryStar(true)
[OutputCache(Duration = 2,
Location = OutputCacheLocation.Any,
VaryByHeader = "Accept-Charset")]
public ActionResult Index()
{
Response.Cache.SetOmitVaryStar(true);
return View("ShowHeaders");
}
I am still trying to figure out what is wrong with Vary:* in this thread: What is the meaning of the HTTP header Vary:*
A: <%@ OutputCache Duration="2000" VaryByParam="*" VaryByHeader="Accept-Language" %>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586515",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Inserting current date to MySql using Zend Date I have a website based on Zend Framework. There is a form for users to fill in and the entered data is inserted in the database.
The users don't enter the date/time. I would like to populate the data value based on the current date/time . The date field is of type datetime.
i'm constantly getting the following error message:
Notice: Array to string conversion in D:\wamp\www\CNFSORG\library\Zend\Db\Statement\Pdo.php on line 228
I have tried doing the following:
<?php $date = new Zend_Date(); ?>
also tried doing:
<?php $date = new Zend_Db_Expr('NOW()'); ?>
<?php $date = new Zend_Db_Expr('CURDATE()'); ?>
I would be very grateful if someone could point me towards the right direction.
thanks in advance...
A: The Correct answer is
<?php $date = new Zend_Db_Expr('NOW()'); ?>
You can try create a current timestamp from php with something like that
<?php $date = new \DateTime(); ?>
A: Well, i'v done this for SqlServer, but i think that for MySql you just need to change the db-expression for the one you want.
$this->_colocation = new Application_Model_Colocation();
$solicitacao = $this->_colocation->find($post['hdnIdSolicitacao'])->current();
$solicitacao->data_chegada = new Zend_Db_Expr('getdate()');
$solicitacao->save();
Hope it helps.
A: In your class of table use this code:
$tme =new Zend_Date();
$data['tme']=$tme->now();
$this->insert($data);
If you have a column with tme name and type of datetime , this code will do what you want!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Append before last tag? Here's my HTML:
<section>
<article></article>
<article></article>
<!-- INSERT HERE -->
<footer></footer>
</section>
How would I insert content after the last article but before the footer?
I've tried doing this:
$('<article>Yipee</article>').appendTo('section article:last');
But that inserts the new article inside the last one instead of as a sibling.
I'm running jQuery 1.6.2.
A: insertAfter is the function your are looking for I think:
$('<article>Yipee</article>').insertAfter('section article:last');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Error when i execute syncdb I am facing an error while executing python manage.py suncdb
the error is
C:\Python25\lib\site-packages\django\conf\__init__.py:75: DeprecationWarning: Th
e ADMIN_MEDIA_PREFIX setting has been removed; use STATIC_URL instead.
"use STATIC_URL instead.", DeprecationWarning)
C:\Python25\lib\site-packages\django\contrib\localflavor\ca\ca_provinces.py:14:
RuntimeWarning: There have been recent changes to the CA localflavor. See the re
lease notes for details
RuntimeWarning
Creating tables ...
Traceback (most recent call last):
File "manage.py", line 14, in <module>
execute_manager(settings)
File "C:\Python25\lib\site-packages\django\core\management\__init__.py", line
442, in execute_manager
utility.execute()
File "C:\Python25\lib\site-packages\django\core\management\__init__.py", line
379, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Python25\lib\site-packages\django\core\management\base.py", line 191,
in run_from_argv
self.execute(*args, **options.__dict__)
File "C:\Python25\lib\site-packages\django\core\management\base.py", line 220,
in execute
output = self.handle(*args, **options)
File "C:\Python25\lib\site-packages\django\core\management\base.py", line 351,
in handle
return self.handle_noargs(**options)
File "C:\Python25\lib\site-packages\django\core\management\commands\syncdb.py"
, line 109, in handle_noargs
emit_post_sync_signal(created_models, verbosity, interactive, db)
File "C:\Python25\lib\site-packages\django\core\management\sql.py", line 189,
in emit_post_sync_signal
interactive=interactive, db=db)
File "C:\Python25\lib\site-packages\django\dispatch\dispatcher.py", line 172,
in send
response = receiver(signal=self, sender=sender, **named)
File "C:\Python25\lib\site-packages\django\contrib\contenttypes\management.py"
, line 47, in update_contenttypes
content_type_display = '\n'.join([' %s | %s' % (ct.app_label, ct.model) f
or ct in content_types])
AttributeError: 'unicode' object has no attribute 'app_label'
and i tried to convert DB and all tables and fields collation to utf8_general_ci but nothing changed
A: The error says you've got a string instead of Model Meta options. It's not related to collation probably.
What change have you made before the error appeared?
A: I had this issue, I just dropped the database and re-ran syncdb and it was fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586526",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why not working the google map api with the different key in android? I'm using the google map api in my android application. I never a problem occurs when I use the api key that I created my computer with own fingerprint. But I change the api key the map does not appear. (appears just a blank gray field)
I don't know why not work with a different key.
To release the application needs to use a different key?
Waiting on your help for this topic.
<com.google.android.maps.MapView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:enabled="true"
android:apiKey="the api key here" />
A: You need a different key to release the app. When working on it yourself, use the default.keystore. Typically, for me at least, using any key besides default.keystore didn't work while I was working on Google Maps API apps.
This link should help you obtain the MD5 fingerprint and default.keystore required to sign for a Google Maps API for your development. But remember, before releasing your app, you must sign for a new API key, not using the default.keystore.
A: For google map api key to work you have to generate it from finger print of certificate with which you are signing your app. For example while in development stage you are signing your app with debug certificate and using api key generated using fingerprint of debug certificate present in that computer on which you are developing and when you want to release app to android market you sign app with your created cerificate instead of debug certificate and you should use fingerprint of certificate with which you have signed app to make map api key works. In short use fingerprint of that certificate with which you are signing app to generate api key.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586529",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: JVMTI Agent_OnLoad handler can't create a System Property I'm using the JVM Tool Interface. I'm trying to create a SystemProperty in the Agent_OnLoad event using the SetSystemProperty() call. If the property exists, it correctly sets a new value. However, if the property does not exist, SetSystemProperty returns an error code saying it cannot write the property (error 98).
Is there another way to create a system property early in the JVM's life, before classes get loaded?
5/24/12 update: As an agent, I am loaded by various programs. I can't ask the programs to set this property (not practical in my use case). I'm looking for a way to do set the property from the agent code itself. After a lot of experimenting, I've come to the conclusion that it's not possible.
A: If you haven't already looked at the JVMTI docs for system properties, it would be worthwhile:
http://docs.oracle.com/javase/6/docs/platform/jvmti/jvmti.html#props
It looks like there is a distinction made between VM system properties and the properties managed by java.lang.System. If you really want to set a property that will be available via System.getProperty, then you're probably stuck with doing it via JNI (per the JVMTI docs).
A: Add the property using -D<property name>=<property value> when launching from the command line.
system properties may be set before they have been used in the
start-up of the VM
taken from http://docs.oracle.com/javase/1.5.0/docs/guide/jvmti/jvmti.html#starting
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586530",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to generate editable drawing of connected shapes in Java Can anybody tell me how I could do the following:
I want my Java code to generate a drawing that has multiple connected shapes. Perhaps hundreds of shapes--not huge. I'd like to generate this and save it as a standard file format that somebody could open in a viewer or an editor. I do not want to implement viewing or editing logic--generation only.
I'd like the user to be able to take my generated file, open it in a WYSIWYG editor, and move the shapes around with the lines that connect the shapes staying connected to the shapes as they move. That way, my generation code does not have to be super smart about making sure that connectors don't overlap.
Can anybody suggest a combination of file format, Java library, editor (or some subset of those three) that would work well for this task?
Thoughts so far:
*
*yEd allows this editing behavior and uses graphml as the format. However, I'm not sure how widely used graphml is, and I'm concerned about availability of glyphs.
*Inkscape and SVG are widely used, but I'm a complete novice, and so far I haven't been able to get lines to stay connected to other shapes using Inkscape when I move them around.
I'm open to other options...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586531",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: local notifications iOS 5 I have an App that uses local notifications intensively. I need sound and visual alert in the same way like iOS 4.0. There is a way I can programmatically enable the notification working in the same way in iOS 5, without having to ask the user to change Settings> Notifications> MyApp?
A: As far as I know, there are no differences in implementation of local notifications between iOS 4 and iOS 5. iOS 5 will display them differently, but triggering them is no different.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586532",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is it possible to upload to S3 directly from URL using POST? I know there is a way to upload to S3 directly from the web browser using POST without the files going to your backend server. But is there a way to do it from URL instead of web browser.
Example, upload a file that resides at http://example.com/dude.jpg directly to S3 using post. I mean I don't want to download the asset to my server then upload it to S3. I just want to make a POST request to S3 and it uploads it automatically.
A: It sounds like you want S3 itself to download the file from a remote server where you only pass the URL of the resource to S3.
This is not currently supported by S3.
It needs an API client to actually transfer the content of the object to S3.
A: I thought I should share my code to achieve something similar. I was working on the backend but possibly could do something similar in frontend though be mindful about AWS credentials likely to be exposed.
For my purposes, I wanted to download a file from the external URL and then ultimately get back the URL form S3 of the uploaded file instead.
I also used axios in order to get the uploadable format and file-type to get the proper type of the file but that is not the requirement.
Below is the snippet of my code:
async function uploadAttachmentToS3(type, buffer) {
var params = {
//file name you can get from URL or in any other way, you could then pass it as parameter to the function for example if necessary
Key : 'yourfolder/directory/filename',
Body : buffer,
Bucket : BUCKET_NAME,
ContentType : type,
ACL: 'public-read' //becomes a public URL
}
//notice use of the upload function, not the putObject function
return s3.upload(params).promise().then((response) => {
return response.Location
}, (err) => {
return {type: 'error', err: err}
})
}
async function downloadAttachment(url) {
return axios.get(url, {
responseType: 'arraybuffer'
})
.then(response => {
const buffer = Buffer.from(response.data, 'base64');
return (async () => {
let type = (await FileType.fromBuffer(buffer)).mime
return uploadAttachmentToS3(type, buffer)
})();
})
.catch(err => {
return {type: 'error', err: err}
});
}
let myS3Url = await downloadAttachment(url)
I hope it helps people who still struggle with similar issues. Good luck!
A: I found this article with some details. You will probably have to modify your buckets' security settings in some fashion to allow this type of interaction.
http://aws.amazon.com/articles/1434
There will be some security issues on the client as well since you never want your keys publicly accessible
A: You can use rclone to achieve this easily:
https://rclone.org/commands/rclone_copyurl/
Create a new access key on AWS for rclone and use rclone config like this:
https://rclone.org/s3/
Then, you can easily interact with your S3 buckets using rclone.
To upload from URL:
rclone -Pva copy {URL} RCLONE_CONFIG_NAME:/{BUCKET_NAME}/{FOLDER}/
It is quite handy for me as I am archiving my old files from Dropbox Business to S3 Glacier Deep Archive to save on Dropbox costs.
I can easily create a file transfer from Dropbox (100GB per file limit), copy the download link and upload directly to S3 using rclone.
It is copying at 10-12 MiB/s on a small DigitalOcean droplet.
A: If you are able you can use Cloudinary as an alternative to S3. They support remote upload via URL and more.
https://cloudinary.com/documentation/image_upload_api_reference#upload_examples
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "43"
}
|
Q: Looking for Polygon Geometry library with specific capabilities I am doing a survey of polygon/geometric algorithm libraries implemented in Objective C, C or C++ (in that order of preference). I have very specific needs, so I figured I'd ask the community to see if anyone knows of one that meets some or all of them since I'd prefer to use one library/API for all my needs. This is what I need to be able to do:
*
*Intersection of 2 polygons
*Determine if two polygons are congruent (i.e. the same shape and size though they may be rotated or mirrored)
*2d bin packing of convex polygons (aka sheet cutting - or open-ended bin packing so I'm maximizing the use of a run of material of fixed width)
*Same as #3 but for concave polygons
*The ability to take a set of line segments, some of which share endpoints and some of which intersect each other and turn it into a set of polygon
*Same as #5 but with the added ability to detect polygons with holes and break it into 2 polygons (at least one of which would be concave)
*Bonus: any or all of the above with closed shapes that consist of lines and curves
These are in the order of priority and I can work around the absence of any of them (my application just becomes less useful). so for example, if I had a library that only did 1 and 2, I would find that more useful than one that did 3-7.
A: In C++ it exists some libraries to work with the polygon geometry but I don't know one that fully corresponds to your needs.
A very useful library that I know in C++ is CGAL. It covers some of your needs, but not all.
A: Some of the things you need are covered by GEOS.
Spatial relations between geometries (intersects, touches, overlaps, is within, contains, etc) are implemented quite nicely by GEOS.
I don't know if 3-7 are built in (you can do line merging (5)).
As for 7, GEOS does not model curves (only points that form lines or polygons). The only closed shapes that you can define in GEOS are polygons.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586535",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Site is getting requests for strange query strings I was evaluating the logs for a website I help run and I noticed a repeating pattern of strange requests. The requests are all very similar, and from different IP addresses (possibly a bot net?). I am curious if anybody understands what the point of such a bizarre request is and if there is a security concern:
%5BPLM=0%5D+GET+http://example.org/+%5B0,7309,7252%5D+-%3E+%5BN%5D+POST+http://example.org/+%5B0,0,7329%5D
which decodes to:
[PLM=0] GET http://example.org/ [0,7309,7252] -> [N] POST http://example.org/ [0,0,7329]
A: Anything you dont recognize can be construed as a security concern and if its happening at any significant volume than I would consider it a threat and start finding a way to filter them out via some access rules / firewall, etc
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586537",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Mapping protected properties in Entity Framework 4.1 I want to have a protected list in a class, accessible via methods.
In this topic it's suggested that I could create a configuration class inside my model class, which I don't really like, but as long as it works.. So I have something along those lines:
public class Person
{
public int Id { set; get; }
public string Name { set; get; }
List<string> _address = new List<string>();
protected virtual ICollection<string> address { get { return this._address; } }
[NotMapped]
public string[] Address { get { return this.address.ToArray(); } } // I know it's not efficient.. I'll cache it.
public void AddAddress(string address)
{
// some business logic
this.address.Add(address);
}
public class OneMapping : EntityTypeConfiguration<Person>
{
public OneMapping()
{
this.HasMany(x => x.address);
}
}
}
and in db context:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add<Person>(new Person.OneMapping());
base.OnModelCreating(modelBuilder);
}
The db context throws this exception when I'm trying to add an instance of person:
The navigation property 'address' is not a declared property on type
'Person'. Verify that it has not been explicitly excluded from the
model and that it is a valid navigation property.
So doesn't really work.
Tried this sample: Mapping private properties with EF 4.1
Failed with same error.
Another solution would be to use ObservableCollection, and wire the business logic in events, but this logic doesn't need to run when objects are constructed by EF - only when they're constructed by user.. which isn't possible.
So I'm somewhat stuck here.. I hope someone out there already ran into this and solved it..
Thanks !
A: Your navigation property doesn't have setter so it cannot be mapped. All mapped properties must have accessible getter and setter because EF can assign them during entity materialization. That was true for EDMX where at least private setter was necessary but in case of code first it works even without setter.
Generally EF code first is not very good tool if you want to play with accessibility of mapped properties.
Edit:
Btw. Your address is not collection of entities but collection of strings - that is also not supported
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: 403 Developer Inactive on an HTTP pull I am trying to query some XML from a hotel database using Ruby, and am getting the results:
403 Developer Inactive
I used the code:
require 'net/http'
url = URI.parse('URL of the HTTP query')
req = Net::HTTP::Get.new(url.path)
res = Net::HTTP.start(url.host, url.port) {|http|
http.request(req)
}
puts res.body
I would give the actual URL, but it contains the API key/etc...so I really cannot divulge it.
Is there anything wrong with the code or might it be on the company needing to activate the key?
Thanks
A: 403 is the HTTP status code FORBIDDEN, which leads me to believe you have a problem authenticating your API request, maybe because of a wrong key or something.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586547",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Does python have an equivalent to C#'s Enumerable.Aggregate? In C#, if I have a collection of strings, and I want to get a comma-separated string representing of the collection (without extraneous comments at the beginning or end), I can do this:
string result = collection.Aggregate((s1, s2) => String.Format("{0}, {1}", s1, s2));
I could do something like
result = collection[0]
for string in collection[1:]:
result = "{0}, {1}".format(result, string)
But this feels like a cludge. Does python have an elegant way to accomplish the same thing?
A: Use str.join:
result = ', '.join(iterable)
If not all the items in the collection are strings, you can use map or a generator expression:
result = ', '.join(str(item) for item in iterable)
A: The Equivalent of the C# Enumerable.Aggregate method is pythons built in "reduce" method.
For example,
reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
Calculates ((((1+2)+3)+4)+5). which is 15
This means you could achieve the same with
result = reduce(lambda s1, s2: "{0}, {1}".format(s1, s2), collection)
Or with
result = reduce(lambda s1, s2: s1 + ", " + s2, collection)
In your Case it would be better to use ', '.join as others have suggested because of pythons immutable strings.
For completeness the C# Enumerable.Select method in python is "map".
Now if anyone asks you can say you know MapReduce :)
A: You could do something like:
> l = [ 1, 3, 5, 7]
> s = ", ".join( [ str(i) for i in l ] )
> print s
1, 3, 5, 7
I suggest looking up "python list comprehensions" (the [ ... for ... ] in the above) for more info.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: php cutting multidimensional array Anyone can help me with a function or point me into the direction on cutting a multidimensional array?
Here is what I need:
$array[x][y][b][q][o][p];
$array[b][c][f][q][l][v];
$newArray = cut_array_depth($array, 2);
// Would return a new array with a maximum dimension of 2 elements
// all others would be left out
$newArray[][];
Thanks,
A: You can write yourself the solution (even if I don't really understand the 'cutting' logic)
<?php
function cut_array_depth($array, $depth, $currDepth = 0){
if($currDepth > $dept){
return null;
}
$returnArray = array();
foreach( $array as $key => $value ){
if( is_array( $value ) ){
$returnArray[$key] = cut_array_depth($value, $depth , $currDepth +1);
} else {
$returnArray[$key] = $value;
}
return $returnArray;
}
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7586550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.