working on it ...

Filters

Explore Public Snippets

Sort by

Found 9,283 snippets matching: calc

    public by lbottaro modified Feb 16, 2013  463486  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  247302  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  159455  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  129777  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 DinhoPutz modified Feb 5, 2019  193  2  3  0

    Calculadora de Reflorestamento em PHP

    Calcula a quanto de área a ser replantada/paga
    <html>
        <head>
            <title>Calculadora Reflorestamento</title>
    		<META charset="UTF-8" lang="pt-br">
    		<style>
    			body { font-family: Arial; }
    			table { border: none; font-weight: bold; }
    			tr, td { border: black 1px solid; }
    		</style>
    	</head>
        <body>
            <div class="Calc">
                <form method="POST">
                    <fieldset>
                        <table>
                            <legend>Calculadora de Reflorestamento</legend>
                            <tr>
                                <td>Ano</td><td>Estado</td><td>Árvores cortadas</td><td>Volume (m³)</td>
    						</tr>
                            <tr>
                                <td><input name="ano" type="text" maxlength="4" size="8"></td>
                                <td>
    								<select name="estado">
    									<option value="AC">Acre</option>
    									<option value="AL">Alagoas</option>
    									<option value="AP">Amapá</option>
    									<option value="AM">Amazonas</option>
    									<option value="BA">Bahia</option>
    									<option value="CE">Ceará</option>
    									<option value="DF">Distrito Federal</option>
    									<option value="ES">Espírito Santo</option>
    									<option value="GO">Goiás</option>
    									<option value="MA">Maranhão</option>
    									<option value="MT">Mato Grosso</option>
    									<option value="MS">Mato Grosso do Sul</option>
    									<option value="MG">Minas Gerais</option>
    									<option value="PA">Pará</option>
    									<option value="PB">Paraíba</option>
    									<option value="PR">Paraná</option>
    									<option value="PE">Pernambuco</option>
    									<option value="PI">Piauí</option>
    									<option value="RJ">Rio de Janeiro</option>
    									<option value="RN">Rio Grande do Norte</option>
    									<option value="RS">Rio Grande do Sul</option>
    									<option value="RO">Rondônia</option>
    									<option value="RR">Roraima</option>
    									<option value="SC">Santa Catarina</option>
    									<option value="SP">São Paulo</option>
    									<option value="SE">Sergipe</option>
    									<option value="TO">Tocantins</option>
    								</select>
    							</td>
                                <td><input name="arvore" type="number" max="9999" value="0"></td>
                                <td><input name="volume" type="number" max="9999" value="0"></td>
    						</tr>
                            <tr>
                                <td colspan="4"><input type="submit" value="Calcular"><input type="reset"></td>
    						</tr>
    					</table>
    				</fieldset>
    			</form>
    		</div>
    	</body>
    </html>
    
    <?php
    	
    	if($_POST != null) {
    		$ano 		= $_POST['ano'];
    		$estado 	= $_POST['estado'];
    		$arvore 	= $_POST['arvore'];
    		$volume 	= $_POST['volume'];
    		$arvoreR 	= (intval($volume) * 6);
    		$totalPagar = (intval($arvore) * 0.75);	
    		} else {
    		$ano 		= 0;
    		$estado 	= 0;
    		$arvore 	= 0;
    		$volume 	= 0;
    		$arvoreR 	= 0;
    		$totalPagar = 0;			
    	}
    	
    ?>
    <legend align='center'></legend>
    <table border='1' align='center'>
    	<tr>
    		<td colspan='6' align='center'>Resultado</td>
    	</tr>
    	<tr style='size: 16px; font-weight:bold; font-family: 'Arial Narrow';>
    		<td>Ano Base </td><td>Estado Origem </td><td>Árvores cortadas </td><td>Volume (m³) </td><td>Árvores a repor </td><td>Total a ser Pago</td>
    	</tr>
    	<tr align='center'>
    		<td><?php echo $ano			?></td>
    		<td><?php echo $estado		?></td>
    		<td><?php echo $arvore		?></td>
    		<td><?php echo $volume		?></td>
    		<td><?php echo $arvoreR		?></td>
    		<td><?php echo $totalPagar	?></td>
    	</tr>
    </table>

    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  1551  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  1519  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 Snippets
    • Channels Snippets