text
stringlengths 8
267k
| meta
dict |
---|---|
Q: Longest common subsequence (Haskell) I've been struggling with this for a while. I'm solving the longest common subsequence problem in Haskell as a learning exercise.
I have a function f1 that is passed two Ints i and j, and a function f2. f1 builds a two dimensional list so that the (i,j) location in the list is equal to f2 i j.
Now I'm trying to write a function called lcs that takes two Strings s1 and s2 and finds the longest common subsequence using f1 for memoization.
I'm not exactly sure how to set this up. Any ideas?
Code:
f1 :: Int -> Int -> (Int -> Int -> a) -> [[a]]
f2 :: Int -> Int -> a
lcs:: String -> String -> Int
A: I assume the Int parameters of f1 are some sort of bounds? Remember that using lists give you the benefit of not needing to specify bounds (because of laziness), but it costs you slow access times.
This function should do what you want f1 to do (memoize a given function):
memo :: (Int -> Int -> a) -> (Int -> Int -> a)
memo f = index where
index x y = (m !! x) !! y
m = [[f x y|y <- [0..]]|x <- [0..]]
-- memoized version of f2
f2' = memo f2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Does rich:extendedDataTable work in JSF 2 I've found that the client-side dynamics for rich:extendedDataTable do not work for me in JSF 2 with either RF 3.3.3 or RF 4. Moving a column just causes the table to hand and the drop down for sorting doesn't drop down. Looking at the RF demo page of RF 4 I noticed that they do not demo sorting/filtering/column moving. Is this because it doesn't work in JSF2?
ref: http://www.richfaces-showcase.appspot.com/richfaces/component-sample.jsf?demo=extendedDataTable&sample=exTableSelection&skin=blueSky
A: There is no header menus for sorting, show/hide columns in rich:extendedDataTable for RF4.0. They are planned for future release. However, column re-ordering, frozen columns and lazy loading definitely works. I tried it myself.
You would like to implement sorting yourself by making header as commandLink and invoking toggle action of sorting order in backing bean.
Also, just for your reference, in RF4.0, you would not be able to save table state as well.
Few of the links which you would be interested in:
http://showcase.richfaces.org/richfaces/component-sample.jsf?demo=extendedDataTable&skin=blueSky
https://issues.jboss.org/browse/RF-10442
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I use the Boolean values returned by a Java method? I have a method that sends a bunch of characters to another method that will return true or false if certain character are present. Once this method evaluates all the character and returns true or false for each of them how do I use those true or false vales in another method?
I think I have the method sending one character at a time. The Boolean method is not a boolean array.
public void Parse(String phrase)
{
// First find out how many words and store in numWords
// Use "isDelim()" to determine delimiters versus words
//
// Create wordArr big enough to hold numWords Strings
// Fill up wordArr with words found in "phrase" parameter
int len = phrase.length();
char[] SeperateString = new char[len];
for (int i = 0; i < len; i++) {
SeperateString[i] = phrase.charAt(i);
isDelim(SeperateString[i]);
System.out.println(SeperateString[i]);
boolean isDelim(char c)
{
{
if (c == delims[0])
return true;
else if (c == delims[1])
return true;
else if (c == delims[2])
return true;
else
return false;
}
//Return true if c is one of the characters in the delims array, otherwise return false
}
A: so your method is like this
boolean myMethod(String s) {
// returns true or false somehow... doesn't matter how
}
you can do this later
boolean b = myMethod("some string");
someOtherMethod(b);
or even
someOtherMethod(myMethod("some string"));
Now if your method is returning lots of booleans, say one for each character, it would look more like this
boolean[] myMethod(String s) {
// generates the booleans
}
You'd have to access them some other manner, perhaps like so:
String str = "some string";
boolean[] bools = myMethod(str);
for(int i = 0; i < str.length(); i++) {
someOtherMethod(bools[i]);
}
For more information on this you'd have to post your code.
In response to the posted code, here's what I would do
/**
* Parse a string to get how many words it has
* @param s the string to parse
* @return the number of words in the string
*/
public int parse(String s) {
int numWords = 1; // always at least one word, right?
for(int i = 0; i < s.length(); i++) {
if(isDelim(s.charAt(i)) numWords++;
}
return numWords;
}
private boolean isDelim(char c) {
for(char d : delims) if(c == d) return true;
return false;
}
A: From what I see, you could be using String.split() instead.
You can use regex with it as well, so you can include your 3 different delimiters.
If you need the number of works still you can get the result's length.
http://download.oracle.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29
Assuming delims is a character array, it would be safe to use this to generate the regex:
String regex = "[" + new String(delims) + "]";
String result = params.split(regex);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set an entity kind name different from a class name Is there any way how to set a kind name different from a class name used in my Google App Engine?
I am using Java and JDO to access a datastore.
There a question about the similar issue in Python. It seems answered. Set a kind name independently of the model name (App Engine datastore)
A: Ooops... It was quite easy to achieve:
@PersistenceCapable(table = "person")
public class PersonEntity {
// ...
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Apache Ant Less Than How on earth do you check a number property is less than in Apache Ant?
<property name="small" value="15"/>
<property name="big" value="156"/>
<fail message="small is less than big!">
<condition>
<lessthan val1="${small}" val2="${big}"/>
</condition>
</fail>
From what I've seen (I'm new to Ant) you can only do <equal/>?
A: You could use a <scriptcondition> (see http://ant.apache.org/manual/Tasks/conditions.html).
Read the documentation carefully because it would need installing additional jar dependencies in ant.
The condition could look like that (not tested):
<scriptcondition language="javascript">
var small = parseInt(project.getProperty("small"));
var big = parseInt(project.getProperty("big"));
self.setValue(small < big);
</scriptcondition>
A: Here is the usage of <isgreaterthan> condition task with out any scripting:
<if>
<isgreaterthan arg1="100" arg2="10"/>
<then>
<echo>Number 100 is greater than number 10</echo>
</then>
</if>
Also, arg1, arg2 value can be of property variable.
Note: <isgreaterthan> is an additional condition available with Ant-Contrib:
http://ant-contrib.sourceforge.net/tasks/tasks/more_conditions.html
A: Cheers JB Nizet, finally got there.
<!-- Test the Ant Version -->
<property name="burning-boots-web-build.required-ant-version" value="1.8.2"/>
<script language="javascript">
<?)+/)[0].replace(/\./g,"");
var required = project.getProperty("burning-boots-web-build.required-ant-version").match(/([0-9](\.)?)+/)[0].replace(/\./g,"");
project.setProperty('ant.valid-version', current < required ? "false" : "true");
]]>
</script>
<fail message="This build requires Ant version ${burning-boots-web-build.required-ant-version}.">
<condition>
<isfalse value="${ant.valid-version}"/>
</condition>
</fail>
A: A "less than" comparioson of properties is not possible without either custom tasks or an embedded script.
But in most cases you can get away by applying the test not to the property but to the source of the values. In in a build system these "sources" are usually files. On files you can use the isfileselected condition together with a selector. Most selectors accept when attributes like less, more or equal.
The manual for the isfileselected condition show an example.
A: The Ant addon Flaka provides a fail task that evaluates EL expressions, f.e. :
<project name="demo" xmlns:fl="antlib:it.haefelinger.flaka">
<property name="small" value="15"/>
<property name="big" value="156"/>
<fl:fail message="small is less than big!" test="small lt big"/>
</project>
output :
BUILD FAILED
/home/rosebud/workspace/Ant/demo.xml:7: small is less than big!
see Flaka manual for further details
A: Actually, the answer provided by @GnanaPrakash is incomplete.
From the Ant Contrib documentation:
These conditions are suitable for use in the element. Unfortunately, they cannot be used in the <condition> task, although all conditions for the task can be used with the <bool> and the <bool> can be used anywhere that <condition> can be used.
So, the islessthan or the alternative isgreaterthan elements must be wrapped in a bool element like so:
<property name="small" value="15" />
<property name="big" value="156" />
<if>
<bool>
<islessthan arg1="${small}" arg2="${big}"/>
</bool>
<then>
<echo message="small is less than big!" />
</then>
<else>
<echo message="big is less than small!" />
</else>
</if>
If you don't do it this way you'll get an error saying:
if doesn't support the nested "islessthan" element.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: SQLite Trigger issue - "No such column" I have a sqlite database with a table named Achievements, it stores whether certain achievements have been met in a simple quiz I am building (iphone project to learn objective-c). The table structure is:
ID Name Completed
=============================
1 FiveInARow 0
2 TenInARow 0
3 AllCorrect 0
4 UnderASecond 0
5 AllCompleted 0
The ID is the primary key, Name is a VARCHAR and Completed is BOOL (0 for false and 1 for true).
I am trying to add a trigger onto the update statements of this table, such that when a Completed column is set to 1 (i.e. achievement completed - this is the only update that will happen on the table) there will be a calculation to see whether all of the other achievements have been completed and if so also update the AllCompleted achievement (ID 5) to 1.
The trigger I created is:
CREATE TRIGGER "checkAllAchievements" AFTER UPDATE ON "Achievements"
WHEN (Select SUM(Completed) from Achievements) = (Select COUNT(Completed) -1 from Achievements)
BEGIN UPDATE Achievements SET Completed = 1 WHERE Name= 'AllCompleted';
So what I am trying to do is take the sum of the completed row and compare it to the total count minus 1, if they match then it means that all achievements apart from the AllCompleted achievement are achieved so we can also set that to true. The trigger gets created fine.
Now on to the problem - When I attempt to update the table with the following statement
UPDATE Achievements SET Completed = 1 WHERE ID = 1
I receive the error message "No such Column Completed".
Am I trying to do something that is fundamentally wrong? Is it not possible for me to achieve this using a trigger? Any advice?
Thanks.
A: Double check that you spelled everything exactly as it is in the database. In your example, you state the table name is "Achievements" however reference "Achievement" in two places.
Fixing that should solve your issue. Final SQL is as follows:
CREATE TRIGGER "checkAllAchievements"
AFTER UPDATE ON Achievements
WHEN (SELECT SUM(Completed) FROM Achievements) = (SELECT COUNT(Completed)-1 FROM Achievements)
BEGIN
UPDATE Achievements SET Completed=1 WHERE Name='AllCompleted';
END;
A: typically this would be a mutation in the table you are updating...
the trigger should just set the value something like
new_rec.completed := 1;
not try to do another update.
(excuse my Oracle syntax)
A: I think you should not update a table from a trigger on updating of that table, could be a infinite recursion. Maybe SQLite doesn't like that, but give a bad diagnositic
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Tricky php class method default parameter syntax I am having difficulty understanding the proper syntax for the second default value in the following method declaration statement. Any suggestions would be greatly appreciated. Thanks!
protected function load($columName = self::_tableIdName, $columnValue = self::_data->{self::_tableIdName})
{...}
Notes: $_tableIdName is a protected variable within the class;
$_data is a protected stdClass object within the class.
I am trying to make the default for $columnValue equal to the corresponding value from the internal $_data object.
A: Just set the defaults to null, then check for null in the function body. You are limited to using constants in the argument intializer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to put() values into Guava's Cache class? I'm a little confused by CacheBuilder and Cache introduced in Guava 10. The documentation hints that it's possible to overwrite values but as far as I can tell, Cache does not contain any methods for doing so. Any ideas?
I'm trying to construct a Map that expires a key 10 seconds after it was last read or written-to. When a value is looked up, I expect the previously-set value to be returned, or a default value to be computed if none exists.
NOTE: This question is outdated. Although the above Javadoc shows the existence of a Cache.put(K key, V value) method, it not exist when the question was first posted.
A: Since long, there's Cache#asMap returning a ConcurrentMap view.
AFAIK, not yet. But there's a thread mentioning that Cache.asMap.put is planned for release 11.
I'd say the current old state of the Javadoc is a remnant if the CacheBuilder's evolution from the MapMaker (where the cache-setting method are currently deprecated).
I'm trying to construct a Map that expires a key 10 seconds after it was last read or written-to. When a value is looked up, I expect the previously-set value to be returned, or a default value to be computed if none exists.
Using expireAfterAccess(10, TimeUnit.SECONDS) will keep an entry alive for 10 seconds after any access to it. And the only values you'll get are those computed by your CacheLoader (either earlier or during get).
A: Minor update. Cache.asMap().put() should show up in Guava 10.1 sometime during the first week of October, 2011. See this thread for more info.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616169",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Standalone module for nodejs? I would like to create a module for nodejs that can be used standalone. The module source is literally just JavaScript files that are executed using nodejs.
I am not sure exactly how this would work, but essentially:
npm install mymodule
node mymodule inputfile
or better
mymodule inputfile
How would this work?
A: There's an excellent guide for writing modules on how to node.
Jade is a great example of executable module.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616175",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Convert to a Type on the fly in C#.NET Alternative Title: Dynamically convert to a type at runtime.
I want to to convert an Object to a type that will be assigned at runtime.
For example, assume that I have a function that assigns a string value(from a TextBox or Dropdownlist) to an Object.Property.
How would I convert the value to proper type? For instance, it could be an integer, string, or enum.
Public void Foo(object obj,string propertyName,object value)
{
//Getting type of the property og object.
Type t= obj.GetType().GetProperty(propName).PropertyType;
//Now Setting the property to the value .
//But it raise an error,because sometimes type is int and value is "2"
//or type is enum (e.a: Gender.Male) and value is "Male"
//Suppose that always the cast is valid("2" can be converted to int 2)
obj.GetType().GetProperty(propName).SetValue(obj, value, null);
}
A: You need to use the Convert.ChangeType(...) function [note: in the function below, the input propertyValue could just as easily have been of type object ... I just had a string version pre-baked]:
/// <summary>
/// Sets a value in an object, used to hide all the logic that goes into
/// handling this sort of thing, so that is works elegantly in a single line.
/// </summary>
/// <param name="target"></param>
/// <param name="propertyName"></param>
/// <param name="propertyValue"></param>
public static void SetPropertyValueFromString(this object target,
string propertyName, string propertyValue)
{
PropertyInfo oProp = target.GetType().GetProperty(propertyName);
Type tProp = oProp.PropertyType;
//Nullable properties have to be treated differently, since we
// use their underlying property to set the value in the object
if (tProp.IsGenericType
&& tProp.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
//if it's null, just set the value from the reserved word null, and return
if (propertyValue == null)
{
oProp.SetValue(target, null, null);
return;
}
//Get the underlying type property instead of the nullable generic
tProp = new NullableConverter(oProp.PropertyType).UnderlyingType;
}
//use the converter to get the correct value
oProp.SetValue(target, Convert.ChangeType(propertyValue, tProp), null);
}
A: A universal Type Converter is what you seek !? Not an easy feat..
Try this approach:
Universal Type Converter
You can in NuGet Install-Package UniversalTypeConverter
Also, is using Generics out of the question here? It would facilitate the solution if you know at least the target type of the conversion.
A: Here's another way you can do it, but I'm not sure
Without support for generic types:
public void Foo(object obj,string propertyName,object value)
{
//Getting type of the property og object.
Type type = obj.GetType().GetProperty(propertyName).PropertyType;
obj.GetType().GetProperty(propertyName).SetValue(obj, Activator.CreateInstance(type, value), null);
}
With support for generic types:
public void Foo(object obj,string propertyName,object value)
{
//Getting type of the property og object.
Type type = obj.GetType().GetProperty(propertyName).PropertyType;
if (type.IsGenericType)
type = type.GetGenericArguments()[0];
obj.GetType().GetProperty(propertyName).SetValue(obj, Activator.CreateInstance(type, value), null);
}
A: I'm not sure it works, but give it a try:
public static T To<T>(this IConvertible obj)
{
return (T)Convert.ChangeType(obj, typeof(T));
}
Public void Foo(object obj,string propertyName,object value)
{
Type t= obj.GetType().GetProperty(propName).PropertyType;
obj.GetType().GetProperty(propName).SetValue(obj, value.To<t>(), null);
}
A: I used the Convert function in C#. The way I'm doing my conversion is using reflection.:
Type type = this.myObject.GetType();
if (type.Name == "MyObjectClass") {
var Voucherrequest = (MyObjectClass)Convert.ChangeType(myObject, typeof(MyObjectClass));
This is all assuming you know what type you want to convert into. You can even make a switch and have multiple types you want to reflect too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "26"
} |
Q: 404 error with Apache rewrite and userdirs On my computer I have an Apache server with rewrite and userdir modules enabled.
The website is located in /home/pedro/Dropbox/www/cocina/ and the webserver root is /home/pedro/Dropbox/www/
If go to http://localhost/~pedro/cocina/index.php the website shows ok.
In my .htaccess I have the following:
RewriteEngine On
RewriteBase /~pedro/cocina/
RewriteRule ^receta/([^/]*)/([^/]*)\.html$ /index.php?receta=$1&desc=$2 [L,PT]
But when I try to open http://localhost/~pedro/cocina/receta/1234/blabla.html I get a 404 error (index.php not found).
Looking at mod-rewrite logs I can't see any problem:
rewrite 'receta/1234/blabla.html' -> '/index.php?receta=1234&desc=blabla'
forcing '/index.php' to get passed through to next API URI-to-filename handler
trying to replace prefix /home/pedro/Dropbox/www/cocina/ with /~pedro/cocina/
internal redirect with /index.php [INTERNAL REDIRECT]
Where's the problem?
note: If I set up a v-host instead of using userdirs, the redirect works fine.
A: try using this:
RewriteRule ^receta/([^/]*)/([^/]*)\.html$ index.php?receta=$1&desc=$2 [L,PT]
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Check out files from Starteam (5.1) but ignore the specified working folder This question is specific to Starteam version 5.1.
How do I export the most recent version of every file in a Starteam project so that the files end up in a directory structure that matches the folder structure in Starteam?
Here’s the catch: many of the Starteam folders have a hardcoded physical path specified as the working folder’s default value instead of just using the relative path.
Here’s an example:
The working folder for “Custom” is “C:\Projects\Custom”
The working folder for “Training” is “C:\Projects\Custom\Training”
However, the working folder for “Configuration Management” is “d:\TestFiles\CM” so all the files in “Configuration Management” end up on the d: drive.
There are thousands of folders and I don’t know which ones have hardcoded paths.
Is this possible?
A: The following actually helped but it was still a manual process:
When looking at a project, show all the files in all of its sub-directories (“File” menu |”All Descendants” will do the trick). If you sort all the files by the “Path” value you can see all of the output directories and easily find ones that are set to something other than the folder’s default value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Python Error Codes are upshifted Consider a python script error.py
import sys
sys.exit(3)
Invoking
python error.py; echo $?
yields the expected "3". However, consider runner.py
import os
result = os.system("python error.py")
print result
yields 768. It seems that somehow the result of python code has been leftshifted by 8, but how these two situations are different is not clear. What's going on?
This is occurring in python 2.5 and 2.6.
A: From the docs:
On Unix, the return value is the exit status of the process encoded in
the format specified for wait(). Note that POSIX does not specify the
meaning of the return value of the C system() function, so the return
value of the Python function is system-dependent.
os.wait()
Wait for completion of a child process, and return a tuple containing
its pid and exit status indication: a 16-bit number, whose low byte is
the signal number that killed the process, and whose high byte is the
exit status (if the signal number is zero); the high bit of the low
byte is set if a core file was produced.
In your case, the return value 768 in binary is 00000011 00000000. The high byte is 3.
A: Docs
os.system()
On Unix, the return value is the exit status of the process encoded in
the format specified for wait()
os.wait()
a 16-bit
number, whose low byte is the signal number that killed the process,
and whose high byte is the exit status (if the signal number is zero)
High/low byte for 768
00000011 00000000
status signal
Specific code
It should be safe to >> 8 the result to get your actual exit status (the result of system() isn't very portable across platforms, however).
import os
result = os.system("python error.py")
print result >> 8
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: Render to Texture OpenGL ES 2.0 I am trying to use a hardware optimized 2D library to zoom (non-interpolated scaling) in and out of an image. Right now I am
*
*Loading the original image
*Making a copy of the original image
*Using the 2D library to "zoom" into the copy
*Generating textures using glTexImage2D from the images
*Applying them to rectangles that I drew
I can't upload images (yet) but here is a link to a screenshot.
http://img.photobucket.com/albums/v336/prankstar008/zoom.png
I would like to zoom in and out of the image on the right by a certain amount every frame, and rather than kill my performance by using glTexImage2D every time, I would like to render to a texture. My questions are
*
*Is this a valid application of rendering to a texture? For clarification, the 2D library takes a pointer to a buffer filled with raw RGB(A) data, and returns a pointer to the new data with the 2D operation applied.
*I think most of my confusion has to do with how textures interact with shaders. Can someone explain the simplest way to apply a texture to a surface in GLES2? I obviously have something working, and I can post snippets of code if necessary.
*Also for clarification, although I'm not sure it matters, this is being run on Android.
Thank you.
A: 1) No, it is not. If you just want to zoom in and out of the image (without using your zoom library), then rendering to another texture would be a waste of time. You can zoom directly in your view.
2) Shaders are programs, that are capable of calculating and transforming coordinates (that is usually done in vertex shaders) and are able to use those coordinates to read from texture (that can only be done in fragment shader at the time).
I believe your shaders could look like this:
precision mediump float;
uniform matrix4 modelviewProjectionMatrix; // input transformation matrix
attribute vec3 position;
attribute vec2 texcoord; // input coordinates of each vertex
varying vec2 _texcoord; // output coordinate for fragment shader
void main()
{
gl_Position = modelviewProjectionMatrix * vec4(position, 1.0); // transform position
_texcoord = texcoord; // copy texcoord
}
That was vertex shader, and now fragment shader:
precision mediump float;
varying vec2 _texcoord; // input coordinate from vertex shader
uniform sampler2D _sampler; // handle of a texturing unit (e.g. 0 for GL_TEXTURE0)
void main()
{
gl_FragColor = glTexture2D(_sampler, _texcoord); // read texture
}
What you can do, is to include a zoom parameter (so called uniform) in vertex shader:
precision mediump float;
uniform float zoom; // zoom
uniform matrix4 modelviewProjectionMatrix; // input transformation matrix
attribute vec3 position;
attribute vec2 texcoord; // input coordinates of each vertex
varying vec2 _texcoord; // output coordinate for fragment shader
void main()
{
gl_Position = modelviewProjectionMatrix * vec4(position, 1.0); // transform position
_texcoord = (texcoord - .5) * zoom + .5; // zoom texcoord
}
There are no changes in fragment shader. This just calculates different coordinates for it, and that's how simple it is. To set zoom, you need to:
int zoomLocation = glGetUniformLocation(yourProgram, "zoom");
// this is done in init, where you call glGetUniformLocation(yourProgram, "modelviewProjectionMatrix")
// also, zoomLocation is not local variable, it needs to be stored somewhere to be used later when drawing
glUniform1f(zoomLocation, 1 + .5f * (float)Math.sin(System.nanotime() * 1e-8f));
// this will set zoom that will animatically zoom in and out of the texture (must be called after glUseProgram(yourProgram))
Now this will cause both textures to zoom in and out. To fix this (I assume you only want the right texture to be zooming), you need to:
// draw the second quad
glUniform1f(zoomLocation, 1);
// this will set no zoom (1:1 scale)
// draw the first quad
I hope this helps ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is the opposite of attr_accessible in Rails? What is the opposite of attr_accessible in Rails?
Instead of writting every single attribute I want to write just the ones I want to block.
A: attr_protected
Mass-assignment to these attributes will simply be ignored, to assign to them you can use direct writer methods. This is meant to protect sensitive attributes from being overwritten by malicious users tampering with URLs or forms.
A: Its attr_protected, information can be found here...
http://api.rubyonrails.org/classes/ActiveModel/MassAssignmentSecurity/ClassMethods.html#method-i-attr_protected
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MSMQ Peek Permissions Only (i.e. without Receive Permissions)? Summary (tl;dr): We're trying to set up a queue with Peek access but not Receive access for testing purposes (so a Receive request will fail but a Peek will succeed), but it seems MSFT has made that more difficult than anticipated.
Background: We have a local private MSMQ queue from which one process receives and processes (/consumes) messages. In some situations the processing can't be completed and the message stays in the queue (e.g. forwarding destination temporarily offline). A monitor was therefore added to peek at the queue every ~10 minutes and see if the message at the top is the same or not - if the consumer is stalled (the same message is at the top), the monitor triggers an alarm to indicate that something's wrong.
To force the queues to stall for testing purposes (to make sure the monitor function works), we thought we'd just remove (but not deny) Receive permissions from the queue itself but still allow Peek (restarting MSMQ and everything to enforce new permissions), which would ideally allow the monitor to Peek the messages without allowing anyone to Receive (/remove) the messages, 'stalling' the queue and generating an alarm.
While testing this scenario out, however, I ran into an exception that seems to foil this approach:
System.Messaging.MessageQueueException: Access to Message Queuing system is denied.
at System.Messaging.MessageQueue.MQCacheableInfo.get_ReadHandle()
at System.Messaging.MessageQueue.StaleSafeReceiveMessage(UInt32 timeout, Int32 action, MQPROPS properties, NativeOverlapped* overlapped, ReceiveCallback receiveCallback, CursorHandle cursorHandle, IntPtr transaction)
at System.Messaging.MessageQueue.ReceiveCurrent(TimeSpan timeout, Int32 action, CursorHandle cursor, MessagePropertyFilter filter, MessageQueueTransaction internalTransaction, MessageQueueTransactionType transactionType)
at System.Messaging.MessageQueue.Peek(TimeSpan timeout)
This indicates (to me at least) that Peek() internally calls ReceiveCurrent() and must try a transactional Receive that it will then roll back /abort after it's done getting the message. Firing up .NET Reflector, I found that all instances of Peek call some variant of Receive, so a different Peek won't help. So it seems like Receive permissions are required in order to Peek as well, which seems kind of dumb as far as queue design goes.
Note that both the consumer and monitor use the same account (/permissions) and changing the monitoring method (using Peek) isn't a viable option at this point (as that would require significant changes to requirements, specifications, and production code that would cost more than its worth) (though I guess you could propose monitoring methodology changes anyways if you really have to as they might be useful to others if they run into the same thing).
Finally, the Question: Is there a better (or even just different :p) way to Peek at the top of the queue without needing Receive permissions? Or a different way to set the permissions (via permissions interface, via code, etc.) such that Receive itself fails but ReceiveCurrent and other methods required to Peek work?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP Object constant runtime Maximum function nesting level I'm reaching the maximum function nesting level (full list at the end of question). I realize that the solution to this is xdebug.max_nesting_level, but what are the detriments to that? Also, how can I better implement my code.
I'm writing an irc client that right now calls itself a lot.
Call Stack (folded)
# | Time | Memory | Function | Location
1 | 0.0010 | 800152 | {main}( ) | ..\index.php:0
2 | 0.0010 | 802416 | IRCBot->__construc | ..\index.php:225
3 | 0.1104 | 804368 | IRCBot->cont( ) | ..\index.php:34
4 | 0.1945 | 814592 | IRCBot->cont( ) | ..\index.php:144
......|................|...............|.......................|.....................
96 | 113.8191 | 1121560 | IRCBot->cont( ) | ..\index.php:144
97 | 114.0116 | 1126928 | IRCBot->cont( ) | ..\index.php:144
98 | 114.2020 | 1132384 | out( ) | ..\index.php:105
99 | 114.2020 | 1132384 | flush2( ) | ..\index.php:14
I know I can solve this by increasing the max_nesting_level, but then what happens when the nesting level gets to the new max? Also, is the way that I'm doing this bad for memory etc.
function cont($config) {
$data = fgets($this->socket, 256);
$this->cont($config);
}
Questions:
Is increasing the max_nesting_level going to increase load on my server?
Is there any way to re-engineer this code to avoid this issue?
Is it bad to run PHP scripts like this on a CGI installation?
A: Recursion is expensive from both a memory and computation standpoint, and if you're already going past 100 calls, that should alert you to the fact that this is not the right application of a recursive call.
For getting data from a socket it absolutely is not a problem that should be solved using recursion.
A: Sure a while loop would be more efficient. And I also believe you actually want to store all the date that comes back from the socket and not overwrite the contents of $data each time. Additionally it seems not useful to pass the $config variable here. Here an updated version:
function cont() {
while (!feof($this->socket)) {
fgets($this->socket, 256);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why is new String("Hello") invalid in C#? What is the logic/reason behind making
String s= new String("Hello World");
Illegal in C#?
The error is
The best overloaded method match for `string.String(char*)' has some invalid arguments
I'm not interested in the API docs, I am interested in why this is illegal.
Is is because of pooling static strings? like Java pools Integer(-128) to Integer(127) with horrendous results? ( of course strings too )
A: Because strings are immutable and have language support in how they are constructed.
In your example, since you are using a string literal, it will get interned. Any copied string that would have been created from it would end up being the same exact reference, as it would come from the intern pool.
A: It's .NET, not C#. Look at the constructors for System.String - none accept a System.String
So it's "illegal" for the same reason you can't construct a string with an int.
string x = new String(1);
Raymond Chen
The answer to "Why doesn't this feature exist?" is usually "By default features don't exist. Somebody has to implement them."
My guess is that every time someone sat down to implement this constructor. They thought about String.ToString's implementation and determined the constructor would logically undermine that method.
A: It would give the impression that the string is being cloned, but strings are immutable.
A: A string is immutable until you start messing with unsafe code, so the language designers chose not to add a feature that isn't needed in normal usage. That is not to say it wouldn't be handy in certain situations.
If you do this:
string a = "foobar";
string b = a;
Mutate(a, "raboof");
Console.WriteLine("b={0}", b);
where:
unsafe void Mutate(string s, string newContents)
{
System.Diagnostics.Debug.Assert(newContents.Length == s.Length);
fixed (char* ps = s)
{
for (int i = 0; i < newContents.Length; ++i)
{
ps[i] = newContents[i];
}
}
}
You may be surprised to know that even though string 'a' is the one that was mutated the output will be:
b=raboof
In this situation one would like to write:
string a = "foobar";
string b = new String(a);
Mutate(a, "raboof");
Console.WriteLine("b={0}", b);
And expect to see output like:
b=foobar
But you can't, because it is not part of the implementation of System.String.
And I guess a reasonable justification for that design decision is that anyone comfortable writing something like the unsafe Mutate method is also capable of implementing a method to clone a string.
A: It would be rather pointless to use the constructor to create a new string based on another existing string - that's why there is no constructor overload that allows this. Just do
string s = "Hello World";
A: The constructor you are trying to use takes in...
A pointer to a null terminated array of Unicode characters
...rather than a String.
(See http://msdn.microsoft.com/en-us/library/aa331864(v=VS.71).aspx)
A: Just to make Eric Lipperts comment visible:
Features have to be justified on a cost-benefit basis. What's the benefit that justifies the cost? If there's no benefit that justifies the cost then it should be illegal simply on the economic grounds that we have better things to do than to design, specify, implement, test, document and maintain a constructor that no one uses or needs.
A: At my end, I get this:
The best overloaded method match for `string.String(char[])' has some invalid arguments
May be you typed "char *" in place of "char[]" while posting.
Perhaps this has got to do with our historic understanding of literals. Prior to C#, a value enclosed in quotes (like "astringvalue") could be treated as a character pointer. However in C# "astringvalue" is just an object of type string class. The statement:
String s= new String("Hello World");
would imply create an object of type String class and invoke its constructor. The compiler checks the list of constructors available for string class. It cannot find any constructor that could accept a string object ("Hello world"). Like in any other situation, the compiler makes a best guess of which is the "closest" method from the list of overloaded methods - in this case, assumes a string value "Hello world" to be closest to a character array (char []) - and tells you that your "Hello world" (value that you passed) is an invalid value for "char []".
A: In my opinion, The basic difference is the 'Pass by Reference' and 'Pass by Value' in .NET and JAVA.
Leading to a design pattern in Java, for a reason which may be
A constructor for copying an object of the same class.
In .NET you don't require such constructor to copy/clone the string because it can do it in following way (directly),
'String test = txtName.Text;'
This is my understanding of .net and java.
I hope I was able to give proper reasoning.
Thanks and Regards
Harsh Baid
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616197",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Relative URLs with .htaccess I have a custom PHP framework in which everything after the domain is sent to PHP as a $_GET variable, like so:
RewriteRule ^(.*)$ index.php?page_request=$1 [QSA,L]
All routing is done by a router file. For example, http://domain.tld/page gets sent to http://domain.tld?page_request=home.
However, if I have a directory-like structure (i.e. http://domain.tld/page/), the request is sent, but any relative URLs in the HTML are now relative to /page, even though we're still in the root level in the domain.
To clarify:
Going to http://domain.tld/page and requesting res/css/style.css in HTML returns a stylesheet.
Going to http://domain.tld/page/ and requesting res/css/style.css returns an 404 error, because the page/ directory doesn't actually exist.
What's the best way to work around this? This seems really simple, but I'm not quite good enough with .htaccess yet to do it off the top of my head. Thanks for any answers in advance.
Edit: Also, my .htaccess file contains:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
Edit #2: Yes, I know about using the leading /.
However, I can't do that with this particular website, because it's a subfolder on a server, so linking to / would go to the root of the server and not the site.
If I put /subfolder/css for every link on the site, that would not only get tedious, but also problematic were the subfolder to change. Is there a better way to work around this?
A: Relative URLs are not affected by apache rewrite rules. They're up to the browser. If the browser sends a request for /some/random/path/, you can rewrite it all you want on the server end, but the browser will interpret all relative urls as being inside /some/random/path/
If you want to include res/css/style.css from the root, you should prefix it with a leading slash to make that clear: /res/css/style.css
A: The other answers that say you have to absolutize the paths are correct. If you are working in a subfolder, there are two things that you can/should do to help:
1) Use RewriteBase in your htaccess file
RewriteEngine on
RewriteBase /framework/
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)/?$ index.php?url=$1 [QSA,L]
2) Create a constant in your framework that has that same path
define('FULL_PATH', '/framework');
Then each time you create a URL in html, make sure you do something like
<a href="<?= FULL_PATH ?>/your/remaining/path">
It's a little bit of extra work to think about this each time you create a URL on the page, but it will serve you well in the long run.
A: If you are looking for a dynamic solution (in case you move the entire site to a subfolder or different domain), you can use PHP to get the absolute path of a file you are running (like your main php file) and then store that path in a constant or variable that you can use for all of your links.
if ( !isset($_SERVER['HTTPS']) ) { $domain = 'http://'.$_SERVER['HTTP_HOST']; }
else { $domain = 'https://'.$_SERVER['HTTP_HOST']; };
$root = $domain.str_replace($_SERVER['DOCUMENT_ROOT'], '', dirname(__FILE__) );
The first two lines just setup how the path will start, whether it should be http or https.
The third line gets the full server path to the file that this code is in, removes the unnecessary parts (user/public_html) and stores it in the variable $root.
You can then link your files this way:
<script src="<?php echo $root; ?>/jquery.js"></script>
With this method, the site can be moved to any domain or subfolder, and you don't have to worry about breaking links.
Edit:
I just thought of an easier way to use this method. Rather than using absolute links, you could use your normal relative links along with this in the head of the document:
<base href="<?php echo $root; ?>/">
This rewrites the base path for your relative links to the correct directory. Then this will work:
<script src="jquery.js"></script>
A: You need to absolutize all the paths in your html code so you link to your CSS using absolute paths instead of relative.
If you are running into this problem, I suspect your CSS looks like this:
<link href="res/css/style.css" rel="stylesheet" type="text/css" media="screen" />
But it should look like:
<link href="/res/css/style.css" rel="stylesheet" type="text/css" media="screen" />
Do the same for javascript, css, image files and links and you should be fine with your rewrite rules.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616201",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Maximum number of JMS Queues We have an application that has
1) a custom server (conventional ServerSocket) that responds to
2) Java SWING applications/applets running on client desktops.
We have more than 140 such custom servers (dedicated to each group of swing clients). We have built an administration application to manage the server startups, shutdowns and other stuff. For the communication between the Admin app and the Server we are building a JMS application.
Due to the heavy burden on the server we are not placing this JMS on the same box, therefore we have left over an option to have seperate JMS box. I need a seperate Queue for every Server.
My Question is can we have 140+ JMS Queues on a single Application Server. If yes what should be the ideal configuration of the hardware. If no, then what do you suggest.
Thanks
A: I found this interesting article some time ago:
[ActiveMQ] Broker fails after opening 700 queues on a node due to too many open files -- apparently it has a tempfile for each queue, and an open file for each JAR (of which there are 124!), and 60 miscellaneous filehandles. The number of open files does not decrease when the client quits. Some googling implies that there are numerous bugs in ActiveMQ relating to leaked filehandles.
A: you can either use fewer queues and message selectors (to pull messages specific to each client) or see this page on how to configure ActiveMQ to handle large numbers of queues...
also, if you are using KahaDB 5.3+, then it is optimized to use fewer file descriptors, etc...
A: I'll answer the "if not" part only.
If needed, you can reduce the queue count by making use of message selectors. A group of servers can send to one queue and be identified by a message property. You surely must have it defined already — an IP, URL that uniquely identifies a server.
This is a last-resort-solution, though, as separate queues can be monitored better.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616202",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Fastest possible Apple Style Flip Counter in native code on iOS I'd like to mimic an Apple style flip counter on iOS.
Specifically, this thing is going to be FLYING FAST. It's not going to be an alarm clock, think player high-score where you are racking up points chunks at a time. The counter may jump from 0 to 100, to 5000, it will not increment sequentially, but when it does increment it will animate to the next number at a nice clip and it's going to be jumping to the next target value in a second or two. It will not have a set number of digit places either, it can count from 0 to 2,000,000 if it wanted to. Like a player high-score, you don't know what they will end up getting. Since it can't be negative, theoretically maximum would be UINT_MAX
I did some searching, and I found a couple of great resources, neither of which seems to me like the correct approach.
This is a js/css approach the theoretically could run inside a UIWebView:
*
*http://cnanney.com/journal/code/apple-style-counter-revisited/
And this article explains how to do page turning in Core Animation. It's detailed enough, but it seems to me like it's missing some key components, and would cause touches to get ignored on the UI while it's flipping.
*
*https://web.archive.org/web/20150321200917/https://www.voyce.com/index.php/2010/04/10/creating-an-ipad-flip-clock-with-core-animation
Now, after reading these I've got some different ideas on how to do it on my own, trying to weigh the pluses and minuses of each approach:
1) Load up the html counter whole-sale in the UIWebView.
*
*Apparent benefits: possibly tons of code reuse, quick and dirty
*Apparent downsides: the overhead of a UIWebView and constant calls to stringByEvaluatingJavaScriptFromString from the host app which has the next number just seems silly
2) Create a custom sprite sheet and use core animation
*
*Apparent benefits: native code, seems like it would be a less fugly approach than using the web view
*Apparent downsides: creating a custom sprite sheets at this point seems a bit pointless in the face of custom drawing since I'm already creating a view with custom drawing anyway. Seems like the only way to get it to perform well would be to draw images to sublayers rather than using UIImageViews
3) Render text/rounded rects with Core Graphics
*
*Apparent benefits: 100% native code solution, no images
*Apparent downsides: boatloads more code that having some UIImage instances. Don't really know if I can get the right look I'm after without the images
4) Render the whole thing with OpenGL ES 2.0
*
*Apparent benefits: complete control over rendering, possibly best performance
*Apparent downsides: seems to me like I would still probably need some images to bind to textures, probably piles more code than core graphics rendering in #3
On the one hand, I can rationalize it and say the animation is only going to last a half a second or a second, so the best thing to do is to just fake it somehow with blurry images and not actually animate anything. On the other hand it seems to me this is precisely what Core Animation + Core Graphics was designed to do well, and I ought to use them.
A: Ended up doing the drawing with images using image sprites.
code here
https://github.com/reklis/flipcounter
A: screen short show both image view from right to left original and from left most re-size image flipCounter work good in Xcode but there is one issue the issue is how i re-size the FlipCounter View. when i change the original image with small image tis work not good.![this image 50% smaller then original image][2]
i am waiting for Positive Reply.
Thanks advane
A: If it were me, I'd go the core graphics route and just draw the text into the view in the drawrect method. I'd probably construct some kind of background and foreground images that I can overlay the text with to achieve the UIPickerView look. Since you'd only really have to animate the text, you could probably overlay some kind of semi-transparent gradient image that will make it look like the numbers are flipping around and going into shadow.
The OpenGL route seems a bit excessive if you're not programming the game in OpenGL. (plus you'll have to write a bunch of boilerplate code to render text and load images into textures, etc.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616207",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Running a process remotely using Python Is it possible to run a System process remotely , i.e. in the background using python?
For e.g. I ave Scilab installed on my system, now I do something like this
xx= os.system('scilab-adv-cli')
in the python console. But this fires up an actual scilab command line interface. Though I need something like this :
xx.add(1,2)
here is some function predefined in scilab module whic on invoking should return 3 here. CAn this be done?
A: If this is limited to Scilib, check out http://forge.scilab.org/index.php/p/sciscipy/
which should let you do everything scilib can do from within python.
Also, while this doesn't solve your problem, you should considering using subprocess instead of os.system
http://docs.python.org/library/subprocess.html#module-subprocess
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616215",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iPhone - launching an UIImagePickerController from a UIWindow How may I launch a UIImagePickerController from the main UIWindow (no view defined) from - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions, on a project for which the main window does not have a built-in Navigation controller into IB (and without having to add one into IB)?
A: If you don't need UINavigationController then just place regular UIViewController as a root view for main windows. And present UIImagePickerController from it.
Example:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window.rootViewController = [[[UIViewController alloc] init] autorelease];
UIImagePickerController *imagePickerController = [[[UIImagePickerController alloc] init] autorelease];
[self.window.rootViewController presentModalViewController:imagePickerController animated:YES];
[self.window makeKeyAndVisible];
return YES;
}
A: self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
[window addSubview:imagePickerController.view];
That should accomplish what you want.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616217",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Like Box Div Code - How to I put it on my website using Dreamweaver....currently does nothing Here is the code that the facebook developer page gave me for my site. I've tried putting it in by itself in the body of my code and with and iframe but cant get it to work. any help is appreciated. thanks
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/all.js#xfbml=1";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
<div class="fb-like-box" data-href="http://www.facebook.com/lapastabella" data-width="292" data-show-faces="true" data-stream="true" data-header="true"></div>
A: Try changing this line:
<div id="fb-root"></div>
To:
<div id="facebook-jssdk"></div>
It looks like an error with the code they give you. If you read the code its looking for an object with an id of facebook-jssdk which doesn't exist.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616224",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Django1.3 , Python2.7 django-admin.py is not working on windows I installed Django1.3 on Windows 7 , i made sure i have Python2.7 , Python2.7/Lib and Python2.7/lib/site-scripts/django/bin in my system PATH ...
but, when i try to make django-admin.py creates a new project :
django-admin.py startproject exampleproject
it opens djangp-admin.py file in text-editor ..
same issue is happening when trying to run GAEFramework - GAE dev_appserver.py
gaeframework/google_appengine/dev_appserver.py
How i can solve this issue ... !
Regards
A: you just need to associate .py files with python. or run it explicitly:python django-admin.py startproject exampleproject
A: You have probably set up python files to be opened by text editor by default. I just tried installing django on windows and everything works fine
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how do I debug the height of a div/span? I have html like this:
<div>
<span style="display: inline-block;height:20px">20</span>
<span style="display: inline-block;"><img src="img/ex.png"/></span>
</div>
The image I am importing in the second span is 15x15 pixels
I can check with chrome and I can see that the first img has height 15
and the second span has height 21. (the first one has height 20 as expected)
can somebody tell me why the second span has height 21 instead of 15 ???
Thanks, it's driving me nuts
I am adding the ode below:
<!DOCTYPE html>
<html>
<head>
<style>
/* http://meyerweb.com/eric/tools/css/reset/
v2.0 | 20110126
License: none (public domain)
*/
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
}
ol, ul {
list-style: none;
}
blockquote, q {
quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
content: '';
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
</style>
</head>
<body>
<div>
<span style="display: inline-block;height:20px">20</span>
<span style="display: inline-block;"><img src="img/ex.png"/></span>
</div>
</body>
</html>
A: Well either the image is bigger than you think, the image has padding/margin that you aren't taking into account or the span has padding/margin that you aren't taking into account.
*
*Inspect each element in Chrome, first image then span.
*Expand Metrics on right side of window
*The little graph will show you what each contributor to element size is (padding, margin, border, element size)
A: test in my page, the height is 15px
do you set any span padding?
or try to do *{padding:0;margin:0;}.
or given the span a class, make .span{padding:0!important;margin:0!important;}
or add
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
to the page top part for W3C
A: Use Chrome's developer tools to inspect the element and trace the computed styles. I think it's very likely you're picking up padding styles from somewhere.
A: To view the layout of your html elements, check out my new tool!
HTML Box Visualizer - GitHub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616233",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Using Java to organize array input into a table? I have a program that receives an array. I want to have it organize the results into ranges (like 60-69). It also needs to know how many of the numbers it received fit into which ranges so it can put them in accordingly. The way I've seen to create tabs in a table is
System.out.print("Column1/tColumn2");
How do you go about organizing the array data into a range? Do you specify it with a bunch of IF statements? And I assume you use a counter to tally up how many numbers fit into which ranges?
EDIT: Here's the code at present.
import java.util.Scanner;
import java.lang.Integer;
import java.lang.String;
public class Salary {
int salary;
int sales;
public static void main(String[] args) {
Scanner input = new Scanner ( System.in );
int Salary;
Salary salary = new Salary();
System.out.print( "Please enter the amount each employee brought in:");
String sales = input.nextLine();
String salesArray[] = sales.split(" ");
for(int i=0; i<salesArray.length; i++){
Integer myInt = Integer.parseInt(salesArray[i]);
System.out.print(salesArray[i] + " ");
if (Integer.parseInt(salesArray[i]) <= 0) {
System.out.println("Please enter a value greater than zero");}
else {
Salary = ((myInt/100) * 9) + 200;
System.out.print(Salary); }
}
int two = 0; //declared a variable, starting it at 0 and intending to increment it
//with input from the array
System.out.print("Range/t#ofEmployees");
for(int i=0; i<salesArray.length; i++) {
if (salesArray[i] <= 200){} //Error on the if statement, using the wrong operand
else{ two++;} //Attempt at the table and increment.
}
}
}
A: i won't post an implementation, since this is homework, but think of this:
your array can be sorted ...
you can itterate that array, and count something up if the current value is less than a certain boundary ... once it is greater you can print one range and startover for the next range ...
boundaries can change from range to range ...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Is there any way to construct System.Web.Services.Protocols.InvokeCompletedEventArgs? This is possibly a dumb question since I'm new to all the technologies I'm using here (C#, .NET and SOAP). There just may not be anyway to do what I want to do here.
I've got an asynchronous SOAP call (code generated from WSDL) that I'm trying to alter in such a way that within my library, I'm actually making multiple calls to multiple different web servers and then aggregating the results to return back to the caller. The problem is that the SendOrPostCallback method of the asynchronous SOAP call expects to take an argument of InvokeCompletedEventArgs. I can't construct this because the constructor is declared internal. So while I can hide what I'm doing internally, and call the callback when what I'm doing is complete, I can't return the Results to the caller. Any suggestions?
Old Code:
public void getStatusesAsync(RequestId[] requestIds, object userState)
{
if ((this.getStatusesOperationCompleted == null))
{
this.getStatusesOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetStatusesOperationCompleted);
}
this.InvokeAsync("getStatuses", new object[] {
requestIds}, this.getStatusesOperationCompleted, userState);
}
private void OngetStatusesOperationCompleted(object arg)
{
if ((this.getStatusesCompleted != null))
{
System.Web.Services.Protocols.InvokeCompletedEventArgs invokeArgs = ((System.Web.Services.Protocols.InvokeCompletedEventArgs)(arg));
this.getStatusesCompleted(this, new getStatusesCompletedEventArgs(invokeArgs.Results, invokeArgs.Error, invokeArgs.Cancelled, invokeArgs.UserState));
}
}
New Code:
public void getStatusesAsync(RequestId[] requestIds, object userState)
{
if ((this.getStatusesOperationCompleted == null))
{
this.getStatusesOperationCompleted = new System.Threading.SendOrPostCallback(this.OngetStatusesOperationCompleted);
}
asyncExecuteMultipleSoapCalls("getStatuses", new object[] { requestIds}, this.getStatusesOperationCompleted, userState);
}
private System.IAsyncResult asyncExecuteMultipleSoapCalls(string methodName, object[] args, System.Threading.SendOrPostCallback callback, object asyncState)
{
Thread backgroundSoapCalls = new Thread(new ParameterizedThreadStart(asyncThreadRun));
object[] threadArgs = new object[] { methodName, args, callback, asyncState };
backgroundSoapCalls.Start(threadArgs);
return null;//How to return AsyncResult?
}
private RequestStatus[] multiSoapCallResults = null;
private void asyncThreadRun(object args)
{
string methodName = (string)(((object[])args)[0]);
object[] methodArgs = (object[])(((object[])args)[1]);
System.Threading.SendOrPostCallback methodCallback = (System.Threading.SendOrPostCallback)(((object[])args)[2]);
object asyncState = (((object[])args)[3]);
//To make a long story short, I'm using this thread to execute synchronous
//SOAP calls, then call the event. The reason is that different requestIds
//in the passed in array may reside on different Web Servers. Hopefully,
//this will work similarly to the original Asynchronous call
multiSoapCallResults = executeMultipleSoapCalls(methodName, methodArgs);
//Now that I'm done, I want to pass the evenArgs to the SendOrPostCallback
RequestStatus[] returnStatusArray = new RequestStatus[multiSoapCallResults.Length];
multiSoapCallResults.CopyTo(returnStatusArray, 0);
multiSoapCallResults = null;
//This line doesn't compile of course, which is the problem
System.Web.Services.Protocols.InvokeCompletedEventArgs eventArgs = new System.Web.Services.Protocols.InvokeCompletedEventArgs(null, false, null, returnStatusArray);
//Need to pass event args here
methodCallback(eventArgs);
}
A: Turns out it was a dumb question. The wsdl generation already subclasses that InvokeCompletedEventArgs. The class I suggested making in my comment above already exists in the generated code. I just needed to find it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to set jquery cookie for a URL with Fragment? I am using the jquery cookie plug-in https://github.com/carhartl/jquery-cookie.
I saw this reference on how to build a URL with Fragment:
AJAX Applications Crawlable
The final url rule looks like this:
localhost/site/search#!key__searchword&page=1
localhost/site/search#!key__searchword&page=2
localhost/site/search#!key__searchword&page=3
(original url should like this: localhost/site/search?_escaped_fragment_key=searchword&page=1)
Each above page has one button, I want to check:
*
*If user never clicked, he/she can do the click,
*If user has clicked, then add class voted for forbidden click again.
*I want set cookie for 7 days.
My javascript code:
$(document).ready(function(){
$(".up").live('click',function() {
$.cookie('up', 'vote', { expires: 7, path: '/', domain: 'http://127.0.0.1/site/' });
var up = $.cookie('up');
if (up == 'vote') {
$(".up").addClass('voted');
};
});
});
In anycase, the jquery cookie does not work for me. How can I set the jquery cookie for a URL with Fragment?
A: You should set the cookie after checking whether the cookie exists or not A basic implementation should look like this:
$(document).ready(function(){
$(".up").live('click',function() {
var up = $.cookie('upvote');
var currentLoc = location.hash;
if (up && up.indexOf(currentLoc) == -1) {
$(this).addClass('voted');
};
else {
var saveCookie = up ? up + currentLoc : currentLoc;
$.cookie('upvote', saveCookie, { expires: 7, path: '/', domain: 'http://127.0.0.1/site/' });
//rest of functions
}
});
});
The current location is retrieved through location.hash. If the location's hash already exists in the cookie, the Already voted routine is followed. Else, a cookie is updated.
Note that this script will prevent a user from voting for seven days, each time the cookie is updated. You can use the hash as a cookie name if you want to set the seven day penalty individually for each page.
A: Fragments are never sent to the server, so you cannot set a cookie for a fragment. You can only set a cookie for the path, and it defaults to the path up to the last forward slash I believe according to the RFC.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Build an IDT (INTERRUPT DESCRIPTOR TABLE) assembly AT&T intel 32 bits I try to build an IDT, after sti execution, the code crashes !!
I have an error message :
SingleStep CPU[1] Error : Processor Running
Remark: I use micro Atom with eclipse Helios, the assembly is AT&T
/** *********** New code *********/
New code after I found that the BIOS puts the atom in the protected mode (CR0.PE = 1) and generates IDT/GDT :
The idea is just to use an ISR with APIC timer.
/*Change the address of idt_entries table */
fill_interrupt(ISR_Nbr,(unsigned int) isr33, 0x08, 0x8E);
static void fill_interrupt(unsigned char num, unsigned int base, unsigned short sel, unsigned char flags)
{
unsigned short *Interrupt_Address;
/*address = idt_ptr.base + num * 8 byte*/
Interrupt_Address = (unsigned short *)(idt_ptr.base + num*8);
*(Interrupt_Address) = base&0xFFFF;
*(Interrupt_Address+1) = sel;
*(Interrupt_Address+2) = (flags<<4)&0xFF00;
*(Interrupt_Address+3) = (base>>16)&0xFFFF;
}
/*********************End new code *********************/
idt_flush:
push %ebp //save the context to swith back
mov %esp,%ebp
cli
mov $idt_ptr, %eax //Get the pointer to the IDT, passed as parameter
lidt (%eax) //Load the IDT pointer
sti
pop %ebp //Return to the calling function
ret
What is wrong ???
see the rest of the code:
isr33:
push %ebp //save the context to swith back
mov %esp,%ebp
pop %ebp //Return to the calling function
ret
static void init_idt()
{
int iIndex;
//Link the IDTR to IDT
idt_ptr.limit = sizeof(idt_entry_t)*256-1;
idt_ptr.base = (unsigned int)&idt_entries;
idt_set_gate(0,(unsigned int) isr0, 0x00, 0xEE);
for ( iIndex=1; iIndex<32; iIndex++)
{
idt_set_gate(iIndex,(unsigned int) isr0, 0x00, 0x00);
}
idt_set_gate(ISR_Nbr,(unsigned int) isr33, 0x00, 0xEE);
//idt_flush((unsigned int)&idt_ptr);
idt_flush();
}
static void idt_set_gate(unsigned char num, unsigned int base, unsigned short sel, unsigned char flags)
{
idt_entries[num].base_lo = base&0xFFFF;
idt_entries[num].base_hi = (base>>16)&0xFFFF;
idt_entries[num].sel = sel;
idt_entries[num].always0 = 0;
idt_entries[num].flags = flags;
}
//IDT
struct idt_entry_struct
{
unsigned short base_lo;
unsigned short sel;
unsigned char always0;
unsigned char flags;
unsigned short base_hi;
}__attribute__((packed));
typedef struct idt_entry_struct idt_entry_t;
//IDT register
struct idt_ptr_struct
{
unsigned short limit;
unsigned int base;
}__attribute__((packed));
typedef struct idt_ptr_struct idt_ptr_t;
//ISR number
int ISR_Nbr = 33;
A: Can you explain why you set the selector values in IDT entries to 0? Aren't they supposed to be somewhat more meaningful?
I don't remember the details (and am too lazy to check the documentation at the moment), but set your access byte in IDT entries to 0x8E, not 0 or 0xEE. That should work. You can make it more complex later.
Finally, is isr33() a C function or assembly function? Does it save and restore segment registers and general-purpose registers? Show us the function.
Don't enable interrupts yet. First make sure that your isr33 functions properly when invoked through INT 33. Why? Having seen the above, I anticipate issues with the PIC configuration and handling and any hardware interrupt can just crash your code if the PIC is not programmed correctly.
A: Resolved, As I use a N450 Atom board, it has already a BIOS, the BIOS makes the IDT and GDT, all I have to do it is just to now where they are by reading thier adressess with : sidt (for IDT) and sgdt (for GDT).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616247",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MVC3 validation attribute breaks model I'm working with MVC3. I have a model object that I created with fluidNhibernate. It contains some value types, and some reference types of other objects also created through fluid. Lazy loading is enabled. In order for the reference types to show up as dropdown boxes on my view I have code like this:
@Html.DropDownListFor(m => m.TheObject.objId, new SelectList(Model.TheObjects, "ObjId", "ItemToDislpay"))
The controller assigns a List<TheObject> to Model.TheObjects before passing the model to the view.
The edit action in my controller:
public ViewResult Edit(int id)
{
myModelType myModel = //get my model object by id here.
myModel.TheObjects = //assign List<SomeObject> here
myModel.TheObjects2 = //assign List<SomeObject2> here
return View(myModel);
}
[HttpPost]
public ActionResult Edit(MyModelType myModel)
{
if(ModelState.IsValid)
{
....
}
else
{
//We end up here even though the validation should have succeeded
// myModel.TheObjects is null, but I don't know why
return View(myModel);
}
}
Example of attribute:
[Required(ErrorMessage = "Please enter Username")]
public virtual string UserName { get; set; }
Everything is working fine, until I add validation attributes to model properties. It doesn't matter to which parameter I assign the attribute to. As long as I have at least one validation attribute ModelState.IsValid returns false and all the Lists that I assigned in the non-post action are null in myModel. I tried disabling client side validation but that didn't help. What could be causing this?
I thought that the lists are supposed to be passed back, but I guess not. Still why is the validation failing if the required string exists?
It seems like the FirstName validation is failing on the server side ModelState.IsValid is saying that First Name is missing, while the model object clearly has the First Name field filled in. Here's how my view is processing FirstName:
<div class="editor-field">
@Html.EditorFor(model => model.FirstName)
@Html.ValidationMessageFor(model => model.FirstName)
</div>
Here's how I submit:
<input type="submit" value="Save" />
client side validation correctly catches the empty FirstName field, and stops the submit, but if I fill in the FirstName then the server side code gives me problems described above.
A: Your question is still a little vague, but this may help with your problem.
Add this attribute to your model:
[MetadataType(typeof(MyModelTypeMeta))]
public partial class MyModelType
{
...
}
and add the MyModelTypeMeta class like shown below, adding a field to match each string property, and telling the model binder to the let the empty string values stay empty instead of changing them to null, which usually causes string properties to fail binding (because you don't have them defined as nullable in your model)
public class MyModelTypeMeta
{
[DisplayFormat(ConvertEmptyStringToNull=false)]
public string myProperty;
}
A: Looking at what you have added, I am betting the problem is with the empty List<someObject> is null when it should at least be an empty list. (and the same goes for the List<someObject2> property)
In your constructor for MyModelType, you should initialize those to empty lists so that the binder does not see them as null. something like:
public MyModelType()
{
myModel.TheObjects = new List<SomeObject>();
myModel.TheObjects2 = new List<SomeObject2>();
...
}
A: Ok, I figured out the problem. Thanks to Neil N with helping me along with troubleshooting ideas. First of all, the lists need to be reassigned in the postback action if the validation fails, as they don't get kept from the view and we will need them again when the model is sent back to the view.
Now, the heart of the problem is this. One of the fields in my model is a property that's of the same type as the model. Specifically, each user has a manager property which is also of type user. It is a reference type that's lazy loaded by nhibernate. When I decorated the FirstName property as required for the user, this applies to the user's manager as well. The manager object only has the UserId field set, since that is what we were binding to the dropdownlist in the view. By looking at ModelState.Values I found the error message saying that first name is required in under value index 9. The critical troubleshooting step was to now look at the ModelState.Keys collection and find the item with the same index 9, which had a value of Manager.FirstName. So, it's the manager object that had a null FirstName, not the immediate User object that was being edited.
I guess the question now is how I should resolve this problem. Should I do my bindings differently? Do I do something on the nHibernate side? Should I do custom validation? Should I somehow specify the Manager object only to check if a valid userId is selected for the Manager? I would love to hear some suggestions. Thanks you very much for everyone's help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616248",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: File Handling : unusual error reading file The output of the program is this :
Although correct contents
(for now only when trying to decrypt producing wrong result)
but why this error ??
udit@udit-Dabba /opt/lampp/htdocs $ ./a.out
Error reading password from BIO
Error getting password
Salted__�Yq\��v��u�&2�t���-�
The code for program is this -
#include <stdio.h>
#include <stdint.h>
void crypto(uint8_t *key, uint32_t keylen, uint8_t *data, uint32_t datalen);
int main () {
uint8_t icv[10]="uditgupta";
uint8_t ekey[14]="1234567891011";
uint8_t *key=ekey;
uint8_t *data=icv;
crypto(ekey,13,icv,9);
return 0;
}
void crypto(uint8_t *key, uint32_t keylen,uint8_t *data, uint32_t datalen)
{
int ch,i;
uint8_t mydata[100],modata[100];
uint8_t *p=mydata;
FILE *fp,*fq,*fr;
fp=fopen("key","w");
fputs(key,fp);
fq=fopen("file.txt","w");
fputs(data,fq);
memset(data,0,sizeof(data));
system("sudo openssl enc -aes-256-cbc -salt -in file.txt
-out file.enc -pass file:key");
fr=fopen("file.enc","r");
memset(mydata,0,sizeof(mydata));
i=0;
while( (ch=fgetc(fr)) != EOF) {
mydata[i]=ch;
i++;
}
i=0;
puts(p);
}
I think i need to change the read/write mode of file but not sure...Please guide me what an I doing wrong ???
A: Try either flushing or closing fq and fp before the call to system. The problem is probably that the data you have just written to the files has not been flushed to disk yet when the openssl command is run.
A: how to upgrade openssl
Upgrade to latest Platform.
OpenSSL Tarballs
For more read How to update OpenSSL using Putty and yum command
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery datatables as a replacement for JSF component library offerings About a year ago, the jQuery protagonist and author Bear Bibeault made a comment on
coderanch to the effect that perhaps JSF component libraries weren't all they're made
out to be and that you can do a lot with javascript & jQuery.
I thought I'd take a fresh look at this, having just transitioned to jQuery UI dialogs,
and wishing I'd done it a long time ago.
One thing I've had nothing but trouble with is putting anything more complicated than
an h:outputText in a datatable (slight exaggeration there). I've just spent the best
part of the day getting a selectOneMenu working in a datatable, porting previously
working code from one xxx:dataTable to another, but things are firing off in different
phases, ajax requests in an unexpected order (despite a single queue), steam coming out
the debugger.
So I thought I'd take a look at the viability of using one of the jQuery datatable
offerings (comparisons available in other posts of course).
I'll want to continue to use various JSF components within the datatable, and I just
wondered if there are any major considerations to take into account. Is fairly serious
jQuery usage in conjunction with a component library a common approach? Is integration
between jQuery and the backing bean a significant irritation?
There've been so many things I've not been able to do according to the original
design because of bugs and I'm fed up with waiting a year for a fix.
Thanks for any opinions.
A: I strongly recommend combining JQuery with any server-side technology. Rich server-side controls just reformat your output and generates lot of JavaScript to implement Web 2.0 effects. However, you cannot be sure would they work in all future browsers and how long. The purpose of JavaScript libraries (JQuery, Mootools, etc) is to enable a base functionality that guarantees cross browser compatibility and them you can create good plugins on top of them.
Also there is an issue with compatibility. As you already say, you can spend a lot of time transforming one server-side table component to another.
However, if you use JQuery plugins you can simply replace them. As an example if you have used JQuery DataTables to enhance web tables:
$("table#theTableId").dataTables();
If you want to replace it with some other JQuery table plugin such as jqGrid, you will replace this line of code with:
$("table#theTableId").jqGrid();
Optionally you should replace some initialization parameters. The only prerequisite is that your server-side component generates the HTML valid output for the table source.
And as a last note if you are using Ajax - use JavaScript. This is the most natural and easiest way to implement Ajax functionality. All other server side components just tries to hide JavaScript code from you but this is fine only in the basic functionalities. If you need any customization you will end-up with mix of Java, JavaScript and markup on the same place, and after lot of updates you will see that it would be better to implement all JavaScript related functions in the oure JavaScript/JQuery.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616254",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: (view-based) NSTableView's reloadDataForRowIndexes:columnIndexes: not removing row view? Trying to use reloadDataForRowIndexes:columnIndexes: for my view based NSTableView in 10.7. Having redraw problems though. If I edit the object and call reloadDataForRowIndexes:columnIndexes: and later delete the object, I end up with a static row view.
To docs warn:
For view-based table views, reloadDataForRowIndexes:columnIndexes:
will drop the view-cells in the table row, but not the NSTableRowView
instances.
Not sure how I should tell the table view to drop the row view too. If I use reloadData everything works but obviously it's a lot heavier a method to call and causes loss of selection.
Any thoughts?
UPDATE: Added a demo app to demonstrate the bug. Can be found on GitHub. It has workaround code but none-the-less I'd still like to find the answer.
https://github.com/zorn/NSTableView-ViewBased-ReloadRowBug
A: I think I fixed this bug. Turns out you have to be careful about closing with [self.tableView endUpdates] before attempting any kind of reloadDataForRowIndexes:columnIndexes: on the tableview.
I'll append my radar requesting a formal console working be logged when attempting to do such a thing.
GitHub project has been updated.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: For Loop on Lua My assignment is how to do a for loop. I have figured it out in terms of numbers but cannot figure it out in terms of names. I would like to create a for loop that runs down a list of names. Following is what I have so far:
names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
print (names)
end
I have tried some other things but it just doesn't work, the terminal always just lists 1, 2, 3... What I am doing wrong?
A: Your problem is simple:
names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
print (names)
end
This code first declares a global variable called names. Then, you start a for loop. The for loop declares a local variable that just happens to be called names too; the fact that a variable had previously been defined with names is entirely irrelevant. Any use of names inside the for loop will refer to the local one, not the global one.
The for loop says that the inner part of the loop will be called with names = 1, then names = 2, and finally names = 3. The for loop declares a counter that counts from the first number to the last, and it will call the inner code once for each value it counts.
What you actually wanted was something like this:
names = {'John', 'Joe', 'Steve'}
for nameCount = 1, 3 do
print (names[nameCount])
end
The [] syntax is how you access the members of a Lua table. Lua tables map "keys" to "values". Your array automatically creates keys of integer type, which increase. So the key associated with "Joe" in the table is 2 (Lua indices always start at 1).
Therefore, you need a for loop that counts from 1 to 3, which you get. You use the count variable to access the element from the table.
However, this has a flaw. What happens if you remove one of the elements from the list?
names = {'John', 'Joe'}
for nameCount = 1, 3 do
print (names[nameCount])
end
Now, we get John Joe nil, because attempting to access values from a table that don't exist results in nil. To prevent this, we need to count from 1 to the length of the table:
names = {'John', 'Joe'}
for nameCount = 1, #names do
print (names[nameCount])
end
The # is the length operator. It works on tables and strings, returning the length of either. Now, no matter how large or small names gets, this will always work.
However, there is a more convenient way to iterate through an array of items:
names = {'John', 'Joe', 'Steve'}
for i, name in ipairs(names) do
print (name)
end
ipairs is a Lua standard function that iterates over a list. This style of for loop, the iterator for loop, uses this kind of iterator function. The i value is the index of the entry in the array. The name value is the value at that index. So it basically does a lot of grunt work for you.
A: By reading online (tables tutorial) it seems tables behave like arrays so you're looking for:
Way1
names = {'John', 'Joe', 'Steve'}
for i = 1,3 do print( names[i] ) end
Way2
names = {'John', 'Joe', 'Steve'}
for k,v in pairs(names) do print(v) end
Way1 uses the table index/key , on your table names each element has a key starting from 1, for example:
names = {'John', 'Joe', 'Steve'}
print( names[1] ) -- prints John
So you just make i go from 1 to 3.
On Way2 instead you specify what table you want to run and assign a variable for its key and value for example:
names = {'John', 'Joe', myKey="myValue" }
for k,v in pairs(names) do print(k,v) end
prints the following:
1 John
2 Joe
myKey myValue
A: names = {'John', 'Joe', 'Steve'}
for names = 1, 3 do
print (names)
end
*
*You're deleting your table and replacing it with an int
*You aren't pulling a value from the table
Try:
names = {'John','Joe','Steve'}
for i = 1,3 do
print(names[i])
end
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "103"
} |
Q: Using DateTime.ParseExact to get only the time (without the day) I get unexpected results when I use DateTime.ParseExact.
Here's my test code:
Dim MinVal As DateTime = #12:00:01 AM#
Dim MaxVal As DateTime = #11:59:59 PM#
Dim TooBig1, Equal1 As Boolean
Dim TooBig2, Equal2 As Boolean
Dim dt1 As DateTime = #12:00:01 AM#
Dim dt2 As DateTime = DateTime.ParseExact("12:00:01 AM", "hh:mm:ss tt", Globalization.DateTimeFormatInfo.InvariantInfo)
TooBig1 = (dt1.CompareTo(MaxVal) > 0)
Equal1 = (dt1.CompareTo(MinVal) = 0)
TooBig2 = (dt2.CompareTo(MaxVal) > 0)
Equal2 = (dt2.CompareTo(MinVal) = 0)
The result is fine for dt1:
*
*it shows in the debugger as #12:00:01 AM# (without the day)
*TooBig1 is False
*Equal1 is True
But the result is (wrong?) unexpected for dt2:
*
*it shows in the debugger as #9/30/2011 12:00:01 AM#
*TooBig2 is True
*Equal2 is False
It looks like it's because the day is systematically added by ParseExact even though I only specify the time in the format.
My question is: How can I read just the time with DateTime.ParseExact?
A: Documentation states:
If format defines a time with no date element and the parse operation succeeds, the resulting DateTime value has a date of DateTime.Now.Date.
If you want a time with no date, you can use:
var parsedDate = DateTime.ParseExact(...);
var timeOnly = parsedDate - parsedDate.Date;
A: use dt1.TimeOfDay and dt2.TimeOfDay for such comparisons... thus taking the day part out of the equation...
A: If you don't specify a day, it apparently assumes today. (Not unreasonable if you're writing, say, time-tracking software.)
If you just want the time portion, you could parse it like you're already doing, and then grab just the time-of-day portion:
' Existing code:
Dim dt2 As DateTime = DateTime.ParseExact("12:00:01 AM", "hh:mm:ss tt", _
Globalization.DateTimeFormatInfo.InvariantInfo)
' Now grab just the time:
Dim ts2 As TimeSpan = dt2.TimeOfDay
That will be a TimeSpan instead of a DateTime, but if you don't actually need it as a DateTime, TimeSpan is more appropriate for something that's just hours/minutes/seconds but not days.
(You might also try using TimeSpan.ParseExact in the first place, but it isn't built to handle AM/PM, and would parse 12:00:01 as being 12 hours. So you probably do want DateTime.ParseExact followed by .TimeOfDay.)
If you actually do need to represent it as a DateTime -- with a date portion of, say, 1/1/0001 -- you could always convert that TimeSpan back to a DateTime manually:
Dim dt3 As New DateTime(1, 1, 1, ts2.Hours, ts2.Minutes, ts2.Seconds, ts2.Milliseconds)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: QDateTime::fromString not accepting my QString? I have a .txt file which is filled with lines like this below:
*
*2011-03-03 03.33.13.222 4 2000 Information BUSINESS ...etc blabla
*2011-03-03 03.33.13.333 4 2000 Information BUSINESS ...etc blabla
*2011-03-03 03.33.13.444 4 2000 Information BUSINESS ...etc blabla
In some point in my code i do some calculating and seeking, where i extract only the dates from the beginning of each line. Now, when i'm positioned correct at the beginning of a file, i extract only the date and time (with the miliseconds) "ex: 2011-03-03 03.33.13.444" and convert to a QDateTime object.
Assuming that my file pointer is positioned correct at the beginning of a certain line,
with readLine i read my datetime text line and convert to QDateTime object
QDateTime dt;
char lineBuff[1024];
qint64 lineLength;
lineLength=file.readLine(lineBuff, 24);
dt = QDateTime::fromString(QString(lineBuff),"yyyy-MM-dd HH.mm.ss.zzz");
This is apsolutely correct.
But, here is the problem:
When i do the same like this:
QDateTime dt;
QByteArray baLine;
char lineBuff[1024];
file.seek(nGotoPos); //QFile, nGotoPos = a position in my file
QString strPrev(baLine); // convert bytearry to qstring -> so i can use mid()
// calculate where the last two newline characters are in that string
int nEndLine = strPrev.lastIndexOf("\n");
int nStartLine = strPrev.lastIndexOf("\n", -2);
QString strMyWholeLineOfTextAtSomePoint = strPrev.mid(nStartLine,nEndLine);
QString strMyDateTime = strMyWholeLineOfTextAtSomePoint.left(24);
// strMyDateTime in debug mode shows me that it is filled with my string
// "ex: 2011-03-03 03.33.13.444"
// THE PROBLEM
// But when i try to covert that string to my QDateTime object it is empty
dt = QDateTime::fromString(strMyDateTime ,"yyyy-MM-dd HH.mm.ss.zzz");
dt.isValid() //false
dt.toString () // "" -> empty ????
BUT IF I DO:
dt = QDateTime::fromString("2011-03-03 03.33.13.444","yyyy-MM-dd HH.mm.ss.zzz");
Then everything is alright.
What could posibly be the problem with my QString?
Do i need to append to strMyDateTime a "\0" or do i need some other conversions??
A: "2011-03-03 03.33.13.444" is actually 23 characters long, not 24. Your extracted string probably has a extra character at the end?
A: Your string has extra characters, most likely a space in the beginning. Your format string is 23 characters and you are using left(24), so there must be one extra character. You said in the comment to Stephen Chu's answer that changing 24 to 23 dropped the last millisecond character, so the extra character must be in the beginning.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Session injection? How should I host the id of the user on the session? just to insert the id? I mean (for example):
$_SESSION['id'] = 1;
There isn't a way to change it by the user himself (as cookie..)? Because if so, he can change to any id.
One more question about it - how can I check if user is logged in (with sessions)? I created a session:
$_SESSION['is_logged_in'] = true;
Again, can't the user just create a session which his name is 'is_logged_in' and his value is true? or just the server has a control about the value of the server?
A: All session variables in PHP are stored server side.
The client stores a cookie that references which session should be used, and then the server looks up the values for the session.
It is safe to store is_logged_in in your session as well as the user id.
What you should be aware of is if another user gets a hold of another user's session cookie, they will be able to imitate that user until the session times out. One simple solution is to link sessions to IPs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: Phone Gap: Writing to Files - Can't Get Example To Work I'm trying to follow the phonegap example file writing code and running into
issues.
I have tried running this both on a 2.2 emulator instance and on a
phone:
here is my code which is basically a near verbatim paste of the write
file code from API docs + jsconsole and console messages:
<script type="text/javascript" src="http://jsconsole.com/remote.js?
[key_ommited]"></script>
<script> console.log('in between loads.'); </script>
<script type="text/javascript" src="phonegap-1.0.0.js"></script>
<script> console.log('after-phonegap.'); </script>
<script type="text/javascript">
console.log('test to see if this fires within new script tag');
//
// // Wait for PhoneGap to load
// //
// console.log('before add event listener!!');
//
document.addEventListener("deviceready", onDeviceReady,
false);
console.log('after event listener declaration');
function onDeviceReady() {
console.log('in onDeviceReady');
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS,
fail);function fail);(args) {
}
var test_file_full_path = 'mnt/sdcard/test_file2.txt'
function gotFS(fileSystem) {
fileSystem.root.getFile(test_file_full_path, { create:
true }, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
fileEntry.createWriter(gotFileWriter, fail);
}
function gotFileWriter(writer) {
writer.onwrite = function(evt) {
console.log("write success");
};
writer.write("some sample text");
// contents of file now 'some sample text'
writer.truncate(11);
// contents of file now 'some sample'
writer.seek(4);
// contents of file still 'some sample' but file pointer
is after the 'e' in 'some'
writer.write("different text");
// contents of file now 'some different text'
}
function fail(error) {
console.log('in failure: ');
console.log(error.code);
}
And The first time i run the code, What i get from the jsconsole
output (oldest messages at bottom) is:
"write success"
"Error in success callback: File4 = 7"
"This is a file"
"in onDeviceReady"
"test to see if this fires within new script tag"
"after-phonegap."
"after event listener declaration"
"in between loads."
The subsequent times that I run the same code, I instead get:
"9"
"in failure: "
"in onDeviceReady"
[rest of messages are the same]
If i go into the DDMS perspective, I see teh generated 'test_file2'
file in the directory, but if I try to pull the generated 'test_file2'
file, it won't let me pull it off the emulator and says:
[2011-09-30 14:47:32] Failed to pull selection
[2011-09-30 14:47:32] (null)
I also cannot delete this file.
In an earlier attempt i was able to pull the file and see that the
first line of the write code 'some sample text' had been written, but
presumably it had stopped short of the other write lines.
Anyone have any idea what I am doing wrong / any advice? This writing to file is bothering me in how much trouble i'm having.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How To: Custom Edit Column name and Value in a Telerik Grid I am kind of a newbie to MVC and Telerik and working on a project that involves both of them, the problem am facing currently is:
Am using teleirk Grids extension with Grid Method (DataTable) bound to a DataTable:
<% var table = ViewData["NewDesigns"] as DataTable;
Html.Telerik() .Grid(table) .Name("oi") .Pageable(pager => pager.PageSize(100)) .Groupable() .Sortable() .Columns(columns => { columns.Bound(r => r.category).Title("Category"); }) .Render(); %>
The grid is being displayed fine but there are two things that I want to do:
*
*Change the column name to my custom heading/title
*Eid Datatable content before printing it in a grid:
For e.g.: if id column has a value ‘21’, I want to print it in as hyper-link 21
I've spent time in telerik help files and learned a lot but not able to find answer of these, ld appericiate if someone here could help me out.
DataTable Object:
ordr {myprod.Models.Orders} myprod.Models.Orders addrss null string cntact null string custmrNam null string dlivrdn null string dsignr null string dsignId null string mail null string id null string rdrCd null string rdrdn null string quantity null string siz null string status null string ttalPric null string twn null string usrId null string'
A: The following example with custom titles and custom templates might help:
Html.Telerik()
.Grid(table)
.Name("ordersInum")
.Columns(columns =>
{
columns.Bound(typeof(Int32), "ID").Title("Row ID").Template(Html.ActionLink(item.ID, "Detail", new { r.ID }));
columns.Bound(typeof(string), "Name").Title("Product").Template(@<text>
<img src="images/product.png" />
@item.Name
</text>);
columns.Bound(typeof(Double), "Price").Title("Price in $");
columns.Bound(typeof(DateTime?), "OrderDate").Format("{0:MM/dd/yyyy}").Width(80);
})
.Pageable(pager => pager.PageSize(100))
.Groupable()
.Sortable()
.Render();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Change paste contents in Textbox How can I dynamically change the contents of what will be pasted in the TextBox.
Here is how I subscribe to the event:
DataObject.AddPastingHandler (uiTextBox, TextBoxPaste);
Here is how I define the event handler:
private void TextBoxPaste (object sender, DataObjectPastingEventArgs args)
{
string clipboard = args.DataObject.GetData (typeof (string)) as string;
Regex nonNumeric = new System.Text.RegularExpressions.Regex (@"\D");
string result = nonNumeric.Replace (clipboard, String.Empty);
// I can't just do "args.DataObject.SetData (result)" here.
}
A: You cannot call args.DataObject.SetData("some data") since the DataObject is frozen. What you can do is replace the DataObject altogether:
private void TextBoxPaste(object sender, DataObjectPastingEventArgs e) {
string text = (String)e.DataObject.GetData(typeof(String));
DataObject d = new DataObject();
d.SetData(DataFormats.Text, text.Replace(Environment.NewLine, " "));
e.DataObject = d;
}
A: I can think of two ways, none of which are very attractive :) And both ways include canceling the paste command.
The first way would be to cancel the paste command and then calculate what the text would look like after the paste if result was pasted instead.
private void TextBoxPaste(object sender, DataObjectPastingEventArgs args)
{
string clipboard = args.DataObject.GetData(typeof(string)) as string;
Regex nonNumeric = new System.Text.RegularExpressions.Regex(@"\D");
string result = nonNumeric.Replace(clipboard, String.Empty);
int start = uiTextBox.SelectionStart;
int length = uiTextBox.SelectionLength;
int caret = uiTextBox.CaretIndex;
string text = uiTextBox.Text.Substring(0, start);
text += uiTextBox.Text.Substring(start + length);
string newText = text.Substring(0, uiTextBox.CaretIndex) + result;
newText += text.Substring(caret);
uiTextBox.Text = newText;
uiTextBox.CaretIndex = caret + result.Length;
args.CancelCommand();
}
The other way would be to cancel the paste command, change the text in the Clipboard and then re-execute paste. This would also require you to differ between the real paste command and the manually invoked paste command. Something like this
bool m_modifiedPaste = false;
private void TextBoxPaste(object sender, DataObjectPastingEventArgs args)
{
if (m_modifiedPaste == false)
{
m_modifiedPaste = true;
string clipboard = args.DataObject.GetData(typeof(string)) as string;
Regex nonNumeric = new System.Text.RegularExpressions.Regex(@"\D");
string result = nonNumeric.Replace(clipboard, String.Empty);
args.CancelCommand();
Clipboard.SetData(DataFormats.Text, result);
ApplicationCommands.Paste.Execute(result, uiTextBox);
}
else
{
m_modifiedPaste = false;
}
}
A: I use VB.net quite a bit, I've tested this C# bit, I used a converter because I'm lame :)
string oClipboard;
private void TextBox1_GotFocus(object sender, System.EventArgs e)
{
oClipboard = Clipboard.GetText();
Clipboard.SetText("foo");
}
private void TextBox1_LostFocus(object sender, System.EventArgs e)
{
Clipboard.SetText(oClipboard);
}
I set the clipboard to the new text when the control gets focus. It stores the old value. Later, when the control loses focus, the clipboard is set back to the old value.
A: Just some modifications of @Fredrik's code, since I've been trying out both of his methods.
First one is just a shortened version
private void TextBox_Pasting(object sender, DataObjectPastingEventArgs e)
{
string clipboard = e.DataObject.GetData(typeof(string)) as string;
Regex nonNumeric = new System.Text.RegularExpressions.Regex (@"\D");
string result = nonNumeric.Replace(clipboard, string.Empty);
int caret = CaretIndex;
Text = Text.Substring(0, SelectionStart) + result +
Text.Substring(SelectionStart + SelectionLength);
CaretIndex = caret + result.Length;
e.CancelCommand();
}
and the other one is updated with keeping the clipboard content
private string oldClipboardContent { get; set; } = "";
private bool pasteModified { get; set; } = false;
private void TextBox_Pasting(object sender, DataObjectPastingEventArgs e)
{
if (pasteModified)
{
pasteModified = false;
}
else
{
pasteModified = true;
string text = (string)e.DataObject.GetData(typeof(string));
oldClipboardContent = text;
Regex nonNumeric = new System.Text.RegularExpressions.Regex (@"\D");
text = nonNumeric.Replace(text, string.Empty);
e.CancelCommand();
Clipboard.SetData(DataFormats.Text, text);
ApplicationCommands.Paste.Execute(text, this);
Clipboard.SetData(DataFormats.Text, OldClipboardContent);
oldClipboardContent = "";
}
}
I was using those inside my custom TextBox control, that is why I could access TextBox properties without writing the name first.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: Can't print jQuery's Tablesorter with lines. lines are missing when I print When I print Tablesorter from an HTML page, the lines don't show up. Can anyone explain to me a possible fix?
A: If you only want the lines and don't care about the colored background, then add this to your print stylesheet:
@media print {
table.tablesorter th, table.tablesorter td {
border: #000 1px solid;
}
}
If you do want the background color, then do as @Matt Ball recommends, and set the browser to print background images... File > Page Setup (for Firefox for Windows); For Chrome, print (Ctrl-P) then set it to print in color, etc.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Linker error while implementing pimpl idiom Edited to provider a little more clarity. Apologies for confusing everyone.
This is under Windows.
I have a static library that implements a class using the pimpl idiom. The pimpl header is not only used by the consuming code but it also links against the static library. Yet, when I compile the consuming code (.exe), the linker complains about unresolved externals on the implementation class that the pimpl header supposedly hides.
How can this be possible?
// Foo.lib
// Foo.h
class FooImpl;
class Foo
{
std::shared_ptr<FooImpl> pimpl_;
public:
Foo();
};
// Foo.cpp
#include "Foo.h"
#include "FooImpl.h"
Foo::Foo() : pimpl_(new FooImpl())
{
}
// This is how its used in Bar.exe
// Bar.exe links against Foo.lib
// Bar.h
#include "Foo.h"
class Bar
{
Foo access_foo_;
};
// Bar.cpp
#include "Bar.h"
When I compile/link Bar.exe, the linker complains that it is unable to resolve FooImpl. I forget what it said exactly since I don't have access to my work PC now but that's the gist of it. The error didn't make sense to me because the objective of going the pimpl route was so that Bar.exe didn't have to worry about FooImpl.
The exact error goes like this:
1>Foo.lib(Foo.obj) : error LNK2019: unresolved external symbol "public: __thiscall FooImpl::FooImpl(void)" (??0FooImpl@@QAE@XZ) referenced in function "public: __thiscall Foo::Foo(void)" (??0Foo@@QAE@XZ)
A: When you create a static library, the linker doesn't try to resolve everything that is missing; it assumes you'll be linking it later to another library, or that the executable itself will contribute some missing function. You must have forgotten to include some crucial implementation file in the library project.
The other possibility is that the pimpl implementation class is a template class. Templates don't generate code immediately, the compiler waits until you try to use them with the template parameters filled in. Your implementation file must include an instantiation of the template with the parameters that will be supported by your library.
After seeing your edit, the problem is that the Foo::Foo constructor needs access to the FooImpl::FooImpl constructor but the linker doesn't know where to find it. When the linker puts together the library, it doesn't try to resolve all of the references at that time, because it might have dependencies on yet another library. The only time that everything needs to be resolved is when it's putting together the executable. So even though Bar doesn't need to know about FooImpl directly, it still has a dependency on it.
You can resolve this in one of two ways: either export FooImpl from the library along with Foo, or make sure that Foo has access to FooImpl at compile time by putting them both in Foo.cpp with FooImpl coming before Foo.
A:
1>Foo.lib(Foo.obj) : error LNK2019: unresolved external symbol "public: __thiscall FooImpl::FooImpl(void)" (??0FooImpl@@QAE@XZ) referenced in function "public: __thiscall Foo::Foo(void)" (??0Foo@@QAE@XZ)
The linker is complaining you that it can not find the definition of FooImpl::FooImpl(). You are calling the constructor here -
Foo::Foo() : pimpl_(new FooImpl())
// ^^^^^^^^^ Invoking the default constructor.
You just provided the declaration of default constructor but not it's definition.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616281",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Concat items in linq I have the following code:
class Person
{
public String Name { get; set; }
public String LastName { get; set; }
public String City { get; set; }
public Person(String name, String lastName, String city)
{
Name = name;
LastName = lastName;
City = city;
}
}
...
personList.Add(new Person("a", "b", "1"));
personList.Add(new Person("c", "d", "1"));
personList.Add(new Person("e", "f", "2"));
personList.Add(new Person("g", "h", "1"));
personList.Add(new Person("i", "j", "2"));
personList.Add(new Person("k", "l", "1"));
personList.Add(new Person("m", "n", "3"));
personList.Add(new Person("o", "p", "3"));
personList.Add(new Person("q", "r", "4"));
personList.Add(new Person("s", "t", "5"));
So then I want to group the list by Cities, and I do the following;
var result = personList.GroupBy(x => x.City);
But now what I want to do is to concatenate the items that have 1 or 3 as a City (it can be specified dynamically)
Example:
The first item on result would return an array of persons that contain cities 1, 3
Thanks!
A: You can just use a Where() filter and project each remaining group into an array using ToArray():
var result = personList.GroupBy(x => x.City)
.Where ( g => g.Key == someCity || g.Key == anotherCity)
.Select( g => g.ToArray());
A: First build your list of cities that you want to search against
List<int> citesToFind = new List<int>();
// add 1, 3, etc to this list (can be generated dyamically)
Then use .Contains() in your LINQ:
var result = from person in personList
where citiesToFind.Contains(person.City)
select person;
Of course you can add whatever other grouping or filtering you want, but using .Contains() is I think the essential part you're missing.
A: How about the following? You could stick it in an extension method if you want to make the usage neater.
var personDictionary = new Dictionary<string, List<Person>>();
foreach(var person in personList)
{
if (personDictionary.HasKey(person.City)
{
personDictionary[person.City].Add(person);
}
else
{
personDictionary[person.City] = new List<Person>{person};
}
}
You can then query the personDictionary for the people from any city of your choosing.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616282",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Source list groups hidden by default In Lion, source list group items now have a Hide/Show button that appears when the mouse rolls over the item. My problem is that all my groups are initially hidden, and I have to click "Show" to see their contents. How do I make them shown by default?
(I'm using a view-based outline view, if that matters)
Relevant code is at https://github.com/Uncommon/Hugbit/commit/9356cf619befdfd5e81d7e0a54f528abf624c0b7
A: The only way I've found is to specifically call -expandItem: for each group row's item in the -windowDidLoad method.
A: I ended up finding the solution myself.
The problem is that I'm loading some of the sidebar content asynchronously. When the outline view sees groups that are initially empty, it also makes them initially collapsed.
The key is to wait until all my sidebar items are loaded, and then expand the groups.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to specify a "Like" on an integer column? This one has me stumped and thought I would pose it to the SO community for help.
A user wants to select all orders that start with a certain ID, example:
123 would return 123, 12345, 1238790, etc. ID is an int column however.
I'm using nHibernate and my line currently is:
criteria.Add(Restrictions.Eq("Id", itemId));
but that's only going to return me 123. I can do a Restrictions.Like, but that converts to a SQL LIKE clause and that won't work on an int col.
Any ideas?
EDIT: Sorry, the DB is SQL Server 2008
A: Unfortunately, you didn't specify what database you're using (SQL is just the query language....), but if you're on SQL Server (the Microsoft RDBMS product), then you could create a computed column of type VARCHAR(15) to hold a string representation of your INT, and then just search on that....
ALTER TABLE dbo.YourTable
ADD IdAsString AS CAST(Id AS VARCHAR(15)) PERSISTED -- PERSISTED might not work - depending on your version of SQL Server
SELECT (list of columns)
FROM dbo.YourTable
WHERE IdAsString LIKE '123%'
Whether that really makes business sense, is a totally different story..... (I agree with Oded and Matt Ball...)
But since that's a string column now, you should be able to use your Restrictions.Like approach in NHibernate as you mention.
A:
A user wants to select all orders that start with a certain ID,
example:
123 would return 123, 12345, 1238790, etc. ID is an int column
however.
It sounds like (pun intended) you may have a couple of issues with your design.
First, although the data element name "order number" may suggest a numeric, order numbers and the like are typically non-numeric (e.g. fixed-width text). For example, the International Standard Book Number (ISBN) is non-numeric, not least because the final character can be X. Even if all the allowable characters are digits, it doesn't necessarily follow that the values are numeric.
A good question to ask yourself is, does it make any sense to apply mathematical operations to these values? For example, does calculating the sum of a customer's order numbers give a meaning result? If the answer is no then the values are probably not numeric. Furthermore, given a requirement use an operator such as LIKE on the values is a strong indication that they are indeed non-numeric.
Second, there seems to be an implied relationship between the value ID = '123' and any ID that starts with the same characters. To return to the ISBN example, you can determine whether two different books were published by the same publisher (subject to knowing the publisher's codes) by splitting an ISBN into its composite groups. If your ID values have similar groupings, and you need to query against these grouping, you may find it easier to stores the 123 sub-element separate from the rest of the identifier and concatenate the parts for display only.
A: I don't know exactly how to do it in nHibernate but since intergers are of a limited size you could just append the restriction the check for the possible ranges
The SQL Versions is like this
With cte as (
select top 10000000 row_number() over(order by t1.number) as N
from master..spt_values t1
cross join master..spt_values t2)
SELECT * FROM cte
WHERE
n = 123
or n between 1230 and 1239
or n between 12300 and 12399
or n between 123000 and 123999
or n between 1230000 and 1239999
A: Since this is possible in Linq (with NHibernate) it's most likely also possible with Criteria. You just need to convert it to an string/varchar before calling the like. Maybe there is a "convert to string" projection?
In Linq this would simply be:
.Where(x => x.Id.ToString().StartsWith("123"))
A: in your mapping for the class you can define a string column that uses a formula to populate it. the conversion from int to string is done using the formula and you'd query against that without having to change your database.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Make sum of an array php I'm having a 2 dimensional array what is passed by a function what's looks as it follows
function crash_reporter($evaluation){
foreach ($evaluation as $agent){
unset($agent['time']);
print_r($agent);
}
than I'm getting the following array and I'm struggling to get the sum of the indexed values.
Array
(
[agent_example1] => 0
[agent_example2] => 2
[agent_example3] => 0
[agent_example4] => 1
[] => 0
)
Array
(
[agent_example1] => 0
[agent_example2] => 1
[agent_example3] => 0
[agent_example4] => 0
[] => 0
)
Array
(
[agent_example1] => 0
[agent_example2] => 3
[agent_example3] => 0
[agent_example4] => 0
[] => 0
)
)
)
result should be int. 7
A: You may want to try something like this:
function sum_2d_array($outer_array) {
$sum = 0;
foreach ($outer_array as $inner_array) {
foreach ($inner_array as $number) {
$sum += $number;
}
}
return $sum;
}
A: Or even easier:
function crash_reporter($evaluation){
$sum = 0;
foreach ($evaluation as $agent){
unset($agent['time']);
$sum += array_sum($agent);
}
echo $sum;
}
A: You can sum the sums of each sub-array ($agent), after your foreach/unset loop, like:
$sum = array_sum(array_map('array_sum', $evaluation));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616290",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Node.js send static files such as HTML files I'm using the following script to show an html file in my browser:
var sys = require("sys"),
http = require("http"),
url = require("url"),
path = require("path"),
fs = require("fs");
http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname;
var filename = path.join(process.cwd(), uri);
path.exists(filename, function(exists) {
if (!exists) {
response.sendHeader(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.close();
return;
}
fs.readFile(filename, "binary", function(err, file) {
if (err) {
response.sendHeader(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.close();
return;
}
response.sendHeader(200);
response.write(file, "binary");
response.close();
});
});
}).listen(8080);
sys.puts("Server running at http://localhost:8080/");
But when I try to navigate to http://localhost:8080/path/to/file I receive this error:
Object #<ServerResponse> has no method 'sendHeader'
(at line 16).
I'm using node-v0.4.12
A: In node v0.4.12 there is no method sendHeader but it looks like the method response.writeHead(statusCode, [reasonPhrase], [headers]) has the same API, so you could just try to replace your sendHeader by writeHead.
See : http://nodejs.org/docs/v0.4.12/api/http.html#http.ServerResponse
A: Anyone reading this recently, should also note that the response object uses response.end() now and not response.close()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Location and heading not working I downloaded the source code of this tutorial and played a bit with it.
All working fine.
Now I wanted to create my own project to implement location and heading. But after writing all, it does not work. I don't even see a GPS indication on the top.
When I run the other app, its al fine.
Xcode does not give any errors or warnings.
my code:
(it did not change anything in the AppDelegate).
LocationAndHeadingTestViewController.h
#import <UIKit/UIKit.h>
#import "LocationController.h"
@interface LocationAndHeadingTestViewController : UIViewController <LocationControllerDelegate>
{
LocationController *_locationController;
IBOutlet UILabel *_errorLabel;
//Location
IBOutlet UILabel *_locationTimeLabel;
IBOutlet UILabel *_latitudeLabel;
IBOutlet UILabel *_longitudeLabel;
IBOutlet UILabel *_altitudeLabel;
//Heading
IBOutlet UILabel *_headingTimeLabel;
IBOutlet UILabel *_trueHeadingLabel;
IBOutlet UILabel *_magneticHeadingLabel;
IBOutlet UILabel *_headingAccuracyLabel;
IBOutlet UIImageView *_compass;
}
@property (nonatomic, retain) LocationController *locationController;
@end
LocationAndHeadingTestViewController.m
#import "LocationAndHeadingTestViewController.h"
@implementation LocationAndHeadingTestViewController
@synthesize locationController = _locationController;
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
_locationController = [LocationController new];
_locationController.delegate = self;
[_locationController.locationManager startUpdatingLocation];
[_locationController.locationManager startUpdatingHeading];
}
- (void)locationUpdate:(CLLocation *)location
{
[_locationTimeLabel setText:[NSString stringWithFormat:@"%@", location.timestamp]];
[_latitudeLabel setText:[NSString stringWithFormat:@"%f", location.coordinate.latitude]];
[_longitudeLabel setText:[NSString stringWithFormat:@"%f", location.coordinate.longitude]];
[_altitudeLabel setText:[NSString stringWithFormat:@"%f", [location altitude]]];
}
- (void)headingUpdate:(CLHeading *)heading
{
[_headingTimeLabel setText:[NSString stringWithFormat:@"%@", heading.timestamp]];
[_trueHeadingLabel setText:[NSString stringWithFormat:@"%f", heading.trueHeading]];
[_magneticHeadingLabel setText:[NSString stringWithFormat:@"%f", heading.magneticHeading]];
[_headingAccuracyLabel setText:[NSString stringWithFormat:@"%f", heading.headingAccuracy]];
}
- (void)locationError:(NSError *)error
{
_errorLabel.text = [error description];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)dealloc
{
[_locationController release];
[super dealloc];
}
@end
LocationController.h
#import <CoreLocation/CoreLocation.h>
@protocol LocationControllerDelegate
@required
- (void)locationUpdate:(CLLocation *)location;
- (void)headingUpdate:(CLHeading *)heading;
- (void)locationError:(NSError *)error;
@end
@interface LocationController : NSObject <CLLocationManagerDelegate>
{
CLLocationManager *_locationManager;
id _delegate;
}
@property (nonatomic, retain) CLLocationManager *locationManager;
@property (nonatomic, assign) id delegate;
@end
LocationController.m
#import <CoreLocation/CoreLocation.h>
#import "LocationController.h"
@implementation LocationController
@synthesize locationManager = _locationManager, delegate = _delegate;
- (id)init
{
if(self = [super init])
{
_locationManager = [[CLLocationManager new] autorelease];
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.delegate = self;
}
return self;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if([self.delegate conformsToProtocol:@protocol(LocationControllerDelegate)])
{
[self.delegate locationUpdate:newLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
if([self.delegate conformsToProtocol:@protocol(LocationControllerDelegate)])
{
[_delegate locationError:error];
}
}
- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading
{
if([self.delegate conformsToProtocol:@protocol(LocationControllerDelegate)])
{
[_delegate headingUpdate:newHeading];
}
}
- (void)dealloc
{
[_locationManager release];
[super dealloc];
}
@end
It is fairly simple but I think I really overlook something.
Ps. I will change the id delegate to id <..> delegate
A: You shouldn't be autoreleasing the CLLocationManager object:
_locationManager = [[CLLocationManager new] autorelease];
That's a "retain" property. You need to remove the autorelease, you are going to release it in the dealloc. You can only release it once.
If you had assigned it using the setter, then the setter would have retained it for you. Like this would be OK:
self.locationManager = [[CLLocationManager new] autorelease];
A: Is your app enabled for location service in the iPhone settings?
Location service (global access) can be on but your specific app in the location service settings could also be denied location access at the same time.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616292",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: force vim background to black Is there any way, in my vimrc, to override the background setting of my colorscheme and force it to black? I'm looking for something like
set colorscheme=wombat256
override_background(black)
so that whatever scheme I select, the background gets forced to black.
A: This is what worked for me:
colorscheme wombat256
hi Normal ctermbg=16 guibg=#000000
hi LineNr ctermbg=16 guibg=#000000
A: colorscheme wombat256
highlight Normal guibg=black guifg=white
set background=dark
Tweak to taste :)
@edit: after reading you later comment I suspect you'll find you need to override more related highlight (group) background colors. It'll be clearest which ones, by reading the existing color schemes
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: How can you get ManagedService configuration immediately? I'm using the Felix Configuration Admin library to read and apply configuration files for OSGi services. Many of the services I'm configuring are third-party (e.g. org.ops4j.pax.web.pax-web-jetty and org.ops4j.pax.url.mvn) and use a simple BundleActivator rather than Declarative Services. I've found that those services are each initialized twice because
*
*on activation they call ManagedService#updated(null), and
*a very short while later, the Felix ConfigurationManager.UpdateThread calls ManagedService#update(non-null) asynchronously.
I hate this delay for getting my configuration applied. It causes erratic failures due to the inherent race condition. Is there an alternative CM implementation that can apply configurations synchronously to avoid this problem? Or can I make Felix be synchronous? (It looks like no, from inspection of the source code and the ManagedService javadoc.)
A: Actually the callback to update() from another thread is a requirement of the Config Admin specification. See section 104.5.3 of the R4 Compendium Spec:
The updated(Dictionary) callback from the Configuration Admin service to the Managed Service must take place asynchronously. This requirement allows the Managed Service to finish its initialization in a synchronized method without interference from the Configuration Admin service call- back.
Unfortunately this means you need to code your ManagedService to not have erratic failures or inherent race conditions. For example, if registering as a service under another interface besides ManagedService, wait until the non-null update has been received before registering it under that interface.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Running 64-bit executable in System32 from 32-bit code I am trying to run an executable from a 32-bit C# app (on a 64-bit OS), but I’m getting “The system cannot find the file specified” probably because wsqmcons.exe does not exist in C:\Windows\SySWOW64. The file does exist in System32. What is the best way to run wsqmcons.exe from code, if possible?
Process p = new Process();
p.StartInfo.Arguments = "-f";
p.StartInfo.FileName = @"C:\Windows\System32\wsqmcons.exe";
p.Start();
p.WaitForExit();
Verify.AreEqual(0, p.ExitCode);
A: You will need to turn off the file system redirection on your 32 bit process with the Wow64DisableWow64FsRedirection and the re-enable it with Wow64RevertWow64FsRedirection.
A:
A 64-bit executable file located under %windir%\System32 cannot be
launched from a 32-bit process, because the file system redirector
redirects the path to %windir%\SysWOW64. Do not disable redirection to
accomplish this; use %windir%\Sysnative instead. For more information,
see File System Redirector.
Quote from http://msdn.microsoft.com/en-us/library/windows/desktop/aa384203%28v=vs.85%29.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Ruby on Rails: how do I find out where a method is called? I am getting up to speed with an existing Rails project and am wondering where a particular attribute (field) in the model (ActiveRecord) is modified. In Java I would either use the Eclipse "find reference" feature on the setter, or set a breakpoint there. With the ActiveRecord, the attribute is not even listed in the class file! Of course I can do a text search and look through hundreds of results, but this defies the point of working with an IDE. Is there a better way? I'm using RubyMine.
A: tl;dr
Kernel.caller
Explanation
Rails uses method_missing to implement attribute methods on ActiveRecord models. You can see that in the ActiveRecord::Base source code. The way I would approach this problem for a model class YourModel is like so:
class YourModel < ActiveRecord::Base
def myfield=(*args)
Rails.logger.debug "myfield called at #{Kernel.caller.inspect}"
super(*args)
end
end
There are actually a few other ways that your attribute might get updated, such as update_attribute and friends. If you can't find the assignment call site you can keep overriding methods till you find that one that your code is using. Alternatively, you can alter ActiveRecord::Base in your local copy of the gem ("bundle show activerecord" gives the path to it).
A: RubyMine has a find reference feature like eclipse. However, it won't help much for navigating the Rails source as AR uses a lot of metaprogramming. When looking through the find results, you'll want to look at lines that use 'send' as well as bare calls to your function.
Another thing you will need to be aware of is that AR synthesizes code at runtime; the method you're looking for may not even be present in the source.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: A WYSIWYG Where it's possible to limit the text/height Ok, so I tried out tinyMCE.
After no luck and a lot of research on how to limit the editors content, I'm looking for other alternatives.
These are the needs for the WYSIWYG:
*
*Able to have these function/buttons: bold,italic,underline,bull list, table controls
*Able to limit the input. If I set the editor to 300 width x 500 height, and you type more than the height, it should NOT apply a scroller and you should be unable to write more.
*Able to set multiple editors in one page
Which WYSIWYG editor can fill my needs?
A: A simple approach would be to use a div element and put the content of the editor inside that div. The div should have set a width (using css).
<div class="calculation_preview"></div>
And the css should be something like:
div.calculation_preview {
width: 200px;
visibility: hidden;
position: absolute;
top: 0px;
left:0px;
}
After each key-stroke, you can measure the height of the div (using the function offsetHeight on the div).
If it is too height, remove the last character the user entered.
To restore the previous content, you can declare a javascript variable as for example:
var savedContent = "";
If you have some initial content in your editor, then you should initialize the variable with that content.
For each key-stroke, you do the following:
// Get current editor content:
var content = tinyMCE.activeEditor.getContent({format : 'raw'});
// Measure the new height of the content:
var measurer = document.getElementById("calculation_preview");
measurer.innerHTML = content;
if(measurer.offsetHeight > 100) {
// Content is too big.. restore previous:
tinyMCE.activeEditor.setContent(savedContent, {format : 'raw'});
} else {
// Content height is ok .. save to variable:
savedContent = content;
}
A: TinyMCE or ck editor should meet your needs.
Regarding the scroll issue, try using jquery and the keypress event along to test the length of the content in the div holding the editor. You could also combine this with a character counter on the screen to dynamically display how many characters a user has left.
charCount = $(this).val().length;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How scale fontsize for change size of UILabel My width and height scaling relative interfaceOrientation, but i can't scale fontSize of my UILabel.
my_label.adjustsFontSizeToFitWidth = YES;
won't work for me.
A: Make sure your my_label.minimumFontSize is less than the my_label.font.pointSize.
You could try something like:
my_label.minimumFontSize = (my_label.font.pointSize / 4.0) * 3.0;
my_label.adjustsFontSizeToFitWidth = YES;
Or set the values in the Interface Builder for Minimum Font Size to something smaller then the Font Size. This way if the label is reduced in width, it will scale the font size down.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616325",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: asp.net mvc 2 project does not render data annotation attributes what can a problem that data annotation attributes are not rendered?
web.config
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
C#
public class SearchCriteria
{
[Required]
public string ControlNo { get; set; }
[Required]
public string Insured { get; set; }
[Required]
public string PolicyNumber { get; set; }
}
ascx
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Core.SearchCriteria>" %>
<%@ Import Namespace="Core" %>
<% using (Html.BeginForm()) {%>
<%= Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div class="editor-label">
<%= Html.LabelFor(model => model.ControlNo) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.ControlNo) %>
<%= Html.ValidationMessageFor(model => model.ControlNo) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model.Insured) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Insured) %>
<%= Html.ValidationMessageFor(model => model.Insured) %>
</div>
A: the problem with validation was that MVC 2 does not render data annotation attributes !!!
instead MVC 2 creates JS object that defines all validation rules and then MicrosoftMvcValidation.js works with it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616326",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android, how to determine if a reboot occurred? How would I programmatically determine when an android device has rebooted (whether on its own, or user initiated) ?
A: This snippet starts an Application automatically after the android-os booted up.
in AndroidManifest.xml (application-part):
// You must hold the RECEIVE_BOOT_COMPLETED permission in order to receive this broadcast.
<receiver android:enabled="true" android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
[..]
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
[..]
In Java Class
public class BootUpReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, MyActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
A: Use a BroadcastReceiver and listen to the broadcast Intent ACTION_BOOT_COMPLETED.
A: If you happen to want to know if the device has been rebooted in-app, then you can use this code.
fun hasDeviceBeenRebooted(app: Application): Boolean {
val REBOOT_PREFS = "reboot prefs"
val REBOOT_KEY = "reboot key"
val sharedPrefs = app.getSharedPreferences(REBOOT_PREFS, MODE_PRIVATE)
val expectedTimeSinceReboot = sharedPrefs.getLong(REBOOT_KEY, 0)
val actualTimeSinceReboot = System.currentTimeMillis() - SystemClock.elapsedRealtime() // Timestamp of rebooted time
sharedPrefs.edit().putLong(REBOOT_KEY, actualTimeSinceReboot).apply()
return actualTimeSinceReboot !in expectedTimeSinceReboot.minus(2000)..expectedTimeSinceReboot.plus(2000) // 2 Second error range.
}
A: Set up a BroadcastReceiver and register it in your manifest to respond to the android.intent.action.BOOT_COMPLETED system even. When the phone starts up the code in your broadcastreceiver's onReceive method will run. Make sure it either spawns a separate thread or takes less than 10 seconds, the OS will destroy your broadcastreceiver thread after 10 seconds.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616335",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
} |
Q: How to make app resources accessible to sbt console initialCommands? I'm using sbt 0.11 and Scala 2.9.1 (which appears to evaluate REPL lines in the same thread). In my build.sbt I have:
initialCommands in console := """
println(Thread.currentThread)
println(Thread.currentThread.getContextClassLoader)
ru.circumflex.orm.Context.get() // reads my src/main/resources/cx.properties
"""
Context.get() loads resources with:
val bundle = ResourceBundle.getBundle(
"cx", Locale.getDefault, Thread.currentThread.getContextClassLoader)
This results in an error (the REPL appears to buffer up its own output after stdout/stderr):
> console
[info] No CoffeeScripts to compile
[info] Starting scala interpreter...
[info]
Thread[run-main,5,trap.exit]
sun.misc.Launcher$AppClassLoader@12360be0
14:17:44.003 [run-main] ERROR ru.circumflex.core - Could not read configuration parameters from cx.properties.
res0: ru.circumflex.core.Context = ctx()
Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_26).
Type in expressions to have them evaluated.
Type :help for more information.
scala> Thread.currentThread
res1: java.lang.Thread = Thread[run-main,5,trap.exit]
scala> Thread.currentThread.getContextClassLoader
res2: java.lang.ClassLoader = scala.tools.nsc.interpreter.IMain$$anon$2@3a8393ef
Removing the last initialCommand line and running it in the REPL results in no error, since by that time the resource is visible.
Any hints on how to deal with this and make my app's resources accessible to initialCommands?
A: Discovered the answer soon after posting this. Just prepend this line to initialCommands:
Thread.currentThread.setContextClassLoader(getClass.getClassLoader)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Session State is erased after calling RedirectToAction() in ASP.NET MVC 3 I use a simple sequences:
*
*Set a Session State in [HttpGet] method.
*Redirect to another action using RedirectToAction() in [HttpPost] method.
*Want to get the value of that Session State, in the destination.
Problem:
If user hits "submit" button on my "Table" view, all the data inside session got cleared and I can't get them in the destination action (which is "Table"). Here is the code:
[HttpGet]
public ActionResult Edit(string TableName, int RowID, NavigationControl nav)
{
if (nav != null) Session["NavigationData"] = nav;
myService svc = new myService (_repository);
EditViewModel model = new EditViewModel();
model.TableDefinitions = svc.GetTableDefinition(TableName);
model.RowData = svc.GetRowData(model.TableDefinitions.Name, RowID);
return View(model);
}
[HttpPost]
public ActionResult Edit(EditViewModel model)
{
MyService svc = new MyService (_repository);
svc.SaveRowData(model.TableDefinitions.Name, model.RowData);
return RedirectToAction("Table");
}
public ActionResult Table(string TableName)
{
myService svc = new myService (_repository);
TableViewModel model = new TableViewModel();
model.TableDefinition = svc.GetTableDefinition(TableName);
NavigationControl nav = (NavigationControl)Session["NavigationData"];
if (nav != null)
{
model.NavigationControl = nav;
}
return View(model);
}
and Session["NavigationData"] is always null when user reaches it via: return RedirectToAction("Table").
If user hits an HTML link on "Edit" View, Session["NavigationData"] can restore its value in "Table" method!
Any idea about what's going on?
Who deletes the Session state?!
A: My browser cookie was off but state was not set to cookie-less.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android Preferences how to go In one of my activity's onCreate I am using the following to get the list view. The xml layout being applied is from xml file "country_row". Now I want to use shared preferences to change some of the layout of my listview for eg font color, background color which should be preserved. As I know I can achieve this using the shared preferences. But assuming that I know the way to define it in xml file, in this section how can I apply some of the changes say different font color or background color using the same "country_row" xml file. Or do I have to completely define new xml file? What is the way I am confused.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int sort = prefs.getInt("sort_pref", -1); // -1 will be the result if no preference was set before
if(sort == 1)
sortOrder = "year";//sort on year
else if (sort == 2)
sortOrder = "country";//sort on country
ContentResolver contentResolver = getContentResolver();
Cursor c = contentResolver.query(CONTENT_URI, null, null, null, sortOrder);
String[] from = new String[] { "year", "country" };
int[] to = new int[] { R.id.year, R.id.country };
SimpleCursorAdapter sca = new SimpleCursorAdapter(this, R.layout.country_row, c, from, to);
setListAdapter(sca);
}
A: This would be quick and dirty:
new SimpleCursorAdapter(this, R.layout.country_row, c, from, to) {
@Override
public void getView(int position, View convertView, ViewGourp parent) {
convertView = super.getView(position, convertView, parent);
View viewToModify = convertView.findViewByid(/* ID of view to modify */);
// apply your changes here
}
}
The clean solution is to create your own adapter and do it there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iOS UIView transition not smooth? I used the following code to show animation during transition:
CATransition *animation = [CATransition animation];
[animation setDuration:0.4];
[animation setType:kCATransitionPush];
[animation setSubtype:kCATransitionFromTop];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut]];
[[newPage.view layer] addAnimation:animation forKey:@"SwitchToView1"];
But the transition seems to be not smooth like the other apps I saw. Does anyone know why it's not smooth? Thanks!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android download progress notification layout not found? I need to display the download progress in the notification area (like the Market does). I found several examples, all of them using the XML layout android.R.layout.download_progress. All the examples look great and simple to implement. The issue is, android.R.layout.download_progress does not seem to exist! It will not show up in Eclipse's intellisense, it won't compile, and even the official Android documentation (sorry, can't provide a link because I'm a new member) does not have this field. So why does it show up in multiple examples online? Am I missing something? I'd really prefer to not have to reinvent the wheel here.
Thanks in advance.
A: You're not really reinventing the wheel. It's a really simple declaration.
<ProgressBar android:id="@+id/progress"
android:padding="5dp"
android:layout_width="200dp"
android:layout_centerHorizontal="true"
android:layout_height="wrap_content"
android:layout_weight="0"
android:layout_below="@+id/currentlyplaying_songimage"
style="@android:style/Widget.ProgressBar.Horizontal"
android:max="100"/>
Now just, instead, use R.layout.progress_file_name
A: It's probably not much help to you since you most likely want to run on older phones too, but there's a new API in ICS that makes this super easy: Notification.Builder.setProgress().
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CSS overflow issue with featured slider On this website http://rwl.rwlwater.com/ I have a small issue... I added overflow: hidden to the featured slider div, the pictures were showing up stacked if the javascript was enabled or the user had a slow internet connection..
But now I have another problem.. The description had a little thing positioned outside the slider and it's hidden now...If I add overflow-x: visible it adds the scroll bar and that's not what I want. I want the description to be fully visible, but the overflow-y to be hidden.
If you want to see the fully thing, just use Firebug and remove overflow: hidden on the slider and the description thing will show up again...If you add the overflow, it will hide. I need to have it without any scroll bar. I tried overflow-x: visible and auto but it only adds a scroll bar at the bottom and that doesn't work for me, I need the original effect.
A: If you only need overflow: hidden for browsers with disabled JavaScript support, then you can keep the rule in the code, but reset it to visible using JavaScript as soon as the document is ready -- this way it won't affect JavaScript-enabled browsers.
Example:
$(function () {
$('#slides').css('overflow', 'visible');
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Oracle: Change Schema based on role There is this post that describes setting up a trigger to change the schema on login. Is there a way to check the role of the user to see if it matches a specific role instead of the username itself?
I tried to do a subquery to user_role_privs in the when clause, but it doesn't allow that. Ideas?
UPDATE
This is what I'm using per Yahia's suggested solution. It does not seem to be working though. When I login with a user with the role, it still does not recognize the table without the schema name before it.
CREATE OR REPLACE TRIGGER db_logon
AFTER logon ON DATABASE
DECLARE
v_count NUMBER;
BEGIN
SELECT COUNT(*) INTO v_count FROM user_role_privs WHERE granted_role = 'USER_ROLE' and username <> 'DEFAULT_SCHEMA';
IF v_count > 0 THEN
execute immediate 'ALTER SESSION SET CURRENT_SCHEMA = DEFAULT_SCHEMA';
END IF;
END;
A: Yes - ditch the WHEN part and build the SQL string inside the trigger dynamically:
CREATE OR REPLACE TRIGGER db_logon
AFTER logon ON DATABASE
Use the SELECT on USER_ROLE_PRIVS and map whatever you want from the ROLE to a SCHEMA.
Then build an SQL string for EXECUTE IMMEDIATE including the mapped SCHEMA.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: PHP creating a new object or use existing one if isset? Many times i find this redundant:
$found = $repo->findOneByCode($code);
$zone = isset($found) ? $found : new Zone();
Can anyone suggest a better way, similar to (not working):
$zone = $repo->findOneByCode($code) || new Zone();
EDIT: i can't modify Zone and findOneByCode as they are auto-generated classes and function by Doctrine ORM.
A: If you're using >= PHP 5.3
$zone = $repo->findOneByCode($code) ?: new Zone();
otherwise maybe this is better? (still a bit ugly)...
if ( ! ($zone = $repo->findOneByCode($code))) {
$zone = new Zone();
}
Assuming on failure, $repo->findOneByCode() returns a falsy value...
A: What you're describing is a lazy singleton pattern. This is when there is only ever one instance of the class, but it doesn't get initialized until you try to use it.
Example: http://blog.millermedeiros.com/2010/02/php-5-3-lazy-singleton-class/
A: You can do the following:
$zone = ($z = $repo->findOneByCode($code)) ? $z : new Zone();
Note, however, that this does not work exactly like using isset(). While using isset() will allow other falsey values other than NULL to pass through (such as FALSE), using a ? b : c will resolve to c on all falsey values.
A: These two methods will also do the job:
$zone = $repo->findOneByCode($code) or $zone = new Zone();
($zone = $repo->findOneByCode($code)) || ($zone = new Zone());
Note that or and && have different precedences and that is why we need the () in the second example. See http://www.php.net/manual/en/language.operators.logical.php. The example there is:
// The result of the expression (false || true) is assigned to $e
// Acts like: ($e = (false || true))
$e = false || true;
// The constant false is assigned to $f and then true is ignored
// Acts like: (($f = false) or true)
$f = false or true;
var_dump($e, $f);
And the result:
bool(true)
bool(false)
This is because and and or have lower precedence than = meaning the assignment will be done first. On the other side, && and || have higher precedence than = meaning the logical operation will be done first, and its result assigned to the variable. That is why we cannot write:
$result = mysql_query(...) || die(...);
$result will hold the result of the logical operation (true or false). But when we write:
$result = mysql_query(...) or die(...);
the assignment is done before the logical operation. And if it is not falsely value, the part after the or is cimpletely ignored.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: how to "usb to tty"? I'm new to the C++ world but have strong knowledge in several languages (so i'm not THAT lost). I just received an usb missile launcher as a gift and wanted to control it via different platforms, including web. To do so, i was planning to use a "serial to socket" proxy i wrote in python (and then use socket after that...). I found an opensource driver for my device, but it does not appear as a tty resource (with ls /dev/tty.*). That way, i'm not able to read/write into it with the pyserial library i use in my python script. My question is about finding tutorial/howto on creating such tty resources and "wire" them to usb devices...
Hoping u'll understand :)
Thanks
A: on linux it is easy to access the usb ports directly using the libusb-dev package and tools. Of course commands etc... are vendor specific but there exist already libs for perl and python to control various usb missle launchers. E.g.:
http://code.google.com/p/pymissile/
https://metacpan.org/pod/Device::USB::MissileLauncher
Sorry that's not a solution but hopefully a good starting point ;-)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android SQLite column int to float possible? I have an app out on the Android market that user data is stored in SQLite. I created a database table with a column of ints. I would like to store floats there now. How can I do this? When I try to insert a float, my app seems to throw an exception.
A: As SQlite doesn't implement full support for ALTER TABLE (only renaming a table and adding a column), you'll have to:
*
*create a temporary table with the new column format, i.e. float
*copy over the data from the original table into the temporary table (the ints will be "widened" into floats, no data loss here), e.g. INSERT INTO tmp SELECT * FROM orig
*drop the original table
*rename temporary table to original table
A: Unfortunately, SQLite does not support the use of alter table to change the datatype of a column. So, the only solution that I know of is to create a new table (with the particular column not specified as an int datatype), fill in the new table, drop the old table, and then rename the new table (via the alter table command) to the same name as the old table.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What uses of eval() (or the indirect eval/execScrtipt()) are legitimate? I have never encountered a situation where I needed eval().
Often times, people say that the [] property accessor makes eval() redundant.
Actually, isn't the execution of a pain statement exactly the same thing as pushing it as an argument into the eval() function. What is it actually used for?
Can you provide examples of when it might be useful to use eval()?
A: eval is something of a hybrid between an expression evaluator and a statement executor. It returns the result of the last expression evaluated (all statements are expressions in Javascript), and allows the final semicolon to be left off.
Example as an expression evaluator:
foo = 2;
alert(eval('foo + 2'));
Example as a statement executor:
foo = 2;
eval('foo = foo + 2;alert(foo);');
One use of JavaScript's eval is to parse JSON text, perhaps as part of an Ajax framework. However, modern browsers provide JSON.parse as a more secure alternative for this task.
source
With that in mind the only real reason I can see you wanting to use eval() is for executing user input.. but that leads to serious security risks... so in short I would say eval() (in javascript at least) has become a mute function; replaced by the many specific functions that would have invoked you to use eval() in the past.
Another idea.
You could possibly use it to execute pure js being returned by ajax
your server could pass back a string containing "alert('hello world');" and you could eval(returnData);.
A: Take your favourite Javascript library and grep for uses of eval. Hopefully your library is made by knowleadgeable people and the only cases of eval are the kind of good example you are looking for.
I looked in the Dojo Toolkit and one of the evals there is in the module loader (it apparently has a mode that does an AJAX request for the missing module and evals to execute the code instead of creating a script tag).
A: The most common situation where I find the need to use eval is when I get a json string that I want to use as an object.
var obj = eval('('+jsonString+')');
A: I don't know about legitimate, but this is how jquery uses eval-
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
A: I don't know how terrible or otherwise this is, but I used it to run scripts inside dynamically loaded HTML templates, as those aren't automatically run.
evaluateScripts = function(container) {
var scripts, i;
scripts = container.querySelectorAll("script[type='application/javascript']");
for (i = 0; i < scripts.length; i++) {
eval(scripts[i].innerHTML);
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616382",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What am I missing in making this simple jquery video player work? I have 2 videos that I'm displaying on a page. Onload, both videos are hidden and simply a poster is shown. On clicking one of the buttons, a video is played. Which video is determined by some nested (hidden) data in the button.
I'm holding my videos in a variable like so:
var video_1 = '<video width="840" height="472" controls autoplay class="video_1">' +
'<source src="/mov/video1.mp4" type="video/mp4" />' +
'<source src="/mov/video1.webm" type="video/webm" /></video>';
var video_2 = '<video width="840" height="472" controls autoplay class="video_2">' +
'<source src="/mov/video2.mp4" type="video/mp4" />' +
'<source src="/mov/video2.webm" type="video/webm" /></video>';
And my jquery to bring this up is like so:
$('#video_selection_wrap .play_wrap').live('click',function(){
// get the nested data from the button
var video = $(this).children('.data').text();
// hide the poster
$('.poster').fadeOut(function(){
$('#main-movie').empty();
switch(video) {
case 'video_1':
video_play = video_1;
break;
case 'video_2':
video_play = video_2;
break;
}
// load the appropriate video_play into the movie box
$('#main-movie').html(video_play).show();
});
});
The above code works a treat for the first video I click. What I was hoping would happen however was that if I clicked on another button, it would empty the movie container and load the other video - this isn't the case.
Can you see the problem?
I'm thinking it has something to do with the 'hide the poster' bit. Because its hidden the first time, the second time it doesn't fadeOut, and so it doesn't execute any of the code within its function. Is that how it works?
Edit:
Here is a working jsfiddle of the problem http://jsfiddle.net/RrC2u/
A: The problem is that your <div id="main-movie"> element is not properly closed:
<div id="movie-selection-wrap">
<div id="main-movie"> <!-- not closed -->
<div class="poster"></div>
</div>
Closing it fixes your issue:
<div id="movie-selection-wrap">
<div id="main-movie"></div>
<div class="poster"></div>
</div>
Updated fiddle here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Proper way to create superclass from subclass I have an client-server application.
The client has a class: Item.java
public class Item
public string name;
public string size;
and the server has a class PersistableItem.java which lets me store it using JPA
public class PersistableItem extends Item
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long Id;
and sends it to the server which executes the addItemToServer method:
public void addItem( Item item){
//create PersistableItem from item
DAO.save([paramerter = PersistableItem]);
}
In my server method do I cast the item as PersistableItem? Do i make a constructor in PersistableItem that takes in a Item?
What's the proper design here?
A: As you suggested, You can create a constructor in SomePersistedItem that takes a SomeItem. In the constructor, you call super with the name and size, so you have your SomePersistedItem correctly populated.
public class SomePersistableItem extends SomeItem
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
public SomePersistableItem(SomeItem originalItem) {
super(originalItem.getName(), originalItem.getSize());
}
And you just add it.
public void addItem( someItem item){
DAO.save(new PersistableItem(item));
}
That's assuming you have a constructor in SomeItem that takes a name and size. Else you use whatever method you have to build SomeItem (Factory, setters...)
A: I would make your persistable item extend an interface
public interface Persistable {
boolean persist();
}
public class SomePersistableItem extends SomeItem implements Persistable {
}
public void addItem(Persistable p) {
p.persist();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616385",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What uses should I make of Entity Framework Entity Partial Classes? I'm working with EF 4.1 Database first. I was wondering what sort of things I may use Entity Partial Classes for. What would some examples of possible functionality I might want to add to partial classes. I'm just trying to understand if I should make my entities more capable or if I should be looking to add the functionality elsewhere? Are there good cases for things I may want to add to my entities?
For example I have an entity that has various child properties with start and end dates. These dates must not overlap. Is that something I should enforce on the parent entity?
Ok so suggestions seem to be validation and business logic. Additionally calculating things so that DB the doesn't have computed columns.
Should I be tying business logic to entity framework entities? What if I wanted to move away from EF?
Thanks
Graeme
A: Validatable Objects and MetadataType attributes are used in the partial classes by frameworks such as MVC, for example.
Here's an example of using the MetadataType attribute:
[MetadataType(typeof(UserMetadata))]
public partial class User
{
private class UserMetadata
{
[DisplayName("User Id")]
public long UserId
{
get;
set;
}
[DisplayName("User Name")]
public string UserName
{
get;
set;
}
}
}
When you use the MVC framework, any model that has these attributes will be read for purposes of automatic generation of label fields for the corresponding displays/editors.
Example of using IValidatableObject
public partial class Apple : IValidatableObject // Assume the Apple class has an IList<Color> property called AvailableColors
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
foreach (var color in this.AvailableColors)
{
if (color.Name == "Blue") // No blue apples, ever!
{
yield return new ValidationResult("You cannot have blue apples.");
}
}
}
}
MVC will pick up on this IValidatableObject and ensure that any Apple that comes its way through it's validation step will never come in blue.
EDIT
As an example of your date range concern using IValidatableObject:
public partial class ObjectWithAStartAndEndDate : IValidatableObject
{
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (this.StartDate >= this.EndDate)
{
yield return new ValidationResult("Start and End dates cannot overlap.");
}
}
}
A: I have used it to augment my generated classes with calculated values, when I'd rather not have the DB have calculated columns.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616387",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Rails Models: Legacy Schema: Table Inheritance I have a legacy SQL schema which looks something like this:
CREATE TABLE `User` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`userType` varchar(255) DEFAULT NULL,
`seqNo` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=30 DEFAULT CHARSET=utf8;
CREATE TABLE `Employee` (
`userType` varchar(255) DEFAULT NULL,
`id` bigint(20) NOT NULL,
`employeeNumber` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
KEY `FKB65C8D4DB07F537D` (`id`),
CONSTRAINT `FKB65C8D4DB07F537D` FOREIGN KEY (`id`) REFERENCES `User` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
In this design, an Employee is-a User in the domain model. i.e. The employee's "id" field is a foreign key which references User.id.
How would I encode this relationship with Rails 3.0 models and migrations?
For example, if I ran
rails g scaffold User userType:string seqNo:integer
it would get me a Rails database migration which would generate a very similar schema, and a model which could access that table. However I am not sure what to do to get the Employee table with Employee.id as a foreign key referring to User.id, as well as getting an Employee model which can access both tables.
How can I accomplish this?
A: There are a couple of options for Rails to use legacy database schemata, e.g. when defining your migration or when defining the relations.
Here are some pointers:
http://www.slideshare.net/napcs/rails-and-legacy-databases-railsconf-2009
http://www.killswitchcollective.com/articles/45_legacy_data_migration_with_activerecord
http://sl33p3r.free.fr/tutorials/rails/legacy/legacy_databases.html
http://lindsaar.net/2007/11/26/connecting-active-record-to-a-legacy-database-with-stored-procedures
http://pragdave.blogs.pragprog.com/pragdave/2006/01/sharing_externa.html
ActiveRecord Join table for legacy Database
I would also recommend the book "Pro Active Record" ... not sure if there is a newer edition for Rails 3.
A: It turns out that after running the scaffolds as follows:
rails g scaffold User userType:string seqNo:integer
rails g scaffold Employee id:integer userType:string employeeNumber:string
I would then have to edit the models to look like this:
class User < ActiveRecord::Base
has_one :employee
end
class Employee < ActiveRecord::Base
belongs_to :user, :foreign_key=>"id"
end
The only other thing to do is delete the generated migrations so that the database is not altered when rake db:migrate is called.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: About animating frame by frame with sprite files I used to animate my CCSprites by iterating through 30 image files (rather big ones) and on each file I changed the CCSprite's texture to that image file.
Someone told me that was not efficient and I should use spritesheets instead. But, can I ask why is this not efficient exactly?
A: There are two parts to this question:
*
*Memory.
OpenGL ES requires textures to have width and height's to the power of 2 eg 64x128, 256x1024, 512x512 etc. If the images don't comply, Cocos2D will automatically resize your image to fit the dimensions by adding in extra transparent space. With successive images being loaded in, you are constantly wasting more and more space. By using a sprite sheet, you already have all the images tightly packed in to reduce wastage.
*Speed. Related to above, it takes time to load an image and resize it. By only calling the 'load' once, you speed the entire process up.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616392",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Developing a client-server iphone app If i want to develop an iPhone app with a client-server design (iPhone devices as the clients and a c# server),two questions:
*
*Is it possible to use my own laptop to run the server on? and if not what are my options?
*Do i have to develop my own protocol for transferring messages?
So if i understood right the process of sending a message like "CREATE NEW USER" from the client to the server is as follow:
1. The client will create a JSON/XML containing the command "CREATE NEW USER" and the new user details.
2. The client will send this JSON/XML via HTTP request (as the body of the HTTP request) with a URL that maps to a c# method on the server side.
3. This will trigger the appropriate method on the server and the new user will be created on the database.
4. The server will create JSON/XML containing the replay "CREATED" and will send it to the client vie HTTP response (as the body of the HTTP response).
Is that correct?
A: You want either xml or json over http. Web Services and REST over http was created for interoperability problems between different platforms which is what you're facing.
Since you're using C# for the server, you can look into WCF and use either a REST pattern or SOAP (web services) to expose your actions and data. Concerning the data you can serialize those objects over the wire as JSON or XML.
For iPhone consumption, I would recommend REST (since that basically maps a url request path to a C# method). From the phones perspective, it's just a url request and xml or json data comes back.
In C# you simply create your methods and decorate them with DataContract attributes. Then, on your methods you map them to url relative paths. Search the net for WCF and REST services. You can run it in any host from a command line to a windows service to IIS.
http://msdn.microsoft.com/en-us/library/bb412178.aspx
When creating those C# services, if REST, you can hit the requests in a browser and see the data come through. You should also look into Fiddler to inspect your traffic: http://www.fiddler2.com/fiddler2/
On the phone side, you first need to make the http request. You can do that with iOS classes but wrappers like ASIHTTPRequest make it much easier. Once you get the response back, you have to parse it. If you choose XML the iOS classes offer simple ways to parse the xml response. If you choose JSON, there's classes like SBJSON.
http://allseeing-i.com/ASIHTTPRequest/ - (Read this ASIHTTPRequest blog before using)
https://github.com/stig/json-framework
rest web services in iphone
There's also a much higher level framework called RESTKit which makes the iPhone side much easier.
https://github.com/RestKit/RestKit
Hope that helps tie it together for you.
EDIT:
Adding the create new user scenario:
The client creates a user object with the data (username, password etc...) and sends an HTTP PUT request to http://yourserver/myservice/users. The client serializes the user object to JSON/XML in the body.
What is the recommended/effective request payload for a REST PUT method?
PUT vs POST in REST
The server receives the request. On the server, you have a WCF "myservice" service (it's a class). It has a "public User CreateUser(User user)" method. In that method it creates a user object by doing whatever it has to do (call database etc...). It returns the User object because perhaps the server added info like the user id. The article below has a put request example.
http://damianm.com/tech/building-a-rest-client-with-wcf/
The client would get the response and the user object with all the details like id, etc... would be in the body as JSON/XML. It would deserialize that into a User object on the phone.
The server could also expose things like:
/User/{id} --> public User GetUser(string id);
A: I'd strongly recommended to rely on the HTTP protocol. Don't implement your own networking protocol!
Use GET requests to fetch data from the server and POST requests to send big amounts of data from the client to the server.
In order to structure your data, encode the data using JSON.
Here is a nice tutorial that explains how to do that with ASIHTTPRequest and JSONKit: http://www.icodeblog.com/2011/09/30/dynamically-controlling-your-application-from-the-web/
And yes, you can run the server on your working machine.
A: You can do this fairly easily with ASIHTTPRequest. It's a free 3rd party solution that can talk to different types of web services.
ASIHTTPRequest website
A: Not sure if this answers your question, but just as a suggestion so you don't have to deal a lot with server side stuff, use Parse
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: WordPress custom permalinks using page children I am creating a wordpress theme and I would like to have a custom permalink structure. Users will add pages that have custom themes and the pages will be nested. So for example, a user might add a page called "Media" and then add a page called "tutorials" that has the parent of "Media". I would like to be able to use the permalink of "example.com/media/tutorials". IS there a way to do this?
A: Will the users be able to modify the pages' "parent" setting? If so, why not set a non-default permalink structure and this should be done automatically.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616402",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Merging two web cameras streaming into a single live streaming - Programmatically I have two web cameras and I want to merge their streams into a single live streaming preview and display it to the screen.
I am skilled in C#/Java programming, could you please help me to find a framework that helps me to achieve this ?
Thanks,
A: If you are aiming only at visualizing the two videos side by side, I would recommend taking a look at DirectShow.Net and GMFBridge toolkit.
Quote from GMFBridge site about the sample project GMFPlay included in the package:
GMFBridge: GMFPlay shows how to view multiple clips as a single movie
If you want to "merge" both streams (as drawing one on top of the other with some transparency level), then you could try this codeproject sample (for visualization only, also using DirectShow).
If you actually want to produce a new video stream and not only visualize, you could again use DirectShow combined with a mixing filter, Medialooks-Video-Mixer for example looks promissing.
A: You can combine two cameras, send the stream to a server (like SRS) and use ffplay to display this in real-time.
.\ffmpeg.exe -f dshow -i video="LRCP USB2.0" -i .\right.avi -filter_complex "nullsrc=size=1280x1440 [base];[0:v] setpts=PTS-STARTPTS,scale=1280x720 [upper];[1:v] setpts=PTS-STARTPTS,scale=1280x720 [lower];[base][upper] overlay=shortest=1 [temp1];[temp1][lower] overlay=shortest=1:y=720" -c:v libx264 -preset:v ultrafast -tune:v zerolatency -f flv rtmp://192.168.1.136:1935/live/stream
You can watch the combined video in real-time like in this image example.
Let me know if still not clear.
A: Checkout this link:
https://codedump.io/share/fbX1tYFjPhdw/1/merging-two-web-cameras-streaming-into-a-single-live-streaming---programmatically
http://www.codeproject.com/KB/directx/DirectShowVMR9.aspx
Quote from GMFBridge site about the sample project GMFPlay included in the package:
GMFBridge: GMFPlay shows how to view multiple clips as a single movie
If you want to "merge" both streams (as drawing one on top of the other with some transparency level), then you could try this codeproject sample (for visualization only, also using DirectShow).
If you actually want to produce a new video stream and not only visualize, you could again use DirectShow combined with a mixing filter, Medialooks-Video-Mixer for example looks promising.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616413",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How do I call Coffeescript templates in a Javascript ERB template in a jquery_ujs response? I am using Coffeescript template in my Rails 3.1 app, so in my app/assets/javascripts/post.js.coffee file, I have something like:
$('#post').html JST['templates/posts/show'] post: post
where post is a JSON object. The template is in app/assets/javascripts/templates/posts/show
Now I am also using jquery_ujs to respond to PostsController#create and want to use app/views/posts/show.js.erb to render a response. In show.js.erb, I want to use the template from above. How would I go about doing that? Thanks.
A: Seems like https://github.com/markbates/coffeebeans might be what you are looking for.
A: Use power of Rails templates.
If you rename your respond file as show.js.coffee.erb (or show.coffee.erb - don't remember) you than rails template engine generates for you .erb code, after that it will translate coffee to js, and only after that your client will gain the response text.
With .erb it works fine. With .haml I have some problems...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616414",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Issues with String to NSDate My dateFromString is not working and i'm not sure why
NSString *purchase = @"2011-09-30 17:47:57";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
NSDate *date = [dateFormat dateFromString:purchase];
date is 'invalid CFStringRef'
See anything i might be overlooking?
A: Try changing the hours in the formatter to capitals, i.e. yyyy-MM-dd HH:mm:ss
I'm not sure if that will solve your error, but that is the correct way to parse a 24 hour time
A: Try this:
NSString *purchase = @"2011-09-30 17:47:57";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [dateFormat dateFromString:purchase];
Date Formatters Guide - HH is used for 24 hour times, hh for 12 hour.
A: in the format
"hh" means Hour [1-12].
"HH" means Hour [0-23].
See UTS Date Field Symbol Table for the date format specifiers.
A: If you mean that "date" is not accepted as an NSString by another function, that's because it's not a string, it's an NSDate.
(Where, precisely, are you getting the error message, and what is the full text?)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Please explain this difference in cross browser string.length I run this code in Firefox v6.0.2 and IE7. In Firefox, I select the radio button. Then click test. I get a string length of 10. In IE7, I get a string length of 9.
<script type="text/javascript">
function TestMethod() {
var name;
var address;
var city;
var state;
var zip;
var indexor = 0;
$('input[name=radioBtnSet1]:checked').parent().siblings().each(function (i, cell) {
if (indexor === 0)
name = $(cell).text();
else if (indexor === 1)
address = $(cell).text();
else if (indexor === 2)
city = $(cell).text();
else if (indexor === 3)
state = $(cell).text();
else if (indexor === 4)
zip = $(cell).text();
indexor++;
});
alert(name.length);
alert('FACILITY NAME: ' + '|' + name + '|');
}
</script>
<input id="runTest" onclick="javascript:TestMethod();" type="button" value="Test"/>
<table id="someTable">
<thead>
<tr>
<th></th>
<th>Header</th>
<th class="DisplayNone"></th>
<th class="DisplayNone"></th>
<th class="DisplayNone"></th>
<th class="DisplayNone"></th>
<th>Date</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="radio" value=" HHH VALUE" name="radioBtnSet1" /></td>
<td style="text-align: left;"> HHH VALUE</td><td class="DisplayNone">200 SOME STREET DR</td>
<td class="DisplayNone">CITY</td><td class="DisplayNone">TX</td>
<td class="DisplayNone">75007-3726</td>
<td style="padding-left: 1em;">9/30/2011</td>
</tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th class="DisplayNone"></th>
<th class="DisplayNone"></th>
<th class="DisplayNone"></th>
<th class="DisplayNone"></th>
<th></th>
</tr>
</tfoot>
</table>
Why? How can I get these to be equivalent?
A: As it can be seen in the comments in this page, the problem is with jQuery's text function. In IE 7 it doesn't preserve the leading and trailing white spaces. In FF, it does. Hence the different strings and different lengths in IE 7 and FF.
If you need the whitespace, try using instead.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What is exactly a measure in star schema in data warehouse design? Star schema consists of dimension and fact tables.
Fact tables contain foreign keys for each dimension and in addition to that, it contains "measures". What exactly comprises of this measure ?
Is it some aggregate function's answer that is stored ?
A: Basically yes.
If you had a simple grid
Salary Januari Februari March April May June
Q1 Q2
Me 1100 1100 1100 1100 1500 1500
Collegue1 2000 2000 2000 0 0 0
Time is a hierarchical dimension with two levels (shown).
The other dimension shown is 'EmployeeID'. The other dimension (not shown) could be in the PointOfView (e.g. Budget/Actual).
The Amount (1100, e.g.) is the Measure and it constitutes your facts (the non-identifying parts of the facts). The dimensions define consolidation functions for each measure on the various levels (E.g. Amount(Q1) == SUM(Amount(January...March))). Note that the consolidation will behave differently depending on the measure (e.g. the income tax % will not be summed, but somehow consolidated: how exactly is the art of OLAP Cube design).
(trivia: you can have calculated measures, that use MDX to query e.g. the deviation of Amount in comparison the the preceding Quarter, the Average salary acoss the whole quarter etc.; it will be pretty clear that again, the consolidation formulas require thought).
At this point you will start to see that designing the consolidation rules depends on the order in which the rules are calculated (if the formula for 'salary deviation %' is is evaluated FIRST and then consolidated, you need to average it; however if the raw SALARY measure is consolidated (summed) to the Q1,Q2 level first, then the derived Measure can be calculated like it was at the lowest level.
Now things become more fun when deciding how to store the cube. Basically two ways exist:
*
*precalculate all cells (including all consolidations in all scenarios)
*calculate on the fly
It won't surprise anyone that most OLAP engines have converged on hybrid methods (HOLAP), where significant parts of frequently accessed consolidation levels are pre-calculated and stored, and other parts are calculated on the fly.
Some will store the underlying data in a standard RDBMS (ROLAP) other won't (OLAP). The engines focused on high performance tend to keep all data in precalculated cubes (only resorting to 'many small sub-cubes' for very sparse dimensions).
Well, anywyas, this was a bit of a rant. I liked rambling off what I once learned when doing datawarehousing and OLAP
A: Fact and measure are synonyms afaik. Facts are data: sales, production, deliveries, etc. Dimensions are information tied to the fact (time, location, department).
A: Measures are one of two kinds of things.
*
*Measures. Measurements. Numbers with units. Dollars, weights, volumes, sizes, etc. Measurements.
*Aggregates. Sums (or sometimes averages) of data. It might be data in the warehouse: pre-computed aggregates for performance reasons. Or it might be data that can't be acquired (or isn't needed) because it's too detailed. Too high volume or something.
The most important thing about a fact table is that the non-key measures are actual measurements with units.
A: If it would be an adjacent tree model it would be the title-field or any other field that contains the data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Integrating N2CMS with existing ASP.Net Website We need to select a CMS for our company's website which will allow the designers to make changes to the pages, add pages, view and publish them.
We r using Visual Studio 2010 for web development and includes Global.asax, Masterpages, User-/Custom-Controls, Security (FormsAuthentication, custom Membership-/RoleProvider). W ehave SQL server 2008 for the DB.
I have looked into various CMS like Sitefinity,N2CMS, Umbraco, DotNetnuke. We kinda liked playing with the demo of N2CMS. We don't want to start developing the site from scratch. We want to integrate some CMS into our application for the designers to use. However, I can't find any helpful documentation regarding the integration. Everyone starts talking building from sctrach. The documentation for N2CMS seems so outdated.
If anyone can guide me how to set a CMS into exsiting application, I will really appreciate it.
Thanks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616423",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Recurrence Relations in Data Structures In my Data Structures Class, we're looking at recurrence relations like T(n) and big O problems O(n). I'd appreciate any resources for learning these, my textbook doesn't cover T(n), and the professor skips over lots of steps.
I haven't seen a good, step-by-step method for solving these things. I realize that every problem is unique, but there has to be some sort of framework for doing these.
Thanks.
A: Check Concrete Mathematics - A Foundation for Computer Science, it's a brilliant book with lots of examples and exercises.
A: Another great book is Introduction to Algorithms. It has a pretty thorough section on solving recurrence relations.
You are right, there is a generalized method for solving simple recurrence relations called the Master Theorem. (The explanation in Introduction to Algorithms is much better than the Wikipedia page.) It doesn't work for every case, but it solves a lot of common ones.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I display clickable wordpress blog post titles in an UITableView for iOS? I am working on a iOS application in which I would like users to be able to access a table view list of blog post titles. The blog is self-hosted and runs on the Wordpress platform. The blog is linked to a twitter account so that each time a new post goes live, a new tweet is generated with the post title and the url. I was thinking that I could retrieve the twitter feed and insert the tweets into my table but I don't know if that's the easiest/best way to do it. Does anyone have any ideas?
A: You might want to setup an RSS to UITableView instead of bringing in the twitter API to do the job for you. If you keep the UITableView dependent on the Twitter API, you are inducing an additional, unwanted level of data dependency. Use RSS and update the UITableViews. You could possibly use this: http://dblog.com.au/iphone-development/rss-reader-part-4-setting-up-the-uitabbar-and-uitableview-with-delegates/ although I'm not sure if this is what you are looking for.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to resolve "minTime in Android 2.3.4 not working" error Comic... I've tested in an android 1.6 and 2.3.3 a very simple gps location... with basically this:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location myLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 10000, 0, listener);
I've tested in both [1.6 and 2.3.3] with the 10 seconds waiting for the notifiers [showing a toast at onLocationChanged...], But strangely in an 2.3.4 version of android it simply ignores the minTime [does not matter if it is 10000 or 120000] it keep looking for changes all the time...
Anyone with this problem? Maybe it is not in the 2.3.4 the problem but anyone else had this problem too?
A: This is working as documented. minTime is a suggestion, not a rule. Quoting the documentation:
This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616431",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Xvfb + firefox: how to know firefox finishes rendering? I'm trying to grab web thumbnails by using X server to run Firefox in headless (Xvfb) X11.
I am looking for a way to know when Firefox FINISHED rendering and then I can use image programs to grab the windows.
Problem: I can NOT determine when Firefox finishes rendering. All I know is that the status bar should have an output of "Done" once it finishes rendering (IE, as shown in Firefox in GUI).
Can anyone know what can I use to determine whether if Firefox finishes rendering a page or not?
What I did is just sleep 40 seconds but this may not always work.
Environment:
Centos 5.7, Xvfb, Firefox 3.6.23
Shell commands:
Xvfb: 1 -screen 0 1024x768x24 &
export DISPLAY=localhost:1.0
DISPLAY=localhost:1.0 firefox http://www.example.com -width 1024 -height 768
sleep 40 **[ NEED some thing to tell me if Firefox finishes rendering ]**
DISPLAY=localhost:1.0 import -window root example.com.png
pkill firefox
A: Three methods off the top of my head.
*
*Write your own extension that hooks to window.onload and fires the image grabber.
*Write a greasemonkey script that hooks to window.onload and fires an alert. Wait for such alert, then run your image grabber.
*Periodically grab the image of the Stop button (should be at known coordinates relative to the window) and analyze its color. If it's disabled, the rendering is finished.
A: Note that I don't think this can be done with FF 4.x and above easily. This is due to "features" of these versions. My recommendation to you is to use some different browser if you can, like Opera. I did not test it myself yet, but I think it does not have all those flaws noticed with FF. See below.
In your case following solution may be efficient:
Write some Greasemonkey script which adds an absolute positioned rectangle somewhere on the screen.
Let this rectangle flash in a 3 cycle when the page has finished loading: red, blue, transparent
Write a script which waits at least 2 such cycles to complete (so it sees red, blue, something, red, blue) and then do a screenshot with the correct timing in the transparent phase.
This should be doable with X11 and VNC and similar. Sorry that I don't have a better solution nor code I can present here.
I for my part would solve it using EasyRFB which I wrote to solve similar things. However I cannot recommend that to you, yet, except if you are very desparate Genius able to read and understand horrible undocumented code fragments with ease ;)
BTW, thanks for noting the idea of a package which is able to screenshot arbitrary web pages, which makes an excellent use case for EasyRFB. Never thought about this myself before.
Looking at GitHub I noticed, that there are some solutions for taking web screenshots based on Selenium or WebKit. These are certainly good for promotional shots, but they apparently cannot cover the general usecase on how users see web pages.
Perhaps it would be interesting to be able to automate screenshots from arbitrary pages as seen by a Windows 95 IE 4, FF 1 or Debian Potato with Chimera etc. I'll have a look into this ;)
Note that there is another posting on Stackoverflow from me.
There is something I call EasyRFB which I wrote in a mix of Python (core), PHP (small web helpers) AJAX and bash (control scripts). It was tested with XVnc but shall work with any VNC. It somehow is able to do what you want, but beware, it is development code, undocumented, complex and horribly written and may be faulty. You can find it there:
*
*GitHub: https://github.com/hilbix/pyrfb/tree/easyrfb
*My old development directory: http://hydra.geht.net/easyrfb/
It was written for following purposes:
*
*Being able to control a remote GUI from a Mobile even in a situation where the Internet connection is extremely slow and extremely unreliable
*Complete UI automation / replace mouse by commandline
*Automated QA tests, based on what the user sees in contrast to what the browser or some windows spy program sees, in cases where the output needs not to be pixel-color-perfect as well
It was not written to be fast nor efficient nor easy to use nor for others (yet). It works, for me, somehow.
What it does:
*
*is Web centric and gives a AJAX Web frontend to VNC servers, somehow.
*keeps a highly compressed .jpg updated to the contents of the screen.
*can take lossless screenshots
*is able to fuzzy-match templates against the contents of the screen
*templates can be Web-edited with edit.html - however this editor is basic, not self-explanatory and not documented at all
*Shell scripts can be written which can wait for these templates to match and send commands like keypresses, mousemoves and clicks to VNC
*There are some .sh scripts which could help to understand how this is done, but I am not able to publish the really helpful stuff yet, sorry
Nothing is documented and I am not able to explain how to use it. Either you find out yourself or you are lost. Sorry. Better don't even look at it, it might hurt you.
And now to the problems noticed with FF while doing all this:
Newer FF versions fail to properly update the screen. The last version known working correctly at my side was the FF 3.6 series, all later sometimes develop some strange behavior.
For example:
*
*Newer versions now update the status before they update the screen contents.
*Also they have such a high CPU and memory demand, that finishing the last step on updating the screen can take some time. On slow hardware (like the NSLU2, never tested) I think it might even take minutes after the Spinners etc. are already in the "finished" state.
So even looking at the spinner to become gray including(!) naive Greasemonkey solutions which notify about "onload()" both fail with FF 4.x and above, because parts of the screen may still not be updated when you detect that it is ready.
Maybe it has only to do with XVnc, perhaps there is a bug in my scripts which triggers all this, but with FF 3.x everything was right and I think, reverting to an old version would immediately solve all those problems seen. (But I already have workarounds in place for all those trouble. But I cannot publish that scripts, sorry.)
It gets worse.
FF 4.x and above apparently delay event processing a bit. So jumping the mouse out of the scrollbar often keeps it highlighted, I think the event does not reach the scrollbar.
On a normal desktop you do not jump your mouse, but my solution is able to do so. The fix is to generate additional, superfluous mouse movement events to have FF do the right thing.
Also I noticed, I really have no idea if it is due to FF or the web pages shown in FF, that sometimes things do not land where they are supposed to be. I never observed this before with FF 3.x though. The trick which solves this is to reload the page. It might have to do with incremental screen updates, but I did not dive into this yet as the retry (automated clicking on the reload button) works for me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I timeout Regex operations to prevent hanging in .NET 4.5? There are times when being able to limit the pattern matching duration of regex operations could be useful. In particular, when working with user supplied patterns to match data, the pattern might exhibit poor performance due to nested quantifiers and excessive back-tracking (see catastrophic backtracking). One way to apply a timeout is to run the regex asynchronously, but this can be tedious and clutters the code.
According to what's new in the .NET Framework 4.5 Developer Preview it looks like there's a new built-in approach to support this:
Ability to limit how long the regular expression engine will attempt
to resolve a regular expression before it times out.
How can I use this feature? Also, what do I need to be aware of when using it?
Note: I'm asking and answering this question since it's encouraged.
A: I recently researched this topic since it interested me and will cover the main points here. The relevant MSDN documentation is available here and you can check out the Regex class to see the new overloaded constructors and static methods. The code samples can be run with Visual Studio 11 Developer Preview.
The Regex class accepts a TimeSpan to specify the timeout duration. You can specify a timeout at a macro and micro level in your application, and they can be used together:
*
*Set the "REGEX_DEFAULT_MATCH_TIMEOUT" property using the AppDomain.SetData method (macro application-wide scope)
*Pass the matchTimeout parameter (micro localized scope)
When the AppDomain property is set, all Regex operations will use that value as the default timeout. To override the application-wide default you simply pass a matchTimeout value to the regex constructor or static method. If an AppDomain default isn't set, and matchTimeout isn't specified, then pattern matching will not timeout (i.e., original pre-.NET 4.5 behavior).
There are 2 main exceptions to handle:
*
*RegexMatchTimeoutException: thrown when a timeout occurs.
*ArgumentOutOfRangeException: thrown when "matchTimeout is negative or greater than approximately 24 days." In addition, a TimeSpan value of zero will cause this to be thrown.
Despite negative values not being allowed, there's one exception: a value of -1 ms is accepted. Internally the Regex class accepts -1 ms, which is the value of the Regex.InfiniteMatchTimeout field, to indicate that a match should not timeout (i.e., original pre-.NET 4.5 behavior).
Using the matchTimeout parameter
In the following example I'll demonstrate both valid and invalid timeout scenarios and how to handle them:
string input = "The quick brown fox jumps over the lazy dog.";
string pattern = @"([a-z ]+)*!";
var timeouts = new[]
{
TimeSpan.FromSeconds(4), // valid
TimeSpan.FromSeconds(-10) // invalid
};
foreach (var matchTimeout in timeouts)
{
Console.WriteLine("Input: " + matchTimeout);
try
{
bool result = Regex.IsMatch(input, pattern,
RegexOptions.None, matchTimeout);
}
catch (RegexMatchTimeoutException ex)
{
Console.WriteLine("Match timed out!");
Console.WriteLine("- Timeout interval specified: " + ex.MatchTimeout);
Console.WriteLine("- Pattern: " + ex.Pattern);
Console.WriteLine("- Input: " + ex.Input);
}
catch (ArgumentOutOfRangeException ex)
{
Console.WriteLine(ex.Message);
}
Console.WriteLine();
}
When using an instance of the Regex class you have access to the MatchTimeout property:
string input = "The English alphabet has 26 letters";
string pattern = @"\d+";
var matchTimeout = TimeSpan.FromMilliseconds(10);
var sw = Stopwatch.StartNew();
try
{
var re = new Regex(pattern, RegexOptions.None, matchTimeout);
bool result = re.IsMatch(input);
sw.Stop();
Console.WriteLine("Completed match in: " + sw.Elapsed);
Console.WriteLine("MatchTimeout specified: " + re.MatchTimeout);
Console.WriteLine("Matched with {0} to spare!",
re.MatchTimeout.Subtract(sw.Elapsed));
}
catch (RegexMatchTimeoutException ex)
{
sw.Stop();
Console.WriteLine(ex.Message);
}
Using the AppDomain property
The "REGEX_DEFAULT_MATCH_TIMEOUT" property is used set an application-wide default:
AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT",
TimeSpan.FromSeconds(2));
If this property is set to an invalid TimeSpan value or an invalid object, a TypeInitializationException will be thrown when attempting to use a regex.
Example with a valid property value:
// AppDomain default set somewhere in your application
AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT",
TimeSpan.FromSeconds(2));
// regex use elsewhere...
string input = "The quick brown fox jumps over the lazy dog.";
string pattern = @"([a-z ]+)*!";
var sw = Stopwatch.StartNew();
try
{
// no timeout specified, defaults to AppDomain setting
bool result = Regex.IsMatch(input, pattern);
sw.Stop();
}
catch (RegexMatchTimeoutException ex)
{
sw.Stop();
Console.WriteLine("Match timed out!");
Console.WriteLine("Applied Default: " + ex.MatchTimeout);
}
catch (ArgumentOutOfRangeException ex)
{
sw.Stop();
}
catch (TypeInitializationException ex)
{
sw.Stop();
Console.WriteLine("TypeInitializationException: " + ex.Message);
Console.WriteLine("InnerException: {0} - {1}",
ex.InnerException.GetType().Name, ex.InnerException.Message);
}
Console.WriteLine("AppDomain Default: {0}",
AppDomain.CurrentDomain.GetData("REGEX_DEFAULT_MATCH_TIMEOUT"));
Console.WriteLine("Stopwatch: " + sw.Elapsed);
Using the above example with an invalid (negative) value would cause the exception to be thrown. The code that handles it writes the following message to the console:
TypeInitializationException: The type initializer for
'System.Text.RegularExpressions.Regex' threw an exception.
InnerException: ArgumentOutOfRangeException - Specified argument was
out of the range of valid values. Parameter name: AppDomain data
'REGEX_DEFAULT_MATCH_TIMEOUT' contains an invalid value or object for
specifying a default matching timeout for
System.Text.RegularExpressions.Regex.
In both examples the ArgumentOutOfRangeException isn't thrown. For completeness the code shows all the exceptions you can handle when working with the new .NET 4.5 Regex timeout feature.
Overriding AppDomain default
Overriding the AppDomain default is done by specifying a matchTimeout value. In the next example the match times out in 2 seconds instead of the default of 5 seconds.
AppDomain.CurrentDomain.SetData("REGEX_DEFAULT_MATCH_TIMEOUT",
TimeSpan.FromSeconds(5));
string input = "The quick brown fox jumps over the lazy dog.";
string pattern = @"([a-z ]+)*!";
var sw = Stopwatch.StartNew();
try
{
var matchTimeout = TimeSpan.FromSeconds(2);
bool result = Regex.IsMatch(input, pattern,
RegexOptions.None, matchTimeout);
sw.Stop();
}
catch (RegexMatchTimeoutException ex)
{
sw.Stop();
Console.WriteLine("Match timed out!");
Console.WriteLine("Applied Default: " + ex.MatchTimeout);
}
Console.WriteLine("AppDomain Default: {0}",
AppDomain.CurrentDomain.GetData("REGEX_DEFAULT_MATCH_TIMEOUT"));
Console.WriteLine("Stopwatch: " + sw.Elapsed);
Closing Remarks
MSDN recommends setting a time-out value in all regular expression pattern-matching operations. However, they don't draw your attention to issues to be aware of when doing so. I don't recommend setting an AppDomain default and calling it a day. You need to know your input and know your patterns. If the input is large, or the pattern is complex, an appropriate timeout value should be used. This might also entail measuring your critically performing regex usages to assign sane defaults. Arbitrarily assigning a timeout value to a regex that used to work fine may cause it to break if the value isn't long enough. Measure existing usages before assigning a value if you think it might abort the matching attempt too early.
Moreover, this feature is useful when handling user supplied patterns. Yet, learning how to write proper patterns that perform well is important. Slapping a timeout on it to make up for a lack of knowledge in proper pattern construction isn't good practice.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: ImageSpan in a widget? Are there any limitations to adding an ImageSpan to a widget?
This identical code works fine in a standard TextView.
SpannableStringBuilder buf = new SpannableStringBuilder("");
if(!TextUtils.isEmpty(message.getMessageBody())) {
SmileyParser parser = SmileyParser.getInstance();
buf.append(parser.addSmileySpans(group ? message.getMessageBodyWithoutName() : message.getMessageBody()));
}
view.setTextViewText(R.id.message_body, buf);
Thanks.
Edit 1:
public CharSequence addSmileySpans(CharSequence text) {
SpannableStringBuilder builder = new SpannableStringBuilder(text);
Matcher matcher = mPattern.matcher(text);
while (matcher.find()) {
int resId = mSmileyToRes.get(matcher.group());
builder.setSpan(new ImageSpan(mContext, resId),
matcher.start(), matcher.end(),
Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return builder;
}
A:
The smiley's are local assets.
I am going to interpret this literally, that you mean your images are in assets/.
My guess is that the home screen is having difficulty resolving your asset reference. As a test, try putting the images on external storage and using Uri.fromFile() to create your Uri. If that works, try putting them as drawable resources and using the resource IDs. Or, try the resource Uri syntax:
Uri.parse("android.resource://your.package.name.goes.here/" + R.raw.myvideo);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how do I compile with mono targetting C# / .net 4 I have an installation of mono 2.10.4 on linux and have been attempting to compile a .NET C# 4 dependent codebase. I have been able to compile in MonoDevelop, but need to be able to do from the command line / build tool.
executing:
gmcs -langversion:4 -target:library -out:foo.dll ... <sources>
produces the following error:
error CS1617: Invalid -langversion option `4'. It must be `ISO-1', `ISO-2', `3'
or `Default'
The compiler version gmcs --version:
Mono C# compiler version 2.10.4.0
Further notes:
*
*ubuntu 11.04
*install in /opt/mono-2.10
*mono install first in path
A: I think you want to run dmcs instead of gmcs. From the CSharp Compiler page:
Starting with Mono version 2.6 a new compiler dmcs is available as a preview of C# 4.0 (a preview since Mono 2.6 will ship before C# 4.0 is finalized).
(That's a little out of date as I'm now running 2.10.5.0, but never mind.)
EDIT: Alternative, use mcs as specified here, as you're running 2.10.
It doesn't support a specific -langversion of 4, but then neither does the Microsoft compiler:
/langversion:<string> Specify language version mode: ISO-1, ISO-2, 3,
or Default
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616438",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Page width in Mobile/iOs I have read the related posts; 'Mobile CSS Page Width - etc' but haven't found a solution.
I've developed a mobile version of a website, and the width fills fine in Android, and Blackberry - but, for some reason in iPhone there remains extra space on the sides of the content, making the site render slightly smaller in content area and with more background. When a user double taps - it then, takes the full screen as it does in Android & Blackberry.
Any suggestions?
I've tried declaring the doc mobile, and using the '<meta name="viewport" content="width=device-width, initial-scale=1.0"> ' but it then zooms in the site way too much (Should I try toggling the 'initial-scale')?
I've tried the basics as well with setting to liquid etc.
Can't I use similar script, as I've used with Mobile Redirects to define how widths could render per device?
<!--Script for Mobile Redirect -->
<script type="text/javascript">
var redirectagent = navigator.userAgent.toLowerCase();
var redirect_devices = ['vnd.wap.xhtml+xml', 'sony', 'symbian', 'nokia', 'samsung', 'mobile', 'windows ce', 'epoc', 'opera mini', 'nitro', 'j2me', 'midp-', 'cldc-', 'netfront', 'mot', 'up.browser', 'up.link', 'audiovox', 'blackberry', 'ericsson', 'panasonic', 'philips', 'sanyo', 'sharp', 'sie-', 'portalmmm', 'blazer', 'avantgo', 'danger', 'palm', 'series60', 'palmsource', 'pocketpc', 'smartphone', 'rover', 'ipaq', 'au-mic', 'alcatel', 'ericy', 'vodafone', 'wap1', 'wap2', 'teleca', 'playstation', 'lge', 'lg-', 'iphone', 'android', 'htc', 'dream', 'webos', 'bolt', 'nintendo'];
for (var i in redirect_devices) {
if (redirectagent.indexOf(redirect_devices[i]) != -1) {
location.replace("http://www.osmproduction.com/crown/maxbrooks/Test/MobileZombie/index.html");
}
}
</script>
<!--End Script for mobile Redirect -->
Sub-question: Can anyone give me advice on best practices for optimizing for Blackberry - The page is rendering super zoomed in a certain Blackberry Model now (Don't recall Model, but 2007)- I'm assuming this discussion to take the width per device should tackle this issue as well, right? Or is developing for Blackberries somewhat of a separate issue? and something I'd have to look at separately as they kind of suck for browsing?
A: Use <meta name="viewport" content="width=800"> where 800 is the amount of pixels that will fit your layout. By default iPhone uses 980, so if your page has a fixed width of 800px you would get 180px of blank space around it.
A: I use the following META-tag. It seems to work fine with my tests:
<META name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no" />
This will scale to the width of the device, no matter what size it is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616441",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Clean up algorithm I've made an C# application which connects to my webcam and reads the images at the speed the webcam delivers them. I'm parsing the stream, in a way that I have a few jpeg's per seconds.
I don't want to write all the webcam data to the disk, I want to store images in memory. Also the application will act as a webserver which I can supply a datetime in the querystring. And the webserver must server the image closest to that time which it still has in memory.
In my code I have this:
Dictionary<DateTime, byte[]> cameraImages;
of which DateTime is the timestamp of the received image and the bytearray is the jpeg.
All of that works; also handling the webrequest works. Basically I want to clean up that dictionary by keep images according to their age.
Now I need an algorithm for it, in that it cleans up older images.
I can't really figure out an algorithm for it, one reason for it is that the datetimes aren't exactly on a specific moment, and I can't be sure that an image always arrives. (Sometimes the image stream is aborted for several minutes). But what I want to do is:
*
*Keep all images for the first minute.
*Keep 2 images per second for the first half hour.
*Keep only one image per second if it's older than 30 minutes.
*Keep only one image per 30 seconds if it's older than 2 hours.
*Keep only one image per minute if it's older than 12 hours.
*Keep only one image per hour if it's older than 24 hours.
*Keep only one image per day if it's older than two days.
*Remove all images older than 1 weeks.
The above intervals are just an example.
Any suggestions?
A: I think @Kevin Holditch's approach is perfectly reasonable and has the advantage that it would be easy to get the code right.
If there were a large number of images, or you otherwise wanted to think about how to do this "efficiently", I would propose a thought process like the following:
Create 7 queues, representing your seven categories. We take care to keep the images in this queue in sorted time order. The queue data structure is able to efficiently insert at its front and remove from its back. .NET's Queue would be perfect for this.
Each Queue (call it Qi) has an "incoming" set and an "outgoing" set. The incoming set for Queue 0 is those images from the camera, and for any other set it is equal to the outgoing set for Queue i-1
Each queue has rules on both its input and output side which determine whether the queue will admit new items from its incoming set and whether it should eject items from its back into its outgoing set. As a specific example, if Q3 is the queue "Keep only one image per 30 seconds if it's older than 2 hours", then Q3 iterates over its incoming set (which is the outcoming set of Q2) and only admits item i where i's timestamp is 30 seconds or more away from Q3.first() (For this to work correctly the items need to be processed from highest to lowest timestamp). On the output side, we eject from Q3's tail any object older than 12 hours and this becomes the input set for Q4.
Again, @Kevin Holditch's approach has the virtue of simplicity and is probably what you should do. I just thought you might find the above to be food for thought.
A: If you are on .net 4 you could use a MemoryCache for each interval with CachItemPolicy objects to expire them when you want them to expire and UpdateCallbacks to move some to the next interval.
A: You could do this quite easily (although it may not be the most efficient way by using Linq).
E.g.
var firstMinImages = cameraImages.Where(
c => c.Key >= DateTime.Now.AddMinutes(-1));
Then do an equivalent query for every time interval. Combine them into one store of images and overwrite your existing store (presuming you dont want to keep them). This will work with your current criteria as the images needed get progressively less over time.
A: My strategy would be to Group the elements into buckets that you plan to weed out, then pick 1 element from the list to keep... I have made an example of how to do this using a List of DateTimes and Ints but Pics would work exactly the same way.
My Class used to store each Pic
class Pic
{
public DateTime when {get;set;}
public int val {get;set;}
}
and a sample of a few items in the list...
List<Pic> intTime = new List<Pic>();
intTime.Add(new Pic() { when = DateTime.Now, val = 0 });
intTime.Add(new Pic() { when = DateTime.Now.AddDays(-1), val = 1 });
intTime.Add(new Pic() { when = DateTime.Now.AddDays(-1.01), val = 2 });
intTime.Add(new Pic() { when = DateTime.Now.AddDays(-1.02), val = 3 });
intTime.Add(new Pic() { when = DateTime.Now.AddDays(-2), val = 4 });
intTime.Add(new Pic() { when = DateTime.Now.AddDays(-2.1), val = 5 });
intTime.Add(new Pic() { when = DateTime.Now.AddDays(-2.2), val = 6 });
intTime.Add(new Pic() { when = DateTime.Now.AddDays(-3), val = 7 });
Now I create a helper function to bucket and remove...
private static void KeepOnlyOneFor(List<Pic> intTime, Func<Pic, int> Grouping, DateTime ApplyBefore)
{
var groups = intTime.Where(a => a.when < ApplyBefore).OrderBy(a=>a.when).GroupBy(Grouping);
foreach (var r in groups)
{
var s = r.Where(a=> a != r.LastOrDefault());
intTime.RemoveAll(a => s.Contains(a));
}
}
What this does is lets you specify how to group the object and set an age threshold on the grouping. Now finally to use...
This will remove all but 1 picture per Day for any pics greater than 2 days old:
KeepOnlyOneFor(intTime, a => a.when.Day, DateTime.Now.AddDays(-2));
This will remove all but 1 picture for each Hour after 1 day old:
KeepOnlyOneFor(intTime, a => a.when.Hour, DateTime.Now.AddDays(-1));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: const string inside a function A snippet from Mricrosoft XNA Education Catalog:
/// <summary>
/// Draws the control, using SpriteBatch and SpriteFont.
/// </summary>
protected override void Draw()
{
const string message = "Hello, World!\n" +
"\n" +
"I'm an XNA Framework GraphicsDevice,\n" +
"running inside a WinForms application.\n" +
"\n" +
"This text is drawn using SpriteBatch,\n" +
"with a SpriteFont that was loaded\n" +
"through the ContentManager.\n" +
"\n" +
"The pane to my right contains a\n" +
"spinning 3D triangle.";
GraphicsDevice.Clear(Color.CornflowerBlue);
spriteBatch.Begin();
spriteBatch.DrawString(font, message, new Vector2(23, 23), Color.White);
spriteBatch.End();
}
Draw is called 60 times per second. Is there any performance overhead with assigning message inside the draw? Is it the same as if I move it to static helper class? As far I recall, cost expression is evaluated by C# compiler. What const modifier change here?
A: A const is evaluated once only. You gain nothing by moving it away into a static variable.
A: Nope its all optimized for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Facebook API for Java application (for example, using the Swing library) I have to write an application which will use some Facebook API to connect with a user account, check the user's message box, and maybe checks the user's wall.
Among others, I saw http://code.google.com/p/facebook-java-api, but getting the started guide shows how to do it only for servlets.
A: There does not seem to be an official way to do this, most likely because of authentication requirements. You have to embed restful APIs in your application. The REST API, that you can use to call Facebook from a Java application, is at http://restfb.com/.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: get the max count per load# and only top 20 In using the following code:
SELECT SUM(LD_NUM) AS Expr1, LD_NUM
FROM Bale
GROUP BY LD_NUM
returns Expr1 = 74987 and LD_NUM = 4411
returns Expr1 = 61768 and LD_NUM = 4412
returns Expr1 = 75021 and LD_NUM = 4413
etc..
if I 74987/4411 = 17, this gives me the count per LD_NUM
is there a way to return the relationship (17,4411), (14, 4412) , (17, 4413)
and get or orderby 'Expr1' the top 20?
Hope this makes since.
A: SELECT TOP 20 SUM(LD_NUM) AS Expr1, LD_NUM, COUNT(LD_NUM) AS RecordCount
FROM Bale
GROUP BY LD_NUM
ORDER BY Expr1 DESC
Not sure if you even need the SUM for any other purpose. It could be as simple as:
SELECT TOP 20 LD_NUM, COUNT(LD_NUM) AS RecordCount
FROM Bale
GROUP BY LD_NUM
ORDER BY RecordCount DESC
A: you don't need to do any calculations to get the count,
count(LD_NUM)
is all that's needed
A: Try this
SELECT TOP 20 Expr1/LD_NUM,LD_NUM
FROM
(
SELECT SUM(LD_NUM) AS Expr1, LD_NUM
FROM Bale
GROUP BY LD_NUM
) xx
ORDER BY xx.expr1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616452",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iPhone - set MKPolylineView lineDashPattern to be animated I have been trying to work on a application using the MapKit and MKPolyline.
I have gotten the annotations and paths drawn on the map, however I am trying to change the lineDashPattern to be a set of animated dashes in the direction of the course. I know that the lineDashPhase and lineDashPattern together give you a dashed line, and the more you increase lineDashPhase, the more the dashes move, however is there a way to increase the values in such a way that it appears that it is moving, sort of like ants along a line I guess is a good analogy.
- (MKOverlayView *)mapView:(MKMapView *)mapView viewForOverlay:(id)overlay
{
MKOverlayView* overlayView = nil;
if(overlay == self.routeLine)
{
//if we have not yet created an overlay view for this overlay, create it now.
if(self.routeLineView == nil)
{
self.routeLineView = [[[MKPolylineView alloc] initWithPolyline:self.routeLine] autorelease];
self.routeLineView.lineWidth = 5;
self.routeLineView.lineDashPhase = 15;
NSArray* array = [NSArray arrayWithObjects:[NSNumber numberWithInt:20], [NSNumber numberWithInt:20], nil];
self.routeLineView.lineDashPattern = array;
}
overlayView = self.routeLineView;
}
return overlayView;
}
This right now give me dashed lines. I know there is a similar topic here, however I am not sure how to go about this. Any input would be greatly appreciated!
A: I know this is a pretty old question, but I have just implemented a similar solution and posted it here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Generate a Hash from string in Javascript I need to convert strings to some form of hash. Is this possible in JavaScript?
I'm not utilizing a server-side language so I can't do it that way.
A: Based on accepted answer in ES6. Smaller, maintainable and works in modern browsers.
function hashCode(str) {
return str.split('').reduce((prevHash, currVal) =>
(((prevHash << 5) - prevHash) + currVal.charCodeAt(0))|0, 0);
}
// Test
console.log("hashCode(\"Hello!\"): ", hashCode('Hello!'));
EDIT (2019-11-04):
one-liner arrow function version :
const hashCode = s => s.split('').reduce((a,b) => (((a << 5) - a) + b.charCodeAt(0))|0, 0)
// test
console.log(hashCode('Hello!'))
A: My quick (very long) one liner based on FNV's Multiply+Xor method:
my_string.split('').map(v=>v.charCodeAt(0)).reduce((a,v)=>a+((a<<7)+(a<<3))^v).toString(16);
A: Thanks to the example by mar10, I found a way to get the same results in C# AND Javascript for an FNV-1a. If unicode chars are present, the upper portion is discarded for the sake of performance. Don't know why it would be helpful to maintain those when hashing, as am only hashing url paths for now.
C# Version
private static readonly UInt32 FNV_OFFSET_32 = 0x811c9dc5; // 2166136261
private static readonly UInt32 FNV_PRIME_32 = 0x1000193; // 16777619
// Unsigned 32bit integer FNV-1a
public static UInt32 HashFnv32u(this string s)
{
// byte[] arr = Encoding.UTF8.GetBytes(s); // 8 bit expanded unicode array
char[] arr = s.ToCharArray(); // 16 bit unicode is native .net
UInt32 hash = FNV_OFFSET_32;
for (var i = 0; i < s.Length; i++)
{
// Strips unicode bits, only the lower 8 bits of the values are used
hash = hash ^ unchecked((byte)(arr[i] & 0xFF));
hash = hash * FNV_PRIME_32;
}
return hash;
}
// Signed hash for storing in SQL Server
public static Int32 HashFnv32s(this string s)
{
return unchecked((int)s.HashFnv32u());
}
JavaScript Version
var utils = utils || {};
utils.FNV_OFFSET_32 = 0x811c9dc5;
utils.hashFnv32a = function (input) {
var hval = utils.FNV_OFFSET_32;
// Strips unicode bits, only the lower 8 bits of the values are used
for (var i = 0; i < input.length; i++) {
hval = hval ^ (input.charCodeAt(i) & 0xFF);
hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
}
return hval >>> 0;
}
utils.toHex = function (val) {
return ("0000000" + (val >>> 0).toString(16)).substr(-8);
}
A: A fast and concise one which was adapted from here:
String.prototype.hashCode = function() {
var hash = 5381, i = this.length
while(i)
hash = (hash * 33) ^ this.charCodeAt(--i)
return hash >>> 0;
}
A: I'm a bit surprised nobody has talked about the new SubtleCrypto API yet.
To get an hash from a string, you can use the subtle.digest method :
function getHash(str, algo = "SHA-256") {
let strBuf = new TextEncoder().encode(str);
return crypto.subtle.digest(algo, strBuf)
.then(hash => {
window.hash = hash;
// here hash is an arrayBuffer,
// so we'll connvert it to its hex version
let result = '';
const view = new DataView(hash);
for (let i = 0; i < hash.byteLength; i += 4) {
result += ('00000000' + view.getUint32(i).toString(16)).slice(-8);
}
return result;
});
}
getHash('hello world')
.then(hash => {
console.log(hash);
});
A: I needed a similar function (but different) to generate a unique-ish ID based on the username and current time. So:
window.newId = ->
# create a number based on the username
unless window.userNumber?
window.userNumber = 0
for c,i in window.MyNamespace.userName
char = window.MyNamespace.userName.charCodeAt(i)
window.MyNamespace.userNumber+=char
((window.MyNamespace.userNumber + Math.floor(Math.random() * 1e15) + new Date().getMilliseconds()).toString(36)).toUpperCase()
Produces:
2DVFXJGEKL
6IZPAKFQFL
ORGOENVMG
... etc
edit Jul 2022: As @canRau points out the authors of shortid prefer nanoid now https://github.com/ai/nanoid/
A: SubtleCrypto.digest
I’m not utilizing a server-side language so I can’t do it that way.
Are you sure you can’t do it that way?
Did you forget you’re using Javascript, the language ever-evolving?
Try SubtleCrypto. It supports SHA-1, SHA-128, SHA-256, and SHA-512 hash functions.
async function hash(message/*: string */) {
const text_encoder = new TextEncoder;
const data = text_encoder.encode(message);
const message_digest = await window.crypto.subtle.digest("SHA-512", data);
return message_digest;
} // -> ArrayBuffer
function in_hex(data/*: ArrayBuffer */) {
const octets = new Uint8Array(data);
const hex = [].map.call(octets, octet => octet.toString(16).padStart(2, "0")).join("");
return hex;
} // -> string
(async function demo() {
console.log(in_hex(await hash("Thanks for the magic.")));
})();
A: The Jenkins One at a Time Hash is quite nice:
//Credits (modified code): Bob Jenkins (http://www.burtleburtle.net/bob/hash/doobs.html)
//See also: https://en.wikipedia.org/wiki/Jenkins_hash_function
//Takes a string of any size and returns an avalanching hash string of 8 hex characters.
function jenkinsOneAtATimeHash(keyString)
{
let hash = 0;
for (charIndex = 0; charIndex < keyString.length; ++charIndex)
{
hash += keyString.charCodeAt(charIndex);
hash += hash << 10;
hash ^= hash >> 6;
}
hash += hash << 3;
hash ^= hash >> 11;
//4,294,967,295 is FFFFFFFF, the maximum 32 bit unsigned integer value, used here as a mask.
return (((hash + (hash << 15)) & 4294967295) >>> 0).toString(16)
};
Examples:
jenkinsOneAtATimeHash('test')
"31c25ec1"
jenkinsOneAtATimeHash('a')
"ca2e9442"
jenkinsOneAtATimeHash('0')
"6e3c5c6b"
You can also remove the .toString(16) part at the end to generate numbers:
jenkinsOneAtATimeHash2('test')
834821825
jenkinsOneAtATimeHash2('a')
3392050242
jenkinsOneAtATimeHash2('0')
1849449579
Note that if you do not need to hash a string or key specifically, but just need a hash generated out of thin air, you can use:
window.crypto.getRandomValues(new Uint32Array(1))[0].toString(16)
Examples:
window.crypto.getRandomValues(new Uint32Array(1))[0].toString(16)
"6ba9ea7"
window.crypto.getRandomValues(new Uint32Array(1))[0].toString(16)
"13fe7edf"
window.crypto.getRandomValues(new Uint32Array(1))[0].toString(16)
"971ffed4"
and the same as above, you can remove the `.toString(16) part at the end to generate numbers:
window.crypto.getRandomValues(new Uint32Array(1))[0]
1154752776
window.crypto.getRandomValues(new Uint32Array(1))[0]
3420298692
window.crypto.getRandomValues(new Uint32Array(1))[0]
1781389127
Note: You can also generate multiple values at once with this method, e.g.:
window.crypto.getRandomValues(new Uint32Array(3))
Uint32Array(3) [ 2050530949, 3280127172, 3001752815 ]
A: This is a refined and better performing variant, and matches Java's implementation of the standard object.hashCode() for CharSequence.
String.prototype.hashCode = function() {
var hash = 0, i = 0, len = this.length;
while ( i < len ) {
hash = ((hash << 5) - hash + this.charCodeAt(i++)) << 0;
}
return hash;
};
Here is also one that returns only positive hashcodes:
String.prototype.hashcode = function() {
return this.hashCode()+ 2147483647 + 1;
};
And here is a matching one for Java that only returns positive hashcodes:
public static long hashcode(Object obj) {
return ((long) obj.hashCode()) + Integer.MAX_VALUE + 1l;
}
Without prototype for those that do not want to attach it to String :
function hashCode(str) {
var hash = 0, i = 0, len = str.length;
while ( i < len ) {
hash = ((hash << 5) - hash + str.charCodeAt(i++)) << 0;
}
return hash;
}
function hashcode(str) {
hashCode(str) + 2147483647 + 1;
}
Enjoy!
A: Many of the answers here are the same String.hashCode hash function taken from Java. It dates back to 1981 from Gosling Emacs, is extremely weak, and makes zero sense performance-wise in modern JavaScript. In fact, implementations could be significantly faster by using ES6 Math.imul, but no one took notice. We can do much better than this, at essentially identical performance.
Here's one I did—cyrb53, a simple but high quality 53-bit hash. It's quite fast, provides very good* hash distribution, and because it outputs 53 bits, has significantly lower collision rates compared to any 32-bit hash. Also, you can ignore SA's CC license as it's public domain on my GitHub.
const cyrb53 = (str, seed = 0) => {
let h1 = 0xdeadbeef ^ seed,
h2 = 0x41c6ce57 ^ seed;
for (let i = 0, ch; i < str.length; i++) {
ch = str.charCodeAt(i);
h1 = Math.imul(h1 ^ ch, 2654435761);
h2 = Math.imul(h2 ^ ch, 1597334677);
}
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
return 4294967296 * (2097151 & h2) + (h1 >>> 0);
};
console.log(`cyrb53('a') -> ${cyrb53('a')}`)
console.log(`cyrb53('b') -> ${cyrb53('b')}`)
console.log(`cyrb53('revenge') -> ${cyrb53('revenge')}`)
console.log(`cyrb53('revenue') -> ${cyrb53('revenue')}`)
console.log(`cyrb53('revenue', 1) -> ${cyrb53('revenue', 1)}`)
console.log(`cyrb53('revenue', 2) -> ${cyrb53('revenue', 2)}`)
console.log(`cyrb53('revenue', 3) -> ${cyrb53('revenue', 3)}`)
*It is roughly similar to the well-known MurmurHash/xxHash algorithms. It uses a combination of multiplication and Xorshift to generate the hash, but not as thorough. As a result it's faster than either would be in JavaScript and significantly simpler to implement, but may not pass all tests in SMHasher. This is not a cryptographic hash function, so don't use this for security purposes.
Like any proper hash, it has an avalanche effect, which basically means small changes in the input have big changes in the output making the resulting hash appear more 'random':
"501c2ba782c97901" = cyrb53("a")
"459eda5bc254d2bf" = cyrb53("b")
"fbce64cc3b748385" = cyrb53("revenge")
"fb1d85148d13f93a" = cyrb53("revenue")
You can optionally supply a seed (unsigned integer, 32-bit max) for alternate streams of the same input:
"76fee5e6598ccd5c" = cyrb53("revenue", 1)
"1f672e2831253862" = cyrb53("revenue", 2)
"2b10de31708e6ab7" = cyrb53("revenue", 3)
Technically, it is a 64-bit hash, that is, two uncorrelated 32-bit hashes computed in parallel, but JavaScript is limited to 53-bit integers. If convenient, the full 64-bit output can be used by altering the return statement with a hex string or array.
return [h2>>>0, h1>>>0];
// or
return (h2>>>0).toString(16).padStart(8,0)+(h1>>>0).toString(16).padStart(8,0);
// or
return 4294967296n * BigInt(h2) + BigInt(h1);
Be aware that constructing hex strings drastically slows down batch processing. The array is much more efficient, but obviously requires two checks instead of one. I also included BigInt, which should be slightly faster than String, but still much slower than Array or Number.
Just for fun, here's TinySimpleHash, the smallest hash I could come up with that's still decent. It's a 32-bit hash in 89 chars with better quality randomness than even FNV or DJB2:
TSH=s=>{for(var i=0,h=9;i<s.length;)h=Math.imul(h^s.charCodeAt(i++),9**9);return h^h>>>9}
A: If it helps anyone, I combined the top two answers into an older-browser-tolerant version, which uses the fast version if reduce is available and falls back to esmiralha's solution if it's not.
/**
* @see http://stackoverflow.com/q/7616461/940217
* @return {number}
*/
String.prototype.hashCode = function(){
if (Array.prototype.reduce){
return this.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);
}
var hash = 0;
if (this.length === 0) return hash;
for (var i = 0; i < this.length; i++) {
var character = this.charCodeAt(i);
hash = ((hash<<5)-hash)+character;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
Usage is like:
var hash = "some string to be hashed".hashCode();
A: If you want to avoid collisions you may want to use a secure hash like SHA-256.
There are several JavaScript SHA-256 implementations.
I wrote tests to compare several hash implementations, see https://github.com/brillout/test-javascript-hash-implementations.
Or go to http://brillout.github.io/test-javascript-hash-implementations/, to run the tests.
A: I do not see any reason to use this overcomplicated crypto code instead of ready-to-use solutions, like object-hash library, or etc. relying on vendor is more productive, saves time and reduces maintenance cost.
Just use https://github.com/puleos/object-hash
var hash = require('object-hash');
hash({foo: 'bar'}) // => '67b69634f9880a282c14a0f0cb7ba20cf5d677e9'
hash([1, 2, 2.718, 3.14159]) // => '136b9b88375971dff9f1af09d7356e3e04281951'
A: I have combined the two solutions (users esmiralha and lordvlad) to get a function that should be faster for browsers that support the js function reduce() and still compatible with old browsers:
String.prototype.hashCode = function() {
if (Array.prototype.reduce) {
return this.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0);
} else {
var hash = 0, i, chr, len;
if (this.length == 0) return hash;
for (i = 0, len = this.length; i < len; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
};
Example:
my_string = 'xyz';
my_string.hashCode();
A: I went for a simple concatenation of char codes converted to hex strings. This serves a relatively narrow purpose, namely just needing a hash representation of a SHORT string (e.g. titles, tags) to be exchanged with a server side that for not relevant reasons can't easily implement the accepted hashCode Java port. Obviously no security application here.
String.prototype.hash = function() {
var self = this, range = Array(this.length);
for(var i = 0; i < this.length; i++) {
range[i] = i;
}
return Array.prototype.map.call(range, function(i) {
return self.charCodeAt(i).toString(16);
}).join('');
}
This can be made more terse and browser-tolerant with Underscore. Example:
"Lorem Ipsum".hash()
"4c6f72656d20497073756d"
I suppose if you wanted to hash larger strings in similar fashion you could just reduce the char codes and hexify the resulting sum rather than concatenate the individual characters together:
String.prototype.hashLarge = function() {
var self = this, range = Array(this.length);
for(var i = 0; i < this.length; i++) {
range[i] = i;
}
return Array.prototype.reduce.call(range, function(sum, i) {
return sum + self.charCodeAt(i);
}, 0).toString(16);
}
'One time, I hired a monkey to take notes for me in class. I would just sit back with my mind completely blank while the monkey scribbled on little pieces of paper. At the end of the week, the teacher said, "Class, I want you to write a paper using your notes." So I wrote a paper that said, "Hello! My name is Bingo! I like to climb on things! Can I have a banana? Eek, eek!" I got an F. When I told my mom about it, she said, "I told you, never trust a monkey!"'.hashLarge()
"9ce7"
Naturally more risk of collision with this method, though you could fiddle with the arithmetic in the reduce however you wanted to diversify and lengthen the hash.
A: Adding this because nobody did yet, and this seems to be asked for and implemented a lot with hashes, but it's always done very poorly...
This takes a string input, and a maximum number you want the hash to equal, and produces a unique number based on the string input.
You can use this to produce a unique index into an array of images (If you want to return a specific avatar for a user, chosen at random, but also chosen based on their name, so it will always be assigned to someone with that name).
You can also use this, of course, to return an index into an array of colors, like for generating unique avatar background colors based on someone's name.
function hashInt (str, max = 1000) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash = hash & hash;
}
return Math.round(max * Math.abs(hash) / 2147483648);
}
A: This generates a consistent hash based on any number of params passed in:
/**
* Generates a hash from params passed in
* @returns {string} hash based on params
*/
function fastHashParams() {
var args = Array.prototype.slice.call(arguments).join('|');
var hash = 0;
if (args.length == 0) {
return hash;
}
for (var i = 0; i < args.length; i++) {
var char = args.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32bit integer
}
return String(hash);
}
fastHashParams('hello world') outputs "990433808"
fastHashParams('this',1,'has','lots','of','params',true) outputs "1465480334"
A: EDIT
based on my jsperf tests, the accepted answer is actually faster: http://jsperf.com/hashcodelordvlad
ORIGINAL
if anyone is interested, here is an improved ( faster ) version, which will fail on older browsers who lack the reduce array function.
hashCode = function(s) {
return s.split("").reduce(function(a, b) {
a = ((a << 5) - a) + b.charCodeAt(0);
return a & a;
}, 0);
}
// testing
console.log(hashCode("hello."));
console.log(hashCode("this is a text."));
console.log(hashCode("Despacito by Luis Fonsi"));
one-liner arrow function version :
hashCode = s => s.split('').reduce((a,b)=>{a=((a<<5)-a)+b.charCodeAt(0);return a&a},0)
// testing
console.log(hashCode("hello."));
console.log(hashCode("this is a text."));
console.log(hashCode("Despacito by Luis Fonsi"));
A: UUID v3 and UUID v5 actually are hashes for a given input string.
*
*UUID v3 is based on MD5,
*UUID v5 is based on SHA-1.
So, the most obvious choice would be to go for UUID v5.
Fortunately, there is a popular npm package, which includes all UUID algorithms.
npm install uuid
To actually generate a UUID v5, you need a unique namespace. This namespace acts like a seed, and should be a constant, to assure that for a given input the output will always be the same. Ironically, you should generate a UUID v4 as a namespace. And the easiest way to do so, is using some online tool.
Once you've got a namespace, you're all set.
import { v5 as uuidv5 } from 'uuid';
const MY_NAMESPACE = '1b671a64-40d5-491e-99b0-da01ff1f3341';
const hash = uuidv5('input', MY_NAMESPACE);
If your input string will always be an URL for instance, then there are some default namespaces which you can use.
const hashForURL = uuidv5('https://www.w3.org/', uuidv5.URL);
A:
Note: Even with the best 32-bit hash, collisions will occur sooner or later.
The hash collision probability can be calculated as
,
approximated as
(see here).
This may be higher than intuition suggests:
Assuming a 32-bit hash and k=10,000 items, a collision will occur with a probability of 1.2%.
For 77,163 samples the probability becomes 50%!
(calculator).
I suggest a workaround at the bottom.
In an answer to this question
Which hashing algorithm is best for uniqueness and speed?,
Ian Boyd posted a good in depth analysis.
In short (as I interpret it), he comes to the conclusion that MurmurHash is best, followed by FNV-1a.
Java’s String.hashCode() algorithm that esmiralha proposed seems to be a variant of DJB2.
*
*FNV-1a has a a better distribution than DJB2, but is slower
*DJB2 is faster than FNV-1a, but tends to yield more collisions
*MurmurHash3 is better and faster than DJB2 and FNV-1a (but the optimized implementation requires more lines of code than FNV and DJB2)
Some benchmarks with large input strings here: http://jsperf.com/32-bit-hash
When short input strings are hashed, murmur's performance drops, relative to DJ2B and FNV-1a: http://jsperf.com/32-bit-hash/3
So in general I would recommend murmur3.
See here for a JavaScript implementation:
https://github.com/garycourt/murmurhash-js
If input strings are short and performance is more important than distribution quality, use DJB2 (as proposed by the accepted answer by esmiralha).
If quality and small code size are more important than speed, I use this implementation of FNV-1a (based on this code).
/**
* Calculate a 32 bit FNV-1a hash
* Found here: https://gist.github.com/vaiorabbit/5657561
* Ref.: http://isthe.com/chongo/tech/comp/fnv/
*
* @param {string} str the input value
* @param {boolean} [asString=false] set to true to return the hash value as
* 8-digit hex string instead of an integer
* @param {integer} [seed] optionally pass the hash of the previous chunk
* @returns {integer | string}
*/
function hashFnv32a(str, asString, seed) {
/*jshint bitwise:false */
var i, l,
hval = (seed === undefined) ? 0x811c9dc5 : seed;
for (i = 0, l = str.length; i < l; i++) {
hval ^= str.charCodeAt(i);
hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
}
if( asString ){
// Convert to 8 digit hex string
return ("0000000" + (hval >>> 0).toString(16)).substr(-8);
}
return hval >>> 0;
}
Improve Collision Probability
As explained here, we can extend the hash bit size using this trick:
function hash64(str) {
var h1 = hash32(str); // returns 32 bit (as 8 byte hex string)
return h1 + hash32(h1 + str); // 64 bit (as 16 byte hex string)
}
Use it with care and don't expect too much though.
A: Here is a compact ES6 friendly readable snippet
const stringHashCode = str => {
let hash = 0
for (let i = 0; i < str.length; ++i)
hash = Math.imul(31, hash) + str.charCodeAt(i)
return hash | 0
}
A: I'm kinda late to the party, but you can use this module: crypto:
const crypto = require('crypto');
const SALT = '$ome$alt';
function generateHash(pass) {
return crypto.createHmac('sha256', SALT)
.update(pass)
.digest('hex');
}
The result of this function is always is 64 characters string; something like this: "aa54e7563b1964037849528e7ba068eb7767b1fab74a8d80fe300828b996714a"
A:
String.prototype.hashCode = function() {
var hash = 0,
i, chr;
if (this.length === 0) return hash;
for (i = 0; i < this.length; i++) {
chr = this.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0; // Convert to 32bit integer
}
return hash;
}
const str = 'revenue'
console.log(str, str.hashCode())
Source
A: Slightly simplified version of @esmiralha's answer.
I don't override String in this version, since that could result in some undesired behaviour.
function hashCode(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = ~~(((hash << 5) - hash) + str.charCodeAt(i));
}
return hash;
}
A:
function hashCode(str) {
return str.split('').reduce((prevHash, currVal) =>
(((prevHash << 5) - prevHash) + currVal.charCodeAt(0))|0, 0);
}
// Test
console.log("hashCode(\"Hello!\"): ", hashCode('Hello!'));
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "884"
} |
Q: How to attach click event at runtime when i have all ids in an array that gets populated when document is ready? I have the following code,
<script type="text/javascript">
$(document).ready(function () {
var dataAnalysisDataFileTableIDs = $("#dataAnalysisDataFileTable tr[id]").map(function () { return this.id; }).get();
//for(var key in dataAnalysisDataFileTableIDs) {
// var id = "#" + dataAnalysisDataFileTableIDs[key];
// $(id).click(function () {
// alert("[" + index + "][" + value + "]");
// });
//}
//$.each(dataAnalysisDataFileTableIDs, function (index, value) {
// var id = "#" + dataAnalysisDataFileTableIDs[key];
// $(id).click(function () {
// alert("[" + index + "][" + value + "]");
// });
//});
$("#dataAnalysisDataFileTable tr[id]").each(function (i, elem) {
$(elem).click(function () { alert("[" + i + "][" + this.id + "]"); });
});
$("#aaa").click(function () {
alert("meow");
});
});
</script>
and it doesn't work i also tried the one in the comments section which does the same as "for in" it doen't work but when i attach click to the id #aaa it works fine how do i approach this problem when i have all the ids in the array and i want to be able to attach events to them?
A: How about just using each ? Like so:
<html>
<head><script type="text/javascript" src="http://code.jquery.com/jquery-1.6.4.min.js"></script></head>
<body>
<table id="dataAnalysisDataFileTable">
<tr id="foo"><td>foo</td></tr>
<tr id="bar"><td>bar</td></tr>
</table>
<script type="text/javascript">
$(document).ready(function () {
$("#dataAnalysisDataFileTable tr[id]").each(function(i, elem) {
$(elem).click(function() { alert("[" + i + "][" + this.id + "]") } );
});
});
</script>
</body>
</html>
A: I've patched the possible errors. I cannot resolve the value variable though.
for(var index=0, length=dataAnalysisFileTableIDs.length; index++) {
var key = dataAnalysisFileTableIDs[index];
var id = "#" + dataAnalysisFileTableIDs[key];
$(id).click(function () {
/* Value ? It's not defined*/
alert("[" + index + "][" + /*value +*/ "]");
});
}
dataAnalysisFileTableIDs is an array. To loop through an array, you have to use the for ( init_index ; condition ; increment ) loop. The key can be obtained through name_of_array[index].
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Container Class Sequence c++ I am new to programming in c++ so can you please help me out? My code doesn't compile
and I can't figure out the errors. This is the implementation file I wrote :
# include <algorithm>
#include <cassert>
#include "sequence1.h" // See below
using namespace std;
namespace main_savitch_3{
const sequence::size_type sequence:: CAPACITY;
sequence::sequence(){
current_index = 0;
used = 0;
}
void sequence::start(){
current_index= 0;
}
void sequence::advance(){
if (is_item()== true)
{current_index++;
}
}
void sequence::insert(const value_type& entry){
int i;
assert (size()< CAPACITY);
if (is_item() == false){
current_index=0;}
for (i= used, i>current_index,i--){
data[i] = data [i-1];}
data[current_index]= entry;
used++;
}
void sequence:: attach(const value_type& entry){
int i;
assert (size()< CAPACITY);
if (is_item() == false){
data[used-1]= entry;}
for (i= used, i> current_index, i--){
data[i]= data[i+1];
}
data[current_index]= entry;
used++;
}
void sequence::remove_current(){
int i;
assert(is_item()== true);
for (i= current_index + 1, i< used - 1, i++){
data [i]= data[i+1];
used--;
}
}
sequence::size_type sequence::size() const{
return used;}
bool is_item() const {
if(current_index< used){
return true;}
}
sequence::value_type sequence:: current() const{
return data[current_index];}
}
Here is the header file provided for my homework
// FILE: sequence1.h
/*
CLASS PROVIDED: sequence (part of the namespace main_savitch_3)
There is no implementation file provided for this class since it is
an exercise from Section 3.2 of "Data Structures and Other Objects Using C++"
TYPEDEFS and MEMBER CONSTANTS for the sequence class:
typedef ____ value_type
sequence::value_type is the data type of the items in the sequence. It
may be any of the C++ built-in types (int, char, etc.), or a class with a
default constructor, an assignment operator, and a copy constructor.
typedef ____ size_type
sequence::size_type is the data type of any variable that keeps track of
how many items are in a sequence.
static const size_type CAPACITY = _____
sequence::CAPACITY is the maximum number of items that a sequence can hold.
CONSTRUCTOR for the sequence class:
sequence( )
Postcondition: The sequence has been initialized as an empty sequence.
MODIFICATION MEMBER FUNCTIONS for the sequence class:
void start( )
Postcondition: The first item on the sequence becomes the current item
(but if the sequence is empty, then there is no current item).
void advance( )
Precondition: is_item returns true.
Postcondition: If the current item was already the last item in the
sequence, then there is no longer any current item. Otherwise, the new
current item is the item immediately after the original current item.
void insert(const value_type& entry)
Precondition: size( ) < CAPACITY.
Postcondition: A new copy of entry has been inserted in the sequence
before the current item. If there was no current item, then the new entry
has been inserted at the front of the sequence. In either case, the newly
inserted item is now the current item of the sequence.
void attach(const value_type& entry)
Precondition: size( ) < CAPACITY.
Postcondition: A new copy of entry has been inserted in the sequence after
the current item. If there was no current item, then the new entry has
been attached to the end of the sequence. In either case, the newly
inserted item is now the current item of the sequence.
void remove_current( )
Precondition: is_item returns true.
Postcondition: The current item has been removed from the sequence, and the
item after this (if there is one) is now the new current item.
CONSTANT MEMBER FUNCTIONS for the sequence class:
size_type size( ) const
Postcondition: The return value is the number of items in the sequence.
bool is_item( ) const
Postcondition: A true return value indicates that there is a valid
"current" item that may be retrieved by activating the current
member function (listed below). A false return value indicates that
there is no valid current item.
value_type current( ) const
Precondition: is_item( ) returns true.
Postcondition: The item returned is the current item in the sequence.
VALUE SEMANTICS for the sequence class:
Assignments and the copy constructor may be used with sequence objects.
*/
#ifndef MAIN_SAVITCH_SEQUENCE_H
#define MAIN_SAVITCH_SEQUENCE_H
#include <cstdlib> // Provides size_t
namespace main_savitch_3
{
class sequence
{
public:
// TYPEDEFS and MEMBER CONSTANTS
typedef double value_type;
typedef std::size_t size_type;
static const size_type CAPACITY = 30;
// CONSTRUCTOR
sequence( );
// MODIFICATION MEMBER FUNCTIONS
void start( );
void advance( );
void insert(const value_type& entry);
void attach(const value_type& entry);
void remove_current( );
// CONSTANT MEMBER FUNCTIONS
size_type size( ) const;
bool is_item( ) const;
value_type current( ) const;
private:
value_type data[CAPACITY];
size_type used;
size_type current_index;
};
}
#endif
These are the mistakes the compiler gives me. How can I fix them and are there any logical errors in my code?
Thank you for your time
this is the link to the sequence_exam file that will be used to grade me www-cs.ccny.cuny.edu/~esther/CSC212/HW/sequence_exam.cxx. when i use jgrasp and compile and link the header file, the implementation file, and the exam code i get undefined reference to main_savitch_3::sequence to all my functions. Am i compiling it wrong? Otherwise my implementation compiles perfectly
A: You should look around closer first, but here's the top error for you ;)
for (i= used, i>current_index,i--){
should be
for (i = used; i > current_index; i--)
Also,
bool is_item() const {
if(current_index< used){
return true;
}
}
should be:
bool sequence::is_item() const {
if(current_index< used){
return true;
}
}
the way you had it, it wasn't a member function - so it said "non-member function cannot have cv-qualifier, meaning you cant declare a non-member function const because const is for protecting data members and non-class functions don't have data members.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Combining NSArrays Through Intersection and Union I have two NSArrays A and B that share some common elements, e.g.
A: 1,2,3,4,5
B: 4,5,6,7
I would like to create a new NSArray consisting of the contents common between the two NSArrays joined with the contents of the second NSArray while maintaining the order of the elements and removing duplicates. That is, I would like (A ∩ B) ∪ B.
The operation on the previous NSArrays would yield:
A ∩ B: 4,5
(A ∩ B) ∪ B: 4,5,6,7
How do I accomplish this in Objective-C?
A: By using NSSet, as others have pointed out. For
NSArray * a = [NSArray arrayWithObjects: ... ];
NSArray * b = [NSArray arratWithObjects: ... ];
NSMutableSet * set = [NSMutableSet setWithArray:a];
[set intersectSet:[NSSet setWithArray:b];
[set unionSet:[NSSet setWithArray:b];
This takes care of dupes but won't preserve order. You'd take the results in "set" and sort them back into an array. There's no native collection functionality that will do it all-- if you prefer to keep the order and worry about dupes separately, use NSMutableArray's -removeObjectsInArray: method, etc.
A: Convert the NSArrays to NSSets, the standard set operations are available.
NSArray *a = [NSArray arrayWithObjects:@"1", @"2", @"3", @"4", @"5", nil];
NSArray *b = [NSArray arrayWithObjects:@"4", @"5", @"6", @"7", nil];
NSMutableSet *setA = [NSMutableSet setWithArray:a];
NSSet *setB = [NSSet setWithArray:b];
[setA intersectSet:setB];
NSLog(@"c: %@", [setA allObjects]);
NSLog output: c: (4, 5)
[setA unionSet:setB];
NSLog(@"d: %@", [setA allObjects]);
NSLog output: d: (6, 4, 7, 5)
A: (A ∩ B) ∪ B will always give you B, so this is a pretty bizarre thing to want to calculate. It's like saying "Give me the set of all cars that are colored green, combined with the set of all cars". That's going to give you the set of all cars.
A: As others have suggested, you can easily do this with NSSet. However, this will not preserve ordering.
If you want to preserve ordering and you can target OS X 10.7+, then you can use the new NSOrderedSet (and mutable subclass) to do the same thing.
A: There is an NSSet class you can use to perform these operations.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: Can Google Mock a method with a smart pointer return type? I have a factory that returns a smart pointer. Regardless of what smart pointer I use, I can't get Google Mock to mock the factory method.
The mock object is the implementation of a pure abstract interface where all methods are virtual. I have a prototype:
MOCK_METHOD0(Create, std::unique_ptr<IMyObjectThing>());
And I get:
"...gmock/gmock-spec-builders.h(1314): error C2248: 'std::unique_ptr<_Ty>::unique_ptr' : cannot access private member declared in class 'std::unique_ptr<_Ty>'"
The type pointed to in the smart pointer is defined.
And I get it's trying to access one of the constructors declared private, but I don't understand why. When this was an std::auto_ptr, the error said there was no copy constructor, which confuses me.
Anyway, is there a way to Mock a method that returns a smart pointer? Or is there a better way to build a factory? Is my only resolve to return a raw pointer (blech...)?
My environment is Visual Studio 2010 Ultimate and Windows 7. I'm not using CLI.
A: in the mock class put same as you want
MOCK_METHOD0(Create, std::unique_ptr());
and in the test as below
EXPECT_CALL(<mock-obj>, Create())
.WillOnce([]()->std::unique_ptr<IMyObjectThing>{
return std::make_unique<IMyObjectThing>();
});
if vs 2010 not support for lambda, you can use a functor
A: I know this post was from a long time ago, so you've probably discovered the answer by now.
gmock previously did not support mock functions that returned any movable type, including smart pointers. However, in April 2017, gmock introduced a new Action modifier ByMove.
EXPECT_CALL(*foo_, Bar(_, )).WillOnce(Return(ByMove(some_move_only_object)));
where some_move_only_object can be e.g. a std::unique_ptr.
So yes, now gmock can mock a function that takes a smart pointer.
A: I have recently discovered that returning smart pointers by mocked functions is still not very user friendly. Yes, the new action ByMove had been introduced, however it turns out it may be used only once during the test. So imagine you have a factory class to test that repeatedly returns unique_ptr to the newly created object.
Any attempt to .WillRepeatedly(Return(ByMove) or multiple ON_CALL with .WillByDefault(Return(ByMove) will result in the following error:
[ FATAL ] Condition !performed_ failed. A ByMove() action should only be performed once.
This is also clearly stated in the GMock Cookbook in the paragraph "Mocking Methods That Use Move-Only Types".
A: A feasible workaround for google mock framework's problems with non (const) copyable function arguments and retun values is to use proxy mock methods.
Suppose you have the following interface definition (if it's good style to use std::unique_ptr in this way seems to be more or less a philosophical question, I personally like it to enforce transfer of ownership):
class IFooInterface {
public:
virtual void nonCopyableParam(std::unique_ptr<IMyObjectThing> uPtr) = 0;
virtual std::unique_ptr<IMyObjectThing> nonCopyableReturn() = 0;
virtual ~IFooInterface() {}
};
The appropriate mock class could be defined like this:
class FooInterfaceMock
: public IFooInterface {
public:
FooInterfaceMock() {}
virtual ~FooInterfaceMock() {}
virtual void nonCopyableParam(std::unique_ptr<IMyObjectThing> uPtr) {
nonCopyableParamProxy(uPtr.get());
}
virtual std::unique_ptr<IMyObjectThing> nonCopyableReturn() {
return std::unique_ptr<IMyObjectThing>(nonCopyableReturnProxy());
}
MOCK_METHOD1(nonCopyableParamProxy,void (IMyObjectThing*));
MOCK_METHOD0(nonCopyableReturnProxy,IMyObjectThing* ());
};
You just need to take care, that configurations (Actions taken) for the nonCopyableReturnProxy() method return either NULL or an instance allocated dynamically on the heap.
There's a google-mock user forum thread discussing this topic where one of the maintainers states that the google-mock framework won't be changed to support this in future arguing that their policies strongly discourage the usage std::auto_ptr parameters. As mentioned this is IMHO a philosophical point of view, and the capabilities of the mocking framework shouldn't steer what kind of interfaces you want to design or you can use from 3rd party APIs.
As said the answer describes a feasible workaround.
A: Google Mock requires parameters and return values of mocked methods to be copyable, in most cases. Per boost's documentation, unique_ptr is not copyable. You have an option of returning one of the smart pointer classes that use shared ownership (shared_ptr, linked_ptr, etc.) and are thus copyable. Or you can use a raw pointer. Since the method in question is apparently the method constructing an object, I see no inherent problem with returning a raw pointer. As long as you assign the result to some shared pointer at every call site, you are going to be fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616475",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "52"
} |
Q: MySQL query error...it does not display the exact data values I want to ask if what is wrong (and probably ask for suggestions on how to better do it) with my MySQL query? I'm trying to generate a daily report within a range of 5days... the problem is it does not display the exact datas, It fills up days that does not have data in it.
This is the case of the MySQL query example below:
In my database, monday, wed and thursday are with datas.. but if I will run the reports using this query, tuesday will have an existing data which it does not actually has in my database. Although the IT, NonIt, and Total table count is correct. I have errors in counting the datas in my days only. please help me... I don't know where the errors already.
To better explain what I mean, here is the screenshot of the output result of my query:
http://www.fileden.com/files/2011/7/27/3174077//daily.JPG
SELECT a.specialist_partner_ID, ss.first_name as SS, ssa.first_name as SSA
,count(CASE WHEN a.receivedDate BETWEEN '2011-09-5' AND '2011-09-9'
THEN a.job_order_number ELSE null END) As MON
,count(CASE WHEN a.receivedDate BETWEEN date_add('2011-09-5', INTERVAL 1 DAY)
AND DATE_ADD('2011-09-9', INTERVAL 1 DAY) THEN a.job_order_number ELSE null END) As TUE
,count(CASE WHEN a.receivedDate BETWEEN date_add('2011-09-5', INTERVAL 2 DAY)
AND DATE_ADD('2011-09-9', INTERVAL 2 DAY) THEN a.job_order_number ELSE null END) As WED
,count(CASE WHEN a.receivedDate BETWEEN date_add('2011-09-5', INTERVAL 3 DAY)
AND DATE_ADD('2011-09-9', INTERVAL 3 DAY) THEN a.job_order_number ELSE null END) As THU
,count(CASE WHEN a.receivedDate BETWEEN date_add('2011-09-5', INTERVAL 4 DAY)
AND DATE_ADD('2011-09-9', INTERVAL 4 DAY) THEN a.job_order_number ELSE null END) As FRI
,count(case WHEN (a.receivedDate between '2011-09-5 00:00:00' and '2011-09-9 23:59:59'
and jo.job_order_type LIKE 'IT') then a.job_order_number else null end) as IT
,count(case WHEN (a.receivedDate between '2011-09-5 00:00:00' and '2011-09-9 23:59:59'
and jo.job_order_type LIKE 'Non-IT') then a.job_order_number else null end) as NonIT
,count(a.job_order_number) As Total FROM jo_partner a
left join specialist_partner sp on a.specialist_Partner_ID = sp.specialistPartnerID
left join staffing_specialist_asst ssa on sp.SSA_ID = ssa.SSA_ID
left join staffing_specialist ss on sp.SS_ID = ss.SS_ID
left join job_order jo on a.job_order_number = jo.job_order_number
left join candidate_jo cjo on a.JO_partner_ID= cjo.jo_partner_ID
left join candidate can on cjo.candidate_jo_ID= can.candidate_ID
WHERE a.receivedDate BETWEEN '2011-09-5 00:00:00' AND '2011-09-9 23:59:59'
GROUP BY a.specialist_partner_ID
A: I think you have wrong dates. For every day column you are selecting data from 5 days, this has no sense.
So instead of:
count(CASE WHEN a.receivedDate BETWEEN date_add('2011-09-5', INTERVAL 1 DAY)
AND DATE_ADD('2011-09-9', INTERVAL 1 DAY) THEN a.job_order_number ELSE null END) As TUE
You should have:
count(CASE WHEN a.receivedDate BETWEEN date_add('2011-09-5', INTERVAL 1 DAY)
and DATE_ADD('2011-09-5', INTERVAL 2 DAY) THEN a.job_order_number ELSE null END) As TUE
Or even better:
count(CASE WHEN a.receivedDate >= date_add('2011-09-5', INTERVAL 1 DAY)
and a.receivedDate < DATE_ADD('2011-09-5', INTERVAL 2 DAY) THEN a.job_order_number ELSE null END) As TUE
The same for the rest of the days.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7616476",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.