text
stringlengths 0
27.6k
| python
int64 0
1
| DeepLearning or NLP
int64 0
1
| Other
int64 0
1
| Machine Learning
int64 0
1
| Mathematics
int64 0
1
| Trash
int64 0
1
|
|---|---|---|---|---|---|---|
Given a set of points in the 2D Euclidean plane: P={V1,V2,..,Vn}, and we assume that there are K different types of points:T1,T2,..,TK, every point Vi in P belongs to exactly one of the K types.
Definition of KTSP tour:
Given an arbitrary location point V0 in the same 2D Euclidean plane (V0 has no type), a path V0->V'1->V'2->V'3->....->V'K->V0 is called a KTSP tour iff V'i belongs to type i.
A KTSP tour is just an ordinary tour starting and ending in the same given arbitrary point but subject to two more constraints:
(1)It passes every type of point one and only once.
(2)The type of point the path passes has order. That is, it first starts from point V0, then first passes type T1 point, then type T2 point, then type T3 point, and so on until it passes type TK point, after which it comes back at V0.
Here is my question:
when the point location V0 is given find the shortest KTSP tour.
For example, in the following figure, every color represents one type of point, there are 3 different types of points, we assume blue colored points are type 1, red type 2, black type 3,
and the little triangle with yellow is the given location V0, then the shortest TSKP tour corresponding to this particular V0 is shown with the four blue arrows.
It seems to me this a variant of the classical TSP problem, but i can't think of an algorithm, need help!
| 0
| 0
| 0
| 0
| 1
| 0
|
I would like to build an internal search engine (I have a very large collection of thousands of XML files) that is able to map queries to concepts. For example, if I search for "big cats", I would want highly ranked results to return documents with "large cats" as well. But I may also be interested in having it return "huge animals", albeit at a much lower relevancy score.
I'm currently reading through the Natural Language Processing in Python book, and it seems WordNet has some word mappings that might prove useful, though I'm not sure how to integrate that into a search engine. Could I use Lucene to do this? How?
From further research, it seems "latent semantic analysis" is relevant to what I'm looking for but I'm not sure how to implement it.
Any advice on how to get this done?
| 0
| 1
| 0
| 0
| 0
| 0
|
I am reading algorithms in C++ by Robert Sedwick it was mentioned as follows
Sequential search in an ordered table examines N numbers for each search in the worst case and about N/2 numbers for each search on average.
This result follows from assuming that the search is equally
likely to terminate at any one of the N+1 intervals defined by the N numbers in th table which leads immediately to the expression (1+2+3+4+...+N+N)/N = (N+3)/2.
Can anyone please help me in understand how we came to above expression i.e., how N+3 /2 is arrived?
| 0
| 0
| 0
| 0
| 1
| 0
|
Grammar by definition contains productions, example of very simple grammar:
E -> E + E
E -> n
I want to implement Grammar class in c#, but I'm not sure how to store productions, for example how to make difference between terminal and non-terminal symbol.
i was thinking about:
struct Production
{
String Left; // for example E
String Right; // for example +
}
Left will always be non-terminal symbol (it's about context-free grammars)
But right side of production can contain terminal & non-terminal symbols
So now I'm thinkig about 2 ways of implementation:
Non-terminal symbols will be written using brackets, for example:
E+E will be represented as string "[E]+[E]"
Create additional data structure NonTerminal
struct NonTerminal
{
String Symbol;
}
and E+E will be represented as array/list:
[new NonTerminal("E"), "+", new NonTerminal("E")]
but think that there are better ideas, it would be helpfull to hear some response
| 0
| 1
| 0
| 0
| 0
| 0
|
If I have a given rectangle, with the width w, height h and angle r
How large does another rectangle which contains all points of the rotated rectangle need to be?
I would need this to perform fast bounding box checks for a 2D physics engine I am making
| 0
| 0
| 0
| 0
| 1
| 0
|
Hii ,
I ran across a interview question of implementing a dictionary that can implement the features of auto-completion , auto - correction , spell check etc...
I actually wanted to know which data structure is the best for implementing a dictionary and how one approaches the above required features...
Any links that guide me on this are welcome...
| 0
| 1
| 0
| 0
| 0
| 0
|
I'm working on a location extraction algorithm but haven't achieved anything considerable yet. For example in this sentence
Riders on the B and Q lines will get some relief from construction as stations reopen, and a major project will soon begin at the Dyckman Street station.
"Dyckman Street" is location information. How we extract this information from a given sentence. (I tried to extract the words from a sentence starting with a Capital letter and search it against a db having city names, but it doesn't work always).
From where i can find an algorithm to extract this information?
Thanks..
| 0
| 1
| 0
| 0
| 0
| 0
|
If I have a function f that computes element m of a sequence of digits in base b, is it in general possible to write a function g that computes element n of the corresponding sequence in base c ?
As a contrived example, say f produces binary and g produces hexadecimal:
f(m) → 1, 0, 1, 0, 1, 0, 1, 0, ...
g(n) → A, A, ...
Now say f is in base 5 and g is in base 6. The bases don't share a common factor, which means that the number of digits required to represent a number from the source base in the target base is fractional (6⁄5). Is it possible to determine a single digit from g using only, say, the corresponding c⁄b digits from f ?
Note that starting the formula at the first element is the same as performing the standard conversion of a fractional number from b to c, but I want an arbitrary element of the target sequence, in the same way that I can retrieve an arbitrary element of the source.
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm a math teacher wanting to insert some dynamic math into a website. What I'd like to achieve is to have a button that a student can press to randomly vary a question so that it's the same type of question, but with different numbers. For example,
Factor the quadratic expression of the form ax^2 + bx + c, where a = 1, and b and c are positive integers between 1 and 100, and such that the roots would be real whole numbers.
If I'm using MathML to encode the math (e.g., like the markup below), stored in a database (e.g., MySQL), how could I set things up so that the computer automatically and randomly varies the math expression in the way I described above? I don't know much about server-side scripting... could I achieve this with PHP? Or would this be more a job of JavaScript on the client side? I'm just looking for some advice to guide my choice of study path.
Thank you
<math xmlns='http://www.w3.org/1998/Math/MathML'>
<mrow>
<msup>
<mi>x</mi>
<mn>2</mn>
</msup>
<mo>+</mo>
<mrow>
<mn>7</mn>
<mo>⁢</mo>
<mi>x</mi>
</mrow>
<mo>+</mo>
<mn>12</mn>
</mrow>
</math>
| 0
| 0
| 0
| 0
| 1
| 0
|
I found a sat solver in
http://code.google.com/p/aima-java/
I tried the following code to solve an expression using dpllsolver
the input is
(A <=> B) AND (C => D) AND (A AND C) AND (NOT (B AND D)) AND (NOT (B AND D AND E))
CNF transformer transforms it to
( ( ( NOT A ) OR B ) AND ( ( NOT B ) OR A ) )
it doesn't consider the other parts of the logic, it considers only first term, how to make it work correctly?
please suggest me if some other sat solver can do it
PEParser parser = new PEParser();
CNFTransformer transformer=new CNFTransformer();
Sentence and;
Sentence transformedAnd;
DPLL dpll = new DPLL();
Sentence sentence = (Sentence) parser.parse("(A <=> B) AND (C => D) AND (A AND C) AND (NOT (B AND D)) AND (NOT (B AND D AND E))");
transformedAnd = transformer.transform(sentence);
System.out.println(transformedAnd.toString());
boolean satisfiable = dpll.dpllSatisfiable(transformedAnd);
System.out.println(satisfiable);
| 0
| 1
| 0
| 0
| 0
| 0
|
I've been experimenting with this and I haven't been able to come up with an adequate solution. Hoping one of you Mathletes can point me in the right direction. I'm building a Snow Globe in ActionScript 3 and I need to come up with a set of equations to control two level of snowflakes - one level random, and the other interactive where a user can click on them.
For the random snow, I need to have it create certain number of random x/y positions at the bottom of the globe, which is a circle with a radius of around 300. Then when the shake action occurs, They should randomly float toward the top, then fall back to a random position at the bottom of the circle again.
For the interactive snow, I need it to randomly layout, but I don't want flakes to overlap so that its easier to interact with them.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am trying to add Laplacian smoothing support to Biopython's Naive Bayes code 1 for my Bioinformatics project.
I have read many documents about Naive Bayes algorithm and Laplacian smoothing and I think I got the basic idea but I just can't integrate this with that code (actually I cannot see which part I will add 1 -laplacian number).
I am not familiar with Python and I am a newbie coder. I appreciate if anyone familiar with Biopython can give me some suggestions.
| 0
| 0
| 0
| 1
| 0
| 0
|
I am a nurse and I know python but I am not an expert, just used it to process DNA sequences
We got hospital records written in human languages and I am supposed to insert these data into a database or csv file but they are more than 5000 lines and this can be so hard. All the data are written in a consistent format let me show you an example
11/11/2010 - 09:00am : He got nausea, vomiting and died 4 hours later
I should get the following data
Sex: Male
Symptoms: Nausea
Vomiting
Death: True
Death Time: 11/11/2010 - 01:00pm
Another example
11/11/2010 - 09:00am : She got heart burn, vomiting of blood and died 1 hours later in the operation room
And I get
Sex: Female
Symptoms: Heart burn
Vomiting of blood
Death: True
Death Time: 11/11/2010 - 10:00am
the order is not consistent by when I say in ....... so in is a keyword and all the text after is a place until i find another keyword
At the beginnning He or She determine sex, got ........ whatever follows is a group of symptoms that i should split according to the separator which can be a comma, hypen or whatever but it's consistent for the same line
died ..... hours later also should get how many hours, sometimes the patient is stil alive and discharged ....etc
That's to say we have a lot of conventions and I think if i can tokenize the text with keywords and patterns i can get the job done. So please if you know a useful function/modules/tutorial/tool for doing that preferably in python (if not python so a gui tool would be nice)
Some few information:
there are a lot of rules to express various medical data but here are few examples
- Start with the same date/time format followed by a space followd by a colon followed by a space followed by He/She followed space followed by rules separated by and
- Rules:
* got <symptoms>,<symptoms>,....
* investigations were done <investigation>,<investigation>,<investigation>,......
* received <drug or procedure>,<drug or procedure>,.....
* discharged <digit> (hour|hours) later
* kept under observation
* died <digit> (hour|hours) later
* died <digit> (hour|hours) later in <place>
other rules do exist but they follow the same idea
| 0
| 1
| 0
| 1
| 0
| 0
|
A helicopter drops two trains, each on a parachute, onto a straight infinite railway line.
There is an undefined distance between the two trains.
Each faces the same direction, and upon landing, the parachute attached to each train falls to the ground next to the train and detaches.
Each train has a microchip that controls its motion. The chips are identical.
There is no way for the trains to know where they are.
You need to write the code in the chip to make the trains bump into each other.
Each line of code takes a single clock cycle to execute.
You can use the following commands (and only these):
MF - moves the train forward
MB - moves the train backward
IF (P) - conditional that is satisfied if the train is next to a parachute. There is no "then" to this IF statement.
GOTO
| 0
| 0
| 0
| 0
| 1
| 0
|
I would like to write a function that has a loop in it which preforms the operations necessary for Euler's method. Below it my poor attempt.
In[15]:= Euler[icx_,icy_,h_,b_,diffeq_] :=
curx;
cury;
n=0;
curx = icx;
cury = icy;
While
[curx != b,
Print["" + n + " | " + curx + cury];
n++;
dq = StringReplace[diffeq, "y[x]" -> curx];
dq = StringReplace[dq, "x" -> cury];
curx+=h;
cury=cury+h*dq;
]
In[21]:= Euler[0, 0, .1, 1, e^-y[x]]
Out[21]= icx
| 0
| 0
| 0
| 0
| 1
| 0
|
I am facing a problem on selecting correct classifier for my data-mining task.
I am labeling webpages using statistical method and label them using a 1-4 scale,1 being the poorest while 4 being the best.
Previously,I used SVM to train the system since I was using a binary(1,0) label then.But now since I switch to this 4-class label,I need to change classifier,because I think the SVM classifier will only work for two-class classification(Please correct me if I am wrong).
So could you please offer some suggestion here on what kind of classifier is most approriate here for my classification purpose.
Thanks in advance for suggestions.
| 0
| 1
| 0
| 1
| 0
| 0
|
I'm having a mental block here, and algebra not really being my thing, can you tell me how to re-write the JavaScript code below to derive the variable, c, in terms of a and b?:
a = Math.pow(b, c);
c = ?
Thanks!
| 0
| 0
| 0
| 0
| 1
| 0
|
All,
How can I calculate 2^301 mod 77? I did check out the link StackOverflow. But did not understand the step wherein 625 mod 221 = 183 mod 221. How did the conversion take place?
| 0
| 0
| 0
| 0
| 1
| 0
|
I am using .NET 2.0 with PlatformTarget x64 and x86. I am giving Math.Exp the same input number, and it returns different results in either platform.
MSDN says you can't rely on a literal/parsed Double to represent the same number between platforms, but I think my use of Int64BitsToDouble below avoids this problem and guarantees the same input to Math.Exp on both platforms.
My question is why are the results different? I would have thought that:
the input is stored in the same way (double/64-bit precision)
the FPU would do the same calculations regardless of processor's bitness
the output is stored in the same way
I know I should not compare floating-point numbers after the 15/17th digit in general, but I am confused about the inconsistency here with what looks like the same operation on the same hardware.
Any one know what's going on under the hood?
double d = BitConverter.Int64BitsToDouble(-4648784593573222648L); // same as Double.Parse("-0.0068846153846153849") but with no concern about losing digits in conversion
Debug.Assert(d.ToString("G17") == "-0.0068846153846153849"
&& BitConverter.DoubleToInt64Bits(d) == -4648784593573222648L); // true on both 32 & 64 bit
double exp = Math.Exp(d);
Console.WriteLine("{0:G17} = {1}", exp, BitConverter.DoubleToInt64Bits(exp));
// 64-bit: 0.99313902928727449 = 4607120620669726947
// 32-bit: 0.9931390292872746 = 4607120620669726948
The results are consistent on both platforms with JIT turned on or off.
[Edit]
I'm not completely satisfied with the answers below so here are some more details from my searching.
http://www.manicai.net/comp/debugging/fpudiff/ says that:
So 32-bit is using the 80-bit FPU registers, 64-bit is using the 128-bit SSE registers.
And the CLI Standard says that doubles can be represented with higher precision if the hardware supports it:
[Rationale: This design allows the CLI to choose a platform-specific high-performance representation for
floating-point numbers until they are placed in storage locations. For example, it might be able to leave
floating-point variables in hardware registers that provide more precision than a user has requested. At the
Partition I 69
same time, CIL generators can force operations to respect language-specific rules for representations through
the use of conversion instructions. end rationale]
http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-335.pdf (12.1.3 Handling of floating-point data types)
I think this is what is happening here, because the results different after Double's standard 15 digits of precision. The 64-bit Math.Exp result is more precise (it has an extra digit) because internally 64-bit .NET is using an FPU register with more precision than the FPU register used by 32-bit .NET.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am working on a Fountain Code based file transfer system. In this system blocks of data are downloaded, combined with an xor function. I want to verify the blocks as they arrive.
What I need is a cryptographically secure hash function which has the property:
Hash(A) ^ Hash(B) == Hash(A ^ B)
does such a thing exist?
Note: The data blocks must be combined with an xor function, the hashes can be combined with any function you like, so long as it's reasonably cheap to compute.
| 0
| 0
| 0
| 0
| 1
| 0
|
I know this is a simple math problem but for some reason im drawing a blank.
If I have two ints which are boundaries for a range:
int q = 100;
int w = 230;
and then another in that is a number that I want to see if it is inside of the range:
int e = ?;
How can I find if e is in the bounds of q and w?
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a draggeable image contained within a box. You can zoom in and zoom out on the image in the box which will make the image larger or smaller but the box size remains the same. The box's height and width will vary as the browser is resized. The top and left values for the image will change as it is dragged around.
I'm trying to keep whatever the point the box was centered on in the image, in the center. Kind of like how zoom on Google Maps works or the zoom on Mac OS X zooms.
What I'm doing right now is calculating the center of the box (x = w/2, y = h/2) and then using the top and left values for the image to calculate the position of the image in the center of the box. (x -= left, y -= top).
Then I zoom the image by growing or shrinking it and I use the scale change to adjust the coordinates (x = (x * (old_width/new_width), y = (y * (old_height/new_height)).
I then reposition the image so that its center is what it was before zoom by grabbing the coordinates it is currently centered on (that changed with the resize) and adding the difference between the old center values and the new values to the top and left values (new_left = post_zoom_left + (old_center_x - new_center_x), new_top = post_zoom_top + (old_center_y - new_center_y).
This works ok for zoom in, but zoom out seems to be somewhat off.
Any suggestions?
My code is below:
app.Puzzle_Viewer.prototype.set_view_dimensions = function () {
var width, height, new_width, new_height, coordinates, x_scale,
y_scale;
coordinates = this.get_center_position();
width = +this.container.width();
height = +this.container.height();
//code to figure out new width and height
//snip ...
x_scale = width/new_width;
y_scale = height/new_height;
coordinates.x = Math.round(coordinates.x * x_scale);
coordinates.y = Math.round(coordinates.y * y_scale);
//resize image to new_width & new_height
this.center_on_position(coordinates);
};
app.Puzzle_Viewer.prototype.get_center_position = function () {
var top, left, bottom, right, x, y, container;
right = +this.node.width();
bottom = +this.node.height();
x = Math.round(right/2);
y = Math.round(bottom/2);
container = this.container.get(0);
left = container.style.left;
top = container.style.top;
left = left ? parseInt(left, 10) : 0;
top = top ? parseInt(top, 10) : 0;
x -= left;
y -= top;
return {x: x, y: y, left: left, top: top};
};
app.Puzzle_Viewer.prototype.center_on_position = function (coordinates) {
var current_center, x, y, container;
current_center = this.get_center_position();
x = current_center.left + coordinates.x - current_center.x;
y = current_center.top + coordinates.y - current_center.y;
container = this.container.get(0);
container.style.left = x + "px";
container.style.top = y + "px";
};
| 0
| 0
| 0
| 0
| 1
| 0
|
When dealing with Dirichlet Processes, according to [Teh, 2007], a DP is defined as by a base Probability H and a scale factor "alpha"
According to the Stick Breaking Construction, the random draws G from a DP:
G~DP(alpha,H)
are given by:
G=sum(pi_k*delta_theta_k) over k from 1 to infinity
pi_k are ordered draws from a Beta Distribution given the length of an unitary stick
delta_theta_k is a point mass centered in "theta_k" (theta_k are random draws from the base distribution)
I have pretty much a clear understanding of all the variables, but I do not know what do they mean by "mass point" is it the probability density of that draw, or is it something else.
It would be great if you could point me in any direction, only a reference would be amazing.
Thanks
| 0
| 0
| 0
| 1
| 0
| 0
|
What is the correct sequence of the math operations in this expression in Java:
a + b * c / ( d - e )
1. 4 1 3 2
2. 4 2 3 1
I understand that result is the same in both answers. But I would like to fully understand the java compiler logic. What is executed first in this example - multiplication or the expression in parentheses? A link to the documentation that covers that would be helpful.
UPDATE: Thank you guys for the answers. Most of you write that the expression in parentheses is evaluated first. After looking at the references provided by Grodriguez I created little tests:
int i = 2;
System.out.println(i * (i=3)); // prints '6'
int j = 2;
System.out.println((j=3) * j); // prints '9'
Could anybody explain why these tests produce different results? If the expression in parentheses is evaluated the first I would expect the same result - 9.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am trying to implement either the Fermat, Miller-Rabin, or AKS algorithm in Java using the BigInteger class.
I think I have the Fermat test implemented except that the BigInteger class doesn't allow taking BigIntegers to the power of BigIntegers (one can only take BigIntegers to the power of primitive ints). Is there a way around this?
The problematic line is denoted in my code:
public static boolean fermatPrimalityTest(BigInteger n)
{
BigInteger a;
Random rand = new Random();
int maxIterations = 100000;
for (int i = 0; i < maxIterations; i++) {
a = new BigInteger(2048, rand);
// PROBLEM WITH a.pow(n) BECAUSE n IS NOT A BigInteger
boolean test = ((a.pow(n)).minus(BigInteger.ONE)).equals((BigInteger.ONE).mod(n));
if (!test)
return false;
}
return true;
}
| 0
| 0
| 0
| 0
| 1
| 0
|
I am searching for a extensional definition for the following set:
E := { m | m subset {a,b,c,d} and |m| = 2}
My idea is
E := {{a,b}, {a,c}, {a,d}, {b,c}, {b,d}, {c,d}, {a,a}, {b,b}, {c,c}, {d,d}}
any ideas?
| 0
| 0
| 0
| 0
| 1
| 0
|
Who wants to help me with my homework?
I'm try to implement Fermat's primality test in Java using BigIntegers. My implementation is as follows, but unfortunately it doesn't work. Any ideas?
public static boolean checkPrime(BigInteger n, int maxIterations)
{
if (n.equals(BigInteger.ONE))
return false;
BigInteger a;
Random rand = new Random();
for (int i = 0; i < maxIterations; i++)
{
a = new BigInteger(n.bitLength() - 1, rand);
a = a.modPow(n.subtract(BigInteger.ONE), n);
if (!a.equals(BigInteger.ONE))
return false;
}
return true;
}
I'm new to BigIntegers.
Thanks!
| 0
| 0
| 0
| 0
| 1
| 0
|
Given that:
The shape is a regular polygon in 3D space
The start point (the end of one arbitrary vertex of the shape) is known
the point in the middle of the shape (not on an edge - equidistant from all corners) is known
the angle at each corner (((numEdges-2)*PI)/numEdges), the radius of the shape (distance from a corner to the midpoint = sqrt(dx^2 + dy^2 + dz^2)), and the length of each edge (radius*2*sin(pi/numEdges)) can be calculated.
Given all this information, is it possible to fill in the blanks, if you like, and work out the rest of the start/endpoints for each vertex of the shape?
I can sort of see the beginnings of the logic in 2D, but in 3D i'm lost.
| 0
| 0
| 0
| 0
| 1
| 0
|
Feeling pretty brain-dead right now. I can, of course, brute-force this, but I feel like there has to be a simple function to return this number. Concerning native functions, I'm using PHP and/or Python.
For example: there exists containers that hold X (5) breadsticks each, and
I need to feed Y (25) people Z (3) breadsticks each.
I need to return the number of containers I have to acquire to feed these people. (There may or may not be remainder breadsticks).
EDIT: Clarified some intention.
| 0
| 0
| 0
| 0
| 1
| 0
|
I have a list of cities, each of them obviously has a longitude and latitude.
Now selecting one of these cities, i want to obtain all the other cities that have a longitude / latitude in a range of 50 km from the selected city.
What formula should I use?
I am only interested in the mathematical formula to convert km to latidutine and longitude from a know city position
Then i will calculate the maximum and minimum latitude and longitude, for considering an acceptable range. (like a Square)
tks
I don't want to calculate the distance between two points!+
I want to calculate min e max latitude and longitude and then filter my cities by this coordinates.
I've found a sample in Php that worked for me.
(i've ported it to C#)
http://blog.fedecarg.com/2009/02/08/geo-proximity-search-the-haversine-equation/
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm trying to write some code that will allow me to perform basic math operations on a "T extends Number" object instance. It needs to be able to handle any number type that is a subclass of Number.
I know some of the types under Number have .add() methods built in, and some even have .multiply() methods. I need to be able to multiply two generic variables of any possible type. I've searched and searched and haven't been able to come up with a clear answer of any kind.
public class Circle<T extends Number> {
private T center;
private T radius;
private T area;
// constructor and other various mutator methods here....
/**
The getArea method returns a Circle
object's area.
@return The product of Pi time Radius squared.
*/
public Number getArea() {
return 3.14 * (circle.getRadius()) * (circle.getRadius());
}
Any help would be much appreciated. Generics are the most difficult thing I've encountered in learning Java. I don't mind doing the leg work because I learn better that way, so even a strong point in the right direction would be very helpful.
| 0
| 0
| 0
| 0
| 1
| 0
|
How do I express this in javascript?
9H squared plus
3H
all over 2
times L
I'm working on something like:
function calculator (height, len) {
var H = height, L = len;
total = (((9 * H)*(9 * H)) + 3*H)/2)*L;
return total;
}
calculator(15, 7);
I don't care if it's terse or not, but I'm not sure the best way to handle math in javascript.
thank you.
| 0
| 0
| 0
| 0
| 1
| 0
|
Given array [a, b, c, d, e, f]
I want to match each letter with any other letter except itself, resulting in something like:
a - c
b - f
d - e
The catch is that each letter may be restricted to being matched with one or more of the other letters.
So let's say for example,
a cannot be matched with c, d
c cannot be matched with e, f
e cannot be matched with a
Any guidance on how to go about this? I'm using Ruby, but any pseudo code would be helpful.
Thanks!
| 0
| 0
| 0
| 0
| 1
| 0
|
How can I detect whether a line (direction d and -d from point p) and a line segment (between points p1 and p2) intersects in 2D? If they do, how can I get their intersection point.
There are lots of example how to detect whether two line segments intersects but this should be even simpler case.
I found this but I do not understand what is a side-operator:
http://www.loria.fr/~lazard//ARC-Visi3D/Pant-project/files/Line_Segment_Line.html
| 0
| 0
| 0
| 0
| 1
| 0
|
I want to extract relevant words from a text statement provided by the user.
eg. For a question "How many sides are there in a rectangle?"
The words should be 'rectangles' , 'sides', 'many' , 'how'.
We've discovered that what exactly I'm aiming to do is a NLP Question answer system.
But right now I want to only extract the required keywords from the question,
The domain of the questions is not very vast.
I've come across various data mining tools but not very sure if they actually will be useful for this. They seem to be a bit too advanced or not exactly related.
Please let me know if there is any tool that suits the requirement or should I go on and try coding myself.
Please provide any kind of pointers, that you think might help.
| 0
| 1
| 0
| 0
| 0
| 0
|
I need to calculate the 2 angles (yaw and pitch) for a 3D object to face an arbitrary 3D point. These rotations are known as "Euler" rotations simply because after the first rotation, (lets say Z, based on the picture below) the Y axis also rotates with the object.
This is the code I'm using but its not working fully. When on the ground plane (Y = 0) the object correctly rotates to face the point, but as soon as I move the point upwards in Y, the rotations don't look correct.
// x, y, z represent a fractional value between -[1] and [1]
// a "unit vector" of the point I need to rotate towards
yaw = Math.atan2( y, x )
pitch = Math.atan2( z, Math.sqrt( x * x + y * y ) )
Do you know how to calculate the 2 Euler angles given a point?
The picture below shows the way I rotate. These are the angles I need to calculate.
(The only difference is I'm rotating the object in the order X,Y,Z and not Z,Y,X)
This is my system.
coordinate system is x = to the right, y = downwards, z = further back
an object is by default at (0,0,1) which is facing backward
rotations are in the order X, Y, Z where rotation upon X is pitch, Y is yaw and Z is roll
| 0
| 0
| 0
| 0
| 1
| 0
|
Setting the 32nd and 64th bits is tricky.
32-bit Solution:
I got it to work for 32-bit fields. The trick is to cast the return value of the POWER function to binary(4) before casting it to int. If you try to cast directly to int, without first casting to binary(4), you will get an arithmetic overflow exception when operating on the 32nd bit (index 31). Also, you must ensure the expression passed to POWER is of a sufficiently large type (e.g. bigint) to store the maximum return value (2^31), or the POWER function will throw an arithmetic overflow exception.
CREATE FUNCTION [dbo].[SetIntBit]
(
@bitfieldvalue int,
@bitindex int, --(0 to 31)
@bit bit --(0 or 1)
)
RETURNS int
AS
BEGIN
DECLARE @bitmask int = CAST(CAST(POWER(CAST(2 as bigint),@bitindex) as binary(4)) as int);
RETURN
CASE
WHEN @bit = 1 THEN (@bitfieldvalue | @bitmask)
WHEN @bit = 0 THEN (@bitfieldvalue & ~@bitmask)
ELSE @bitfieldvalue --NO CHANGE
END
END
64-bit Problem:
I was going to use a similar approach for 64-bit fields, however I'm finding that the POWER function is returning inaccurate values, despite using the decimal(38) type for the expression/return value.
For example: "select POWER(CAST(2 as decimal(38)), 64)" returns 18446744073709552000 (only the first 16 digits are accurate) rather than the correct value of 18446744073709551616. And even though I'd only raise 2 to the 63rd power, that result is still inaccurate.
The documentation of the POWER function indicates that "Internal conversion to float can cause loss of precision if either the money or numeric data types are used." (note that numeric type is functionally equivalent to decimal type).
I think the only way to handle 64-bit fields properly is to operate on their 32-bit halves, but that involves an extra check on the @bitindex property to see which half I need to operate on. Are there any built-in function or better ways to explicitly set those final bits in 32-bit and 64-bit bitmasked fields in TSQL?
| 0
| 0
| 0
| 0
| 1
| 0
|
Given two arrays of doubles, how Can I compute the F Test?
(F test is defined here: http://www.excelfunctions.net/Excel-Ftest-Function.html)
I am looking for answer like this one:
How can I efficiently calculate the binomial cumulative distribution function?
| 0
| 0
| 0
| 0
| 1
| 0
|
This post is really helpful:
How can I efficiently calculate the binomial cumulative distribution function?
(Title = How can I efficiently calculate the binomial cumulative distribution function?)
However, I need the negative binomial cumulative distribution function.
Is there a way to tweek the code to get a negative cumulative distribution function?
| 0
| 0
| 0
| 0
| 1
| 0
|
Is there any way to optimize the following line of C code (to avoid branching)?
if (i < -threshold || i > threshold) {
counter++;
}
All variables are 16-bit signed integers. An optimized version should be highly portable.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am attempting to train a neural network for a system that can be thought of as a macro-level postal network. My inputs are two locations (one of the 50 US states) along with 1 to 3 other variables, and I want a numeric result out.
My first inclination was to represent the states as a numeric value from 0-49 and then then have a network with only 3 or so inputs. What I've found, however, is that my training never converges on a useful value. I am assuming that this is because the values for the states are wholly arbitrary - a value of 39 for MA has no relation to a value of 38 for CA, especially when 37 represents a jump back to CT.
Is there a better way for me to do this? Should I be creating a network with over 100 inputs, representing boolean values for origin and destination states?
| 0
| 1
| 0
| 0
| 0
| 0
|
I need help with a homework assignment for my beginner computer science class. I am completely lost!
I need to write a program in Perl that will calculate the distance between 2 points with three values (x,y,z) by the given formula by my professor. the program must do the following:
prompt for 'c' to continue 'q' to quit
prompt for the x, y, z coordinate indivually of the first set
prompt for the x, y, z coordinate indivually of the second set
compute the distance between the distance between the two sets
and then display the value and quit.
This is what I've done so far:
Psuedo code outline the above
IF THEN process outline for the c to continue and q to quit part
Found a sqrt equation for computing the distance
Rather than getting code, I'm really looking for tips on where to start here. Do I start by defining my variables? Any tips or direction on a first outline would be really appreciated! ;)
| 0
| 0
| 0
| 0
| 1
| 0
|
Reviewing for midterm, need some help with the following:
Given the points p0 = [1 0] and p1 = [4 6] write the implicit equation for a line in vector form (i.e. compute the appropriate v and n). Is the point p2 = [1.5 3] on the line or above or below the line?
What is the equation for a plane with the norman n = [5 3 4] going through the origin?
What is the equation for the planes with the same normal but which include the point p1 = [4 6 7]?
Can someone walk me through these problems. Any help is appreciated, thank you.
| 0
| 0
| 0
| 0
| 1
| 0
|
I got stuck with the following Python code
>>> a = 0xff
>>> b = 1 << 8
>>> ~a & ~b
-512
Why is it -512? In binary notation it should look like this:
a 0 1111 1111 -> 255
b 01 0000 0000 -> 256
~a 1 0000 0000 -> -256
~b 10 1111 1111 -> -257
~a&~b 00 0000 0000 -> 0
I expected 0 as with signed int in C:
signed int a = 0xff;
signed int b = 1 << 8;
signed int k = ~a & ~b;
Any help?
| 0
| 0
| 0
| 0
| 1
| 0
|
I am having the numbers follows taken as strings
My actual number is 1234567890123456789
from this i have to separate it as s=12 s1=6789 s3=3456789012345
remaining as i said
I would like to add as follows
11+3, 2+4, 6+5, 7+6, 8+7, 9+8 such that the output should be as follows
4613579012345
Any help please
| 0
| 0
| 0
| 0
| 1
| 0
|
I have the following setting:
I know P1, P2 and the angle alpha, now how do i calculate the coordinates of P3? (Note: P3 is on the same circle with origin P1 and radius P1P2)
The blue lines indicate the coordinate system
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm writing my own 3D engine and I have this matrix to make a perspective look. (It's a standard matrix so there is nothing interesting)
public static Matrix3D PrespectiveFromHV(double fieldOfViewY, double aspectRatio, double zNearPlane, double zFarPlane, double mod)
{
double height = 1.0 / Math.Tan(fieldOfViewY / 2.0);
double width = height / aspectRatio;
double d = zNearPlane - zFarPlane;
var rm = Math.Round(mod, 1);
var m = new Matrix3D(
width, 0, 0, 0,
0, height, 0, 0,
0, 0, (zFarPlane / d) * rm, (zNearPlane * zFarPlane / d) * rm,
0, 0, (-1 * rm), (1 - rm)
);
return m;
}
I could make my scene look 2D like just by ignoring that matrix.
But want to do is to make smooth transition from 3D to 2D and back...
Any one have any idea? What do I have to change in this matrix to make smooth transitions possible?
| 0
| 0
| 0
| 0
| 1
| 0
|
I need to do a project on Computational Linguistics course. Is there any interesting "linguistic" problem which is data intensive enough to work on using Hadoop map reduce. Solution or algorithm should try and analyse and provide some insight in "lingustic" domain. however it should be applicable to large datasets so that i can use hadoop for it. I know there is a python natural language processing toolkit for hadoop.
| 0
| 1
| 0
| 0
| 0
| 0
|
basically i have a page on my site with boxes that slide to reveal a background color. I want this background color to be random on load of page by adding a class to the element, eg .blue, .green etc...
I have created this code and as you may notice this randomly sorts the color class and applies to the element, this works for the first 6 elements however this page in particular has 12 elements i wish this to apply to, so my question is how do i apply a random selection of the variable classes to all ".portfolio ul li a "? Would it need to have some form of a repeat?
This is my script ..
function randCol() {
return (Math.round(Math.random())*7); }
$(document).ready(function() {
var classes = [ 'blue', 'orange', 'green', 'pink', 'black', 'white'];
classes.sort( randCol );
$('.portfolio ul li a').each(function(i, val) {
$(this).addClass(classes[i]);
});
})
This is my source code structure
<div class="portfolio">
<ul>
<li>
<a href="#">
<img src="images/content/portfolio/sample1.png" height="175" width="294" alt="sample" class="front" />
Text for behind the image
</a>
</li>
| 0
| 0
| 0
| 0
| 1
| 0
|
just a really random question but is the property Math.PI in javascript always 3.141592653589793 in every browser/engine?
| 0
| 0
| 0
| 0
| 1
| 0
|
How would you find the correct words in a long stream of characters?
Input :
"The revised report onthesyntactictheoriesofsequentialcontrolandstate"
Google's Output:
"The revised report on syntactic theories sequential controlandstate"
(which is close enough considering the time that they produced the output)
How do you think Google does it?
How would you increase the accuracy?
| 0
| 1
| 0
| 0
| 0
| 0
|
This is a super naive question (I know), but I think that it will make for a good jumping off point into considering how the basic instruction set of a CPU actually gets carried out:
In a two's complement system, you cannot invert the sign of the most negative number that your implementation can represent. The theoretical reason for this is obvious in that the negation of the most negative number would be out of the range of the implementation (the range is always something like
-128 to 127).
However, what actually happens when you try to carry out the negation operation on the most negative number is pretty strange. For example, in an 8 bit representation, the most negative number is -128, or 1000 0000 in binary. Normally, to negate a number you would flip all the bits and then add one. However, if you try to do this with -128 you end up with:
1000 0000 ->
0111 1111 ->
1000 0000
the same number that you started out with. For this reason, wikipedia calls it "the weird number".
In that same wikipedia article, it says that the above negation
is detected as an overflow condition since there was a carry into but not out of the most-significant bit.
So my question is this:
A) What the heck does that mean? and
B) It seems like the CPU would need to perform an extra error checking step each and every time it carried out a basic arithmetic operation in order to avoid accidents relating to this negation, creating significant overhead. If that is the case, why not just truncate the range of numbers that can be represented to leave the weird number out (i.e. -127 to 127 for 8 bits)? If that isn't the case, how can you implement such error checking without creating extra overhead?
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm wondering whether major SQL engines out there (MS SQL, Oracle, MySQL) have the ability to understand that 2 words are related because they share the same root.
We know it's easy to match "networking" when searching for "network" because the latter is a substring of the former.
But do SQL engines have functions that can match "network" when searching for "networking"?
Thanks a lot.
| 0
| 1
| 0
| 0
| 0
| 0
|
I'm programming a 3D game where the user controls a first-person camera, and movement is constrained to the inside surface of a sphere. I've managed to constrain the movement, but I'm having trouble figuring out how to manage the camera orientation using quaternions. Ideally the camera up vector should point along the normal of the sphere towards its center, and user should be able to free look around - as if we was always on the bottom of the sphere, no matter where he moves.
| 0
| 0
| 0
| 0
| 1
| 0
|
I have to write, for academic purposes, an application that plots user-input expressions like: f(x) = 1 - exp(3^(5*ln(cosx)) + x)
The approach I've chosen to write the parser is to convert the expression in RPN with the Shunting-Yard algorithm, treating primitive functions like "cos" as unary operators. This means the function written above would be converted in a series of tokens like:
1, x, cos, ln, 5, *,3, ^, exp, -
The problem is that to plot the function I have to evaluate it LOTS of times, so applying the stack evaluation algorithm for each input value would be very inefficient.
How can I solve this? Do I have to forget the RPN idea?
| 0
| 0
| 0
| 0
| 1
| 0
|
I want to experiment with guiding an RC car via my laptop using bluetooth and an X10 camera to snap the pictures. Basically I want to create the DARPA not so grand challenge of guiding my RC car around the house and avoiding obstacles and teaching it how to navigate. Not terribly practical but fun to mess with. Any suggestions on books, tutorials or alternatives to optical flow that accomplish the goal of allowing the RC car to perceive motion relative to its optics. Thanks in advance!
| 0
| 1
| 0
| 0
| 0
| 0
|
this is a Math problem for a 2d game.
Given 2 object ( 2 car, 2 tank, 2...), for each object i know:
1. X, Y
2. Actual Speed
3. Degree of movement (or radiant)
How to calculate the "effect" of a collision for the 2 object
Ps:
I "move" the object with this simple formula each tick of my "game loop":
ychange = Math.Sin(radiant) * ((carspeed / xVar));
xchange = Math.Cos(radiant) * ((carspeed / xVar));
(where xVar is a "multiplicator" to make more slow my car on the screen)
And for the "first" object which collide, if i add a "minus" (-) in front of that formula, i can simulate a good "bounce" of the first object.. but not for the second.
So my question regard a way to calculate a good (not perfect ! ) and more realistic "impact effect" for the second object.
Thanks for your help
| 0
| 0
| 0
| 0
| 1
| 0
|
I want to write a ruby wrapper swi-prolog. Can anyone please tell me how to proceed with writing one?
I would appreciate if anyone please explain me what steps need to be considered while attempting to write this sort.
| 0
| 1
| 0
| 0
| 0
| 0
|
OK, so I'm performing an annoying math computation here, trying to solve for one of the cubic roots.
Now, here is my C# code:
public void CubeCalculate()
{
//Calculate discriminant
double insideSquareRoot = (18 * cubicAValue * cubicBValue * cubicCValue * cubicDValue) + (-4 * (Math.Pow(cubicBValue, 3) * cubicDValue) + (Math.Pow(cubicBValue, 2) * Math.Pow(cubicCValue, 2)) + (-4 * cubicAValue * Math.Pow(cubicCValue, 3)) + (-27 * Math.Pow(cubicAValue, 2) * Math.Pow(cubicDValue, 2)));
if (insideSquareRoot < 0)
{
//One real solution, two imaginary
double onecuberootradical1 = (1 / 2) * (((2 * Math.Pow(cubicBValue, 3)) + (-9 * cubicAValue * cubicBValue * cubicCValue) + (27 * Math.Pow(cubicAValue, 2) * cubicDValue)) + (Math.Sqrt(Math.Pow((2 * Math.Pow(cubicBValue, 3)) + (-9 * cubicAValue * cubicBValue * cubicCValue) + (27 * Math.Pow(cubicAValue, 2) * cubicDValue), 2) + (-4 * Math.Pow(Math.Pow(cubicBValue, 2) + (-3 * cubicAValue * cubicCValue), 3)))));
double onecuberootradical2 = (1 / 2) * (((2 * Math.Pow(cubicBValue, 3)) + (-9 * cubicAValue * cubicBValue * cubicCValue) + (27 * Math.Pow(cubicAValue, 2) * cubicDValue)) - (Math.Sqrt(Math.Pow((2 * Math.Pow(cubicBValue, 3)) + (-9 * cubicAValue * cubicBValue * cubicCValue) + (27 * Math.Pow(cubicAValue, 2) * cubicDValue), 2) + (-4 * Math.Pow(Math.Pow(cubicBValue, 2) + (-3 * cubicAValue * cubicCValue), 3)))));
x1 = (-cubicBValue / (3 * cubicAValue)) + ((-1 / (3 * cubicAValue)) * (Math.Pow(onecuberootradical1, 1 / 3))) + (-1 / (3 * cubicAValue) * Math.Pow(onecuberootradical2, 1 / 3));
x2 = double.NaN;
x3 = double.NaN;
}
OK, I'm trying to figure out what's going wrong here.
First of all, since this is part of an MVC application, I have made sure my other roots are working properly, so this is purely the fault of the following computation, not a problem from anywhere else.
Now, I've checked many times here and I have not found anything wrong.
You can compare to the proper formula here:
It is the x1 root that I'm trying to replicate here.
Also, if you would like to know the official discriminant form the same Wikiepdia article here it is:
Do you guys see anything wrong???
| 0
| 0
| 0
| 0
| 1
| 0
|
Is there a font that can be used for math notation? I'm thinking there isn't. If that is the case, does anyone know what the simplest route is to having nice math notation in my iPad app?
Update: Thank you for all the great responses. Looking at the current replies, would people generally recommend that if what I want to do is essentially create a feature that allows people to enter math equations intuitively then I should probably start with MathML as something I would work towards? What I mean is should I take a strategy of creating a UI that enables the user to write his/her math notation such that said notation they input gets converted into MathML (versus simply using a unicode math font which wouldn't already contain some semblance of the typesetting functionality?
| 0
| 0
| 0
| 0
| 1
| 0
|
I am trying to learn Verlet integration, mainly because I'm bored, and want to spice up my normal "bouncing ball" learning exercise.
I have a simple bouncing ball Canvas/HTML5 page at http://sandbox.electricgrey.com:8080/physics/. If you click on it you'll notice that the ball doesn't always bounce back to the same height. Sometimes it is higher, sometimes it is lower. Why is it doing that?
Is it because I am simplifying it too much? Do I really need to calculate partial time steps so I get exactly when/where the ball collides and then continue from there?
PS: If you have any comments about my HTML or Javascript, I would love to hear them. I'm just learning how to code with Javascript, and I want to make sure I am doing it The Right Way™.
| 0
| 0
| 0
| 0
| 1
| 0
|
hope it's allowed to "crosspost" between stackexchange site...
Does anyone know how to solve the following "math" problem ?
https://gamedev.stackexchange.com/questions/5041/correct-blitting-2-surface-problem
Thanks in advance
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm simulating a physical object, using a mass spring system. By means of deltas and cross products, I can easily calulate the up, forward and side vectors.
I want to calculate what the angular rate (how fast it's spinning), for the object space X, Y and Z axis. Calculating the world space angle first won't help, since I need the angular rate in object space (how a sensor glued to the object would see it).
Any 3D maths people out there know how to do this?
| 0
| 0
| 0
| 0
| 1
| 0
|
In a game such as Warcraft 3 or Age of Empires, the ways that an AI opponent can move about the map seem almost limitless. The maps are huge and the position of other players is constantly changing.
How does the AI path-finding in games like these work? Standard graph-search methods (such as DFS, BFS or A*) seem impossible in such a setup.
| 0
| 1
| 0
| 0
| 0
| 0
|
I'm doing an Information Retrieval Task. As part of pre-processing I want to doing.
Stopword removal
Tokenization
Stemming (Porter Stemmer)
Initially, I skipped tokenization. As a result I got terms like this:
broker
broker'
broker,
broker.
broker/deal
broker/dealer'
broker/dealer,
broker/dealer.
broker/dealer;
broker/dealers),
broker/dealers,
broker/dealers.
brokerag
brokerage,
broker-deal
broker-dealer,
broker-dealers,
broker-dealers.
brokered.
brokers,
brokers.
So, Now I realized importance of tokenization. Is there any standard algorithm for tokenization for English language? Based on string.whitespace and commonly used puncuation marks. I wrote
def Tokenize(text):
words = text.split(['.',',', '?', '!', ':', ';', '-','_', '(', ')', '[', ']', ''', '`', '"', '/',' ','\t','
','\x0b','\x0c','\r'])
return [word.strip() for word in words if word.strip() != '']
I'm getting TypeError: coercing to Unicode: need string or buffer, list found error!
How can this Tokenization routine be improved?
| 0
| 1
| 0
| 0
| 0
| 0
|
I have some code doing this right now. It works fine with small to medium sized lists, but when I have a list of size n > 5000 then the my algorithm can take almost 1 minute on a mobile device to run. I'm basically comparing a Coordinate object in Java to a list (Vector) of Coordinate objects.
Here's my basic algorithm:
traverse each element in the list nx
if there is less 10 items in the "10 closest" list then add nx to the list
and go to the next element
if the "10 closest" list has 10 items already, then calculate the
distance between nx and the base
Coordinates
if the distance is less than furthest distance in the "10 closest
list" then remove the furthest item
from that list and replace it with nx
I keep looking at this and am trying to find a more efficient way of doing this. It's sort of like a sorting algorithm problem so there must be a better way.
Here is my distance calculation method:
public static double distance(double lat1, double lon1, double lat2, double lon2, char unit) {
double theta = lon1 - lon2;
double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));
dist = acos(dist);
dist = rad2deg(dist);
dist = dist * 60 * 1.1515;
if (unit == 'K') {
dist = dist * 1.609344;
} else if (unit == 'N') {
dist = dist * 0.8684;
}
return (dist);
}
| 0
| 0
| 0
| 0
| 1
| 0
|
Following my previous question (I assume that 64-bit compiler uses only SSE instructions for floating point calculations):
How transcendental math functions
(sin, atan, exp, log, etc.) are
implemented in 64-bit Delphi compiler?
AFAIK there are no SSE
hardware implementations. What
software library is used, what about the
performance and accuracy compared with the
current FPU hardware implementation?
See also
| 0
| 0
| 0
| 0
| 1
| 0
|
Can you recommend me a good decision tree C++ class with support for continous features and pruning(its very important)? Im writing a simple classifier(two classes) using 9 features. I've been using Waffles recently, but looks like tree is overfitting so i get Precision around 82% but Recall is around 51% which is inacceptable. Waffles have no ability to prune decision trees, and im running out of time :)
| 0
| 0
| 0
| 1
| 0
| 0
|
Mahjong is one of the most popular games in Asia (not the solitaire style found in Windows 7). There were plenty of Mahjong games out there including online ones from Yahoo or offline ones back in the DOS days!
Just another day I was thinking to myself, how can I write one (excluding the GUI)?
The data modeling part is easy.
The winning and scoring rules are... pattern matching?
The strategic part of the game, such as determining which tile to throw out and when to make the Chow or Pong moves are the most difficult part. How to implement this?
Thanks!
Research:
A demo of Mahjong (japanese style) : http://www.nobleflash.com/game/4495/Japanese-Mahjong.html
http://www.ninedragons.com/ - a Mah Jong game I used to play, its scoring system: http://www.ninedragons.com/mahjong/scoring2.html
function language fits better? In what way? Is F# a good language for card game AI?
AI Mahjong - http://www.stanford.edu/class/cs229/proj2009/Loh.pdf
| 0
| 1
| 0
| 0
| 0
| 0
|
I would like to synchronize a spoken recording against a known text. Is there a speech-to-text / natural language processing library that would facilitate this? I imagine I'd want to detect word boundaries and compute candidate matches from a dictionary. Most of the questions I've found on SO concern written language.
Desired, but not required:
Open Source
Compatible with American English out-of-the-box
Cross-platform
Thoroughly documented
Edit: I realize this is a very broad, even naive, question, so thanks in advance for your guidance.
What I've found so far:
OpenEars (iOS Sphinx/Flite wrapper)
| 0
| 1
| 0
| 0
| 0
| 0
|
Design a function f such that:
f(f(x)) == 1/x
Where x is a 32 bit float
Or how about
Given a function f, find a function g
such that
f(x) == g(g(x))
See Also
Interview question: f(f(n)) == -n
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm trying to create a running total, unsuccessfully, what way would you do this:
var total = 0;
value = $('.price').text();
total += value;
$('#subtotal span').html(total);
All it does it add the next value to the "span" not actually add the figures together!
EDIT: From content of answer posted by OP.
$('.addtocart').click(function(){
$('#cart').show();
var omPartNo = $(this).next().text();
var supPartNo = $(this).next().next().text();
var cat = $(this).next().next().next().text();
var desc = $(this).next().next().next().next().text();
var manuf = $(this).next().next().next().next().next().text();
var list = $(this).next().next().next().next().next().next().text();
var disc = $(this).next().next().next().next().next().next().next().text();
var priceEach = $(this).next().next().next().next().next().next().next().next().text();
$('#cart table').append('<tr class="tableRow"><td><a class="removeItem" href="#"><img src="/admin/images/delete.png"></img></a><td>' + omPartNo + '</td><td>' + supPartNo + '</td><td>' + cat + '</td><td>' + desc + '</td><td>' + manuf + '</td><td>' + list + '</td><td>' + disc + '</td><td class="price">' + priceEach + '</td></tr>');
var total = 0;
value = parseInt($('.price').text(), 10);
total += value;
$('#subtotal span').html(total);
});
This is my complete code. I think i'm doing this wrong, this isnt going to give me a running total is it??
Any help!?
| 0
| 0
| 0
| 0
| 1
| 0
|
I've got a list of items. Users can occasionally select them. Now I want to order the items by their popularity. What's a good weighting function for that?
Constraints:
The weight should be in [0,1)
Recursive calculation is prefered (not required)
Newer events must have more influence than old ones.
I'd favor approved functions. As I've developped something like this once and it worked not as expected.
| 0
| 0
| 0
| 0
| 1
| 0
|
This is my code for a shopping cart (the total so far, but a shopping cart eventually) i'm trying to put the code in to minus the clicked item's value from the "total", this is my code:
$('.addtocart').click(function(){
$('#cart').show();
var omPartNo = $(this).next().text();
var supPartNo = $(this).next().next().text();
var cat = $(this).next().next().next().text();
var desc = $(this).next().next().next().next().text();
var manuf = $(this).next().next().next().next().next().text();
var list = $(this).next().next().next().next().next().next().text();
var disc = $(this).next().next().next().next().next().next().next().text();
var priceEach = $(this).next().next().next().next().next().next().next().next().text();
$('#cart table').append('<tr class="tableRow"><td><a class="removeItem" href="#"><img src="/admin/images/delete.png"></img></a><td>' + omPartNo + '</td><td>' + supPartNo + '</td><td>' + cat + '</td><td>' + desc + '</td><td>' + manuf + '</td><td>' + list + '</td><td>' + disc + '</td><td class="price">' + priceEach + '</td></tr>');
var total = 0;
$('.price').each(function() {
total += parseFloat($.text([this]));
});
$('#subtotal span').html(total.toFixed(2));
});
$('.removeItem').live('click',function(){
$(this).closest('tr').remove();
});
So when i click the .removeItem i need it to subtract from the "subtotal span" if possible??
Thanks
| 0
| 0
| 0
| 0
| 1
| 0
|
How can I isolate the 'slope' parameter in the super ellipse function given by:
MyY := (1.0- (power(1.0-power(x, 2.0/Slope), Slope*0.5)))
when I know 'x' and 'MyY' ?
(the function is always used in the range of 0 to 1).
| 0
| 0
| 0
| 0
| 1
| 0
|
Has anyone seen a library to access Wordnet using some sort of query language? My idea is that there should be a way to write something like:
SELECT hypernyms(word, level)
WHERE word = 'art'
I've already consulted SharpNLP, but is not quite what I want. It's awesome, but not what I'm looking for. Should I use some query language, like SPARQL or some homemade dialect of SQL?
| 0
| 1
| 0
| 0
| 0
| 0
|
Using PHP or Python, but I'm sure the basic functions are agnostic.
I am unsure what the proper term, mathematical theory, or algorithm is, otherwise I'm sure Google would have fixed this for me in minutes.
I have a data set similar to the following:
cost | qty | ppl | store
------------------------
30| 500| 10| 1
40| 600| 12| 2
35| 500| 14| 3
50| 700| 10| 1
30| 700| 12| 1
40| 250| 14| 2
What I'm trying to do is find the "optimal" row, based on these qualifiers:
cost: lower is better.
qty: higher is better.
ppl: lower is better.
store: Doesn't matter in this case, but used later to find "best" depending on 'store'.
Essentially, I'm trying to find the best particular "deal" in a "group buy"-like situation, where the fewest amount of people are required to get the best "value" (quantity -vs- cost).
To my eye, it appears that the best-overall would be Row #5, because of the jump in quantity.
If there is a name for this, and a good (Wikipedia?) article on the subject, I'd be happy to finish this myself. Thanks for your time!
| 0
| 0
| 0
| 0
| 1
| 0
|
I wish to implement a zoom-to-mouse-position-with-scrollwheel-algorithm for a CAD application I work on.
Similar question have been asked (This one for example), but all the solutions i found used the
Translate to origin
Scale to zoom
Translate back
approach. While this works in principle, it leads to objects being clipped away on high zoom levels since they become bigger then the viewing volume is. A more elegant solution would be to modify the projection matrix for the zooming.
I tried to implement this, but only got a zoom to the center of the window working.
glGetIntegerv(GL_VIEWPORT, @fViewport);
//convert window coordinates of the mouse to gl's coordinates
zoomtoxgl := mouse.zoomtox;
zoomtoygl := (fviewport[3] - (mouse.zoomtoy));
//set up projection matrix
glMatrixMode(GL_PROJECTION);
glLoadidentiy;
left := -width / 2 * scale;
right := width / 2 * scale;
top := height / 2 * scale;
bottom := -height / 2 * scale;
glOrtho(left, right, bottom, top, near, far);
My questions are: Is it possible to perform a zoom on an arbitrary point using the projection matrix alone in an orthographic view, and if so, How can the zoom target position be factored into the projection matrix?
Update
I changed my code to
zoomtoxgl := camera.zoomtox;
zoomtoygl := (fviewport[3] - camera.zoomtoy);
dx := zoomtoxgl-width/2;
dy := zoomtoygl-height/2;
a := width * 0.5 * scale;
b := width * 0.5 * scale;
c := height * 0.5 * scale;
d := height * 0.5 * scale;
left := - a - dx * scale;
right := +b - dx * scale;
bottom := -c - dy * scale;
top := d - dy * scale;
glOrtho(left, right, bottom, top, -10000.5, Camera.viewdepth);
which gave this result:
Instead of scaling around the cursor position, i can know shift the world origin to any screen location i wish. Nice to have, but not what i want.
Since i am stuck on this for quite some time now, I wonder : Can a zoom relative to an arbitrary screen position be generated just by modifying the projection matrix? Or will I have to modify my Modelview matrix after all?
| 0
| 0
| 0
| 0
| 1
| 0
|
I am working on a Facebook App that needs to be able to average three numbers. But, it always return 0 as the answer. Here is my code:
$y = 100;
$n = 250;
$m = 300;
$number = ($y + $n + $m / 3);
echo 'Index: '.$number;
It always displays Index: 0
Any ideas?
| 0
| 0
| 0
| 0
| 1
| 0
|
Recently I have studied k-nearest neighbour and decision trees and I am quite curious about the difference between the two,i.e,for task like seperating a target function "return 1 if x2>x1,return 0 otherwise",then choosing Nearest Neighbour would be good here since decision tree will invovle too many splits.
So I am just considering in what kind of cases,chossing a decision tree would be more appropriate than k-nearest neighbour?
The other question is just to do with K-nearest neighbour,I understand that when K=1,then it is just a baseline classification(classify the instance to its nearset neighbour' class).Could any one give me an idea on what kind of classification task,will a 3-nearest neighbour definitely outperfom a 1-nearest neightbour classifier?
Thanks in advance!
| 0
| 1
| 0
| 1
| 0
| 0
|
Here is my problem:
I have two random points (x,y) and (x2, y2). I would like to great a 'random-step' or fractal line between the two. I have set up a situation wherein the step distance and direction are randomly generated based on a probability matrix. However, leaving it solely to the direction of this matrix, the line will have a random endpoint which is impossible to pre-determine. I have therefore attempted to set up bounds for my line where--if a point falls--the location is adjusted accordingly. These bounds are not working.
Ideally, my boundaries would be a circle created with each random point at opposite ends of the area. I have tried the following.
I have set up a loop which will iterate through each x-point of the line using a variable i which starts with the lesser of x and x2 and moves towards the greater.
I have set up a variable j to which the random step will be added and initialised it to the equivalent y-value for the lesser x-value (if x1 is greater set to y1 else set to x).
I have set up a variable which contains the slope of the theoretical straight line between x,y and x1,y1.
I have set up a probability matrix which takes a variable mod and sets it to a value between 8 and -8.
I have set up checks to disallow the formation of the line outside of the boundaries of the given plane.
I have set up a check to determine if the variable i is one less than the greater of x and x2. If so, variable j is set to that x-value's y-value;
It is at this point that I fail to find the appropriate algorithm to set up the final check. Here is what I would like the algorithm to do:
A. I would like it to be able to, given a random x-value between x and x1, determine if the current variable j added to the current variable mod is outside of the circle generated by the two aforementioned points (see the second paragraph). If it is not, add mod to variable j and increment the loop.
B. If this point would fall outside the bounds, I would like the step direction to be reversed (e.g. -6 to 6 and 2 to -2) and the same check to be made again.
C. If adding in either direction would put it out of bounds (which will most likely happen near the far end of the circle where the boundaries constrict the most), I would like to be able to run through a loop which checks each value and its inverse beginning at 0 and moving to consecutively larger values until a workable value is determined.
I hope you experience mathematicians and programmers out there see this as a surmountable challenge. It has stumped me for three weeks and I have run out of ideas.
| 0
| 0
| 0
| 0
| 1
| 0
|
What should I keep in mind when performing calculations using .NET?
For example, I know a little about floating point errors, but am unfamilliar with this forum post on CodeProject. What do I need to know to complete my knowledge of .NET-based math so that I can advise how to work with parameters and results of varying bit-sizes.
| 0
| 0
| 0
| 0
| 1
| 0
|
I would like to better understand how the various common search algorithms relate to each other. Does anyone know of a resource, such as a hierarchy diagram or concise textual description of this?
A small example of what I mean is:
A* Search
-> Uniform-cost is a variant of A* where the heuristic is a constant function
-> Dijkstra's is a variant of uniform-cost search with no goal
-> Breadth-first search is a variant of A* where all step costs are +ve and identical
etc.
Thanks!
| 0
| 1
| 0
| 0
| 0
| 0
|
An article has been making the rounds lately discussing the use of genetic algorithms to optimize "build orders" in StarCraft II.
http://lbrandy.com/blog/2010/11/using-genetic-algorithms-to-find-starcraft-2-build-orders/
The initial state of a StarCraft match is pre-determined and constant. And like chess, decisions made in this early stage of the match have long-standing consequences to a player's ability to perform in the mid and late game. So the various opening possibilities or "build orders" are under heavy study and scrutiny. Until the circulation of the above article, computer-assisted build order creation probably wasn't as popularity as it has been recently.
My question is... Is a genetic algorithm really the best way to model optimizing build orders?
A build order is a sequence of actions. Some actions have prerequisites like, "You need building B before you can create building C, but you can have building A at any time." So a chromosome may look like AABAC.
I'm wondering if a genetic algorithm really is the best way to tackle this problem. Although I'm not too familiar with the field, I'm having a difficult time shoe-horning the concept of genes into a data structure that is a sequence of actions. These aren't independent choices that can be mixed and matched like a head and a foot. So what value is there to things like reproduction and crossing?
I'm thinking whatever chess AIs use would be more appropriate since the array of choices at any given time could be viewed as tree-like in a way.
| 0
| 1
| 0
| 0
| 0
| 0
|
I have two points in 2D space, centred on origin (0,0). The first point represents the starting location and the second represents the end location. I need to calculate the angle of rotation between the two points, my problem being that the hypoteneuse from each point to (0,0) is not equal.
Could someone tell me how to work out the angle between the two points, bearing in mind that they could be anywhere relative to (0,0).
Many thanks,
Matt.
| 0
| 0
| 0
| 0
| 1
| 0
|
I want to find the zero points of a sine function. The parameter is a interval [a,b]. I have to it similar to binary search.
Implement a function that searches for null points in the sinus function in a interval between a and b. The search-interval[lower limit, upper limit] should be halved until lower limit and upper limit are less then 0.0001 away from each other.
Here is my code:
public class Aufg3 {
public static void main(String[] args) {
System.out.println(zeropoint(5,8));
}
private static double zeropoint(double a, double b){
double middle = (a + b)/2;
if(Math.sin(middle) < 0){
return zeropoint(a,middle);
}else if(Math.sin(middle) > 0){
return zeropoint(middle,b);
}else{
return middle;
}
}
}
It gives me a lot of errors at the line with return zeropoint(middle,b);
In a first step I want to find just the first zero point in the interval.
Any ideas?
| 0
| 0
| 0
| 0
| 1
| 0
|
It's really all in the title, but here's a breakdown for anyone who is interested in Evolutionary Algorithms:
In an EA, the basic premise is that you randomly generate a certain number of organisms (which are really just sets of parameters), run them against a problem, and then let the top performers survive.
You then repopulate with a combination of crossbreeds of the survivors, mutations of the survivors, and also a certain number of new random organisms.
Do that several thousand times, and efficient organisms arise.
Some people also do things like introduce multiple "islands" of organisms, which are seperate populations that are allowed to crossbreed once in awhile.
So, my question is: what are the optimal repopulation percentages?
I have been keeping the top 10% performers, and repopulating with 30% crossbreeds and 30% mutations. The remaining 30% is for new organisms.
I have also tried out the multiple island theory, and I'm interested in your results on that as well.
It is not lost on me that this is exactly the type of problem an EA could solve. Are you aware of anyone trying that?
Thanks in advance!
| 0
| 1
| 0
| 0
| 0
| 0
|
What I am supposed to do. I have an black and white image (100x100px):
I am supposed to train a backpropagation neural network with this image. The inputs are x, y coordinates of the image (from 0 to 99) and output is either 1 (white color) or 0 (black color).
Once the network has learned, I would like it to reproduce the image based on its weights and get the closest possible image to the original.
Here is my backprop implementation:
import os
import math
import Image
import random
from random import sample
#------------------------------ class definitions
class Weight:
def __init__(self, fromNeuron, toNeuron):
self.value = random.uniform(-0.5, 0.5)
self.fromNeuron = fromNeuron
self.toNeuron = toNeuron
fromNeuron.outputWeights.append(self)
toNeuron.inputWeights.append(self)
self.delta = 0.0 # delta value, this will accumulate and after each training cycle used to adjust the weight value
def calculateDelta(self, network):
self.delta += self.fromNeuron.value * self.toNeuron.error
class Neuron:
def __init__(self):
self.value = 0.0 # the output
self.idealValue = 0.0 # the ideal output
self.error = 0.0 # error between output and ideal output
self.inputWeights = []
self.outputWeights = []
def activate(self, network):
x = 0.0;
for weight in self.inputWeights:
x += weight.value * weight.fromNeuron.value
# sigmoid function
if x < -320:
self.value = 0
elif x > 320:
self.value = 1
else:
self.value = 1 / (1 + math.exp(-x))
class Layer:
def __init__(self, neurons):
self.neurons = neurons
def activate(self, network):
for neuron in self.neurons:
neuron.activate(network)
class Network:
def __init__(self, layers, learningRate):
self.layers = layers
self.learningRate = learningRate # the rate at which the network learns
self.weights = []
for hiddenNeuron in self.layers[1].neurons:
for inputNeuron in self.layers[0].neurons:
self.weights.append(Weight(inputNeuron, hiddenNeuron))
for outputNeuron in self.layers[2].neurons:
self.weights.append(Weight(hiddenNeuron, outputNeuron))
def setInputs(self, inputs):
self.layers[0].neurons[0].value = float(inputs[0])
self.layers[0].neurons[1].value = float(inputs[1])
def setExpectedOutputs(self, expectedOutputs):
self.layers[2].neurons[0].idealValue = expectedOutputs[0]
def calculateOutputs(self, expectedOutputs):
self.setExpectedOutputs(expectedOutputs)
self.layers[1].activate(self) # activation function for hidden layer
self.layers[2].activate(self) # activation function for output layer
def calculateOutputErrors(self):
for neuron in self.layers[2].neurons:
neuron.error = (neuron.idealValue - neuron.value) * neuron.value * (1 - neuron.value)
def calculateHiddenErrors(self):
for neuron in self.layers[1].neurons:
error = 0.0
for weight in neuron.outputWeights:
error += weight.toNeuron.error * weight.value
neuron.error = error * neuron.value * (1 - neuron.value)
def calculateDeltas(self):
for weight in self.weights:
weight.calculateDelta(self)
def train(self, inputs, expectedOutputs):
self.setInputs(inputs)
self.calculateOutputs(expectedOutputs)
self.calculateOutputErrors()
self.calculateHiddenErrors()
self.calculateDeltas()
def learn(self):
for weight in self.weights:
weight.value += self.learningRate * weight.delta
def calculateSingleOutput(self, inputs):
self.setInputs(inputs)
self.layers[1].activate(self)
self.layers[2].activate(self)
#return round(self.layers[2].neurons[0].value, 0)
return self.layers[2].neurons[0].value
#------------------------------ initialize objects etc
inputLayer = Layer([Neuron() for n in range(2)])
hiddenLayer = Layer([Neuron() for n in range(10)])
outputLayer = Layer([Neuron() for n in range(1)])
learningRate = 0.4
network = Network([inputLayer, hiddenLayer, outputLayer], learningRate)
# let's get the training set
os.chdir("D:/stuff")
image = Image.open("backprop-input.gif")
pixels = image.load()
bbox = image.getbbox()
width = 5#bbox[2] # image width
height = 5#bbox[3] # image height
trainingInputs = []
trainingOutputs = []
b = w = 0
for x in range(0, width):
for y in range(0, height):
if (0, 0, 0, 255) == pixels[x, y]:
color = 0
b += 1
elif (255, 255, 255, 255) == pixels[x, y]:
color = 1
w += 1
trainingInputs.append([float(x), float(y)])
trainingOutputs.append([float(color)])
print "
Original image ... Black:"+str(b)+" White:"+str(w)+"
"
#------------------------------ let's train
for i in range(500):
for j in range(len(trainingOutputs)):
network.train(trainingInputs[j], trainingOutputs[j])
network.learn()
for w in network.weights:
w.delta = 0.0
#------------------------------ let's check
b = w = 0
for x in range(0, width):
for y in range(0, height):
out = network.calculateSingleOutput([float(x), float(y)])
if 0.0 == round(out):
color = (0, 0, 0, 255)
b += 1
elif 1.0 == round(out):
color = (255, 255, 255, 255)
w += 1
pixels[x, y] = color
#print out
print "
After learning the network thinks ... Black:"+str(b)+" White:"+str(w)+"
"
Obviously, there is some issue with my implementation. The above code returns:
Original image ... Black:21 White:4
After learning the network thinks ...
Black:25 White:0
It does the same thing if I try to use larger training set (I'm testing just 25 pixels from the image above for testing purposes). It returns that all pixels should be black after learning.
Now, if I use a manual training set like this instead:
trainingInputs = [
[0.0,0.0],
[1.0,0.0],
[2.0,0.0],
[0.0,1.0],
[1.0,1.0],
[2.0,1.0],
[0.0,2.0],
[1.0,2.0],
[2.0,2.0]
]
trainingOutputs = [
[0.0],
[1.0],
[1.0],
[0.0],
[1.0],
[0.0],
[0.0],
[0.0],
[1.0]
]
#------------------------------ let's train
for i in range(500):
for j in range(len(trainingOutputs)):
network.train(trainingInputs[j], trainingOutputs[j])
network.learn()
for w in network.weights:
w.delta = 0.0
#------------------------------ let's check
for inputs in trainingInputs:
print network.calculateSingleOutput(inputs)
The output is for example:
0.0330125791296 # this should be 0, OK
0.953539182136 # this should be 1, OK
0.971854575477 # this should be 1, OK
0.00046146137467 # this should be 0, OK
0.896699762781 # this should be 1, OK
0.112909223162 # this should be 0, OK
0.00034058462280 # this should be 0, OK
0.0929886299643 # this should be 0, OK
0.940489647869 # this should be 1, OK
In other words the network guessed all pixels right (both black and white). Why does it say all pixels should be black if I use actual pixels from the image instead of hard coded training set like the above?
I tried changing the amount of neurons in the hidden layers (up to 100 neurons) with no success.
This is a homework.
This is also a continuation of my previous question about backprop.
| 0
| 1
| 0
| 1
| 0
| 0
|
I'm new to Java and also new to while, for, and if/else statements. I've really been struggling with this beast of a problem.
The code and description is below. It compiles, but I'm it doesn't calculate as expected. I'm not really sure if it's a mathematical logic error, loop layout error, or both.
I've been grinding my gears for quite some time now, and I'm not able to see it. I feel like I'm really close... but still so far away.
Code:
/*
This program uses a while loop to to request two numbers and output (inclusively) the odd numbers between them,
the sum of the even numbers between them, the numbers and their squares between 1 & 10, the sum of the squares
of odd numbers.
*/
import java.io.*;
import java.util.*;
public class SumOfaSquare
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
int firstnum = 0, secondnum = 0, tempnum = 0;
int sum = 0,squaresum = 0, squarenum = 0;
int number = 1;
String oddOutputMessage = "The odd numbers between" + firstnum + " and " + secondnum + " inclusively are:";
String evenSumMessage = "The sum of all even numbers between " + firstnum + " and " + secondnum + "is: ";
String oddSquareMessage = "The odd numbers and their squares are : ";
String squareMessage = "The numbers and their squares from 1-10 are : ";
System.out.println ("Please enter 2 integers. The first number should be greater than the second: ");
firstnum = console.nextInt();
secondnum = console.nextInt();
//used to find out if first number is greater than the second. If not, inform user of error.
if (firstnum > secondnum)
{
tempnum = firstnum;
System.out.println ("You entered: " + firstnum + " and: " + secondnum);
}
else
System.out.println ("Your first number was not greater than your second number. Please try again.");
//while the frist number is greater, do this....
while (tempnum <= secondnum)
{
//if it's odd....
if (tempnum %2 == 1)
{
oddOutputMessage = (oddOutputMessage + tempnum + " ");
squaresum = (squaresum + tempnum * tempnum);
}
//otherwise it's even..
else
{
sum = sum + tempnum;
evenSumMessage = (evenSumMessage + sum + " ");
tempnum++;
}
}
// figures squares from 1 - 10
while (number <=10)
{
squarenum = (squarenum + number * number);
squareMessage = (squareMessage + number + " " + squarenum);
number++;
}
oddSquareMessage = oddSquareMessage + squaresum;
System.out.println (oddOutputMessage);
System.out.println (oddOutputMessage);
System.out.println (squareMessage);
System.out.println (evenSumMessage);
System.out.println (oddSquareMessage);
}
}
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm looking for a way to influence Math.random().
I have this function to generate a number from min to max:
var rand = function(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Is there a way to make it more likely to get a low and high number than a number in the middle?
For example; rand(0, 10) would return more of 0,1,9,10 than the rest.
| 0
| 0
| 0
| 0
| 1
| 0
|
I am interested in learning the basics on machine learning and am wondering what the best ONLINE resources are. Keep in mind i am a total novice and know very little about the subject.
| 0
| 1
| 0
| 1
| 0
| 0
|
Does the real and/or imaginary part get multiplied by the same coefficient or does the window frame size have to be doubled?
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm trying to write some c code (objective c) which will take a bank account balance and a desired balance from the user and produce a value which I can add or subtract from the current balance to achieve the desired balance.
I think I'm made things overcomplicated, heres what I have...
//get desired amount to variable dblDesiredBalance
//get balance from database to variable balFromDB
double addAmount = fabs(balFromDB) + fabs(dblDesiredBalance);
double minusAmount = fabs(dblDesiredBalance) - fabs(balFromDB);
// create amount to add to db
if (dblDesiredBalance < 0 ) {
if (balFromDB < 0 ) {
dblCommitToDB = balFromDB - minusAmount;
} else {
dblCommitToDB = balFromDB - addAmount;
}
} else {
if (balFromDB < 0 ) {
dblCommitToDB = balFromDB + addAmount;
} else {
dblCommitToDB = balFromDB + minusAmount;
}
}
// update db with dblCommitToDB
Can anyone help me ?
| 0
| 0
| 0
| 0
| 1
| 0
|
I'm attempting to do some calculations for a "running total", this is my code:
$('.quantity_input').live('change',function(){
var ValOne = parseFloat($(this).val());
var ValTwo = parseFloat($(".price").text())
var totalTotal = ((ValOne) * (ValTwo));
$('.cost_of_items').closest('.cost_of_items').text(totalTotal.toFixed(2));
calcTotal();
});
.quantity_input is an input, .price is the price of the product, .cost_of_items is where i want to update the total cost for the item, ie. item1 = £5 x 3 quantity = £15 total for item1
calcTotal() is a function that just updates a total cost for the order. The problem is keeping all the math in one row of the table, ie i'm doing the calc in the code above and its not sticking to its row, its updating all the fields with class .cost_of_items etc...
the problem with showing my html is that its dynamically added by jQuery .appends() but here is the relevant jQuery:
$('#items').append('<tr class="tableRow"><td><a class="removeItem" href="#"><img src="/admin/images/delete.png"></img></a><td class="om_part_no">' + omPartNo + '</td><td>' + supPartNo + '</td><td>' + cat + '</td><td class="description">' + desc + '</td><td>' + manuf + '</td><td>' + list + '</td><td>' + disc + '</td><td><p class="add_edit">Add/Edit</p><input type="text" class="quantity_input" name="quantity_input" /></td><td class="price_each_nett price">' + priceEach + '</td><td class="cost_of_items"></td><td><p class="add_edit">Add/Edit</p><input type="text" class="project_ref_input" name="project_ref_input" /><p class="project_ref"></p></td></tr>');
EDIT:
Working solution:
$('.quantity_input').live('change',function(){
var ValOne = parseFloat($(this).val());
var ValTwo = parseFloat($(this).closest('tr').find('.price').text())
var totalTotal = ((ValOne) * (ValTwo));
$(this).closest('tr').find('.cost_of_items').text(totalTotal.toFixed(2));
calcTotal();
});
| 0
| 0
| 0
| 0
| 1
| 0
|
recently I came to study clustering in data-mining and I've studied sequential clustering and hierarchical clustering and k-means.
I also read about a statement that distinguishes k-means from the other two clustering technique,saying k-means is not very good at dealing with nominal attributes,but the text didn't explain this point.So far,the only difference that I can see is that for K-means,we will know in advance we will need exactly K clusters while we don't know how many clusters we need for other two clustering methods.
So could anybody give me some idea here on why such statement exists,i.e.,k-means has this problem when dealing with examples of nominal attributes and is there a way to overcome this?
Thanks in advance.
| 0
| 1
| 0
| 1
| 0
| 0
|
This is not a homework question, it is an exam preparation question.
I should define a function syllables(word) that counts the number of syllables in
A word in the following way:
• a maximal sequence of vowels is a syllable;
• a final e in a word is not a syllable (or the vowel sequence it is a part
Of).
I do not have to deal with any special cases, such as a final e in a
One-syllable word (e.g., ’be’ or ’bee’).
>>> syllables(’honour’)
2
>>> syllables(’decode’)
2
>>> syllables(’oiseau’)
2
Should I use regular expression here or just list comprehension ?
| 0
| 1
| 0
| 0
| 0
| 0
|
I'm sure most are familiar with the closest pair problem, but is there another alogrithm or a way to modify the current CP algorithm to get the next closest pair?
| 0
| 0
| 0
| 0
| 1
| 0
|
Is the are java alternative to Bayesian Belief Network framework - Infer.NET?
Preferable if it be scalable(online learning for large datasets), well-supported(last updated since 2010) and open source and easy to write network structure. So all features from Infer.NET.
| 0
| 0
| 0
| 1
| 0
| 0
|
What are the relevant differences, in terms of performance and use cases, between simulated annealing (with bean search) and genetic algorithms?
I know that SA can be thought as GA where the population size is only one, but I don't know the key difference between the two.
Also, I am trying to think of a situation where SA will outperform GA or GA will outperform SA. Just one simple example which will help me understand will be enough.
| 0
| 1
| 0
| 0
| 0
| 0
|
Lets start out with an simple 16 x 16 array of ints.
How would I insert the 'SomeValue' into the array in a 90 degree clockwise order.
int[] image = new int[16 * 16];
for (int x = 0; x < 16; x++)
{
for (int y = 0; y < 16; y++)
{
int someValue = x * y;
// This is the line I think is wrong
image[x + (y * 16)] = someValue;
}
}
The result should be like the Rotated Array below.
Normal order:
0, 1, 2,
3, 4, 5,
6, 7, 8,
Rotated Clockwise:
6, 3, 0,
7, 4, 1,
8, 5, 2,
| 0
| 0
| 0
| 0
| 1
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.