working on it ...

Filters

Explore Public Snippets

Sort by

Found 9,295 snippets matching: calc

    public by lbottaro modified Feb 16, 2013  463473  0  7  0

    Excel function to calculate the average of positive data in range

    This excel function calculate the average of a specific range of cells, regarding only positive values. Zero or less than zero value won't be used in average calculation. The italian version of this snippet can be used as well on OpenOffice 3.
    =SUMIF(B2:B6;">0")/MAX(COUNTIF(B2:B6;">0");1)
    
    # Italian version
    =SOMMA.SE(B2:B6;">0")/MAX(CONTA.SE(B2:B6;">0");1)

    public by cghersi modified Nov 4, 2014  246904  1  6  1

    Calculate the occurrences of words in Rss feed

    Creates a dictionary with keys=words and values=occurrences of that word in the given Rss (specified by the URL). The caller should specify the maximum number of items in the returning dictionary and, optionally, the minimum length of the words that will be added to the output.
    public static Dictionary<string, int> ComputeWordsOccurrencesInRss(string url, int maxItems, int minLenOfAcceptedWords = 1)
    {
      Dictionary<string, int> occurrences = new Dictionary<string, int>();
    
      IList<RssReader.RssItem> singleRssResult = RssReader.ReadRss(url, maxItems, true);
      string[] splitted = null;
      foreach (RssReader.RssItem rss in singleRssResult)
      {
        List<string> words = new List<string>();
    
        //split title in words:
        splitted = StringHelper.SplitIntoWords(rss.Title);
        if (splitted != null)
          words.AddRange(splitted);
    
        //split summary in words:
        splitted = StringHelper.SplitIntoWords(rss.Summary);
        if (splitted != null)
          words.AddRange(splitted);
    
        //compute occurrences of words:
        for (int w = 0; w < words.Count; w++)
        {
          string word = words[w].ToLower();
          if (word.Length < minLenOfAcceptedWords)
            continue;
          if (occurrences.ContainsKey(word))
            occurrences[word]++;
          else
            occurrences.Add(word, 1);
        }
      }
    
      return occurrences;
    }
    

    public by lbottaro modified Sep 2, 2013  247301  3  7  0

    Lock and synchronization in python

    This example shows how to deal with lock in python parallel programming. Here we want to calculate the disk occupancy for a given directory in Linux OS, evaluating the disk occupancy for any subdirectory using threads. Note the usage of lock mechanism to ensure atomic operation on the total sum.
    import os
    import string
    import threading
    from threading import Thread
    
    disk_usage = 0
    lock = threading.Lock()
    
    for dir in os.popen('ls -d *').readlines():
        print "Dir: " + dir
        t = Thread(target=methodToBeExecutedInParallel, args=(dir,))
        t.start()
        #Join all existing threads to main thread.
        for thread in threading.enumerate():
            if thread is not threading.currentThread():
              thread.join()
        print "Disk usage = " + str(disk_usage)
    
    # Function invoked by each thread
    def methodToBeExecutedInParallel(directory):
        print "Working on dir = " + directory
        cmd = 'du -s ' + directory
        line = os.popen(cmd).readlines()[0]
        dirUsage = int(line.split()[0])
        print "Acquiring lock for "+directory+"..."
        with lock:
            print "Acquired lock for "+directory
            global disk_usage
            disk_usage += dirUsage
        print "Disk usage = " + str(dirUsage)

    public by michaelp modified Apr 10, 2013  159453  0  3  0

    Basic way to calculate length of a string

    Basic way to calculate length of a string: gistfile1.txt
    # breaks if string includes a 0
    def string_length(a)
      string = a + "0"
      length = 0
    
      while string[length] != "0"
        length += 1
      end
    
      puts "Your statement is #{length} characters long"
    end
    
    string_length("I am a meat popsicle.")
    
    

    public by boloka modified Feb 22, 2015  129772  1  5  0

    process time

    How much time running is my php process? Calculate this time. Very simple.
    PHP
    $start_time = microtime(true);
    
    // code...
    
    $end_time = microtime(true);
    
    $process_time = $end_time - $start_time;
    echo 'This code running is: ' . $process_time . ' sec.';

    public by Geometry modified Jul 28, 2016  1159  0  5  0

    CalculateTargetTemperature: Calculates the target temperature of the sensor. More info about the calculation: http://www.ti.com/lit/ug/sbou107/sbou107.pdf

    Calculates the target temperature of the sensor. More info about the calculation: http://www.ti.com/lit/ug/sbou107/sbou107.pdf
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Devices.Bluetooth.GenericAttributeProfile;
    using Windows.Storage.Streams;
    using X2CodingLab.Utils;
    
    /// <summary>
    /// Calculates the target temperature of the sensor.
    /// More info about the calculation: http://www.ti.com/lit/ug/sbou107/sbou107.pdf
    /// </summary>
    /// <param name="sensorData"></param>
    /// <param name="ambientTemperature"></param>
    /// <returns></returns>
    private static double CalculateTargetTemperature(byte[] sensorData, double ambientTemperature)
    {
        double Vobj2 = BitConverter.ToInt16(sensorData, 0);
        Vobj2 *= 0.00000015625;
    
        double Tdie = ambientTemperature + 273.15;
    
        double S0 = 5.593E-14;
        double a1 = 1.75E-3;
        double a2 = -1.678E-5;
        double b0 = -2.94E-5;
        double b1 = -5.7E-7;
        double b2 = 4.63E-9;
        double c2 = 13.4;
        double Tref = 298.15;
        double S = S0 * (1 + a1 * (Tdie - Tref) + a2 * Math.Pow((Tdie - Tref), 2));
        double Vos = b0 + b1 * (Tdie - Tref) + b2 * Math.Pow((Tdie - Tref), 2);
        double fObj = (Vobj2 - Vos) + c2 * Math.Pow((Vobj2 - Vos), 2);
        double tObj = Math.Pow(Math.Pow(Tdie, 4) + (fObj / S), .25);
    
        return tObj - 273.15;
    }

    public by Geometry modified Jul 28, 2016  1775  1  4  0

    CalculateTargetTemperature: Calculates the target temperature.

    Calculates the target temperature. Complete array of data retrieved from the sensor calculated ambient temperature, saves another calculation of the ambient temoerature.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Devices.Bluetooth.GenericAttributeProfile;
    using Windows.Storage.Streams;
    using X2CodingLab.Utils;
    
    /// <summary>
    /// Calculates the target temperature.
    /// </summary>
    /// <param name="sensorData">Complete array of data retrieved from the sensor</param>
    /// <param name="ambientTemperature">calculated ambient temperature, saves another calculation of the ambient temoerature.</param>
    /// <param name="scale"></param>
    /// <returns></returns>
    public static double CalculateTargetTemperature(byte[] sensorData, double ambientTemperature, TemperatureScale scale)
    {
        Validator.RequiresNotNull(sensorData, "sensorData");
        Validator.RequiresNotNull(ambientTemperature, "ambientTemperature");
        Validator.RequiresArgument(!double.IsNaN(ambientTemperature), "ambientTemperature cannot be double.NaN");
        if (scale == TemperatureScale.Celsius)
            return CalculateTargetTemperature(sensorData, ambientTemperature);
        else
            return CalculateTargetTemperature(sensorData, ambientTemperature) * 1.8 + 32;
    }

    public by Geometry modified Jul 28, 2016  1552  1  4  0

    CalculateTargetTemperature: Calculates the target temperature.

    Calculates the target temperature. Complete array of data retrieved from the sensor
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Devices.Bluetooth.GenericAttributeProfile;
    using Windows.Storage.Streams;
    using X2CodingLab.Utils;
    
    /// <summary>
    /// Calculates the target temperature.
    /// </summary>
    /// <param name="sensorData">Complete array of data retrieved from the sensor</param>
    /// <param name="scale"></param>
    /// <returns></returns>
    public static double CalculateTargetTemperature(byte[] sensorData, TemperatureScale scale)
    {
        Validator.RequiresNotNull(sensorData);
        if(scale == TemperatureScale.Celsius)
            return CalculateTargetTemperature(sensorData, (BitConverter.ToUInt16(sensorData, 2) / 128.0));
        else
            return CalculateTargetTemperature(sensorData, (BitConverter.ToUInt16(sensorData, 2) / 128.0)) * 1.8 + 32;
    }

    public by Geometry modified Jul 28, 2016  1509  0  4  0

    CalculatePressure: Calculates the pressure from the raw sensor data.

    Calculates the pressure from the raw sensor data. Pressure in pascal
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Devices.Bluetooth.GenericAttributeProfile;
    using Windows.Storage.Streams;
    using System.Runtime.InteropServices.WindowsRuntime;
    using X2CodingLab.SensorTag.Exceptions;
    using X2CodingLab.Utils;
    
    /// <summary>
    /// Calculates the pressure from the raw sensor data.
    /// </summary>
    /// <param name="sensorData"></param>
    /// <param name="calibrationData"></param>
    /// <param name="calibrationDataSigned"></param>
    /// <returns>Pressure in pascal</returns>
    public static double CalculatePressure(byte[] sensorData, int[] calibrationData)
    {
        Validator.RequiresNotNull(sensorData, "sensorData");
        Validator.RequiresNotNull(calibrationData, "sensorData");
        Validator.RequiresArgument(calibrationData.Length == 8, "Calibration data doesn't have the appropriate lenth. Use PressureSensorInstance.CalibrationData.");
    
        //more info about the calculation:
        //http://www.epcos.com/web/generator/Web/Sections/ProductCatalog/Sensors/PressureSensors/T5400-ApplicationNote,property=Data__en.pdf;/T5400_ApplicationNote.pdf
        int t_r, p_r;	// Temperature raw value, Pressure raw value from sensor
        double t_a, S, O; 	// Temperature actual value in unit centi degrees celsius, interim values in calculation
    
        t_r = BitConverter.ToInt16(sensorData, 0);
        p_r = BitConverter.ToUInt16(sensorData, 2);
    
        t_a = (100 * (calibrationData[0] * t_r / Math.Pow(2, 8) + calibrationData[1] * Math.Pow(2, 6))) / Math.Pow(2, 16);
        S = calibrationData[2] + calibrationData[3] * t_r / Math.Pow(2, 17) + ((calibrationData[4] * t_r / Math.Pow(2, 15)) * t_r) / Math.Pow(2, 19);
        O = calibrationData[5] * Math.Pow(2, 14) + calibrationData[6] * t_r / Math.Pow(2, 3) + ((calibrationData[7] * t_r / Math.Pow(2, 15)) * t_r) / Math.Pow(2, 4);
        return (S * p_r + O) / Math.Pow(2, 14);
    }

    public by Geometry modified Jul 28, 2016  1353  1  4  0

    CalculateHumidityInPercent: Calculates the humidity in percent.

    Calculates the humidity in percent. Complete array of data retrieved from the sensor
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Windows.Devices.Bluetooth.GenericAttributeProfile;
    using Windows.Storage.Streams;
    using X2CodingLab.Utils;
    
    /// <summary>
    /// Calculates the humidity in percent.
    /// </summary>
    /// <param name="sensorData">Complete array of data retrieved from the sensor</param>
    /// <returns></returns>
    public static double CalculateHumidityInPercent(byte[] sensorData)
    {
        Validator.RequiresNotNull(sensorData);
    
        // more info http://www.sensirion.com/nc/en/products/humidity-temperature/download-center/?cid=880&did=102&sechash=c204b9cc
        int hum = BitConverter.ToUInt16(sensorData, 2);
    
        //cut first two statusbits
        hum = hum - (hum % 4);
    
        // calculate in percent
        return (-6f) + 125f * (hum / 65535f);
    }
    • Public Snippets
    • Channels Snippets