I had the following code:
func pi() -> Double {
func iteration(denominator: Double) -> Double {
let nextNumber: Double = 1.0 / denominator
let isPreciseEnough = abs(nextNumber) < 0.0002
if isPreciseEnough {
return nextNumber
}
let newDenominator = (abs(denominator) + 2.0) * denominator / abs(denominator) * -1.0
return nextNumber + iteration(newDenominator)
}
return 4.0 * iteration(1.0)
}
When I ran it, it stopped with bad access at the second run in playground, and when I tried to build it in a project, it stopped with
"swift failed with exit code 1"
I checked the value of denominator and it was 2.23690525377983e-314 at the second run. However, when I separated the methods like
func pi() -> Double {
return 4.0 * iteration(1.0)
}
func iteration(denominator: Double) -> Double {
let nextNumber: Double = 1.0 / denominator
let isPreciseEnough = abs(nextNumber) < 0.0002
if isPreciseEnough {
return nextNumber
}
let newDenominator = (abs(denominator) + 2.0) * denominator / abs(denominator) * -1.0
return nextNumber + iteration(newDenominator)
}
it worked perfectly. Can anyone explain, why the example on the top doesn't work?
Related
In the context of verifying this program using Aorai plugin for frama-c, what would be the corresponding automaton in .ya file format ?
void f() {
;
}
void g(){
;
}
int main(){
f();
g();
return 0;
}
My guess is this
%init: S0;
%accept: S4;
S0 : { CALL(main) } -> S1
;
S1 : { CALL(f) } -> S2
;
S2 : { CALL(g) } -> S3
;
S3 : {RETURN(main) } -> S4
;
S4 : -> S4
;
But I get this error using Aorai plugin
[aorai] Warning: Call to main does not follow automaton's specification. This path is assumed to be dead
[aorai] Threestateaut.c:12: Warning:
Call to main not conforming to automaton (pre-cond). Assuming it is on a dead path
Don't forget that at each event a transition must be taken from the current state of the automaton. Here, when you are in S2 after the CALL to f, the next event that happens is the RETURN from f to main, but the only transition from S2 is guarded by CALL(g) (the beginning of the automaton describes thus a program where f itself calls g).
To fix this, you can either take the RETURN into account, as in
...
S2: { RETURN(f) } -> S3;
S3: { CALL(g) } -> S4;
...
or use YA extensions (as described in section 3.1.3 of the manual, which in particular allow indicating that you have a CALL(f) directly followed by a RETURN(f) with:
...
S2: { f() } -> S3;
...
Actually, with these extensions, the complete execution flow can be specified in a more compact way, since you can nest call sequences:
%init: S0;
%accept: S1;
S0 : { main([f();g()]) } -> S1;
S1: -> S1;
I need to write a factorial function that takes in one input and returns the factorial of the given number. if the function is passed in to be 0 or less than 0 then the function should return 0.
I am not actually sure how to write this only using the features of PSScript version 1.0 however I just wrote this, please can someone help me.
JAVA -
public static int factorial (int n) {
if (n<0) {
return 0;
}
return (n<2) ? 1 : n *factorial(n-1);
}
I want to know if there is any I could write this so could use this to write a function in PSScript version 1.0
This is what I have done so far ;
func fac (int n) return int {
if (n<0){
return 0;
}
else
{
return (n<2) ? 1 : n *factorial(n-1);
}
}
Based on the language spec you linked to I would guess the recursive factorial function would look like this in your fictional language:
func fac (int n) returns int {
if (n == 0) {
return 1;
} else {
return n * fac(n - 1);
}
}
Maybe it should check for negative arguments too.
I'm building a generic vector class in Swift with three types: Float, Double and Int. This works so far, but when I try to calculate the length of the vector I run into an issue.
The formula for vector length is the square root of (x²+y²). But since I use a generic class for my vectors, the values of x and y are called T.
The sqrt function of Swift only accepts Double as an argument but no generic argument.
Is there any way to use the sqrt function with generic parameters?
Here is a snippet of the code I use for the vector length and the dot product:
protocol ArithmeticType {
func + (left: Self, right: Self) -> Self
func - (left: Self, right: Self) -> Self
func * (left: Self, right: Self) -> Self
func / (left: Self, right: Self) -> Self
prefix func - (left: Self) -> Self
func toDouble() -> Double
}
extension Double: ArithmeticType {
func toDouble() -> Double {
return Double(self)
}
}
extension Float: ArithmeticType {
func toDouble() -> Double {
return Double(self)
}
}
extension Int: ArithmeticType {
func toDouble() -> Double {
return Double(self)
}
}
class Vector<T where T: ArithmeticType, T: Comparable> {
var length: T { return sqrt((self ⋅ self).toDouble()) }
}
infix operator ⋅ { associativity left }
func ⋅<T: ArithmeticType> (left: Vector<T>, right: Vector<T>) -> T {
var result: T? = nil
for (index, value) in enumerate(left.values) {
let additive = value * right.values[index]
if result == nil {
result = additive
} else if let oldResult = result {
result = oldResult + additive
}
}
if let unwrappedResult = result {
return unwrappedResult
}
}
In Swift 3, just use the FloatingPoint protocol that is part of the standard library instead of your ArithmeticType protocol. Floatand Double conform to the FloatingPoint protocol. The FlotingPoint protocol has a squareRoot() method, so
class Vector<T where T: FloatingPoint> {
var length: T { return (self ⋅ self).squareRoot() }
}
should do the trick.
No need to import any libraries or do any run-time type checking! Invoking this method turns into an LLVM built-in, so there isn't even any function calling overhead. On an x86, sqareRoot() should just generate a single machine language instruction, leaving the result in a register for the return statement to copy.
I see that you're using using a custom Arithmetic protocol to constraint the generic.
My approach would be to declare 2 required methods in that protocol: toDouble() and fromDouble(), and implement both in Float, Double and Int extensions. Note that fromDouble() should be a static method.
This way you can convert T to Double, hence be able to use sqrt(), and convert back from Double to T.
Last, there's a bug in your code: if left is an empty vector, the function will crash, because the code in the loop will never be executed, so result will keep its nil initial value. The forced unwrapping in the return statement will fail, causing the exception.
There is no generic sqrt in Swift. But you can make your own generic.
import Foundation // for sqrt sqrtf
public func sqrt<T:FloatingPointType>(v:T) -> T {
if let vv = v as? Double {
return sqrt(vv) as! T
}
if let vv = v as? Float {
return sqrtf(vv) as! T
}
preconditionFailure()
}
print(sqrt(Float(9))) // == 3
print(sqrt(Double(9))) // == 3
I am trying to load a java class to oracle as a function. In the server I managed to use loadjava as below:
C:\Users\n12017>loadjava -user USER1/passw E:\JAVA_repository\SOOSProjects\Mehmet_java_2db_trial\classes\mehmet_java_2db_trial\kondrakk.class
And in the oracle db side:
create or replace function ngram_kondrakk(src in varchar2, trg in varchar2)
return float
as language java
name 'mehmet_java_2db_trial/kondrakk.getDistance(java.lang.string, java.lang.string) return java.lang.float';
/
However, when I apply the query as below, I got error. (As a result of the query I am expecting a similarity score of 1 since two identical strings are compared)
select ngram_kondrakk('mehmet','mehmet') from dual;
Here is the error:
ORA-29532: Java call terminated by uncaught Java exception: System error : java/lang/UnsupportedClassVersionError
29532. 00000 - "Java call terminated by uncaught Java exception: %s"
*Cause: A Java exception or error was signaled and could not be
resolved by the Java code.
*Action: Modify Java code, if this behavior is not intended.
Finally, here is the code that I am trying to use:
package mehmet_java_2db_trial;
public class kondrakk {
public static float getDistance(String source, String target) {
final int sl = source.length();
final int tl = target.length();
if (sl == 0 || tl == 0) {
if (sl == tl) {
return 1;
}
else {
return 0;
}
}
int n=3;
int cost = 0;
if (sl < n || tl < n) {
for (int i=0,ni=Math.min(sl,tl);i<ni;i++) {
if (source.charAt(i) == target.charAt(i)) {
cost++;
}
}
return (float) cost/Math.max(sl, tl);
}
char[] sa = new char[sl+n-1];
float p[]; //'previous' cost array, horizontally
float d[]; // cost array, horizontally
float _d[]; //placeholder to assist in swapping p and d
//construct sa with prefix
for (int i=0;i<sa.length;i++) {
if (i < n-1) {
sa[i]=0; //add prefix
}
else {
sa[i] = source.charAt(i-n+1);
}
}
p = new float[sl+1];
d = new float[sl+1];
// indexes into strings s and t
int i; // iterates through source
int j; // iterates through target
char[] t_j = new char[n]; // jth n-gram of t
for (i = 0; i<=sl; i++) {
p[i] = i;
}
for (j = 1; j<=tl; j++) {
//construct t_j n-gram
if (j < n) {
for (int ti=0;ti<n-j;ti++) {
t_j[ti]=0; //add prefix
}
for (int ti=n-j;ti<n;ti++) {
t_j[ti]=target.charAt(ti-(n-j));
}
}
else {
t_j = target.substring(j-n, j).toCharArray();
}
d[0] = j;
for (i=1; i<=sl; i++) {
cost = 0;
int tn=n;
//compare sa to t_j
for (int ni=0;ni<n;ni++) {
if (sa[i-1+ni] != t_j[ni]) {
cost++;
}
else if (sa[i-1+ni] == 0) { //discount matches on prefix
tn--;
}
}
float ec = (float) cost/tn;
// minimum of cell to the left+1, to the top+1, diagonally left and up +cost
d[i] = Math.min(Math.min(d[i-1]+1, p[i]+1), p[i-1]+ec);
}
// copy current distance counts to 'previous row' distance counts
_d = p;
p = d;
d = _d;
}
// our last action in the above loop was to switch d and p, so p now
// actually has the most recent cost counts
System.out.println(1.0f - (p[sl] / Math.max(tl, sl)));
return 1.0f - (p[sl] / Math.max(tl, sl));
}
}
Please HELP!
Thanks in advance...
When compiling Java classes to load into an Oracle database, be sure that you compile your Java classes to run with the JVM inside the Oracle database.
The version of Java that comes with an Oracle database is typically out of date compared to the current Java: expect to be using Java 1.4 with Oracle 10g and 1.5 with 11g. Your best bet is to use the Java compiler that ships with the database, but if you can't do that, use -target 1.5 or suchlike to force the compiler to compile classes to run on Java 1.5.
Your plsql wrapper function has "/"
...mehmet_java_2db_trial/kondrakk.getDistance...
replace / with . [dot]
Check the docs
and as it was already mentioned - sync JVM of compilation with JVM for run-time( which will be Oracle JVM that is "attached" to DB)
I have a Heatmap that currently works on a stand alone sever that I am porting to Azure Storage. How do I go about saving the butmap file in Azure Storage. Originally I had a entry in my web.config file that pointed the image cache to a direct path on anther drive (IE ) Everything now will be in ~/map_cache folder in the Storage Account. How can I mod this for storage locally in Azure.
protected void Page_Load(object sender, EventArgs e)
{
xxxxxxxdb = new xxxxxxx(ConfigurationManager.AppSettings["xxxxxxx"]);
string imageCachePath = Server.MapPath("/map_cache/HotSpots");
int fileExpirationTime = int.Parse(ConfigurationManager.AppSettings["HotspotImageExpirationTime"]);
Bitmap bitmap;
string requestParam = Page.Request.Params["id"];
string bitmapFileName = Path.Combine(imageCachePath, requestParam + ".png");
if (File.Exists(bitmapFileName) && File.GetCreationTime(bitmapFileName) > DateTime.Now.AddHours(-fileExpirationTime))
{
bitmap = (Bitmap)Image.FromFile(bitmapFileName);
}
else
{
int zoomLevel = requestParam.Length;
double tileX = 0;
double tileY = 0;
for (int index = 0; index < zoomLevel; index++)
{
int digit = int.Parse(requestParam[index].ToString());
tileY += ((digit & 2) / 2) * Math.Pow(2, (zoomLevel - index - 1));
tileX += (digit & 1) * Math.Pow(2, (zoomLevel - index - 1));
}
double pixelXMin = tileX * 256;
double pixelYMin = tileY * 256;
double pixelXMax = (tileX + 1) * 256 - 1;
double pixelYMax = (tileY + 1) * 256 - 1;
double longMin = ((pixelXMin * 360) / (256 * Math.Pow(2, zoomLevel))) - 180;
double longMax = ((pixelXMax * 360) / (256 * Math.Pow(2, zoomLevel))) - 180;
double latMin = Math.Asin((Math.Exp((0.5 - pixelYMin / 256 / Math.Pow(2, zoomLevel)) * 4 * Math.PI) - 1) /
(Math.Exp((0.5 - pixelYMin / 256 / Math.Pow(2, zoomLevel)) * 4 * Math.PI) + 1)) * 180 /
Math.PI;
double latMax = Math.Asin((Math.Exp((0.5 - pixelYMax / 256 / Math.Pow(2, zoomLevel)) * 4 * Math.PI) - 1) /
(Math.Exp((0.5 - pixelYMax / 256 / Math.Pow(2, zoomLevel)) * 4 * Math.PI) + 1)) * 180 /
Math.PI;
double pixelResolution = (Math.Cos(latMax * Math.PI / 180) * 2 * Math.PI * 6378137) / (256 * Math.Pow(2, zoomLevel));
double pixelArea = Math.Pow(pixelResolution, 2);
double maxHotspotDensity = Math.Max(120.0 / zoomLevel, 3.0) / pixelArea;
bitmap = GenerateBlankBitmap();
var accidents = from hs in db.cs_PT_VEGeoDatas
where hs.Latitude <= latMin && hs.Latitude >= latMax
&& hs.Longitude >= longMin && hs.Longitude <= longMax
select new { hs.Latitude, hs.Longitude };
Dictionary<Point, HotSpot> hotSpots = new Dictionary<Point, HotSpot>();
foreach (var accident in accidents)
{
int pixelX, pixelY;
LatLongToPixelXY(accident.Latitude, accident.Longitude, zoomLevel, out pixelX, out pixelY);
pixelX %= 256;
pixelY %= 256;
for (int ix = -doublePixelSize; ix <= doublePixelSize; ix++)
{
for (int iy = -doublePixelSize; iy <= doublePixelSize; iy++)
{
Point point;
bool borderPoint = false;
if (zoomLevel < doublePixelZoomLevel)
{
point = new Point(pixelX, pixelY);
}
else
{
if (pixelX + ix >= 0 && pixelX + ix <= 255 && pixelY + iy >= 0 && pixelY + iy <= 255)
{
point = new Point(pixelX + ix, pixelY + iy);
borderPoint = (ix == -doublePixelSize) || (iy == -doublePixelSize) ||
(ix == doublePixelSize) || (iy == doublePixelSize);
}
else
{
break;
}
}
HotSpot hotSpot;
if (hotSpots.ContainsKey(point))
{
hotSpot = hotSpots[point];
hotSpot.borderPoint &= borderPoint;
hotSpot.count += 1;
}
else
{
hotSpot = new HotSpot { borderPoint = borderPoint, count = 1 };
hotSpots.Add(point, hotSpot);
}
if (zoomLevel < doublePixelZoomLevel)
{
break;
}
}
if (zoomLevel < doublePixelZoomLevel)
{
break;
}
}
}
foreach (var hotspotPixel in hotSpots)
{
double hc = hotspotPixel.Value.count;
double hcDensity = hc / pixelArea;
Color color;
if (!hotspotPixel.Value.borderPoint)
{
color = Color.FromArgb(255, 255,
(int)
Math.Max((maxHotspotDensity - hcDensity) / maxHotspotDensity * 255, 0.0),
0);
}
else
{
color = Color.Black;
}
bitmap.SetPixel(hotspotPixel.Key.X, hotspotPixel.Key.Y, color);
}
bitmap.Save(bitmapFileName);
}
WritePngToStream(bitmap, Response.OutputStream);
}
Currently I get the following Error message
A generic error occurred in GDI+.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Runtime.InteropServices.ExternalException: A generic error occurred in GDI+.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ExternalException (0x80004005): A generic error occurred in GDI+.]
System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams) +772265
HotSpotTileServer.Page_Load(Object sender, EventArgs e) in C:\Projects\xxx\xxx\SpeedTrap\HotSpotTileServer.aspx.cs:141
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +3048
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1
There are three things you can try:
for temporary files - that don't need to be shared across web servers (which is rare!) - then you can use Local Storage - http://vkreynin.wordpress.com/2010/01/10/learning-azure-local-storage-with-me/
for a disk shared between web servers (but only one of these will have write access) you could use an Azure Drive - http://blog.maartenballiauw.be/post/2010/02/02/Using-Windows-Azure-Drive-(aka-X-Drive).aspx
for general flexible shared file storage, try using Azure Blob Storage - http://blogs.msdn.com/b/jnak/archive/2008/10/29/walkthrough-simple-blob-storage-sample.aspx
Definitely the last of these is the one I'd recommend - it's fast, flexible and scalable.
(I agree with Stuart 100%.) Here are more reasons why I recommend you consider using Azure Blob Storage for storing heatmap png file:
The local hard disk is not guaranteed to be durable. (This may not be important to you, however, if they can be regenerated easily.)
Blobs can be made publicly visible (so, for example, they can be directly referenced from HTML code with an img tag).
Blobs can easily be made available in the AppFabric CDN (for better performance, including around 24 global distribution points).
Blobs will scale in ways that using the local file system will not. For example, if you ever want to scale your site to use more than one Heatmap generator role instance (running 2 of them on different machines in the cloud), you will want to be on Blob storage since none of the other options will work.
Blobs are optimized for cloud scale and reliability and high availability.
I recommend you use the very handy Windows Azure SDK for writing your blobs. The SDK wraps the official REST interfaces with a very nice set of classes that are really easy to use from .NET code. Specifically you would use the CloudBlobClient class, and the method UploadByteArray. You can download the Azure SDK 1.4 here.