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 |
|---|---|---|---|---|---|---|
I'm a total newbie to Haskell, and programming in general, but I'm trying to work through some Project Euler problems because I do like problem solving. However, I have a problem with problem #12.
I devised a solution I thought would work, but alas, it does not.
Can you help me by opening my eyes to the problem with my code,
and maybe push me in the right direction towards fixing it? Thank you.
Here is the code:
triangleNumber = scanl1 (+) [1..]
factors n = [x | x <- [1..n], n `mod` x == 0]
numFactors = length . factors
eulerTwelve = find ((>500) . numFactors) triangleNumber
Thank you very much! :)
| 0 | 0 | 0 | 0 | 1 | 0 |
Abstract: Which Python package or C-Library is the best option for very high precision arithmetic operations?
I have some functions which convert fractional days (0.0-0.99999..) to a human-readible format (hours, minutes, seconds; but more importantly: milliseconds, microsecond, nanoseconds).
Conversion is done by these functions:
(note that I haven't implemented timezone correction yet)
d = lambda x: decimal.Decimal(str(x))
cdef object fractional2hms(double fractional, double timezone):
cdef object total, hms, ms_mult
cdef int i
hms = [0,0,0,0,0,0]
ms_mult = (d(3600000000000), d(60000000000), d(1000000000), d(1000000), d(1000), d(1))
# hms = [0,0,0,0,0]
total = d(fractional) * d(86400000000000)
for i in range(len(ms_mult)):
hms[i] = (total - (total % ms_mult[i])) / ms_mult[i]
total = d(total % ms_mult[i])
return ([int(x) for x in hms])
And to fractional:
def to_fractional(self):
output = (self.hour / d(24.0)) + (self.minute / d(1440.0))
output += (self.second / d(86400.0)) + (self.millisecond / d(86400000.0))
output += self.microsecond / d(86400000000.0)
output += self.nanosecond * (d(8.64) * d(10)**d(-9))
return output
My results of a back-and-forth conversion are inaccurate, however:
jdatetime.DayTime.fromfractional(d(0.567784356873)).to_fractional()
Decimal('0.56779150214342592592592592592592592592592592592592592592592592592592592592592592592592592592592592592592592592592')
# Difference in-out: Decimal('0.000007145270')
When I change d() to return a regular Python float:
# Difference in-out: 7.1452704258900823e-06 (same)
My question is therefore: Which Python package or C-library is able to do this more accurately?
| 0 | 0 | 0 | 0 | 1 | 0 |
What is an efficient way of finding the number of ways k gifts can be chosen from N gifts where N can be very large (N ~ 10^18). That is we have to calculate N(C)K or N chose K. K can also be of the order of N.
| 0 | 0 | 0 | 0 | 1 | 0 |
I've been following a tutorial written for Actionscript 2, and have successfully converted it to AS 3, however on the second to last part I'm stuck.
The tutorial here (http://www.cleverpig.com/tutorials/whackapig/whack.htm step 8) has the following piece of code:
if (_currentframe==1) {
// randomly choose whether or not to play
if (random(100)>97) {
// should we tease or popup?
if (random(3)<1) {
this.gotoAndPlay ("popup");
} else {
this.gotoAndPlay (1);
}
}
}
it is meant to add some randomness to the character's movement. After some googling I created this code in AS 3 hoping it would work.
if (currentFrame==1) {
// randomly choose whether or not to play
if(Math.floor(Math.random()*99)-97) {
// should we tease or popup?
if (Math.floor(Math.random() *3)-1)
) {
this.gotoAndPlay ("popup");
} else {
this.gotoAndPlay (1);
}
}
}
When I run the program with this code the character's entire animation plays once (down, halfway up, up, hit). It is supposed to only play the first 3 frames, and repeat this.
EDIT:
function random (n:int ) : int {
return Math.floor (Math.random() * n);
}
if (currentFrame==1) {
// randomly choose whether or not to play
if(random(100)): 97 {
// should we tease or popup?
if (random(3)): 1
{
this.gotoAndPlay ("popup");
} else {
this.gotoAndPlay (1);
}
}
}
Symbol 'hole', Layer 'Actionscript', Frame 1, Line 10 1084: Syntax error: expecting identifier before colon.
Symbol 'hole', Layer 'Actionscript', Frame 1, Line 10 1008: Attribute is invalid.
Symbol 'hole', Layer 'Actionscript', Frame 1, Line 12 1084: Syntax error: expecting identifier before colon.
Symbol 'hole', Layer 'Actionscript', Frame 1, Line 13 1008: Attribute is invalid.
Symbol 'hole', Layer 'Actionscript', Frame 1, Line 15 1083: Syntax error: else is unexpected.
| 0 | 0 | 0 | 0 | 1 | 0 |
Given a list
ms = [2,1,1,1]
of multiplicities, a stock of prime numbers corresponding to ms (here, the stock could be : 2,2,3,5,7) and a list, of length lc,
cs = [3,1,1]
of capacities, we consider any list xs of length lc such that xs !! i = product of (cs !! i) numbers from the stock, 0 <= i < lc, the stock being empty at the end of the construction of xs (so
sum ms == sum cs
should hold).
Here are, for instance, the 13 possibilities for xs with the chosen stock:
[12,5,7], [12,7,5], [20,3,7], [20,7,3]
, [28,3,5], [28,5,3], [30,3,7], [30,7,3]
, [42,2,5], [42,5,2], [70,2,3], [70,3,2], [105,2,2].
The programming problem is to write a fast function
nbOfLists :: (Integral a,Integral b) => [a] -> [a] -> b
counting the number of distinct such lists (here nbOfLists ms cs == 13).
Here is a solution in Haskell
nbOfLists [u] _ = 1
nbOfLists (u:us) vs =
let clean = map (filter (/=0))
corpus = filter (all (>=0)) $ map (zipWith (-) vs) $ base u (length vs)
base k 1 = [[k]]
base k l = concat [map (i :) $ base (k-i) (l-1) | i <- [0..k]]
in sum $ map (nbOfLists us) $ clean corpus
that performs nbOfLists [2..6] [2..6] == 604137 in 10s. Can you do better ?
By the way, can you proove that nbOfLists ms cs == nbOfLists cs ms ? That is, for instance, from the 2,2,2,3,5 stock, xs is among the 13 lists :
[4,2,3,5], [4,2,5,3], [4,3,2,5], [4,3,5,2]
, [4,5,2,3], [4,5,3,2], [6,2,2,5], [6,2,5,2]
, [6,5,2,2], [10,2,2,3], [10,2,3,2], [10,3,2,2], [15,2,2,2]
(I have no clue here) ?
| 0 | 0 | 0 | 0 | 1 | 0 |
I got that "interesting" exception in my in-the-wild server errorlog. My app posts exceptions and "wtf"-errors to my central server, so I don't have much information what exactly happend. I just know THAT it happend, and I don't have any clue.
Stacktrace:
java.io.IOException: Math result not representable
at org.apache.harmony.luni.platform.OSFileSystem.writeImpl(Native Method)
at org.apache.harmony.luni.platform.OSFileSystem.write(OSFileSystem.java:129)
at java.io.FileOutputStream.write(FileOutputStream.java:297)
at net.jav.apps.romeolive.RomeoInterface.fetchBinaryToFile(RomeoInterface.java:299)
at net.jav.apps.romeolive.HeartBeatService$_fetchPic.run(HeartBeatService.java:327)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
at java.lang.Thread.run(Thread.java:1096)
The code in place of net.jav.apps.romeolive.RomeoInterface:
byte[] ret=fetchBinary(fullurl);
if (ret==null) return false;
try
{
FileOutputStream os=new FileOutputStream(getCacheFileName(type,fullurl));
os.write(ret, 0, ret.length);
The "failing" line #299 is the os.write()
fetchBinary(url) fetches some binary file (thumbnail jpg) from a web server and returns it as a byte[], or NULL if not found/error.
getCacheFileName(type,fullurl) returns the cacheDir() plus type plus the sanitized fullurl (removing slashes, only use the localpart of the url).
So what exactly fails, is... Trying to write the existing thumbnail jpg byte[] to a perfectly crafted filename in cacheDir().
The device where this exception showed up (ONCE only until now) is: GT-I9000@samsung/GT-I9000/GT-I9000/GT-I9000:2.2.1/FROYO/XXJPY:user/release-keys
Did anyone have this "Math result not representable" as IOException?
I'd really like to nail down that thing ;) Google and Stackoverflow didn't show up anything helpful or even related.
Thanks a lot,
Oliver
| 0 | 0 | 0 | 0 | 1 | 0 |
I know it's not strictly a programming question but computer scientists might know the answer. why is the sum of the first n non-negative numbers equal to the number of 2-element subsets?
| 0 | 0 | 0 | 0 | 1 | 0 |
How would one go about echoing a variable multiple times..
A way to understand this question better would be if I said:
$foo = '<div>bar</div>';
echo $foo*7;
It's probably the most simple thing, but I'm not sure.
And
| 0 | 0 | 0 | 0 | 1 | 0 |
Does anyone know why this happens and if it can be fixed. I'm comparing results from C and PHP, but PHP is giving me different results.
I can supply some code if needed but has anyone experienced this before?
PHP code
$tempnum = 1.0e - 5 * -44954; // substr($line1,53,6);
$bstar = $tempnum / pow(10.0, 3);
$bstar gives me -0.00044954 in PHP but it should be -0.000450
C code
double tempnum = 1.0e - 5 * -44954;
double bstar = tempnum / pow(10.0, 3);
printf bstar gives me -0.000450
Thanks for your responses so far, but how does PHP come to this conclusion...
$twopi = 6.28318530717958623; /* 2*Pi */
$xmnpda= 1440; //1.44E3 ; /* Minutes per day */
$temp = (($twopi/$xmnpda)/$xmnpda);
$xndt2o = -0.000603;
$xndt2o = $xndt2o * $temp;
echo $xndt2o gives me -1.8256568188E-9 in PHP but in C it gives me -0.000000
I don't know what all that is about in PHP.
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a large set of strings that I'm using for natural language processing research, and I'd like a nice way to store it in Python.
I could use pickle, but loading the entire list into memory would then be an impossibility (I believe), as it's about 10 GB large, and I don't have that much main memory. Currently I have the list stored with the shelve library... The shelf is indexed by strings, "0", "1", ..., "n" which is a bit clunky.
Are there nicer ways to store such an object in a single file, and still have random (ish) access to it?
It may be that the best option is to split it into multiple lists.
Thanks!
| 0 | 1 | 0 | 0 | 0 | 0 |
just wondering if there is any clever way to do the following.
I have an N dimensional array representing a 3x3 grid
grid = [[1,2,3],
[4,5,6],
[7,8,9]]
In order to get the first row I do the following:
grid[0][0:3]
>> [1,2,3]
In order to get the first column I would like to do something like this (even though it is not possible):
grid[0:3][0]
>> [1,4,7]
Does NumPy support anything similar to this by chance?
Any ideas?
| 0 | 0 | 0 | 0 | 1 | 0 |
Situation:
I wish to perform a Deep-level Analysis of a given text, which would mean:
Ability to extract keywords and assign importance levels based on contextual usage.
Ability to draw conclusions on the mood expressed.
Ability to hint on the education level (word does this a little bit though, but something more automated)
Ability to mix-and match phrases and find out certain communication patterns
Ability to draw substantial meaning out of it, so that it can be quantified and can be processed for answering by a machine.
Question:
What kind of algorithms and techniques need to be employed for this?
Is there a software that can help me in doing this?
| 0 | 1 | 0 | 0 | 0 | 0 |
I'm in need of rendering an influence map in OpenGL. At present I have 100 x 100 quads rendering with a set color to represent the influence at each point on the map. I've been recommended to change my rendering method to one quad with a texture, then allowing the rendering pipeline to take over in speed.
Basic testing has shown that glTexSubImage2D is too slow for setting 10,000 texels per frame. Do you have any suggestions? Would it better to create an entirely new texture each frame? My influence map is in normalized floats (0.0 to 1.0) and that is converted to grayscale colors (1.0f = white).
Thanks :D
| 0 | 1 | 0 | 0 | 0 | 0 |
Having a number e.g. 510510
The prime divisors are: [2, 3, 5, 7, 11, 13, 17]
Using the list of primes, what could an efficient way to calculate the non-prime divisors be?
| 0 | 0 | 0 | 0 | 1 | 0 |
I am attempting to create a program that can find human figures in video of game play of call of duty. I have compiled a list of ~2200 separate images from this video that either contain a human figure or do not. I have then attempted to train a neural network to tell the difference between the two sets of images.
Then, I divide each video frame up into a couple hundred gridded rectangles and I check each with my ANN. The rectangles are overlapping to attempt to capture figures that are between grid rects, but this doesn't seem to work well. So I have a few questions:
Are neural networks the way to go? I have read that they are very fast compared to other machine learning algorithms, and eventually I plan to use this with real time video and speed is very important.
What is the best way to search for the figures in the image frame to test on the ANN? I feel like the way I do it isn't very good. It's definitely not very fast or accurate. It takes about a second per frame of an image 960 x 540 and has poor accuracy.
Another problem I have had is the best way to build the feature vector to use as the input to the ANN. Currently, I just scale all input images down to25 x 50 pixels and create a feature vector containing the intensity of every pixel. This is a very large vector (1250 floats). What are better ways to build a feature vectors?
For a more detailed explanation of what I do here: CodAI: Computer Vision
EDIT: I would like a little more detail. What is the best way to calculates features. I need to be able to recognize a human figure in many different positions. Do I need to create separate classifiers for recognizing the difference between upright, crouched, and prone?
| 0 | 0 | 0 | 1 | 0 | 0 |
Background
Split database column names into equivalent English text to seed a data dictionary. The English dictionary is created from a corpus of corporate documents, wikis, and email. The dictionary (lexicon.csv) is a CSV file with words and probabilities. Thus, the more often someone writes the word "therapist" (in email or on a wiki page) the higher the chance of "therapistname" splits to "therapist name" as opposed to something else. (The lexicon probably won't even include the word rapist.)
Source Code
TextSegmenter.java @ http://pastebin.com/taXyE03L
SortableValueMap.java @ http://pastebin.com/v3hRXYan
Data Files
lexicon.csv - http://pastebin.com/0crECtXY
columns.txt - http://pastebin.com/EtN9Qesr
Problem (updated 2011-01-03)
When the following problem is encountered:
dependentrelationship::end depend ent dependent relationship
end=0.86
ent=0.001
dependent=0.8
relationship=0.9
These possible solutions exist:
dependentrelationship::dependent relationship
dependentrelationship::dep end ent relationship
dependentrelationship::depend ent relationship
The lexicon contains words with their relative probabilities (based on word frequency): dependent 0.8, end 0.86, relationship 0.9, depend 0.3, and ent 0.001.
Eliminate the solution of dep end ent relationship because dep is not in the lexicon (i.e., 75% word usage), whereas the other two solutions cover 100% of words in the lexicon. Of the remaining solutions, the probability of dependent relationship is 0.72 whereas depend ent relationship is 0.00027. We can therefore select dependent relationship as the correct solution.
Related
How to separate words in a "sentence" with spaces?
Top Coder - Text Segmentation Presentation 1/2
Top Coder - Text Segmentation Presentation 2/2
Linear Text Segmentation using Dynamic Programming Algorithm
Dynamic Programming: Segmentation
Dynamic Programming: A Computational Tool
Question
Given:
// The concatenated phrase or database column (e.g., dependentrelationship).
String concat;
// All words (String) in the lexicon within concat, in left-to-right order; and
// the ranked probability of those words (Double). (E.g., {end, 0.97}
// {dependent, 0.86}, {relationship, 0.95}.)
Map.Entry<String, Double> word;
How would you implement a routine that generates the most likely solution based on lexicon coverage and probabilities? For example:
for( Map.Entry<String, Double> word : words ) {
result.append( word.getKey() ).append( ' ' );
// What goes here?
System.out.printf( "%s=%f
", word.getKey(), word.getValue() );
}
Thank you!
| 0 | 1 | 0 | 0 | 0 | 0 |
I'm using the code below to build a table, but because the values in my database table are constantly incrementing, I'm doing some math to work out differences in values (numerically) but this has screwed up the table layout somehow. I've included a screenshot so you can see that the first row beneath the table header is just not right.
$column is a $_GET value from the user.
$sql = "select * from (select * from mash order by tstamp desc limit 10) s order by s.id";
$result = mysql_query($sql);
$previous = 0;
$firstRun = true;
echo "<table id='dataTable' border='1'>";
echo "<tr><th>Date</th>
<th>Value</th></tr>";
while($row = mysql_fetch_array($result)){
$difference = $row[$column] - $previous;
if (!$firstRun)
echo "<tr><td>" . date("G:i:s", strtotime($row["tstamp"])) . "</td>";
echo "<td>" . $difference . "</td></tr>";
$previous = $row[$column];
$firstRun = false;
}
echo "</table>";
My question: Can anyone spot from the code, why the first row would come out like this?
| 0 | 0 | 0 | 0 | 1 | 0 |
this set of values:
1 2 3 3 4 1
looks pretty nice if you think of it on a bar chart:
* *
* * * *
=======
1 2 3 4
while this one looks bad..
1 2 2 2 2 2 2 2 2 9 8
*
*
*
*
*
*
*
* * * *
=================
1 2 3 4 5 6 7 8 9
This is because there are a lot of 2 and a big gap between the 2 and the 8...
I need to find a formula which computes how nice a set of number looks..
I think I'll need some deviation function.. any idea?
thanks
| 0 | 0 | 0 | 0 | 1 | 0 |
Has there been any research in the field of data-mining regarding classifying data which has a one to many relationship?
For example of a problem like this, say I am trying to predict which students are going to drop out of university based on their class grades and personal information. Obviously there is a one to many relationship between the students personal information and the grades they achieved in their classes.
Obvious approaches include:
Aggregate - The multiple records could be aggregated together in some way reducing the problem to a basic classification problem. In the case of the student classification, the average of their grades could be combined with their personal data. While this solution is simple, often key information is lost. For example what if most students who take organic chemistry and get below a C- end up dropping out even if their average is above a B+ rating.
Voting - Create multiple classifiers (often weak ones) and have them cast votes to determine the overall class of the data in question. This would be like if two classifiers were built, one for the student's course data and one for their personal data. Each course record would be passed to the course classifier and based on the grade and the course name, the classifier would predict whether the student would drop out using that course record alone. The personal data record would be classified using the personal data classifier. Then all the class record predictions along with the personal information record prediction would be voted together. This voting could be done in a number of different ways, but most likely would take into account how accurate the classifiers are and how certain the classifier was of the vote. Clearly this scheme allows for more complicated classification patterns than aggregation, yet there is a lot of extra complexity involved. Also if the voting is not performed well, accuracy can easily suffer.
So I am looking for other possible solutions to the classification of data with a one to many relationship.
| 0 | 0 | 0 | 1 | 0 | 0 |
I've been trying back and forth, but I can't figure out the math on how to scroll my view (or rather offset all objects) when using the flick gesture. I would like the scrolling to have some kind of ease-out.
public override void Update(GameTime gameTime, bool otherScreenHasFocus, bool coveredByOtherScreen)
{
float elapsed = (float)gameTime.ElapsedGameTime.TotalSeconds;
//Some math to change 'matrixOffsetY'
//I use 'matrixOffsetY' to offset my objects in Draw()
base.Update(gameTime, otherScreenHasFocus, coveredByOtherScreen);
}
Here's the gesture event
public override void HandleInput(InputState input)
{
if (input == null)
throw new ArgumentNullException("input");
while (TouchPanel.IsGestureAvailable)
{
GestureSample gesture = TouchPanel.ReadGesture();
switch (gesture.GestureType)
{
case GestureType.Flick:
{
//Set a variable with some math? Using:
//gesture.Delta
//gesture.Delta gives us pixels/sec
break;
}
default: return;
}
}
}
This shouldn't be that hard, but I have a brain-freeze :) Please help me out!
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm brushing up on my software testing theory and came across an interesting phenomenon called the Oracle problem. I've picked up bits and pieces as to what the problem alludes to but haven't yet pieced it all together.
One rather dark version of the problem goes a little something like this:
An island has 100 inhabitants. Each of the inhabitants has either green or blue eyes. None of the inhabitants are allowed to communicate with each other to let them know what color eyes they have, nor are there any reflective surfaces in which the inhabitants can see their own eye colors. Basically everyone knows what color eyes everyone has but none of them know what color eyes they themselves have. The rule on the island is that if you find out that you have blue eyes you must kill yourself. The island's population remains stable until one day an oracle arrives and tells the inhabitants that some people on the island have blue eyes.
The question is what happens to the people?
An answer I found is that 100 days later the last person on the island kills themselves.
I have no clue how this makes sense and I was hoping that someone could help relate this problem back to software testing. Thanks for coming on the journey and I look forward to some interesting responses.
| 0 | 0 | 0 | 0 | 1 | 0 |
This is hopefully a very simple maths question. If I have two number ranges, what is the simplest and most efficient way to check if they clash, eg:
10-20 and 11-14 // clash as B is contained in A
11-15 and 20-22 // don't clash
24-26 and 20-30 // clash as A is contained in B
15-25 and 20-30 // clash as they overlap at each end
I currently have this mess, but there must be a much simpler way to do this check:
$clash = ($b1 >= $a1 && $b1 <= $a2)
|| ($b2 >= $a1 && $b2 <= $a2)
|| ($a1 >= $b1 && $a1 <= $b2)
|| ($a2 >= $b1 && $a2 <= $b2);
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a value from 0 to 200 where 0 is better quality and 200 the worst quality.
How could I convert (In obj-c/cocoa framework) that to an integer from 0-5 being 5 best?.
For example 200 would be 0 and 0 would be 5.
| 0 | 0 | 0 | 0 | 1 | 0 |
I want to draw a plane which is given by the equation: Ax+By+Cz+D=0.
I first tried to draw him by setting x,y and then get z from the equation. this did not work fine because there are some planes like 0x+0y+z + 0 = 0 and etc...
my current solution is this:
- draw the plane on ZY plane by giving 4 coordinates which goes to infinity.
- find out to rotation that should be done in order to bring the normal of the given plane(a,b,c) to lay
on z axis.
- find the translation that should be done in order for that plane be on x axis.
- make the exactly opposite transformation to those rotation and to this translation hence i will get the
plane in his place.
ok
this is a great thing but I can make the proper math calculations(tried a lot of times...) with the dot product and etc....
can someone help me in understanding the exact way it should be done OR give me some formula in which I will put ABCD and get the right transformation?
| 0 | 0 | 0 | 0 | 1 | 0 |
Suppose I have 10 points. I know the distance between each point.
I need to find the shortest possible route passing through all points.
I have tried a couple of algorithms (Dijkstra, Floyd Warshall,...) and they all give me the shortest path between start and end, but they don't make a route with all points on it.
Permutations work fine, but they are too resource-expensive.
What algorithms can you advise me to look into for this problem? Or is there a documented way to do this with the above-mentioned algorithms?
| 0 | 1 | 0 | 0 | 0 | 0 |
I have output like this:
LL= [['a', 2, 3, 4, 13], ['b', 6, 7, 8, 13], ['c', 10, 11, 12, 13]]
Instead of "13", I would like to get maximum of elements by "row" using 2, 3 ,4
where ['a', 2, 3, 4, 13] would be 4
['b', 6, 7, 8, 13], would be 8.
EDIT: I need to replace "13" with the max value.
Then add "14" after 13
for row in LL: row[5:6] = [14]
then replace "14" with a another inter row math..
How can I do this... these are tables but not matrices.
Should use Numpy?
Ref please so I can look up.
| 0 | 0 | 0 | 0 | 1 | 0 |
I want to iterate over a fairly large collection of records in console, divide their date by half of the time since from Time.now and save it. So say records with created_at two months ago would now be 1 month old, 1 day becomes 12 hours etc.
This doesn't work but just for example:
Log.all.each{|l| l.created_at = l.created_at - (Time.now - l.created_at * 0.5); l.save}
| 0 | 0 | 0 | 0 | 1 | 0 |
I've been wondering how programs like mathematica and mathlab, and so on, plot graphs of functions so gracefully and fast. Can anyone explain to me how they do this and, furthermore, how I can do this? Is it related to an aspect or course in Computer Programming or Math? Which then?
| 0 | 0 | 0 | 0 | 1 | 0 |
What is the best turnkey (ready to use, industrial-strength) relation detection library?
I have been playing around with NLTK and the results I get are not very satisfactory.
http://nltk.googlecode.com/svn/trunk/doc/book/ch07.html
http://nltk.googlecode.com/svn/trunk/doc/howto/relextract.html
Ideally, I would like a library that can take sentences like:
"Sarah killed a wolf that was eating a child"
and turn it into a data structure that means something like:
killed(Sarah, wolf) AND eating(wolf,child)
I know that this is the subject of a large body of research and that it is not an easy task. That said, is anyone aware of a reasonably robust ready-to-use library for detecting relations?
| 0 | 1 | 0 | 0 | 0 | 0 |
I have a bookmarking feature on my site, when the person clicks a paragraph, the box that is already hovering over that paragraph that reads "bookmark this" inserts "sweet man" in place of "bookmark this". so 'bookmark this' disappears and "sweet man" takes its place, how would i make it so when i click on the paragraph, it places 1 of 3 random phrases in there, lets say the 3 phrases are "success", "sweet man", and "awesome". here's a little bit of my code to show you where the random phrase would be placed.
$('p').click(function (e) {
var offset = $(this).offset();
var top = offset.top
if ($('#placeBookmark').hasClass('placing')) {
$('#placeBookmark').trigger('click')
$('#bookmark').css({left: offset.left - 30, top: top}).show();
$('#bookmarkThis').html('***SWEET MAN.***').delay(1000).fadeOut(400, function(){
$(this).html('BOOKMARK THIS')
})
}
});
See where in my code it says "SWEET MAN.", that's where the 1 of 3 random phrases should be placed after the user clicks the paragraph.
THANK-YOU
| 0 | 0 | 0 | 0 | 1 | 0 |
This code is fully functional in its job of revealing and hiding containers however the calculations are producing NaN. I have never tried Maths with JQuery before so prehaps one of you can show me where I have wrong.
function product_analysis_global() {
$(':checked').each(function(){
$('#product_' + this.alt).css('display','block');
$('#product_quantity_PRI_' + this.alt).val(this.value);
var quantity = $('#product_quantity_PRI_' + this.alt).val;
var price = $('#product_price_PRI_' + this.alt).val;
var duration = $('#product_duration_PRI_' + this.alt).val;
var dives = $('#product_dives_PRI_' + this.alt).val;
var hire = $('#product_quantity_PRI_' + this.alt).val;
$('#product_price_total_PRI_' + this.alt).val(price * quantity);
$('#product_duration_total_PRI_' + this.alt).val(duration * quantity);
$('#product_dives_total_PRI_' + this.alt).val(dives * quantity);
$('#product_hire_total_PRI_' + this.alt).val(hire * quantity);
});
$(':not(:checked)').each(function(){
$('#product_' + this.alt).css('display','none');
$('#product_quantity_PRI_' + this.alt).val('0');
var quantity = $('#product_quantity_PRI_' + this.alt).val;
var price = $('#product_price_PRI_' + this.alt).val;
var duration = $('#product_duration_PRI_' + this.alt).val;
var dives = $('#product_dives_PRI_' + this.alt).val;
var hire = $('#product_quantity_PRI_' + this.alt).val;
$('#product_price_total_PRI_' + this.alt).val(price * quantity);
$('#product_duration_total_PRI_' + this.alt).val(duration * quantity);
$('#product_dives_total_PRI_' + this.alt).val(dives * quantity);
$('#product_hire_total_PRI_' + this.alt).val(hire * quantity);
});
}
Marvellous
| 0 | 0 | 0 | 0 | 1 | 0 |
I am using Delphi 2007 and working on some presentation software. The current module I am working on is the transition filter for video. The transition code I am using (TPicShow's PSEffects unit) requires and X and a Y value based on the dimensions of the frame and the progress of the transition. Here is the code
Type
TPercent = 0..100;
var
ATo : TBitmap; //
Prog : Integer; //Progress of the transition
if ATo.Width >= ATo.Height then
begin
X := MulDiv(ATo.Width, Prog, High(TPercent));
Y := MulDiv(X, ATo.Height, ATo.Width);
end
else
begin
Y := MulDiv(ATo.Height, Prog, High(TPercent));
X := MulDiv(Y, ATo.Width, ATo.Height);
end;
I am trying to optimize this and saw that I could save the calculations that would be constant (until the dimensions of ATo change) and remove 2 division calculations each frame.
So it would be something like
{All of these are calculated when the dimensions of ATo Change}
WDP : real; // width divided by High(TPercent)
HDW : real; // Height divided by width
HDP : real; // Height divided by High(TPercent)
WDH : real; // Width divided by Height
if ATo.Width >= ATo.Height then
begin
X := Trunc(WDP * Prog);
Y := Trunc(HDW * X);
end
else
begin
Y := Trunc(HDP * Prog);
X := Trunc(WDH * Y);
end;
It sounds good but not having the actual code of MulDiv I cant be sure. If it simply does (very simplified)
MulDiv(a,b,c : Integer)
begin
Round((A*B)/C);
end
Then I know my change will be more efficient, however if MulDiv does anything very cool with optimizing the function (Which I'd thing it might) then I'm not sure if my change would net me anything.
Would my change be more efficient?
EDIT: I have not yet implemented this, I'm just entertaining the notion.
| 0 | 0 | 0 | 0 | 1 | 0 |
I've been working on this for the past several days and have been stuck. I need to be able to touch the screen and return the x,y,z coordinates of the point on my model closest to the near plane that intersects the ray generated at the pick point. I think part of my problem is I'm doing a bunch of matrix transformations and rotations throughout the render code for my model, although the geometry I'm interested in is all rendered at a specific transformation state. My code that I'm using is below. If anyone can help me figure out how to get this working, that would be awesome. checkCollision() is fed the point that the user clicks on, and gluUnProject() is supposed to transform my 2d pick point into 3D coordinates on my near and far planes, 0 being the near plane and 1 being the far plane. My usage is here and is called right before the geometry is rendered, so all transforms have already been applied:
[self checkCollision:touchPoint panVector:panVec];
This code below is the collision checking code:
-(Boolean) checkCollision:(CGPoint)winPos panVector:(Vector3f*)panVec
{
glGetIntegerv(GL_VIEWPORT, viewport);
winPos.y = (float)viewport[3] - winPos.y;
Vector3f nearPoint;
Vector3f farPoint;
glGetFloatv(GL_PROJECTION_MATRIX, projection);
glGetFloatv(GL_MODELVIEW_MATRIX, modelview);
//Retreiving position projected on near plane
gluUnProject(winPos.x, winPos.y , 0, modelview, projection, viewport, &nearPoint.x, &nearPoint.y, &nearPoint.z);
//Retreiving position projected on far plane
gluUnProject(winPos.x, winPos.y, 1, modelview, projection, viewport, &farPoint.x, &farPoint.y, &farPoint.z);
Vector3f *near = [[Vector3f alloc] initWithFloatsX:nearPoint.x Y:nearPoint.y Z:nearPoint.z];
Vector3f *far = [[Vector3f alloc] initWithFloatsX:farPoint.x Y:farPoint.y Z:farPoint.z];
Vector3f *d = [Vector3f subtractV1:far minusV2:near];
Vector3f *v0 = [[Vector3f alloc] init];
Vector3f *v1 = [[Vector3f alloc] init];
Vector3f *v2 = [[Vector3f alloc] init];
Vector3f *e1; // = [[Vector3f alloc] init];
Vector3f *e2; // = [[Vector3f alloc] init];
for (int i = 0; i < assemblyObj->numObjects; i++) {
for (int j = 0; j < assemblyObj->partList[i].numVertices; j+=18) {
v0.x = assemblyObj->partList[i].vertices[j+0];
v0.y = assemblyObj->partList[i].vertices[j+1];
v0.z = assemblyObj->partList[i].vertices[j+2];
v1.x = assemblyObj->partList[i].vertices[j+6];
v1.y = assemblyObj->partList[i].vertices[j+7];
v1.z = assemblyObj->partList[i].vertices[j+8];
v2.x = assemblyObj->partList[i].vertices[j+12];
v2.y = assemblyObj->partList[i].vertices[j+13];
v2.z = assemblyObj->partList[i].vertices[j+14];
e1 = [Vector3f subtractV1:v1 minusV2:v0];
e2 = [Vector3f subtractV1:v2 minusV2:v0];
Vector3f *p = [[Vector3f alloc] init];
[Vector3f cross:p V1:d V2:e2];
float a = [Vector3f dot:e1 V2:p];
if (a > -.000001 && a < .000001) {
continue;
}
float f = 1/a;
Vector3f *s = [Vector3f subtractV1:near minusV2:v0];
float u = f*([Vector3f dot:s V2:p]);
if (u<0 || u>1) {
continue;
}
Vector3f *q = [[Vector3f alloc] init];
[Vector3f cross:q V1:s V2:e1];
float v = f*([Vector3f dot:d V2:q]);
if (v<0 || (u+v)>1) {
continue;
}
//NSLog(@"hit polygon");
return true;
}
}
//NSLog(@"didn't hit polygon");
return FALSE;
}
GLint gluUnProject(GLfloat winx, GLfloat winy, GLfloat winz,
const GLfloat model[16], const GLfloat proj[16],
const GLint viewport[4],
GLfloat * objx, GLfloat * objy, GLfloat * objz)
{
/* matrice de transformation */
GLfloat m[16], A[16];
GLfloat in[4], out[4];
/* transformation coordonnees normalisees entre -1 et 1 */
in[0] = (winx - viewport[0]) * 2 / viewport[2] - 1.f;
in[1] = (winy - viewport[1]) * 2 / viewport[3] - 1.f;
in[2] = 2 * winz - 1.f;
in[3] = 1.f;
/* calcul transformation inverse */
matmul(A, proj, model);
invert_matrix(A, m);
/* d'ou les coordonnees objets */
transform_point(out, m, in);
if (out[3] == 0.f)
return GL_FALSE;
*objx = out[0] / out[3];
*objy = out[1] / out[3];
*objz = out[2] / out[3];
return GL_TRUE;
}
void transform_point(GLfloat out[4], const GLfloat m[16], const GLfloat in[4])
{
#define M(row,col) m[col*4+row]
out[0] =
M(0, 0) * in[0] + M(0, 1) * in[1] + M(0, 2) * in[2] + M(0, 3) * in[3];
out[1] =
M(1, 0) * in[0] + M(1, 1) * in[1] + M(1, 2) * in[2] + M(1, 3) * in[3];
out[2] =
M(2, 0) * in[0] + M(2, 1) * in[1] + M(2, 2) * in[2] + M(2, 3) * in[3];
out[3] =
M(3, 0) * in[0] + M(3, 1) * in[1] + M(3, 2) * in[2] + M(3, 3) * in[3];
#undef M
}
void matmul(GLfloat * product, const GLfloat * a, const GLfloat * b)
{
/* This matmul was contributed by Thomas Malik */
GLfloat temp[16];
GLint i;
#define A(row,col) a[(col<<2)+row]
#define B(row,col) b[(col<<2)+row]
#define T(row,col) temp[(col<<2)+row]
/* i-te Zeile */
for (i = 0; i < 4; i++) {
T(i, 0) =
A(i, 0) * B(0, 0) + A(i, 1) * B(1, 0) + A(i, 2) * B(2, 0) + A(i,
3) *
B(3, 0);
T(i, 1) =
A(i, 0) * B(0, 1) + A(i, 1) * B(1, 1) + A(i, 2) * B(2, 1) + A(i,
3) *
B(3, 1);
T(i, 2) =
A(i, 0) * B(0, 2) + A(i, 1) * B(1, 2) + A(i, 2) * B(2, 2) + A(i,
3) *
B(3, 2);
T(i, 3) =
A(i, 0) * B(0, 3) + A(i, 1) * B(1, 3) + A(i, 2) * B(2, 3) + A(i,
3) *
B(3, 3);
}
#undef A
#undef B
#undef T
memcpy(product, temp, 16 * sizeof(GLfloat));
}
int invert_matrix(const GLfloat * m, GLfloat * out)
{
/* NB. OpenGL Matrices are COLUMN major. */
#define SWAP_ROWS(a, b) { GLfloat *_tmp = a; (a)=(b); (b)=_tmp; }
#define MAT(m,r,c) (m)[(c)*4+(r)]
GLfloat wtmp[4][8];
GLfloat m0, m1, m2, m3, s;
GLfloat *r0, *r1, *r2, *r3;
r0 = wtmp[0], r1 = wtmp[1], r2 = wtmp[2], r3 = wtmp[3];
r0[0] = MAT(m, 0, 0), r0[1] = MAT(m, 0, 1),
r0[2] = MAT(m, 0, 2), r0[3] = MAT(m, 0, 3),
r0[4] = 1.f, r0[5] = r0[6] = r0[7] = 0.f,
r1[0] = MAT(m, 1, 0), r1[1] = MAT(m, 1, 1),
r1[2] = MAT(m, 1, 2), r1[3] = MAT(m, 1, 3),
r1[5] = 1.f, r1[4] = r1[6] = r1[7] = 0.f,
r2[0] = MAT(m, 2, 0), r2[1] = MAT(m, 2, 1),
r2[2] = MAT(m, 2, 2), r2[3] = MAT(m, 2, 3),
r2[6] = 1.f, r2[4] = r2[5] = r2[7] = 0.f,
r3[0] = MAT(m, 3, 0), r3[1] = MAT(m, 3, 1),
r3[2] = MAT(m, 3, 2), r3[3] = MAT(m, 3, 3),
r3[7] = 1.f, r3[4] = r3[5] = r3[6] = 0.f;
/* choose pivot - or die */
if (fabsf(r3[0]) > fabsf(r2[0]))
SWAP_ROWS(r3, r2);
if (fabsf(r2[0]) > fabsf(r1[0]))
SWAP_ROWS(r2, r1);
if (fabsf(r1[0]) > fabsf(r0[0]))
SWAP_ROWS(r1, r0);
if (0.f == r0[0])
return GL_FALSE;
/* eliminate first variable */
m1 = r1[0] / r0[0];
m2 = r2[0] / r0[0];
m3 = r3[0] / r0[0];
s = r0[1];
r1[1] -= m1 * s;
r2[1] -= m2 * s;
r3[1] -= m3 * s;
s = r0[2];
r1[2] -= m1 * s;
r2[2] -= m2 * s;
r3[2] -= m3 * s;
s = r0[3];
r1[3] -= m1 * s;
r2[3] -= m2 * s;
r3[3] -= m3 * s;
s = r0[4];
if (s != 0.f) {
r1[4] -= m1 * s;
r2[4] -= m2 * s;
r3[4] -= m3 * s;
}
s = r0[5];
if (s != 0.f) {
r1[5] -= m1 * s;
r2[5] -= m2 * s;
r3[5] -= m3 * s;
}
s = r0[6];
if (s != 0.f) {
r1[6] -= m1 * s;
r2[6] -= m2 * s;
r3[6] -= m3 * s;
}
s = r0[7];
if (s != 0.f) {
r1[7] -= m1 * s;
r2[7] -= m2 * s;
r3[7] -= m3 * s;
}
/* choose pivot - or die */
if (fabsf(r3[1]) > fabsf(r2[1]))
SWAP_ROWS(r3, r2);
if (fabsf(r2[1]) > fabsf(r1[1]))
SWAP_ROWS(r2, r1);
if (0.f == r1[1])
return GL_FALSE;
/* eliminate second variable */
m2 = r2[1] / r1[1];
m3 = r3[1] / r1[1];
r2[2] -= m2 * r1[2];
r3[2] -= m3 * r1[2];
r2[3] -= m2 * r1[3];
r3[3] -= m3 * r1[3];
s = r1[4];
if (0.f != s) {
r2[4] -= m2 * s;
r3[4] -= m3 * s;
}
s = r1[5];
if (0.f != s) {
r2[5] -= m2 * s;
r3[5] -= m3 * s;
}
s = r1[6];
if (0.f != s) {
r2[6] -= m2 * s;
r3[6] -= m3 * s;
}
s = r1[7];
if (0.f != s) {
r2[7] -= m2 * s;
r3[7] -= m3 * s;
}
/* choose pivot - or die */
if (fabs(r3[2]) > fabs(r2[2]))
SWAP_ROWS(r3, r2);
if (0.f == r2[2])
return GL_FALSE;
/* eliminate third variable */
m3 = r3[2] / r2[2];
r3[3] -= m3 * r2[3], r3[4] -= m3 * r2[4],
r3[5] -= m3 * r2[5], r3[6] -= m3 * r2[6], r3[7] -= m3 * r2[7];
/* last check */
if (0.f == r3[3])
return GL_FALSE;
s = 1.f / r3[3]; /* now back substitute row 3 */
r3[4] *= s;
r3[5] *= s;
r3[6] *= s;
r3[7] *= s;
m2 = r2[3]; /* now back substitute row 2 */
s = 1.f / r2[2];
r2[4] = s * (r2[4] - r3[4] * m2), r2[5] = s * (r2[5] - r3[5] * m2),
r2[6] = s * (r2[6] - r3[6] * m2), r2[7] = s * (r2[7] - r3[7] * m2);
m1 = r1[3];
r1[4] -= r3[4] * m1, r1[5] -= r3[5] * m1,
r1[6] -= r3[6] * m1, r1[7] -= r3[7] * m1;
m0 = r0[3];
r0[4] -= r3[4] * m0, r0[5] -= r3[5] * m0,
r0[6] -= r3[6] * m0, r0[7] -= r3[7] * m0;
m1 = r1[2]; /* now back substitute row 1 */
s = 1.f / r1[1];
r1[4] = s * (r1[4] - r2[4] * m1), r1[5] = s * (r1[5] - r2[5] * m1),
r1[6] = s * (r1[6] - r2[6] * m1), r1[7] = s * (r1[7] - r2[7] * m1);
m0 = r0[2];
r0[4] -= r2[4] * m0, r0[5] -= r2[5] * m0,
r0[6] -= r2[6] * m0, r0[7] -= r2[7] * m0;
m0 = r0[1]; /* now back substitute row 0 */
s = 1.f / r0[0];
r0[4] = s * (r0[4] - r1[4] * m0), r0[5] = s * (r0[5] - r1[5] * m0),
r0[6] = s * (r0[6] - r1[6] * m0), r0[7] = s * (r0[7] - r1[7] * m0);
MAT(out, 0, 0) = r0[4];
MAT(out, 0, 1) = r0[5], MAT(out, 0, 2) = r0[6];
MAT(out, 0, 3) = r0[7], MAT(out, 1, 0) = r1[4];
MAT(out, 1, 1) = r1[5], MAT(out, 1, 2) = r1[6];
MAT(out, 1, 3) = r1[7], MAT(out, 2, 0) = r2[4];
MAT(out, 2, 1) = r2[5], MAT(out, 2, 2) = r2[6];
MAT(out, 2, 3) = r2[7], MAT(out, 3, 0) = r3[4];
MAT(out, 3, 1) = r3[5], MAT(out, 3, 2) = r3[6];
MAT(out, 3, 3) = r3[7];
return GL_TRUE;
#undef MAT
#undef SWAP_ROWS
}
Edit:
I followed Justin Meiners suggestion of rendering points to show me where my pick ray is getting generated and I can see what's happening now, but don't know why. My scene implements arcball rotation, zooming and panning through quaternions. I'll roughly lay out what my scene is doing then what is happening with my pick ray.
First, setup my viewport:
glViewport(0, 0, scene.width, scene.height);
glOrthof(-11.25, 11.25, -14.355, 14.355, -1000, 1000);
Next, I grab the 16 element matrix that I use as part of my arcball method to navigate my scene and multiply my modelview matrix by it:
float mat[16];
[arcball get_Renamed:mat];
glMultMatrixf(mat);
Now, I do my pick ray:
glGetIntegerv(GL_VIEWPORT, viewport);
glGetFloatv(GL_PROJECTION_MATRIX, projection);
glGetFloatv(GL_MODELVIEW_MATRIX, modelview);
touchPoint.y = (float)viewport[3] - touchPoint.y;
Vector3f nearPoint, farPoint;
//Retreiving position projected on near plane
gluUnProject(touchPoint.x, touchPoint.y , 0, modelview, projection, viewport, &nearPoint.x, &nearPoint.y, &nearPoint.z);
//Retreiving position projected on far plane
gluUnProject(touchPoint.x, touchPoint.y, 1, modelview, projection, viewport, &farPoint.x, &farPoint.y, &farPoint.z);
float coords[3] = {nearPoint.x, nearPoint.y, nearPoint.z};
float coords2[3] = {farPoint.x, farPoint.y, farPoint.z};
glPointSize(100);
glColor4f(1, 0, 0, 1);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(coords[0])*3, coords);
glDrawArrays(GL_POINTS, 0, 1);
glPointSize(150);
glColor4f(0, 0, 1, 1);
glEnableClientState(GL_VERTEX_ARRAY);
glVertexPointer(3, GL_FLOAT, sizeof(coords2[0])*3, coords2);
glDrawArrays(GL_POINTS, 0, 1);
glDisableClientState(GL_VERTEX_ARRAY);
I do this, and it works fine before I rotate my scene, but as soon as I start to rotate my scene, the far point starts to move around. If I rotate the scene around exactly 180 degrees, the far point is back in line with the near point. Any idea what is going on? The arcball is just based on Ken Shoemake's algorithm.
| 0 | 0 | 0 | 0 | 1 | 0 |
Does BigInteger only have equals for comparison?
Are there substitutes for math notation like < (greater than) or < (less than)?
^Answered!
now i want to know, is there a way using BigInteger in iteration such as while and for?
| 0 | 0 | 0 | 0 | 1 | 0 |
Everyday I struggle with algorithm questions and try to ask here which I can't answer. Excuse me, if I cause any headache. Anyway,
Here is the problem from the University of Waterloo ACM Programming Contest.
In how many ways can you tile a 3xn rectangle with 2x1 dominoes?
Nirvana : smells like recursion spirit
| 0 | 0 | 0 | 0 | 1 | 0 |
I have some random integers like
99 20 30 1 100 400 5 10
I have to find a sum from any combination of these integers that is closest(equal or more but not less) to a given number like
183
what is the fastest and accurate way of doing this?
| 0 | 0 | 0 | 0 | 1 | 0 |
If one wanted to perform the K-nearest-neighbors algorithm to do classification on images, how are features extracted from the images? What are the easiest, most effective methods?
| 0 | 0 | 0 | 1 | 0 | 0 |
Currently I'm reading Natural Language Processing for the Working Programmer (a work in progress book http://nlpwp.org/) and wondering if there is a decent library for statistical natural language processing tasks.
| 0 | 1 | 0 | 0 | 0 | 0 |
I am trying to make a 'brush' tool in AS3 (pure, not Flex) which simulates handwriting, making strokes to be smooth instead of cornered. Then, the trace must be reduced to cubic bezier curves which can be dragged and deformed, affecting the previously drawn path (like the illustrator's pen tool).
I'm tracking the mouse movement to get a set of points to draw the path. As far as I know, I need to do a B-Spline path using that set of points. Then I should reduce it to cubic bezier curves (adding the the 'pen tool' functionality to the path).
I have already developed the pen tool, using an algorithm which reduces Cubic Beziers to Quadratic Beziers (and then using the Flash curveTo function). But I have no idea how to create a B-Spline (or another simplification), an then reduce it to Bezier curves.
Do you know any way to accomplish this?
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm looking for an algorithm (or better yet, code!) for a the generation of powers, specifically numbers with an odd exponent greater than 1: third powers, fifth powers, seventh powers, and so forth. My desired output is then
8, 27, 32, 125, 128, 216, 243, 343, 512, 1000
and so forth up to a specified limit.
I don't want to store the powers in a list and sort them, because I'm making too many to fit in memory -- hopefully the limit be 1030 or so, corresponding to a memory requirement of β 1 TB.
My basic idea is to have an array holding the current number (starting at 2) for each exponent, starting with 3 and going up to the binary log of the limit. At each step I loop through the exponent array, finding the one which yields the smallest power (finding either pow(base, exponent) or more likely exponent * log(base), probably memoizing these values). At that point call the 'output' function, which will actually do calculations with the number but of course you don't need to worry about that.
Of course because of the range of the numbers involved, bignums must be used -- built into the language, in a library, or self-rolled. Relevant code or code snippets would be appreciated: I feel that this task is similar to some classic problems (e.g., Hamming's problem of generating numbers that are of the form 2x3y5z) and can be solved efficiently. I'm fairly language-agnostic here: all I'll need for my 'output' function are arrays, subtraction, bignum-word comparison, and a bignum integer square root function.
| 0 | 0 | 0 | 0 | 1 | 0 |
There are n bus stops and we know the fee between i-th and j-th stops.
It's a one-way road. What is the min price of the route from 1-st to n-th stops considering all possible connections? Time and memory consumption should be the least possible.
p.s. To give an example, say, there are 4 stops. We have such a table of prices:
. 3$ 5$ 7$
. . 1$ 3$
. . . 1$
to go from 1-st to 4-th with no stops we pay 7$. if we change routes on the second stop we pay 3$+1$ = 4$ to drive to the 3rd stop, but we pay 2$ more if we go to the end, so overall it will cost 6$, but again if we change routes on the 3-rd stop, we would pay 4+1=5$.
| 0 | 0 | 0 | 0 | 1 | 0 |
So I am learning OpenGL with as the main resource having the "Red book". I am reading about matrix algebra, rotation/scaling/transform matrices and everything is great, but I just don't get one simple thing. Let's say the function glLoadIdentity(). It sets the default matrix of 4x4. So it sets 3 vertices and 1 point: (1,0,0) (0,1,0) (0,0,1) vertices, (0,0,0) point. But my question is, what do those correspond? Generally speaking, what does a matrix correspond in OpenGL? I got an idea that these are the directions of axies. But the axies of what? The camera?
| 0 | 0 | 0 | 0 | 1 | 0 |
I am trying to get a 2d sprite to move in an "arc" (half ellipse) instead of a straight line. I have X and Y starting and ending positions as well as a desired radius.
What is the best way to implement this?
| 0 | 0 | 0 | 0 | 1 | 0 |
I have the following piece of code to calculate how far back in the future a day lies
var totalPixels = this._endX - this._startX;
var segmentPixels = this._nowX - this._startX;
var startTime = this._nowDate.getTime() - Timeline._minToMs((segmentPixels/totalPixels*this._rangeInMinutes));
//console.log(this._nowDate.getTime() + '
' + Timeline._minToMs(segmentPixels/totalPixels*this._rangeInMinutes));
this._startDate.setTime(startTime);
console.log(this._rangeInMinutes + ', ' + this._startDate.toString());
Typical values are
endX: 1037
startX: 40
nowX: 134.625
rangeInMinutes ranges from 1 to the number of minutes in a year.
minToMs simply multiplies the input by 60*1000.
My output varies from my expected output by roughly a factor of ten. Am I experiencing a rounding error, or some sort of truncation in the process of converting minutes to milliseconds?
P.S.: A fiddle of what I'm trying to do is http://jsfiddle.net/NRx9m/21/
| 0 | 0 | 0 | 0 | 1 | 0 |
I have done a method to implement the Kullback-leibler divergence in java. I have used the log with base 2 value and i am not sure whether i have used it right or i should used log base 10 value. I am using this method to measure the divergence between two text units(each of different length).
My problem is i don't get the desired divergence measure .
for example for two text units namely => "Free Ringtones" and the second one "Free Ringtones for your Mobile Phone from PremieRingtones.com"
I should get a divergence of 0.25(as of my project references) but i get a divergence of 2.0 if i use log base2 and 1.38 for log base10.
Also i am unaware of what value to substitute instead of zero value for demnominator.Plz help in giving clear explaination with some examples if possible and even some links to where i can get details.
This is My code snippet:
public Double calculateKLD(List<String> values,List<String> value2)
{
Map<String, Integer> map = new HashMap<String, Integer>();
Map<String, Integer> map2 = new HashMap<String, Integer>();
for (String sequence : values)
{
if (!map.containsKey(sequence))
{
map.put(sequence, 0);
}
map.put(sequence, map.get(sequence) + 1);
}
for (String sequence : value2)
{
if (!map2.containsKey(sequence)) {
map2.put(sequence, 0);
}
map2.put(sequence, map2.get(sequence) + 1);
}
Double result = 0.0;
Double frequency2=0.0;
for (String sequence : map.keySet())
{
Double frequency1 = (double) map.get(sequence) / values.size();
System.out.println("Freuency1 "+frequency1.toString());
if(map2.containsKey(sequence))
{
frequency2 = (double) map2.get(sequence) / value2.size();
}
result += frequency1 * (Math.log(frequency1/frequency2) / Math.log(2));
}
return result/2.4;
}
My Input is like this
First text unit
list.add("Free");list.add("Ringtones");
Second text unit
list2.add("Free");list2.add("Ringtones");list2.add("for");list2.add("your");list2.add("Mobiile");list2.add("Phone");list2.add("from");list2.add("PremieRingtones.com");
Calling function
calculateKLD(list, list2)
| 0 | 1 | 0 | 0 | 1 | 0 |
So I am adding and subtracting floats in javascript, and I need to know how to always take the ceiling of any number that has more than 3 decimal places. For example:
3.19 = 3.19
3.191 = 3.20
3.00000001 = 3.01
| 0 | 0 | 0 | 0 | 1 | 0 |
I have some environmental sensors and I want to detect sudden changes in temperature, and slow trends over time... however I'd like to do most of the math based on what's in memory with parameters that may look like this: (subject to change)
(note: Items in parens are computed in realtime as data is added)
5 minute (derivative, max, min, avg) + 36 datapoints for most current 3 hours
10 minute (derivative, max, min, avg) + 0 datapoints, calc is based on 5min sample
30 minute (derivative, max, min, avg) + 0 datapoints, calc is based on 5 min sample
Hourly (derivative, max, min, avg) + 24 datapoints for most current 1 day
Daily (derivative, max,min,avg) + 32 datapoints for most current month
Monthly (derivative, max,min,avg) + 12 datapoints for past year
Each datapoint is a two byte float. So each sensor will consume up to 124 Floats, plus the 24 calculated variables. I'd like to support as many sensors as the .NET embededd device will permit.
Since I'm using an embedded device for this project, my memory is constrained and so is my IO and CPU power.
How would you go about implementing this in .NET? So far, I've created a couple of structs and called it a "TrackableFloat" where the insertion of a value causes the old one to drop off the array and a recalculation is done.
The only thing that makes this more
complicated than it would be, is that
for any sensor does not report back
data, then that datapoint needs to be
excluded/ignored from all subsequent
realtime calulations.
When all is said and done, if any of the values: (derivative, max,min,avg) reach a pre defined setting, then a .NET event fires
I think someone out there will think this is an interesting problem, and would love to hear how they would approach implementing it.
Would you use a Class or a Struct?
How would you trigger the calculations? (Events most likely)
How would the alerts be triggered?
How would you store the data, in tiers?
Is there a library that already does something like this? (maybe that should be my first question )
How would you efficiently calculate the derivative?
Here is my first crack at this, and it doesn't completely hit the spec, but is very efficient. Would be interested in hearing your thoughts.
enum UnitToTrackEnum
{
Minute,
FiveMinute,
TenMinute,
FifteenMinute,
Hour,
Day,
Week,
Month,
unknown
}
class TrackableFloat
{
object Gate = new object();
UnitToTrackEnum trackingMode = UnitToTrackEnum.unknown;
int ValidFloats = 0;
float[] FloatsToTrack;
public TrackableFloat(int HistoryLength, UnitToTrackEnum unitToTrack)
{
if (unitToTrack == UnitToTrackEnum.unknown)
throw new InvalidOperationException("You must not have an unknown measure of time to track.");
FloatsToTrack = new float[HistoryLength];
foreach (var i in FloatsToTrack)
{
float[i] = float.MaxValue;
}
trackingMode = unitToTrack;
Min = float.MaxValue;
Max = float.MinValue;
Sum = 0;
}
public void Add(DateTime dt, float value)
{
int RoundedDTUnit = 0;
switch (trackingMode)
{
case UnitToTrackEnum.Minute:
{
RoundedDTUnit = dt.Minute;
break;
}
case UnitToTrackEnum.FiveMinute:
{
RoundedDTUnit = System.Math.Abs(dt.Minute / 5);
break;
}
case UnitToTrackEnum.TenMinute:
{
RoundedDTUnit = System.Math.Abs(dt.Minute / 10);
break;
}
case UnitToTrackEnum.FifteenMinute:
{
RoundedDTUnit = System.Math.Abs(dt.Minute / 15);
break;
}
case UnitToTrackEnum.Hour:
{
RoundedDTUnit = dt.Hour;
break;
}
case UnitToTrackEnum.Day:
{
RoundedDTUnit = dt.Day;
break;
}
case UnitToTrackEnum.Week:
{
//RoundedDTUnit = System.Math.Abs( );
break;
}
case UnitToTrackEnum.Month:
{
RoundedDTUnit = dt.Month;
break;
}
case UnitToTrackEnum.unknown:
{
throw new InvalidOperationException("You must not have an unknown measure of time to track.");
}
default:
break;
}
bool DoRefreshMaxMin = false;
if (FloatsToTrack.Length < RoundedDTUnit)
{
if (value == float.MaxValue || value == float.MinValue)
{
// If invalid data...
lock (Gate)
{
// Get rid of old data...
var OldValue = FloatsToTrack[RoundedDTUnit];
if (OldValue != float.MaxValue || OldValue != float.MinValue)
{
Sum -= OldValue;
ValidFloats--;
if (OldValue == Max || OldValue == Min)
DoRefreshMaxMin = true;
}
// Save new data
FloatsToTrack[RoundedDTUnit] = value;
}
}
else
{
lock (Gate)
{
// Get rid of old data...
var OldValue = FloatsToTrack[RoundedDTUnit];
if (OldValue != float.MaxValue || OldValue != float.MinValue)
{
Sum -= OldValue;
ValidFloats--;
}
// Save new data
FloatsToTrack[RoundedDTUnit] = value;
Sum += value;
ValidFloats++;
if (value < Min)
Min = value;
if (value > Max)
Max = value;
if (OldValue == Max || OldValue == Min)
DoRefreshMaxMin = true;
}
}
// Function is placed here to avoid a deadlock
if (DoRefreshMaxMin == true)
RefreshMaxMin();
}
else
{
throw new IndexOutOfRangeException("Index " + RoundedDTUnit + " is out of range for tracking mode: " + trackingMode.ToString());
}
}
public float Sum { get; set; }
public float Average
{
get
{
if (ValidFloats > 0)
return Sum / ValidFloats;
else
return float.MaxValue;
}
}
public float Min { get; set; }
public float Max { get; set; }
public float Derivative { get; set; }
public void RefreshCounters()
{
lock (Gate)
{
float sum = 0;
ValidFloats = 0;
Min = float.MaxValue;
Max = float.MinValue;
foreach (var i in FloatsToTrack)
{
if (i != float.MaxValue || i != float.MinValue)
{
if (Min == float.MaxValue)
{
Min = i;
Max = i;
}
sum += i;
ValidFloats++;
if (i < Min)
Min = i;
if (i > Max)
Max = i;
}
}
Sum = sum;
}
}
public void RefreshMaxMin()
{
if (ValidFloats > 0)
{
Min = float.MaxValue;
Max = float.MinValue;
lock (Gate)
{
foreach (var i in FloatsToTrack)
{
if (i != float.MaxValue || i != float.MinValue)
{
if (i < Min)
Min = i;
if (i > Max)
Max = i;
}
}
}
}
}
}
| 0 | 0 | 0 | 0 | 1 | 0 |
I am trying to implement panning using Google's static image api, but don't really know where to start.
Given:
lat,lng = 36.059534,-94.171257 of the center of the image
zoom level = 19
image size = 400x400
Question:
How do I calculate the lat,lng of the upper left and lower right corners of the image?
| 0 | 0 | 0 | 0 | 1 | 0 |
Does the method for computing the cross-product change for left handed coordinates?
| 0 | 0 | 0 | 0 | 1 | 0 |
I want to check if a line (or any point of a line) is within a rectangle or intersects a rectangle.
I have (x0, y0) and (x1, y1) as starting and ending points of a line.
Also, (ax,ay) and (bx,by) as the top-left and bottom-right points of a rectangle
For example,
____________
| |
---|----- | Result: true
| |
|____________|
/
_/__________
|/ |
/ | Result: true
/| |
|____________|
____________
| |
| -------- | Result: true
| |
|____________| ---------- Result: false
Can anyone suggest how to do this? I dont want to know which point is that, i just want to know if its there or not.
Thanks a lot for help
| 0 | 0 | 0 | 0 | 1 | 0 |
All the methods in System.Math takes double as parameters and returns parameters. The constants are also of type double. I checked out MathNet.Numerics, and the same seems to be the case there.
Why is this? Especially for constants. Isn't decimal supposed to be more exact? Wouldn't that often be kind of useful when doing calculations?
| 0 | 0 | 0 | 0 | 1 | 0 |
Let's imagine, I have two English language texts written by the same person.
Is it possible to apply some Markov chain algorithm to analyse each: create some kind of fingerprint based on statistical data, and compare fingerprints gotten from different texts?
Let's say, we have a library with 100 texts. Some person wrote text number 1 and some other as well, and we need to guess which one by analyzing his/her writing style.
Is there any known algorithm doing it? Can be Markov chains applied here?
| 0 | 1 | 0 | 1 | 0 | 0 |
The project is about translating semi-natural language to SQL tables. The code:
label(S) --> label_h(C), {atom_codes(A, C), string_to_atom(S, A)}, !.
label_h([C|D]) --> letter(C), letters_or_digits(D), !.
letters_or_digits([C|D]) --> letter_or_digit(C), letters_or_digits(D), !.
letters_or_digits([C]) --> letter_or_digit(C), !.
letters_or_digits([]) --> "", !.
letter(C) --> [C], {"a"=<C, C=<"z"}, !.
letter(C) --> [C], {"A"=<C, C=<"Z"}, !.
letter_or_digit(C) --> [C], {"a"=<C, C=<"z"}, !.
letter_or_digit(C) --> [C], {"A"=<C, C=<"Z"}, !.
letter_or_digit(C) --> [C], {"0"=<C, C=<"9"}, !.
table("student").
sbvr2sql --> label(Name), " is an integer.", {assert(fields(Name, "INT"))}.
sbvr2sql --> label(Name), " is a string.", {assert(fields(Name, "VARCHAR(64)"))}.
sbvr2sql(Table, Property) --> label(Table), " has ", label(Property), ".".
Here is how it works fine:
?- sbvr2sql("age is an integer.", []).
true
?- sbvr2sql("firstName is a string.", []).
true.
?- sbvr2sql(T, P, "student has firstName.", []).
T = "student",
P = "firstName".
?- fields(F, T).
F = "age",
T = [73, 78, 84] n
F = "firstName",
T = [86, 65, 82, 67, 72, 65, 82, 40, 54|...].
?- sbvr2sql(T, P, "student has firstName.", []), fields(P, _).
T = "student",
P = "firstName".
But it doesn't work here:
?- table(T).
T = [115, 116, 117, 100, 101, 110, 116]. % "student"
?- sbvr2sql(T, P, "student has firstName.", []), table(T).
false.
Apparently it doesn't recognise table("student") as true. It recognises "student" as a label as seen above. What gives?
| 0 | 1 | 0 | 0 | 0 | 0 |
If a = 15 and 152 is represented as a2 while 215 is represented as 2a then a number x has to be found such that
8x = 8*x8
I tried this naive Python code
>>> i = 0
>>> while(i<=100000000000000000):
... if(int("8"+str(i))==8*int(str(i)+"8")):
... break
... i = i+1
... print i
but it is taking a huge amount of time to produce a correct result.
How to optimize the code?
| 0 | 0 | 0 | 0 | 1 | 0 |
Found this puzzle inside an image. According to my thinking the total number of ways should be
2*comb(7,i) for i <- 1 to 7 where comb is defined as follows. Is my approach correct? I am concerned with the result that I get and not the function written below.
def comb(N,k):
if (k > N) or (N < 0) or (k < 0):
return 0L
N,k = map(long,(N,k))
top = N
val = 1L
while (top > (N-k)):
val *= top
top -= 1
n = 1L
while (n < k+1L):
val /= n
n += 1
return val
Don't mind me asking too many questions in a short time period. I am just enthusiastic.
| 0 | 0 | 0 | 0 | 1 | 0 |
Anyone knows a source, website where I can get some good implementations of 3D intersection algorithms, like
intersection of sphere and sphere
sphere/ellipsoid
sphere/cuboid
ellipsoid/ellipsoid
ellipsoid/cuboid
cuboid/cuboid
sphere/ray
ellipsoid/ray
cuboid/ray
triangle/ray
quad/ray
triangle/triangle
quad/quad
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm currently using a 3x3 rotation matrix to work with 3D points.
How does this matrix differ from a 4x4 Matrix?
And how do I convert a 3x3 matrix into a 4x4?
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a simple class that contains three unsigned integer fields: a whole value, a numerator, and a denominator, representing a mixed number of the form:
<Whole> <Num>/<Den> // e.g. 3 1/2
I'd like to be able to multiply instances of these classes with each other, but since my main app uses relatively large numbers, I'm concerned about overflow. Is there an algorithm for performing this kind of multiplication that minimizes the potential for multiplication overflow?
I'm OK with having overflow if it's unavoidable, what I'm looking for is for a way to "intelligently" multiply to avoid having overflow if it's possible.
| 0 | 0 | 0 | 0 | 1 | 0 |
Given:
F(F(n)) = n
F(F(n + 2) + 2) = n
F(0) = 1
where n is a non-negative integer. F(129) = ?
How can we solve such kind of functional equations programmatically? My programming language of choice is Python.
| 0 | 0 | 0 | 0 | 1 | 0 |
Picking up from where we left...
So I can use linalg.eig or linalg.svd to compute the PCA. Each one returns different Principal Components/Eigenvectors and Eigenvalues when they're fed the same data (I'm currently using the Iris dataset).
Looking here or any other tutorial with the PCA applied to the Iris dataset, I'll find that the Eigenvalues are [2.9108 0.9212 0.1474 0.0206]. The eig method gives me a different set of eigenvalues/vectors to work with which I don't mind, except that these eigenvalues, once summed, equal the number of dimensions (4) and can be used to find how much each component contributes to the total variance.
Taking the eigenvalues returned by linalg.eig I can't do that. For example, the values returned are [9206.53059607 314.10307292 12.03601935 3.53031167]. The proportion of variance in this case would be [0.96542969 0.03293797 0.00126214 0.0003702]. This other page says that ("The proportion of the variation explained by a component is just its eigenvalue divided by the sum of the eigenvalues.")
Since the variance explained by each dimension should be constant (I think), these proportions are wrong. So, if I use the values returned by svd(), which are the values used in all tutorials, I can get the correct percentage of variation from each dimension, but I'm wondering why the values returned by eig can't be used like that.
I assume the results returned are still a valid way to project the variables, so is there a way to transform them so that I can get the correct proportion of variance explained by each variable? In other words, can I use the eig method and still have the proportion of variance for each variable? Additionally, could this mapping be done only in the eigenvalues so that I can have both the real eigenvalues and the normalized ones?
Sorry for the long writeup btw. Here's a (::) for having gotten this far. Assuming you didn't just read this line.
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm looking for an algorithm that can find/assign order and overlap given a list of ordered elements and a list of unordered elements. (of which overlap might or might not exist).
For this example I'll use the integers but they could just as well be peoples names, ID codes etc. IE the number can't be used to solve the real problem but to help explain the problem I used the ordered set (1,2,3,4,5,6,7,8,9,10) as the holy grail answer.
Input:
Ordered List of Lists: (1,2,3,4), (8,9,10), (3,4,5)
UnOrdered List of Lists: (3,4,2), (6,4,5,7), (10,9)
Thought process in how I do this algorithm in my head:
list 3,4,5 and 1,2,3,4 are ordered and have 3,4 in common therefore the 2 ordered lists overlap to form: 1,2,3,4,5 in that order.
The unordered list 3,4,2 is a subset of ordered list 1,2,3,4,5 therefor it could be reordered as 2,3,4 and said to overlap the ordered list 1,2,3,4,5
Same idea (as step 2) for the ordered list 8,9,10 when compared with the unordered 10,9. It should be 9,10 overlapped with 8,9,10.
Now comparing ordered list 1,2,3,4,5 and the unordered 6,4,5,7 they have an intersection set of 4,5 so you could conclude that its 1,2,3,4,5,(6,7|7,6) where (6,7|7,6) means that its either a 6 followed by a 7 or a 7 followed by a 6 (but its unknown which is correct)
Output:
I would like to beable to parse a matrix/tree/whatever kind of data structure to see what overlapped where and in what order
and a summarized list containing sets of partially known order
set1: 1,2,3,4,5,(6,7|7,6)
set2: 2: 8,9,10
Does anyone know of a similar problem or algorithm I could use? Ideally it would be in Perl but pseudo code or algorithms from another language would be fine.
Thanks
| 0 | 0 | 0 | 0 | 1 | 0 |
I would like to do the following using the MapKit in iOS.
I want to place a position on a map and draw a circle around it where the diameter of the circle represents a range. This circle should have a solid color with an alpha of 25%. Much like the circle you get around your own position using google maps when the position is not accurate enough. Deciding how large the circle should be could either be using an extra view or using pinching.
How can I do this?
| 0 | 0 | 0 | 0 | 1 | 0 |
with naming variables i'd like to be as clear as possible.
a percentage can range from 0 and 100. my public variable only accepts values between 0.0 and 1.0, so naming it a "percentage" can lead to confusion and simply naming it a "value" will not clarify the range limit.
is there a "percent" equivalent or naming convention for variables representing values that range from 0.0 and 1.0?
| 0 | 0 | 0 | 0 | 1 | 0 |
The following code
console.log(Math.pow(2, 53));
console.log(Math.pow(2, 53) + 1);
produces exactly same output for both calculations:
9007199254740992
Why?
| 0 | 0 | 0 | 0 | 1 | 0 |
According to http://www.html5samples.com/2010/03/html-5-canvas-the-2d-context-part-1/
This is the signature for the context.transform method
context.transform(m11, m12, m21, m22, dx, dy) is to multiply the current transformation matrix with the matrix described by:
m11 m21 dx
m12 m22 dy
0 0 1
I am trying to figure out what is the logic behind this signature? Why can't you set all the elements of the matrix and why are the arguments listed in column order instead of row order?
| 0 | 0 | 0 | 0 | 1 | 0 |
The code below solves the 1D heat equation that represents a rod whose ends are kept at zero temparature with initial condition 10*np.sin(np.pi*x).
How are the Dirichlet boundary conditions (zero temp at both ends) worked into this calculation? I was told the upper, lower rows of matrix A contain two non-zero elements, and the missing third element is the Dirichlet condition. But I do not understand by which mechanism this condition affects the calculation. With missing elements in A, how can u_{0} or u_{n} be zero?
The finite difference method below uses Crank-Nicholson.
import numpy as np
import scipy.linalg
# Number of internal points
N = 200
# Calculate Spatial Step-Size
h = 1/(N+1.0)
k = h/2
x = np.linspace(0,1,N+2)
x = x[1:-1] # get rid of the '0' and '1' at each end
# Initial Conditions
u = np.transpose(np.mat(10*np.sin(np.pi*x)))
# second derivative matrix
I2 = -2*np.eye(N)
E = np.diag(np.ones((N-1)), k=1)
D2 = (I2 + E + E.T)/(h**2)
I = np.eye(N)
TFinal = 1
NumOfTimeSteps = int(TFinal/k)
for i in range(NumOfTimeSteps):
# Solve the System: (I - k/2*D2) u_new = (I + k/2*D2)*u_old
A = (I - k/2*D2)
b = np.dot((I + k/2*D2), u)
u = scipy.linalg.solve(A, b)
| 0 | 0 | 0 | 0 | 1 | 0 |
I've to implement text classification for a long list of words. I've some categories defined e.g. If the word "UK" is in the list, it will come under "Regions". If the word is "Pizza", it will come under category "food".
How can I classify the words under different categories? Is there any open source tool available to do that?
| 0 | 1 | 0 | 0 | 0 | 0 |
How can i write a regular expression to describe this language :
| 0 | 0 | 0 | 0 | 1 | 0 |
If R(x) is a random function, is R(x) || R(x') also a random function ?
R(x) is random in the true sense.
x is a bit string over 0s and 1s.
x' is complement of x.
|| is the simple concatenation
Edit :
This R(x) is selected randomly from the family of functions {0,1}^k -> {0,1)^k. Once R(x) has been chosen, it gets fixed. Thus Same input will generate same output. Length of R(x) is fixed (k, say 32)
G(x) = R(x) || R(x')
| 0 | 0 | 0 | 0 | 1 | 0 |
I've written a simple mandelbrot fractal generator (pretty pics available upon request :)
The problem I'm running into is that when I "zoom in" far enough, the image starts to pixelate. After a bit of investigation, this seems to be caused by hitting the precision limit of the double type used by System.Numerics.Complex to store the real and imaginary values used in my calculations.
Is there any other type I can use or another way to gain greater precision (presumably at the expense of more memory)
Failing that, is there an easy way I can determine the maximum precision of a double and disable zoom functionality if the zoom would result in pixelation?
Thanks in advance for any help you can provide
| 0 | 0 | 0 | 0 | 1 | 0 |
Last week I participated in round 1b of the Facebook Hacker cup.
One of the problems was basically the Josephus problem
I've studied the Josephus problem before as a discrete math problem, so I basically understand how to get the recurrence:
f(n,k) = (f(n-1,k) + k) mod n, with f(1,k) = 0
But that didn't work in the Facebook Hacker Cup, because the max value of n was 10^12. The mak value of k was 10^4.
Wikipedia mentions an approach when k is small and n is large. Basically remove people from a single round, and then renumber.
But it's not described much and I don't understand why the renumbering works.
I looked at sample working source code for the solution, but I still don't understand that final portion.
long long joseph (long long n,long long k) {
if (n==1LL) return 0LL;
if (k==1LL) return n-1LL;
if (k>n) return (joseph(n-1LL,k)+k)%n;
long long cnt=n/k;
long long res=joseph(n-cnt,k);
res-=n%k;
if (res<0LL) res+=n;
else res+=res/(k-1LL);
return res;
}
The part I really don't understand is starting from res-=n%k (and the lines thereafter). How do you derive that that is the way to adjust the result?
Could someone show the reasoning behind how this is derived? Or a link that derives it?
(I didn't find any info on UVA or topcoder forums)
| 0 | 0 | 0 | 0 | 1 | 0 |
I am writing a decimal multiplier in C++. The multiplier is implemented by taking two integers represented as vectors of digits. Each vector stores its digits in reverse order, for easier representation by powers of ten. For example, 3497 = 3 * 10^3 + 4 * 10^2 + 9 * 10^1 + 7 *10^0 and is stored in a vector as {7, 9, 4, 3}. Thus, each index of the vector represents that digit's respective power of ten in the integer.
However, I'm having some bugs in my multiplication. 1-digit x 1-digit and 2-digit x 1-digit multiplication work perfectly, but it breaks down at 2-digit x 2-digit. I'm fairly certain that fixing this bug would fix all the other bugs with n-digit x m-digit. My code for both my multiplication and addition methods are below.
vector<int> multiply(vector<int> &a, vector<int> &b) {
// check for emptiness
if(a.size() == 0)
return b;
else if(b.size() == 0)
return a;
unsigned int i; // increment counter
// compensate for size differences
if(a.size() > b.size())
for(i = 0; i < a.size()-b.size(); ++i)
b.push_back(0);
else
for(i = 0; i < b.size()-a.size(); ++i)
a.push_back(0);
int c = 0; // carry value
int temp; // temporary integer
vector<int> p; // product vector
vector<int> s; // sum vector
s.push_back(0); // initialize to 0
// multiply each digit of a by an index of b
for(i = 0; i < b.size(); ++i) {
// skip digits of 0
if(b[i] == 0)
continue;
p.resize(i,0); // resize p and add 0s
// multiply b[i] by each digit of a
for(unsigned int j = 0; j < a.size(); ++j) {
temp = c + b[i] * a[j]; // calculate temporary value
// two cases
if(temp > 9) {
c = temp / 10; // new carry
p.push_back(temp % 10);
}
else {
c = 0;
p.push_back(temp);
}
}
// append carry if relevant
if(c != 0)
p.push_back(c);
// sum p and s
s = add(p, s);
p.clear(); // empty p
}
return s; // return summed vector (total product)
}
vector<int> add(vector<int> &a, vector<int> &b) {
// check for emptiness
if(a.size() == 0)
return b;
else if(b.size() == 0)
return a;
unsigned int i; // increment counter
// compensate size differences
if(a.size() > b.size())
for(i = 0; i < a.size()-b.size(); ++i)
b.push_back(0);
else
for(i = 0; i < b.size()-a.size(); ++i)
a.push_back(0);
int c = 0; // carry value
vector<int> s; // sum vector
int temp; // temporary value
// iterate through decimal vectors
for(i = 0; i < a.size(); ++i) {
temp = c + a[i] + b[i]; // sum three terms
// two cases
if(temp > 9) {
c = temp / 10; // new carry
s.push_back(temp % 10); // push back remainder
}
else {
c = 0;
s.push_back(temp);
}
}
// append carry if relevant
if(c != 0)
s.push_back(c);
return s; // return sum
}
A few test cases:
45 * 16 returns 740 (should be 720)
34 * 18 returns 542 (should be 532)
67 * 29 returns 2003 (should be 1943)
28 * 12 returns 336 (correct)
The only problem I could think of would be an issue with the carries, but everything seems to check out as I walk through the code. Can anyone see the error? Or am I taking the wrong approach to this entirely?
| 0 | 0 | 0 | 0 | 1 | 0 |
like we have a grate array of matrices N*N and x1 x2 outputs for them. we want to get a trainable network that would give x1 and x2 close to our data. how should its hidden layer structure look like? I would like if it would not to turn x1 into x2 and x2 into x1.
So I want to build a trainable network that takes an NxN matrix as input and produces two numbers, x1, and x2, as output.
| 0 | 0 | 0 | 0 | 1 | 0 |
Which type of artificial neural network would you suggest to be able to make continuous time-dependant signal predictions? It should predict smallscale steps over very few signals up to very large scale steps with very many signals, possibly with less precision (abstraction by some kind of hierarchy?).
See:
Actually the system should learn and predict simultaneously.
| 0 | 1 | 0 | 0 | 0 | 0 |
I have a long "binary string" like the output of PHPs pack function.
How can I convert this value to base62 (0-9a-zA-Z)?
The built in maths functions overflow with such long inputs, and BCmath doesn't have a base_convert function, or anything that specific. I would also need a matching "pack base62" function.
| 0 | 0 | 0 | 0 | 1 | 0 |
Let's concatenate the squares of numbers that start with 1. So, what is the n'th digit in this string ?
For example, the 10th digit is 4.
1 4 9 16 25 36 49 64 81
It is just an ordinary question that come to mine ordinary mind. How can I solve this to sleep well tonight? any algorithm without looping ?
| 0 | 0 | 0 | 0 | 1 | 0 |
Does anybody know a simple and differentiable function that converts a 3D vector u = (x, y, z) to another vector that is orthogonal to u.
To be more precise, I am looking for three differentiable functions {f, g, h} such that the vector u = (x, y, z) is orthogonal to v = (f(x,y,z), g(x,y,z), h(x,y,z)) and v is zero only if u is zero.
The functions {f, g, h} should be as simple as possible. I prefer them linear, but I think no such linear functions exist. Low degree polynomials are also good.
P.S. I found such functions, but they are not polynomials. For example:
f(x, y, z) = y*(exp(x) + 3) - z*(exp(x) + 2)
g(x, y, z) = z*(exp(x) + 1) - x*(exp(x) + 3)
h(x, y, z) = x*(exp(x) + 2) - y*(exp(x) + 1)
It's simply the cross product of (x,y,z) with (exp(x)+1, exp(x)+2, exp(x)+3). It satisfies all requirements except for being polynomials. But they are quite simple.
| 0 | 0 | 0 | 0 | 1 | 0 |
What number between 1 and 7 do the following equal? A=, B=, C=, D=, E=, F=, G=
Given that:
A !=οΎ 2
A + B = F
C - D = G
D + E = 2F
E + G = F
The rules are:
All the variables (A, B, C, D, E, F, G) are equal to integer values between 1 and 7
None of the variables (A, B, C, D, E, F, G) are equal to each other i.e. all seven values will be used, no repeat use of integers
| 0 | 0 | 0 | 0 | 1 | 0 |
I am having trouble getting divide and conquer matrix multiplication to work. From what I understand, you split the matrices of size nxn into quadrants (each quadrant is n/2) and then you do:
C11 = A11β
B11 + A12 β
B21
C12 = A11β
B12 + A12 β
B22
C21 = A21 β
B11 + A22 β
B21
C22 = A21 β
B12 + A22 β
B22
My output for divide and conquer is really large and I'm having trouble figuring out the problem as I am not very good with recursion.
example output:
Original Matrix A:
4 0 4 3
5 4 0 4
4 0 4 0
4 1 1 1
A x A
Classical:
44 3 35 15
56 20 24 35
32 0 32 12
29 5 21 17
Divide and Conquer:
992 24 632 408
1600 272 720 1232
512 0 512 384
460 17 405 497
Could someone tell me what I am doing wrong for divide and conquer? All my matrices are int[][] and classical method is the traditional 3 for loop matrix multiplication
| 0 | 0 | 0 | 0 | 1 | 0 |
Let's say I have a paragraph of text like so:
Snails can be found in a very wide
range of environments including
ditches, deserts, and the abyssal
depths of the sea. Numerous kinds of snail can
also be found in fresh waters. (source)
I have 10,000 regex rules to match text, which can overlap. For example, the regex /Snails? can/i will find two matches (italicized in the text). The regex /can( also)? be/i has two matches (bolded).
After iterating through my regexes and finding matches, what is the best data structure to use, that given some place in the text, it returns all regexes that mached it? For example, if I want the matches for line 1, character 8 (0-based, which is the a in can), I would get a match for both regexes previously described.
I can create a hashmap: (key: character location, value: set of all matching regexes). Is this optimal? Is there a better way to parse the text with thousands of regexes (to not loop through each one)?
Thanks!
| 0 | 1 | 0 | 0 | 0 | 0 |
What I am trying to accomplish, is to be able to put some values inside an array, then based on a t (0-1), get a value out of the array based on its stored values.
To make this more clear, here's an example:
Array values = [0, 10]
Now this array would return value 0 for t=1 and value 10 for t=1. So t=.3 will give a value of 3.
Another example:
Array values = [10, 5, 5, 35]
t=.25 will give a value of 5
t=.125 will give a value of 7.5
Im looking for the most efficient formula to get the value at any given t using a given array.
Currently I'm using this (pseudo code)
var t:Number = .25;
var values:Array = [10, 5, 5, 35];
if(t == 1) value = [values.length-1];
else
var offset:Number = 1/values.length;
var startIndex:int = int(t/offset);
var fraction:Number = t % offset;
var roundPart:Number = (values[startIndex+1] - values[startIndex]) * fraction;
var value:Number = values[startIndex] + roundPart;
But i'm sure there's a far more better way of doing this. So i'm calling for the mathematicians on here!
| 0 | 0 | 0 | 0 | 1 | 0 |
Suppose random points P1 to P20 scattered in a plane.
Then is there any way to sort those points in either clock-wise or anti-clock wise.
Here we canβt use degree because you can see from the image many points can have same degree.
E.g, here P4,P5 and P13 acquire the same degree.
| 0 | 0 | 0 | 0 | 1 | 0 |
I do a lot of heavy math programming. Often there is a need to check some calculations "by hand", specifically while debugging. Do have good experience with some calculator tool (preferably not with gui buttons like windows calc). It could even be a programming language I guess, such as matlab. I like matlab, but I'm looking for something more lightweight here. Any ideas?
| 0 | 0 | 0 | 0 | 1 | 0 |
I've ported the arcball classes I've been using from vb.net to the iPhone using objective C++, but now I'm having a problem. When I rotate my object, everything is fine. As soon as I pan the view, my center of rotation is no longer at the center of my objects origin like it used to be. Ideally, I'd like to be able to set where in the objects frame of reference the rotation point is. I'm not sure where in the arcball routines I'd need to make changes to do this. The implementation I've based mine off of is found at the below link:
http://www.codeproject.com/KB/openGL/Tao_Arcball.aspx
I've made some small modification to how it behaves and converted it to a touch interface, but how it acts is still the same as this implementation as far as the problem I'm having is concerned.
These links explain some more of the math behind quaternions and matrix rotations:
http://www.j3d.org/matrix_faq/matrfaq_latest.html
http://www.gamedev.net/reference/articles/article1095.asp
http://en.wikipedia.org/wiki/Quaternion_rotation
The main part of the code that I imagine would have to be modified is below (in vb.net):
Public WriteOnly Property Rotation() As Quat4f
Set(ByVal value As Quat4f)
Dim n, s As Single
Dim xs, ys, zs As Single
Dim wx, wy, wz As Single
Dim xx, xy, xz As Single
Dim yy, yz, zz As Single
M = New Single(3, 3) {}
n = (value.x * value.x) + (value.y * value.y) + (value.z * value.z) + (value.w * value.w)
s = If((n > 0.0f), 2.0f / n, 0.0f)
xs = value.x * s
ys = value.y * s
zs = value.z * s
wx = value.w * xs
wy = value.w * ys
wz = value.w * zs
xx = value.x * xs
xy = value.x * ys
xz = value.x * zs
yy = value.y * ys
yz = value.y * zs
zz = value.z * zs
' rotation
M(0, 0) = 1.0f - (yy + zz)
M(0, 1) = xy - wz
M(0, 2) = xz + wy
M(1, 0) = xy + wz
M(1, 1) = 1.0f - (xx + zz)
M(1, 2) = yz - wx
M(2, 0) = xz - wy
M(2, 1) = yz + wx
M(2, 2) = 1.0f - (xx + yy)
M(3, 3) = 1.0f
' translation (pan)
M(0, 3) = pan_Renamed.x
M(1, 3) = pan_Renamed.y
' scale (zoom)
For i As Integer = 0 To 2
For j As Integer = 0 To 2
M(i, j) *= scl
Next j
Next i
End Set
End Property
Edit:
I've almost figured out how to do this. I've gotten to the point that I can set the center of rotation for my Arcball, but now I've run into another problem. When I apply the transformations to do rotation about a specified center point, there are two problems:
The model jumps to a different location. I'd like to keep the model at the exact same location and orientation.
The model scales about the new center point, but I'd like to have the model scale about the point that is the average of where the user touches with two fingers.
For number 2, I think I know how to do it, but I'll need to figure out number 1 in order to make number 2 work properly. For number 2, I can just project the average touch point to a plane that is parallel to the near plane but goes through the origin of the part, then make that my center of rotation until the user lifts their fingers up. Any ideas on number 1? The code that I use for changing the center of rotation is below:
glTranslatef(panVector.x, panVector.y, 0); //panVector is a variable that keeps track of the user panning the model
glMultMatrixf(arcballMatrix); //arcball matrix is the 16 element rotation/scale matrix that controls the model orientation
glTranslatef(-centerOfRotation.x, -centerOfRotation.y, -centerOfRotation.z); //centerOfRotation is a point that is set where I want the center of rotation to be
Just for your information, OpenGL applies matrix transformations in reverse order because of how its stacks work. So in my code, the bottom line will be executed first, then on up from there. Effectively it moves the model so its center of rotation is at the origin, then it rotates/scales, then it translates the model where it needs to go for panning.
The problem I believe I'm running into is that I need to add centerOfRotation back when I do my panning, but the problem is that once the model rotates, the centerOfRotation point needs to be transformed somehow to be in a different model space. Before I rotate the model it works fine, but once rotations are introduced, everything blows up.
| 0 | 0 | 0 | 0 | 1 | 0 |
I have a two data sets as lists, for example:
xa = [1, 2, 3, 10, 1383, 0, 12, 9229, 2, 494, 10, 49]
xb = [1, 1, 4, 12, 1100, 43, 9, 4848, 2, 454, 6, 9]
Series are market data that may contain tens of thousands numbers, their length is same.
I need to find "difference" in percents, that shows "how much similarity/dissimilarity between series in percents".
Currently I have an idea to build charts for every list (xa, xb as Y ax, and range(1, len(xa)) as X ax). interpolate functions for xa, xb, then calculate the area of xa, xb (with integration) and area of difference between xa and xb. After this the dissimilarity is (difference area)*100%/(xa area + xb area).
I wonder if this question has more simple solution.
If not - how can I calculate difference area of xa, xb? Charts are build with scipy, numpy, matplotlib.
update: I'm looking for ONE number that represent the difference between sets. Percents are preferred.
| 0 | 0 | 0 | 0 | 1 | 0 |
I have recently read an article about fast sqrt calculation. Therefore, I have decided to ask SO community and its experts to help me find out, which STL algorithms or mathematical calculations can be implemented faster with programming hacks?
It would be great if you can give examples or links.
Thanks in advance.
| 0 | 0 | 0 | 0 | 1 | 0 |
So, alpha-beta pruning seems to be the most efficient algorithm out there aside from hard coding (for tic-tac-toe). However, I'm having problems converting the algorithm from the C++ example given in the link: http://www.webkinesia.com/games/gametree.php.
Players are either 1 or 0, so doing 1-player will switch the player.
WIN = 1
LOSS = -1
DRAW = 0
INFINITY = 100
def calculate_ai_next_move
best_move = -1
best_score = -INFINITY
cur_player = COMPUTER
self.remaining_moves.each do |move|
self.make_move_with_index(move, cur_player)
score = -self.alphabeta(-INFINITY,INFINITY, 1 - cur_player)
self.undo_move(move)
if score > best_score
best_score = score
best_move = move
end
end
return best_move
end
def alphabeta(alpha, beta, player)
best_score = -INFINITY
if not self.has_available_moves?
return WIN if self.has_this_player_won?(player) == player
return LOSS if self.has_this_player_won?(1 - player) == 1 - player
return DRAW
else
self.remaining_moves.each do |move|
break if alpha > beta
self.make_move_with_index(move, player)
move_score = -alphabeta(-beta, -alpha, 1 - player)
self.undo_move(move)
if move_score > alpha
alpha = move_score
next_move = move
end
best_score = alpha
end
end
return best_score
end
Currently, the algorithm is playing terribly. It will initially pick the last space, and then choose the first (from left to right) available space after that.
Any idea with what's wrong with it?
Also, I've been doing TDD, so I know that self.has_this_player_won?, self.undo_move and self.remaining_moves is correct.
| 0 | 1 | 0 | 0 | 0 | 0 |
how can i update progress bar correctly?
I have a loop in seconds... from 60 to 0 (x--) and I need to update correctly progress bar.
What matematically method i need use to update bar?, considering that bar values are from 0.0 to 1.0 ???
NSLog(@"PROGRESS: %2.2f", ABS(log(100/x)) );
[countDownBar setProgress:ABS(log(100/x)) ];
thanks.
| 0 | 0 | 0 | 0 | 1 | 0 |
i am working on a two player board game in html5/JavaScript. the two player version is almost complete. i want to add single player mode, where computer would be opponent. this game will be played in single browser (no server side integration).
i am new to AI. i want some guidelines on AI implementation in JavaScript games, where should i begin?
please help.
Edited:
The game is Bagh-Chal
Thanks for the answers: I've managed to implement Minimax on the baghchal game. Here.
| 0 | 1 | 0 | 0 | 0 | 0 |
I need to represent a number n using ONLY x bits. Usually, I can choose the suitable base, and find the number of digits needed. But here my constraint is that I have only 'x' bits available. I can have more 1 set of 'x' bits, however.
I am trying to understand about how numbers can be represented in any given system like this one.
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm writing in C for OSX, running on a 64-bit machine in 32-bit mode. I'm compiling using GCC for 386. The project is large; I've not seen any odd behavior from the compiler (possibly until now.) The application is multithreaded, and this code is meant to be, but is being run single-threaded at this time. I am compiling using the position independent clib, and using posix threads, when threading. This code, btw, acts exactly the same if I do thread it.
The following is a simplified procedure that demonstrates the problem in the simplest form. Basically, I'm moving 16-bit image channels here from one set of three RGB channels (mr,mg,mb) to another set of 3 RGB channels (lr,lg,lb) of exactly the same size. The fragment, as I'm about to dump it, works perfectly:
void lrip_me( unsigned short *mr, // RIP from source image
unsigned short *mg,
unsigned short *mb,
unsigned short *lr, // into RGB layer
unsigned short *lg,
unsigned short *lb,
struct layer *lay,
long start,long finish)
{
long xw,yw;
long xf,yf;
long x,y;
unsigned long offset;
xw = lay->parent->x;
yw = lay->parent->y;
xf = xw - 1;
yf = yw - 1;
for (y=start; y<finish; y++)
{
for (x=0; x<xw; x++)
{
offset = (y * xw) + x;
if (x==0 || x==xf || y==0 || y==yf) // then on edge
{
lr[offset] = mr[offset];
lg[offset] = mg[offset];
lb[offset] = mb[offset];
}
else
{
lr[offset] = mr[offset];
lg[offset] = mg[offset];
lb[offset] = mb[offset];
}
}
}
}
As you can see, the action at the edge of the image and inside the edges is the same; I'm simply moving the data. And this works -- the output of this is an image in the lr,lg, and lb channels.
BUT. If, inside the else clause, I change the lines to read...
lr[offset] = mr[offset-xw];
lg[offset] = mg[offset-xw];
lb[offset] = mb[offset-xw];
...you'd expect the interior of the image to move one scan line, as the data fetches would be coming from a full scan line's distance away but going to an un-shifted target location. Instead, the output looks completely random. Like the shorts were loaded on the wrong boundaries, perhaps, or from somewhere else. This does the same thing...
lr[offset] = mr[offset-1];
lg[offset] = mg[offset-1];
lb[offset] = mb[offset-1];
...there, I'd expect the image to move one pixel horizontally. No. Same result -- purest hash.
I have tried changing to pointer math instead of arrays //*(mr+offset-1)// and get exactly the same result. I've compiled it in a library, and inside objc environment. I've tried using even offset, thinking perhaps the compiler is confused about the size of the data. I get the same results every time. The offset value can be used as is, but ONLY as is. It can't be modified inside the brackets, and furthermore, it can't be modified OUTSIDE the brackets, just being treated as a long.
I have NO idea what is going on here. I would surely appreciate it if someone would help me understand what is.
A little background; this is a RIP (remove isolated pixel) operation, or at least, it will be, if I can get at the 8 pixels surrounding the one the loop is currently looking at. That's why the edges are treated differently; I don't want to run the 8-pixel lookaround on the edges, only inside them where I'll always have all 8 to look at:
ooo
oxo
ooo
In this test case, I've removed all the RIP code, as it adds a lot of complexity and doesn't shed any light on the problem. It's simply (hah!) a situtation where array and pointer offsets don't seem to work sensibly.
| 0 | 0 | 0 | 0 | 1 | 0 |
I'm trying to use OpenNLP for tokenization. I don't know what's the problem. Following is the exception:
opennlp.tools.util.InvalidFormatException: Missing the manifest.properties!
at opennlp.tools.util.model.BaseModel.validateArtifactMap(BaseModel.java:209)
at opennlp.tools.tokenize.TokenizerModel.validateArtifactMap(TokenizerModel.java:108)
at opennlp.tools.util.model.BaseModel.(BaseModel.java:142)
at opennlp.tools.tokenize.TokenizerModel.(TokenizerModel.java:93)
at pk.edu.kics.JSFController.getAllTokens(JSFController.java:105)
at pk.edu.kics.JSFController.(JSFController.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188)
at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102)
at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:405)
at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:267)
at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:86)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:175)
at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:72)
at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:99)
at com.sun.el.parser.AstValue.getValue(AstValue.java:158)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:219)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:102)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:190)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:178)
at javax.faces.component.UIOutput.getValue(UIOutput.java:168)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getValue(HtmlBasicInputRenderer.java:205)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.getCurrentValue(HtmlBasicRenderer.java:338)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeEnd(HtmlBasicRenderer.java:164)
at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:878)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1620)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:848)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1613)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1616)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:380)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:126)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:127)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:313)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
at java.lang.Thread.run(Thread.java:662)
| 0 | 1 | 0 | 0 | 0 | 0 |
I know about alpha-beta pruning and the minimax algorithm.
What other algorithms would you suggest?
Is it possible if we use negascout?
| 0 | 1 | 0 | 0 | 0 | 0 |
I am looking for a project (application) that makes use of Ontology (for an academic course). Every body is talking about the health care application. I want to work on a different project. please any suggestion could help.
| 0 | 1 | 0 | 0 | 0 | 0 |
I am processing text corpus. It contains several characters belonging to different languages, symbols, numbers, etc.
-> All I need to do is to skip the symbols like arrow mark, heart symbol, etc.
-> I should not be spoiling any characters of different languages.
Any leads?
----UPDATE----
Character.isLetter('\unicode') is working for most of them, if not some. I have checked my regional languages, it seems it's working for some but not each and every.
Thanks.
| 0 | 1 | 0 | 0 | 0 | 0 |
I have a list L, and x in L evaluates to True if x is a member of L. What can I use instead of L in order x in smth will evaluate to True independently on the value of x?
So, I need something, what contains all objects, including itself, because x can also be this "smth".
| 0 | 0 | 0 | 0 | 1 | 0 |
Just curious but what is the probability of matching a Guid?
Say a Guid from SQL server: 5AC7E650-CFC3-4534-803C-E7E5BBE29B3D
is it a factorial?: (36*32)! = (1152)!
discuss
=D
| 0 | 0 | 0 | 0 | 1 | 0 |
I have been looking into training/using OpenCV to attempt to detect human figures. I want to try training a HOG for my specific purposes and not use the provided getDefaultPeopleDetector function. I have been unable to find any usable documentation on the HOGDescriptor class.
How do I train my own classifier for my own purposes?
| 0 | 0 | 0 | 1 | 0 | 0 |
I've been thinking of ways to handle placing my GUI interface in a 3D perspective projection, so that I can have 3D rotation effects on my "2D" interface elements. The problem I've been having is that it's been difficult positioning elements and making certain they all fit in view at once.
The idea I've had so far is to define a 2D quad in space to represent a "screen" surface, and layout the GUI on top of the quad in the same way I'd layout the gui in 2D. Then I'd move the camera to the center of the quad, point the camera at it and project the camera's position a certain distance along the quad's surface normal until the entire quad fits into the viewing frustum. The problem with that is I'm not sure how to find the minimum distance to project the camera position.
Anyone know an equation/algorithm for finding this?
| 0 | 0 | 0 | 0 | 1 | 0 |
I am working on a solution to split long lines of Khmer (the Cambodian language) into individual words (in UTF-8). Khmer does not use spaces between words. There are a few solutions out there, but they are far from adequate (here and here), and those projects have fallen by the wayside.
Here is a sample line of Khmer that needs to be split (they can be longer than this):
α
αΌαααααΎαααααααααααααααααααΆααααααΆαααΆαααΆααα’ααααααααααααΌαα’αααααααααααα’ααααααααααααΌα α αΎααααα’ααααα·αα’αΆα
ααααΆαααΆααα’ααααααααααΆαααΆααααααααΉαααααααα’αααα‘αΎαα
The goal of creating a viable solution that splits Khmer words is twofold: it will encourage those who used Khmer legacy (non-Unicode) fonts to convert over to Unicode (which has many benefits), and it will enable legacy Khmer fonts to be imported into Unicode to be used with a spelling checker quickly (rather than manually going through and splitting words which, with a large document, can take a very long time).
I don't need 100% accuracy, but speed is important (especially since the line that needs to be split into Khmer words can be quite long).
I am open to suggestions, but currently I have a large corpus of Khmer words that are correctly split (with a non-breaking space), and I have created a word probability dictionary file (frequency.csv) to use as a dictionary for the word splitter.
I found this python code here that uses the Viterbi algorithm and it supposedly runs fast.
import re
from itertools import groupby
def viterbi_segment(text):
probs, lasts = [1.0], [0]
for i in range(1, len(text) + 1):
prob_k, k = max((probs[j] * word_prob(text[j:i]), j)
for j in range(max(0, i - max_word_length), i))
probs.append(prob_k)
lasts.append(k)
words = []
i = len(text)
while 0 < i:
words.append(text[lasts[i]:i])
i = lasts[i]
words.reverse()
return words, probs[-1]
def word_prob(word): return dictionary.get(word, 0) / total
def words(text): return re.findall('[a-z]+', text.lower())
dictionary = dict((w, len(list(ws)))
for w, ws in groupby(sorted(words(open('big.txt').read()))))
max_word_length = max(map(len, dictionary))
total = float(sum(dictionary.values()))
I also tried using the source java code from the author of this page: Text segmentation: dictionary-based word splitting but it ran too slow to be of any use (because my word probability dictionary has over 100k terms...).
And here is another option in python from Detect most likely words from text without spaces / combined words:
WORD_FREQUENCIES = {
'file': 0.00123,
'files': 0.00124,
'save': 0.002,
'ave': 0.00001,
'as': 0.00555
}
def split_text(text, word_frequencies, cache):
if text in cache:
return cache[text]
if not text:
return 1, []
best_freq, best_split = 0, []
for i in xrange(1, len(text) + 1):
word, remainder = text[:i], text[i:]
freq = word_frequencies.get(word, None)
if freq:
remainder_freq, remainder = split_text(
remainder, word_frequencies, cache)
freq *= remainder_freq
if freq > best_freq:
best_freq = freq
best_split = [word] + remainder
cache[text] = (best_freq, best_split)
return cache[text]
print split_text('filesaveas', WORD_FREQUENCIES, {})
--> (1.3653e-08, ['file', 'save', 'as'])
I am a newbee when it comes to python and I am really new to all real programming (outside of websites), so please bear with me. Does anyone have any options that they feel would work well?
| 0 | 1 | 0 | 0 | 0 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.