text:
<!DOCTYPE html>

      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Jeruk Nipis
      </title>
      <meta name="description" content="Download free amazing responsive Fashion Blog template."/>
      <meta name="keywords" content="free, responsive, blog, fashion"/>
      <link rel="stylesheet" href="css/components.css">
      <link rel="stylesheet" href="css/responsee.css">

      <link href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,700&subset=latin,latin-ext' rel='stylesheet' type='text/css'>
      <link rel="stylesheet" href="css/template-style.css">

					Beauty Inside | Healty Outside

                        Blog

                        About

                        Archive

                        Contact

06

mar

Jeruk Nipis Untuk Tubuh

                     Sudah sejak dulu jeruk nipis dikenal sebagai salah satu buah yang mempunyai manfaat untuk kesehatan dan kecantikan. Khasiat jeruk nipis ini tidak lepas dari berbagai kandungan yang ada dalam buah tersebut. Vitamin C yang melimpah pada jeruk nipis ternyata lebih banyak ketimbang jeruk jenis lainnya. Mungkin banyak diantara anda hanya mengetahui bahwa jeruk nipis hanya digunakan sebagai penyedap rasa pada makanan saja, padahal khasiat jeruk nipis untuk kesehatan sangatlah banyak

Salah satu manfaat jeruk nipis untuk kesehatan yakni meningkatkan kekebalan tubuh karena mengandung Vitamin C yang tinggi. Untuk mengobati berbagai penyakit pun jeruk nipis juga cukup ampuh. Beberapa penyakit yang dapat disembuhkan dengan jeruk nipis yakni seperti ambeien, amandel, batuk, radang tenggorokan, jerawat, dan masih banyak lagi.

penggunaan jeruk nipis

1. Mengobati jerawat

Caranya cukup dengan mengoleskan air perasan jeruk nipis pada jerawat kemudian diamkan selama 30 menit, setelah itu bilas wajah dengan air. Terapkan secara rutin untuk mendapatkan hasil maksimal.

2. Mengobati batuk

Langkah pertama peras 1 buah jeruk nipis dan ambil airnya. Setelah itu campurkan air perasan tersebut dengan 1 sendok madu dan sedikit garam. Aduk hingga tercampur rata kemudian konsumsi 2-3 kali sehari.

3. Mengobati radang tenggorokan

Ambil setengah buah jeruk nipis lalu peras dan ambil airnya. Campurkan air perasan tersebut dengan setengah gelas air hangat dan minumlah. Cara ini dapat anda terapkan 2-3 kali salam sehari.

4. Menghilangkan lendir di tenggorokan

Potonglah 2 jeruk nipis dan peras untuk mengambil airnya. Setelah itu campurkan air perasan jeruk nipis tersebut dengan sedikit garam. Aduk hingga rata lalu minum campuran tersebut.

5. Mengatasi haid tidak teratur

Caranya yakni dengan mencampurkan 3 sendok makan air perasan jeruk nipis, 1 sendok makan madu, dan 2 gelas air panas. Setelah itu aduk hingga rata lalu minumlah saat sudah hangat. Terapkan cara ini 3 kali sehari.

6. Mengobati anyang-anyangan

Siapkan 2 buah jeruk nipis lalu potong dan peras. Campurkan perasan jeruk nipis tersebut kedalam segelas air panas. Tambahkan sedikit gula batu dan aduk hingga tercampur rata. Setelah itu tinggal minum campuran tersebut saat masih hangat.

Responsee Team : Hadid Bestkarna & Eka Dwi Cahyani

                  Tugas UAS Hadid Bestkarna & Eka Dwi Cahyani

redpajama_set_name: RedPajamaGithub


text:
package com.alain898.dscache.cache;

import java.util.List;

/**
 * Created by alain on 16/9/3.
 */
public class CacheGroupMeta {
    private String cacheGroupName;
    private String entryClassName;
    private int subCachesPerCache;
    private int cacheGroupCapacity;     // 2^C
    private int partitionsPerSubCache;
    private int blocksPerPartition;
    private int blockCapacity;

    private List<CacheMeta> cacheMetas;

    private int currentCachesNumber;    // 2^cm

    public String getCacheGroupName() {
        return cacheGroupName;
    }

    public void setCacheGroupName(String cacheGroupName) {
        this.cacheGroupName = cacheGroupName;
    }

    public List<CacheMeta> getCacheMetas() {
        return cacheMetas;
    }

    public void setCacheMetas(List<CacheMeta> cacheMetas) {
        this.cacheMetas = cacheMetas;
    }

    public int getCurrentCachesNumber() {
        return currentCachesNumber;
    }

    public void setCurrentCachesNumber(int currentCachesNumber) {
        this.currentCachesNumber = currentCachesNumber;
    }

    public int getCacheGroupCapacity() {
        return cacheGroupCapacity;
    }

    public void setCacheGroupCapacity(int cacheGroupCapacity) {
        this.cacheGroupCapacity = cacheGroupCapacity;
    }

    public String getEntryClassName() {
        return entryClassName;
    }

    public void setEntryClassName(String entryClassName) {
        this.entryClassName = entryClassName;
    }

    public int getSubCachesPerCache() {
        return subCachesPerCache;
    }

    public void setSubCachesPerCache(int subCachesPerCache) {
        this.subCachesPerCache = subCachesPerCache;
    }

    public int getPartitionsPerSubCache() {
        return partitionsPerSubCache;
    }

    public void setPartitionsPerSubCache(int partitionsPerSubCache) {
        this.partitionsPerSubCache = partitionsPerSubCache;
    }

    public int getBlocksPerPartition() {
        return blocksPerPartition;
    }

    public void setBlocksPerPartition(int blocksPerPartition) {
        this.blocksPerPartition = blocksPerPartition;
    }

    public int getBlockCapacity() {
        return blockCapacity;
    }

    public void setBlockCapacity(int blockCapacity) {
        this.blockCapacity = blockCapacity;
    }
}


text:
class FluxTypeController
{
/////////////
// DEFINES //
public: /////

//////////////////
// CONSTRUCTORS //
public: //////////

	// Constructor / destructor
	FluxTypeController();
	~FluxTypeController();

	// Add a new type
	void AddType(std::string _typeName, FluxType::TypeOrigin _origin = FluxType::TypeOrigin::System);

	// Remove a type
	void RemoveType(FluxType _type);

	// Validate if a given type exist
	bool ValidateType(FluxType _type);

	// Return a type by name
	FluxType GetTypeByName(std::string _typeName);

//////////////////
// MAIN METHODS //
public: //////////

///////////////
// VARIABLES //
protected: ////

	// The type map
	std::unordered_map <std::string, FluxType> m_TypeMap;
};


text:
/* global assert, process, setup, suite, test */
var entityFactory = require('../../helpers').entityFactory;

suite('fog', function () {
  'use strict';

  setup(function () {
    this.entityEl = entityFactory();
    var el = this.el = this.entityEl.parentNode;
    this.updateMaterialsSpy = this.sinon.spy(el.systems.material, 'updateMaterials');

    // Stub scene load to avoid WebGL code.
    el.hasLoaded = true;
    el.setAttribute('fog', '');
  });

  test('does not set fog for entities', function () {
    var entityEl = this.entityEl;
    entityEl.setAttribute('fog', '');
    assert.notOk(entityEl.object3D.fog);
  });

  suite('update', function () {
    test('creates fog', function () {
      assert.ok(this.el.object3D.fog);
    });

    test('triggers material update when adding fog', function () {
      assert.ok(this.updateMaterialsSpy.called);
    });

    test('updates fog', function () {
      var el = this.el;
      el.setAttribute('fog', 'color: #F0F');
      assert.shallowDeepEqual(el.object3D.fog.color, {r: 1, g: 0, b: 1});
    });

    test('does not recreate fog when updating', function () {
      var el = this.el;
      var uuid = el.object3D.fog.uuid;
      el.setAttribute('fog', 'color: #F0F');
      assert.equal(el.object3D.fog.uuid, uuid);
    });

    test('can update fog type', function () {
      var el = this.el;
      el.setAttribute('fog', 'type: exponential; density: 0.25');
      el.setAttribute('fog', 'density: 0.25');
      assert.notOk('density' in el.object3D.fog);
      assert.ok('near' in el.object3D.fog);
    });

    test('can remove and add linear fog', function () {
      var el = this.el;
      el.removeAttribute('fog');
      el.setAttribute('fog', '');
    });
  });

  suite('remove', function () {
    test('removes fog when detaching fog', function () {
      var el = this.el;
      el.removeAttribute('fog');
      assert.equal(el.object3D.fog.far, 0);
      assert.equal(el.object3D.fog.near, 0);
    });

    test('removes exp. fog when detaching fog', function () {
      var el = this.el;
      el.setAttribute('fog', 'type: exponential');
      el.removeAttribute('fog');
      assert.equal(el.object3D.fog.density, 0);
    });
  });
});


text:
<?xml version="1.0" encoding="UTF-8" ?>
<module>
	<name>blockreinsurance</name>
	<displayName><![CDATA[bloco de Resseguros]]></displayName>
	<version><![CDATA[2.1.1]]></version>
	<description><![CDATA[Adicionar um bloco para exibir informações para tranquilizar seus clientes]]></description>
	<author><![CDATA[PrestaShop]]></author>
	<tab><![CDATA[front_office_features]]></tab>
	<is_configurable>1</is_configurable>
	<need_instance>1</need_instance>
	<limited_countries></limited_countries>
</module>


text:
import config from 'config';
import { request } from 'lib/request';
import { checkStatus, parseJSON } from 'lib/response';

export default class SessionSource {
  static urlRoot = `${config.apiPath}/users/sign_in`;

  static create(user) {
    const { email, password } = user;
    const params = { email, password };

    return request(this.urlRoot, {
      method: 'POST',
      body: JSON.stringify(params)
    })
    .then(checkStatus)
    .then(parseJSON);
  }

  static delete(user) {
    console.log('signed out', user);
  }
}


text:
@interface PodsDummy_Pods_MposTest_Example : NSObject
@end
@implementation PodsDummy_Pods_MposTest_Example
@end


text:
package com.pie.tlatoani.ZExperimental.SyntaxPiece;

import java.util.Set;

/**
 * Created by Tlatoani on 8/21/17.
 */
public class Literal extends SyntaxPiece {
    public final String text;

    public static final Literal EMPTY = new Literal("");

    public Literal(String text) {
        this.text = text;
    }

    @Override
    public boolean equals(Object object) {
        return object instanceof Literal && text.equals(((Literal) object).text);
    }

    @Override
    public boolean containsVariables() {
        return false;
    }

    @Override
    public VariableUsage getVariableUsage(String variable) {
        return VariableUsage.NONE;
    }

    @Override
    public int markLength() {
        return 0;
    }

    @Override
    public int expressionAmount() {
        return 0;
    }

    @Override
    public void addVariables(VariableCollective collective) {}

    @Override
    public String readableSyntax() {
        return text;
    }

    @Override
    public String actualSyntax(int prevMarkLength) {
        return text;
    }

    @Override
    public String originalSyntax() {
        return text;
    }

    @Override
    public void setInformation(MarkSpecificInformation information, int mark, int prevExprAmount) {
    }

    @Override
    public String toString(int mark) {
        return text;
    }

    @Override
    public String toString() {
        return "Literal(\"" + text + "\")";
    }
}


text:
/**
 *
This package contains the operations on the ISemaphore.

 *
 * @since 2
 */
package com.hazelcast.concurrent.semaphore.operations;


text:
package com.ote.keystore.secretkey.annotation;

import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface SecretKey {
}


text:
package mono;

import java.io.*;
import java.lang.String;
import java.util.Locale;
import java.util.HashSet;
import java.util.zip.*;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.res.AssetManager;
import android.util.Log;
import mono.android.Runtime;

public class MonoPackageManager {

	static Object lock = new Object ();
	static boolean initialized;

	public static void LoadApplication (Context context, String runtimeDataDir, String[] apks)
	{
		synchronized (lock) {
			if (!initialized) {
				System.loadLibrary("monodroid");
				Locale locale       = Locale.getDefault ();
				String language     = locale.getLanguage () + "-" + locale.getCountry ();
				String filesDir     = context.getFilesDir ().getAbsolutePath ();
				String cacheDir     = context.getCacheDir ().getAbsolutePath ();
				String dataDir      = context.getApplicationInfo ().dataDir + "/lib";
				ClassLoader loader  = context.getClassLoader ();

				Runtime.init (
						language,
						apks,
						runtimeDataDir,
						new String[]{
							filesDir,
							cacheDir,
							dataDir,
						},
						loader,
						new java.io.File (
							android.os.Environment.getExternalStorageDirectory (),
							"Android/data/" + context.getPackageName () + "/files/.__override__").getAbsolutePath (),
						MonoPackageManager_Resources.Assemblies,
						context.getPackageName ());
				initialized = true;
			}
		}
	}

	public static String[] getAssemblies ()
	{
		return MonoPackageManager_Resources.Assemblies;
	}

	public static String[] getDependencies ()
	{
		return MonoPackageManager_Resources.Dependencies;
	}

	public static String getApiPackageName ()
	{
		return MonoPackageManager_Resources.ApiPackageName;
	}
}

class MonoPackageManager_Resources {
	public static final String[] Assemblies = new String[]{
		"OrderNowAndroid.dll",
		"GooglePlayServicesLib.dll",
		"Xamarin.Android.Support.v4.dll",
		"Xamarin.Android.Support.v7.AppCompat.dll",
		"Xamarin.Android.Support.v7.CardView.dll",
		"Xamarin.Android.Support.v7.MediaRouter.dll",
		"Xamarin.Android.Support.v7.RecyclerView.dll",
		"Xamarin.Facebook.dll",
	};
	public static final String[] Dependencies = new String[]{
	};
	public static final String ApiPackageName = "Mono.Android.Platform.ApiLevel_21";
}


text:
"""Unit tests for scripts/common.py."""

from __future__ import absolute_import  # pylint: disable=import-only-modules
from __future__ import unicode_literals  # pylint: disable=import-only-modules

import contextlib
import getpass
import http.server
import os
import re
import shutil
import socketserver
import stat
import subprocess
import sys
import tempfile

from core.tests import test_utils

import psutil
import python_utils
import release_constants

from . import common

_PARENT_DIR = os.path.abspath(os.path.join(os.getcwd(), os.pardir))
_PY_GITHUB_PATH = os.path.join(
    _PARENT_DIR, 'oppia_tools', 'PyGithub-%s' % common.PYGITHUB_VERSION)
sys.path.insert(0, _PY_GITHUB_PATH)

import github # isort:skip  pylint: disable=wrong-import-position

class MockPsutilProcess(python_utils.OBJECT):
    """A mock class for Process class in Psutil."""

    cmdlines = [
        ['dev_appserver.py', '--host', '0.0.0.0', '--port', '9001'],
        ['downloads']
    ]

    def __init__(self, index):
        """Constructor for this mock object.

        Args:
            index: int. The index of process to be checked.
        """
        self.index = index

    def cmdline(self):
        """Return the command line of this process."""
        pass

    def kill(self):
        """Kill the process."""
        pass

    def is_running(self):
        """Check whether the function is running."""
        return True

class CommonTests(test_utils.GenericTestBase):
    """Test the methods which handle common functionalities."""

    def test_is_x64_architecture_in_x86(self):
        maxsize_swap = self.swap(sys, 'maxsize', 1)
        with maxsize_swap:
            self.assertFalse(common.is_x64_architecture())

    def test_is_x64_architecture_in_x64(self):
        maxsize_swap = self.swap(sys, 'maxsize', 2**32 + 1)
        with maxsize_swap:
            self.assertTrue(common.is_x64_architecture())

    def test_run_cmd(self):
        self.assertEqual(
            common.run_cmd(('echo Test for common.py ').split(' ')),
            'Test for common.py')

    def test_ensure_directory_exists_with_existing_dir(self):
        check_function_calls = {
            'makedirs_gets_called': False
        }
        def mock_makedirs(unused_dirpath):
            check_function_calls['makedirs_gets_called'] = True
        with self.swap(os, 'makedirs', mock_makedirs):
            common.ensure_directory_exists('assets')
        self.assertEqual(check_function_calls, {'makedirs_gets_called': False})

    def test_ensure_directory_exists_with_non_existing_dir(self):
        check_function_calls = {
            'makedirs_gets_called': False
        }
        def mock_makedirs(unused_dirpath):
            check_function_calls['makedirs_gets_called'] = True
        with self.swap(os, 'makedirs', mock_makedirs):
            common.ensure_directory_exists('test-dir')
        self.assertEqual(check_function_calls, {'makedirs_gets_called': True})

    def test_require_cwd_to_be_oppia_with_correct_cwd_and_unallowed_deploy_dir(
            self):
        common.require_cwd_to_be_oppia()

    def test_require_cwd_to_be_oppia_with_correct_cwd_and_allowed_deploy_dir(
            self):
        common.require_cwd_to_be_oppia(allow_deploy_dir=True)

    def test_require_cwd_to_be_oppia_with_wrong_cwd_and_unallowed_deploy_dir(
            self):
        def mock_getcwd():
            return 'invalid'
        getcwd_swap = self.swap(os, 'getcwd', mock_getcwd)
        with getcwd_swap, self.assertRaisesRegexp(
            Exception, 'Please run this script from the oppia/ directory.'):
            common.require_cwd_to_be_oppia()

    def test_require_cwd_to_be_oppia_with_wrong_cwd_and_allowed_deploy_dir(
            self):
        def mock_getcwd():
            return 'invalid'
        def mock_basename(unused_dirpath):
            return 'deploy-dir'
        def mock_isdir(unused_dirpath):
            return True
        getcwd_swap = self.swap(os, 'getcwd', mock_getcwd)
        basename_swap = self.swap(os.path, 'basename', mock_basename)
        isdir_swap = self.swap(os.path, 'isdir', mock_isdir)
        with getcwd_swap, basename_swap, isdir_swap:
            common.require_cwd_to_be_oppia(allow_deploy_dir=True)

    def test_open_new_tab_in_browser_if_possible_with_user_manually_opening_url(
            self):
        try:
            check_function_calls = {
                'input_gets_called': 0,
                'check_call_gets_called': False
            }
            expected_check_function_calls = {
                'input_gets_called': 1,
                'check_call_gets_called': False
            }
            def mock_call(unused_cmd_tokens):
                return 0
            def mock_check_call(unused_cmd_tokens):
                check_function_calls['check_call_gets_called'] = True
            def mock_input():
                check_function_calls['input_gets_called'] += 1
                return 'n'
            call_swap = self.swap(subprocess, 'call', mock_call)
            check_call_swap = self.swap(
                subprocess, 'check_call', mock_check_call)
            input_swap = self.swap(python_utils, 'INPUT', mock_input)
            with call_swap, check_call_swap, input_swap:
                common.open_new_tab_in_browser_if_possible('test-url')
            self.assertEqual(
                check_function_calls, expected_check_function_calls)
        finally:
            common.USER_PREFERENCES['open_new_tab_in_browser'] = None

    def test_open_new_tab_in_browser_if_possible_with_url_opening_correctly(
            self):
        try:
            check_function_calls = {
                'input_gets_called': 0,
                'check_call_gets_called': False
            }
            expected_check_function_calls = {
                'input_gets_called': 1,
                'check_call_gets_called': True
            }
            def mock_call(unused_cmd_tokens):
                return 0
            def mock_check_call(unused_cmd_tokens):
                check_function_calls['check_call_gets_called'] = True
            def mock_input():
                check_function_calls['input_gets_called'] += 1
                return 'y'
            call_swap = self.swap(subprocess, 'call', mock_call)
            check_call_swap = self.swap(
                subprocess, 'check_call', mock_check_call)
            input_swap = self.swap(python_utils, 'INPUT', mock_input)
            with call_swap, check_call_swap, input_swap:
                common.open_new_tab_in_browser_if_possible('test-url')
            self.assertEqual(
                check_function_calls, expected_check_function_calls)
        finally:
            common.USER_PREFERENCES['open_new_tab_in_browser'] = None

    def test_open_new_tab_in_browser_if_possible_with_url_not_opening_correctly(
            self):
        try:
            check_function_calls = {
                'input_gets_called': 0,
                'check_call_gets_called': False
            }
            expected_check_function_calls = {
                'input_gets_called': 2,
                'check_call_gets_called': False
            }
            def mock_call(unused_cmd_tokens):
                return 1
            def mock_check_call(unused_cmd_tokens):
                check_function_calls['check_call_gets_called'] = True
            def mock_input():
                check_function_calls['input_gets_called'] += 1
                return 'y'
            call_swap = self.swap(subprocess, 'call', mock_call)
            check_call_swap = self.swap(
                subprocess, 'check_call', mock_check_call)
            input_swap = self.swap(python_utils, 'INPUT', mock_input)
            with call_swap, check_call_swap, input_swap:
                common.open_new_tab_in_browser_if_possible('test-url')
            self.assertEqual(
                check_function_calls, expected_check_function_calls)
        finally:
            common.USER_PREFERENCES['open_new_tab_in_browser'] = None

    def test_get_remote_alias_with_correct_alias(self):
        def mock_check_output(unused_cmd_tokens):
            return 'remote1 url1\nremote2 url2'
        with self.swap(
            subprocess, 'check_output', mock_check_output):
            self.assertEqual(common.get_remote_alias('url1'), 'remote1')

    def test_get_remote_alias_with_incorrect_alias(self):
        def mock_check_output(unused_cmd_tokens):
            return 'remote1 url1\nremote2 url2'
        check_output_swap = self.swap(
            subprocess, 'check_output', mock_check_output)
        with check_output_swap, self.assertRaisesRegexp(
            Exception,
            'ERROR: There is no existing remote alias for the url3 repo.'):
            common.get_remote_alias('url3')

    def test_verify_local_repo_is_clean_with_clean_repo(self):
        def mock_check_output(unused_cmd_tokens):
            return 'nothing to commit, working directory clean'
        with self.swap(
            subprocess, 'check_output', mock_check_output):
            common.verify_local_repo_is_clean()

    def test_verify_local_repo_is_clean_with_unclean_repo(self):
        def mock_check_output(unused_cmd_tokens):
            return 'invalid'
        check_output_swap = self.swap(
            subprocess, 'check_output', mock_check_output)
        with check_output_swap, self.assertRaisesRegexp(
            Exception, 'ERROR: This script should be run from a clean branch.'):
            common.verify_local_repo_is_clean()

    def test_get_current_branch_name(self):
        def mock_check_output(unused_cmd_tokens):
            return 'On branch test'
        with self.swap(
            subprocess, 'check_output', mock_check_output):
            self.assertEqual(common.get_current_branch_name(), 'test')

    def test_get_current_release_version_number_with_non_hotfix_branch(self):
        self.assertEqual(
            common.get_current_release_version_number('release-1.2.3'), '1.2.3')

    def test_get_current_release_version_number_with_hotfix_branch(self):
        self.assertEqual(
            common.get_current_release_version_number('release-1.2.3-hotfix-1'),
            '1.2.3')

    def test_get_current_release_version_number_with_maintenance_branch(self):
        self.assertEqual(
            common.get_current_release_version_number(
                'release-maintenance-1.2.3'), '1.2.3')

    def test_get_current_release_version_number_with_invalid_branch(self):
        with self.assertRaisesRegexp(
            Exception, 'Invalid branch name: invalid-branch.'):
            common.get_current_release_version_number('invalid-branch')

    def test_is_current_branch_a_hotfix_branch_with_non_hotfix_branch(self):
        def mock_check_output(unused_cmd_tokens):
            return 'On branch release-1.2.3'
        with self.swap(
            subprocess, 'check_output', mock_check_output):
            self.assertEqual(common.is_current_branch_a_hotfix_branch(), False)

    def test_is_current_branch_a_hotfix_branch_with_hotfix_branch(self):
        def mock_check_output(unused_cmd_tokens):
            return 'On branch release-1.2.3-hotfix-1'
        with self.swap(
            subprocess, 'check_output', mock_check_output):
            self.assertEqual(common.is_current_branch_a_hotfix_branch(), True)

    def test_is_current_branch_a_release_branch_with_release_branch(self):
        def mock_check_output(unused_cmd_tokens):
            return 'On branch release-1.2.3'
        with self.swap(
            subprocess, 'check_output', mock_check_output):
            self.assertEqual(common.is_current_branch_a_release_branch(), True)

    def test_is_current_branch_a_release_branch_with_hotfix_branch(self):
        def mock_check_output(unused_cmd_tokens):
            return 'On branch release-1.2.3-hotfix-1'
        with self.swap(
            subprocess, 'check_output', mock_check_output):
            self.assertEqual(common.is_current_branch_a_release_branch(), True)

    def test_is_current_branch_a_release_branch_with_maintenance_branch(self):
        def mock_check_output(unused_cmd_tokens):
            return 'On branch release-maintenance-1.2.3'
        with self.swap(
            subprocess, 'check_output', mock_check_output):
            self.assertEqual(common.is_current_branch_a_release_branch(), True)

    def test_is_current_branch_a_release_branch_with_non_release_branch(self):
        def mock_check_output(unused_cmd_tokens):
            return 'On branch test'
        with self.swap(
            subprocess, 'check_output', mock_check_output):
            self.assertEqual(common.is_current_branch_a_release_branch(), False)

    def test_is_current_branch_a_test_branch_with_test_branch(self):
        def mock_check_output(unused_cmd_tokens):
            return 'On branch test-common'
        with self.swap(
            subprocess, 'check_output', mock_check_output):
            self.assertEqual(common.is_current_branch_a_test_branch(), True)

    def test_is_current_branch_a_test_branch_with_non_test_branch(self):
        def mock_check_output(unused_cmd_tokens):
            return 'On branch invalid-test'
        with self.swap(
            subprocess, 'check_output', mock_check_output):
            self.assertEqual(common.is_current_branch_a_test_branch(), False)

    def test_verify_current_branch_name_with_correct_branch(self):
        def mock_check_output(unused_cmd_tokens):
            return 'On branch test'
        with self.swap(
            subprocess, 'check_output', mock_check_output):
            common.verify_current_branch_name('test')

    def test_verify_current_branch_name_with_incorrect_branch(self):
        def mock_check_output(unused_cmd_tokens):
            return 'On branch invalid'
        check_output_swap = self.swap(
            subprocess, 'check_output', mock_check_output)
        with check_output_swap, self.assertRaisesRegexp(
            Exception,
            'ERROR: This script can only be run from the "test" branch.'):
            common.verify_current_branch_name('test')

    def test_ensure_release_scripts_folder_exists_with_invalid_access(self):
        process = subprocess.Popen(['test'], stdout=subprocess.PIPE)
        def mock_isdir(unused_dirpath):
            return False
        def mock_chdir(unused_dirpath):
            pass
        def mock_popen(unused_cmd, stdin, stdout, stderr):  # pylint: disable=unused-argument
            return process
        def mock_communicate(unused_self):
            return ('Output', 'Invalid')
        isdir_swap = self.swap(os.path, 'isdir', mock_isdir)
        chdir_swap = self.swap(os, 'chdir', mock_chdir)
        popen_swap = self.swap(subprocess, 'Popen', mock_popen)
        communicate_swap = self.swap(
            subprocess.Popen, 'communicate', mock_communicate)
        with isdir_swap, chdir_swap, popen_swap, communicate_swap:
            with self.assertRaisesRegexp(
                Exception, (
                    'You need SSH access to GitHub. See the '
                    '"Check your SSH access" section here and follow the '
                    'instructions: '
                    'https://help.github.com/articles/'
                    'error-repository-not-found/#check-your-ssh-access')):
                common.ensure_release_scripts_folder_exists_and_is_up_to_date()

    def test_ensure_release_scripts_folder_exists_with_valid_access(self):
        process = subprocess.Popen(['test'], stdout=subprocess.PIPE)
        def mock_isdir(unused_dirpath):
            return False
        def mock_chdir(unused_dirpath):
            pass
        def mock_popen(unused_cmd, stdin, stdout, stderr):  # pylint: disable=unused-argument
            return process
        def mock_communicate(unused_self):
            return ('Output', 'You\'ve successfully authenticated!')
        def mock_check_call(unused_cmd_tokens):
            pass
        def mock_verify_local_repo_is_clean():
            pass
        def mock_verify_current_branch_name(unused_branch_name):
            pass
        def mock_get_remote_alias(unused_url):
            return 'remote'
        def mock_ask_user_to_confirm(unused_msg):
            pass
        isdir_swap = self.swap(os.path, 'isdir', mock_isdir)
        chdir_swap = self.swap(os, 'chdir', mock_chdir)
        popen_swap = self.swap(subprocess, 'Popen', mock_popen)
        communicate_swap = self.swap(
            subprocess.Popen, 'communicate', mock_communicate)
        check_call_swap = self.swap(
            subprocess, 'check_call', mock_check_call)
        verify_local_repo_swap = self.swap(
            common, 'verify_local_repo_is_clean',
            mock_verify_local_repo_is_clean)
        verify_current_branch_name_swap = self.swap(
            common, 'verify_current_branch_name',
            mock_verify_current_branch_name)
        get_remote_alias_swap = self.swap(
            common, 'get_remote_alias', mock_get_remote_alias)
        ask_user_swap = self.swap(
            common, 'ask_user_to_confirm', mock_ask_user_to_confirm)
        with isdir_swap, chdir_swap, popen_swap, communicate_swap:
            with check_call_swap, verify_local_repo_swap, ask_user_swap:
                with verify_current_branch_name_swap, get_remote_alias_swap:
                    (
                        common
                        .ensure_release_scripts_folder_exists_and_is_up_to_date(
                            ))

    def test_is_port_open(self):
        self.assertFalse(common.is_port_open(4444))

        handler = http.server.SimpleHTTPRequestHandler
        httpd = socketserver.TCPServer(('', 4444), handler)

        self.assertTrue(common.is_port_open(4444))
        httpd.server_close()

    def test_permissions_of_file(self):
        root_temp_dir = tempfile.mkdtemp()
        temp_dirpath = tempfile.mkdtemp(dir=root_temp_dir)
        temp_file = tempfile.NamedTemporaryFile(dir=temp_dirpath)
        temp_file.name = 'temp_file'
        temp_file_path = os.path.join(temp_dirpath, 'temp_file')
        with python_utils.open_file(temp_file_path, 'w') as f:
            f.write('content')

        common.recursive_chown(root_temp_dir, os.getuid(), -1)
        common.recursive_chmod(root_temp_dir, 0o744)

        for root, directories, filenames in os.walk(root_temp_dir):
            for directory in directories:
                self.assertEqual(
                    oct(stat.S_IMODE(
                        os.stat(os.path.join(root, directory)).st_mode)),
                    '0744')
                self.assertEqual(
                    os.stat(os.path.join(root, directory)).st_uid, os.getuid())

            for filename in filenames:
                self.assertEqual(
                    oct(stat.S_IMODE(
                        os.stat(os.path.join(root, filename)).st_mode)), '0744')
                self.assertEqual(
                    os.stat(os.path.join(root, filename)).st_uid, os.getuid())

        shutil.rmtree(root_temp_dir)

    def test_print_each_string_after_two_new_lines(self):
        @contextlib.contextmanager
        def _redirect_stdout(new_target):
            """Redirect stdout to the new target.

            Args:
                new_target: TextIOWrapper. The new target to which stdout is
                    redirected.

            Yields:
                TextIOWrapper. The new target.
            """
            old_target = sys.stdout
            sys.stdout = new_target
            try:
                yield new_target
            finally:
                sys.stdout = old_target

        target_stdout = python_utils.string_io()
        with _redirect_stdout(target_stdout):
            common.print_each_string_after_two_new_lines([
                'These', 'are', 'sample', 'strings.'])

        self.assertEqual(
            target_stdout.getvalue(), 'These\n\nare\n\nsample\n\nstrings.\n\n')

    def test_install_npm_library(self):

        def _mock_subprocess_check_call(unused_command):
            """Mocks subprocess.check_call() to create a temporary file instead
            of the actual npm library.
            """
            temp_file = tempfile.NamedTemporaryFile()
            temp_file.name = 'temp_file'
            with python_utils.open_file('temp_file', 'w') as f:
                f.write('content')

            self.assertTrue(os.path.exists('temp_file'))
            temp_file.close()

        self.assertFalse(os.path.exists('temp_file'))

        with self.swap(subprocess, 'check_call', _mock_subprocess_check_call):
            common.install_npm_library('library_name', 'version', 'path')

    def test_ask_user_to_confirm(self):
        def mock_input():
            return 'Y'
        with self.swap(python_utils, 'INPUT', mock_input):
            common.ask_user_to_confirm('Testing')

    def test_get_personal_access_token_with_valid_token(self):
        def mock_getpass(prompt):  # pylint: disable=unused-argument
            return 'token'
        with self.swap(getpass, 'getpass', mock_getpass):
            self.assertEqual(common.get_personal_access_token(), 'token')

    def test_get_personal_access_token_with_token_as_none(self):
        def mock_getpass(prompt):  # pylint: disable=unused-argument
            return None
        getpass_swap = self.swap(getpass, 'getpass', mock_getpass)
        with getpass_swap, self.assertRaisesRegexp(
            Exception,
            'No personal access token provided, please set up a personal '
            'access token at https://github.com/settings/tokens and re-run '
            'the script'):
            common.get_personal_access_token()

    def test_closed_blocking_bugs_milestone_results_in_exception(self):
        mock_repo = github.Repository.Repository(
            requester='', headers='', attributes={}, completed='')
        def mock_get_milestone(unused_self, number):  # pylint: disable=unused-argument
            return github.Milestone.Milestone(
                requester='', headers='',
                attributes={'state': 'closed'}, completed='')
        get_milestone_swap = self.swap(
            github.Repository.Repository, 'get_milestone', mock_get_milestone)
        with get_milestone_swap, self.assertRaisesRegexp(
            Exception, 'The blocking bug milestone is closed.'):
            common.check_blocking_bug_issue_count(mock_repo)

    def test_non_zero_blocking_bug_issue_count_results_in_exception(self):
        mock_repo = github.Repository.Repository(
            requester='', headers='', attributes={}, completed='')
        def mock_open_tab(unused_url):
            pass
        def mock_get_milestone(unused_self, number):  # pylint: disable=unused-argument
            return github.Milestone.Milestone(
                requester='', headers='',
                attributes={'open_issues': 10, 'state': 'open'}, completed='')
        get_milestone_swap = self.swap(
            github.Repository.Repository, 'get_milestone', mock_get_milestone)
        open_tab_swap = self.swap(
            common, 'open_new_tab_in_browser_if_possible', mock_open_tab)
        with get_milestone_swap, open_tab_swap, self.assertRaisesRegexp(
            Exception, (
                'There are 10 unresolved blocking bugs. Please '
                'ensure that they are resolved before release '
                'summary generation.')):
            common.check_blocking_bug_issue_count(mock_repo)

    def test_zero_blocking_bug_issue_count_results_in_no_exception(self):
        mock_repo = github.Repository.Repository(
            requester='', headers='', attributes={}, completed='')
        def mock_get_milestone(unused_self, number):  # pylint: disable=unused-argument
            return github.Milestone.Milestone(
                requester='', headers='',
                attributes={'open_issues': 0, 'state': 'open'}, completed='')
        with self.swap(
            github.Repository.Repository, 'get_milestone', mock_get_milestone):
            common.check_blocking_bug_issue_count(mock_repo)

    def test_check_prs_for_current_release_are_released_with_no_unreleased_prs(
            self):
        mock_repo = github.Repository.Repository(
            requester='', headers='', attributes={}, completed='')
        pull1 = github.PullRequest.PullRequest(
            requester='', headers='',
            attributes={
                'title': 'PR1', 'number': 1, 'labels': [
                    {'name': release_constants.LABEL_FOR_RELEASED_PRS},
                    {'name': release_constants.LABEL_FOR_CURRENT_RELEASE_PRS}]},
            completed='')
        pull2 = github.PullRequest.PullRequest(
            requester='', headers='',
            attributes={
                'title': 'PR2', 'number': 2, 'labels': [
                    {'name': release_constants.LABEL_FOR_RELEASED_PRS},
                    {'name': release_constants.LABEL_FOR_CURRENT_RELEASE_PRS}]},
            completed='')
        label = github.Label.Label(
            requester='', headers='',
            attributes={
                'name': release_constants.LABEL_FOR_CURRENT_RELEASE_PRS},
            completed='')
        def mock_get_issues(unused_self, state, labels):  # pylint: disable=unused-argument
            return [pull1, pull2]
        def mock_get_label(unused_self, unused_name):
            return [label]

        get_issues_swap = self.swap(
            github.Repository.Repository, 'get_issues', mock_get_issues)
        get_label_swap = self.swap(
            github.Repository.Repository, 'get_label', mock_get_label)
        with get_issues_swap, get_label_swap:
            common.check_prs_for_current_release_are_released(mock_repo)

    def test_check_prs_for_current_release_are_released_with_unreleased_prs(
            self):
        mock_repo = github.Repository.Repository(
            requester='', headers='', attributes={}, completed='')
        def mock_open_tab(unused_url):
            pass
        pull1 = github.PullRequest.PullRequest(
            requester='', headers='',
            attributes={
                'title': 'PR1', 'number': 1, 'labels': [
                    {'name': release_constants.LABEL_FOR_CURRENT_RELEASE_PRS}]},
            completed='')
        pull2 = github.PullRequest.PullRequest(
            requester='', headers='',
            attributes={
                'title': 'PR2', 'number': 2, 'labels': [
                    {'name': release_constants.LABEL_FOR_RELEASED_PRS},
                    {'name': release_constants.LABEL_FOR_CURRENT_RELEASE_PRS}]},
            completed='')
        label = github.Label.Label(
            requester='', headers='',
            attributes={
                'name': release_constants.LABEL_FOR_CURRENT_RELEASE_PRS},
            completed='')
        def mock_get_issues(unused_self, state, labels):  # pylint: disable=unused-argument
            return [pull1, pull2]
        def mock_get_label(unused_self, unused_name):
            return [label]

        get_issues_swap = self.swap(
            github.Repository.Repository, 'get_issues', mock_get_issues)
        get_label_swap = self.swap(
            github.Repository.Repository, 'get_label', mock_get_label)
        open_tab_swap = self.swap(
            common, 'open_new_tab_in_browser_if_possible', mock_open_tab)
        with get_issues_swap, get_label_swap, open_tab_swap:
            with self.assertRaisesRegexp(
                Exception, (
                    'There are PRs for current release which do not '
                    'have a \'%s\' label. Please ensure that '
                    'they are released before release summary '
                    'generation.') % (
                        release_constants.LABEL_FOR_RELEASED_PRS)):
                common.check_prs_for_current_release_are_released(mock_repo)

    def test_kill_processes_based_on_regex(self):
        killed = []

        def mock_kill(p):
            killed.append(MockPsutilProcess.cmdlines[p.index])

        def mock_cmdlines(p):
            return MockPsutilProcess.cmdlines[p.index]

        def mock_process_iter():
            return [MockPsutilProcess(0), MockPsutilProcess(1)]

        process_iter_swap = self.swap_with_checks(
            psutil, 'process_iter', mock_process_iter)
        kill_swap = self.swap(MockPsutilProcess, 'kill', mock_kill)
        cmdlines_swap = self.swap(MockPsutilProcess, 'cmdline', mock_cmdlines)
        with process_iter_swap, kill_swap, cmdlines_swap:
            common.kill_processes_based_on_regex(r'.*dev_appserver\.py')
        self.assertEqual(killed, [MockPsutilProcess.cmdlines[0]])

    def test_kill_processes_based_on_regex_when_access_denied(self):
        killed = []

        def mock_kill(p):
            killed.append(MockPsutilProcess.cmdlines[p.index])

        def mock_cmdlines(p):
            if p.index == 0:
                raise psutil.AccessDenied()
            return MockPsutilProcess.cmdlines[p.index]

        def mock_process_iter():
            return [MockPsutilProcess(0), MockPsutilProcess(1)]

        process_iter_swap = self.swap_with_checks(
            psutil, 'process_iter', mock_process_iter)
        kill_swap = self.swap(MockPsutilProcess, 'kill', mock_kill)
        cmdlines_swap = self.swap(MockPsutilProcess, 'cmdline', mock_cmdlines)
        with process_iter_swap, kill_swap, cmdlines_swap:
            common.kill_processes_based_on_regex(r'.*dev_appserver\.py')
        self.assertEqual(killed, [])

    def test_kill_process_when_psutil_not_in_path(self):
        path_swap = self.swap(sys, 'path', [])
        def mock_process_iter():
            return []
        process_iter_swap = self.swap(psutil, 'process_iter', mock_process_iter)
        with path_swap, process_iter_swap:
            common.kill_processes_based_on_regex('')

    def test_inplace_replace_file(self):
        origin_file = os.path.join(
            'core', 'tests', 'data', 'inplace_replace_test.json')
        backup_file = os.path.join(
            'core', 'tests', 'data', 'inplace_replace_test.json.bak')
        expected_lines = [
            '{\n',
            '    "RANDMON1" : "randomValue1",\n',
            '    "312RANDOM" : "ValueRanDom2",\n',
            '    "DEV_MODE": true,\n',
            '    "RAN213DOM" : "raNdoVaLue3"\n',
            '}\n'
        ]

        def mock_remove(unused_file):
            return

        remove_swap = self.swap_with_checks(
            os, 'remove', mock_remove, expected_args=[(backup_file,)]
        )
        with remove_swap:
            common.inplace_replace_file(
                origin_file, '"DEV_MODE": .*', '"DEV_MODE": true,')
        with python_utils.open_file(origin_file, 'r') as f:
            self.assertEqual(expected_lines, f.readlines())
        # Revert the file.
        os.remove(origin_file)
        shutil.move(backup_file, origin_file)

    def test_inplace_replace_file_with_exception_raised(self):
        origin_file = os.path.join(
            'core', 'tests', 'data', 'inplace_replace_test.json')
        backup_file = os.path.join(
            'core', 'tests', 'data', 'inplace_replace_test.json.bak')
        with python_utils.open_file(origin_file, 'r') as f:
            origin_content = f.readlines()

        def mock_compile(unused_arg):
            raise ValueError('Exception raised from compile()')

        compile_swap = self.swap_with_checks(re, 'compile', mock_compile)
        with self.assertRaisesRegexp(
            ValueError, r'Exception raised from compile\(\)'), compile_swap:
            common.inplace_replace_file(
                origin_file, '"DEV_MODE": .*', '"DEV_MODE": true,')
        self.assertFalse(os.path.isfile(backup_file))
        with python_utils.open_file(origin_file, 'r') as f:
            new_content = f.readlines()
        self.assertEqual(origin_content, new_content)

    def test_convert_to_posixpath_on_windows(self):
        def mock_is_windows():
            return True

        is_windows_swap = self.swap(common, 'is_windows_os', mock_is_windows)
        original_filepath = 'c:\\path\\to\\a\\file.js'
        with is_windows_swap:
            actual_file_path = common.convert_to_posixpath(original_filepath)
        self.assertEqual(actual_file_path, 'c:/path/to/a/file.js')

    def test_convert_to_posixpath_on_platform_other_than_windows(self):
        def mock_is_windows():
            return False

        is_windows_swap = self.swap(common, 'is_windows_os', mock_is_windows)
        original_filepath = 'c:\\path\\to\\a\\file.js'
        with is_windows_swap:
            actual_file_path = common.convert_to_posixpath(original_filepath)
        self.assertEqual(actual_file_path, original_filepath)

    def test_create_readme(self):
        try:
            os.makedirs('readme_test_dir')
            common.create_readme('readme_test_dir', 'Testing readme.')
            with python_utils.open_file('readme_test_dir/README.md', 'r') as f:
                self.assertEqual(f.read(), 'Testing readme.')
        finally:
            if os.path.exists('readme_test_dir'):
                shutil.rmtree('readme_test_dir')

    def test_windows_os_throws_exception_when_starting_redis_server(self):
        def mock_is_windows_os():
            return True
        windows_not_supported_exception = self.assertRaisesRegexp(
            Exception,
            'The redis command line interface is not installed because your '
            'machine is on the Windows operating system. The redis server '
            'cannot start.')
        swap_os_check = self.swap(common, 'is_windows_os', mock_is_windows_os)
        with swap_os_check, windows_not_supported_exception:
            common.start_redis_server()

    def test_windows_os_throws_exception_when_stopping_redis_server(self):
        def mock_is_windows_os():
            return True
        windows_not_supported_exception = self.assertRaisesRegexp(
            Exception,
            'The redis command line interface is not installed because your '
            'machine is on the Windows operating system. There is no redis '
            'server to shutdown.')
        swap_os_check = self.swap(common, 'is_windows_os', mock_is_windows_os)

        with swap_os_check, windows_not_supported_exception:
            common.stop_redis_server()

    def test_start_and_stop_server_calls_are_called(self):
        # Test that starting the server calls subprocess.call().
        check_function_calls = {
            'subprocess_call_is_called': False
        }
        expected_check_function_calls = {
            'subprocess_call_is_called': True
        }

        def mock_call(unused_cmd_tokens, *args, **kwargs):  # pylint: disable=unused-argument
            check_function_calls['subprocess_call_is_called'] = True
            class Ret(python_utils.OBJECT):
                """Return object with required attributes."""

                def __init__(self):
                    self.returncode = 0
                def communicate(self):
                    """Return required method."""
                    return '', ''
            return Ret()

        def mock_wait_for_port_to_be_open(port): # pylint: disable=unused-argument
            return

        swap_call = self.swap(subprocess, 'call', mock_call)
        swap_wait_for_port_to_be_open = self.swap(
            common, 'wait_for_port_to_be_open',
            mock_wait_for_port_to_be_open)
        with swap_call, swap_wait_for_port_to_be_open:
            common.start_redis_server()

        self.assertEqual(check_function_calls, expected_check_function_calls)

        # Test that stopping the server calls subprocess.call().
        check_function_calls = {
            'subprocess_call_is_called': False
        }
        expected_check_function_calls = {
            'subprocess_call_is_called': True
        }

        swap_call = self.swap(subprocess, 'call', mock_call)
        with swap_call:
            common.stop_redis_server()

        self.assertEqual(check_function_calls, expected_check_function_calls)

    def test_start_server_removes_redis_dump(self):
        check_function_calls = {
            'os_remove_is_called': False
        }

        def mock_os_remove_file(file_path): # pylint: disable=unused-argument
            check_function_calls['os_remove_is_called'] = True

        def mock_os_path_exists(file_path): # pylint: disable=unused-argument
            return True

        def mock_call(unused_cmd_tokens, *args, **kwargs):  # pylint: disable=unused-argument
            class Ret(python_utils.OBJECT):
                """Return object with required attributes."""

                def __init__(self):
                    self.returncode = 0
                def communicate(self):
                    """Return required method."""
                    return '', ''
            return Ret()

        def mock_wait_for_port_to_be_open(port): # pylint: disable=unused-argument
            return

        swap_call = self.swap(subprocess, 'call', mock_call)
        swap_wait_for_port_to_be_open = self.swap(
            common, 'wait_for_port_to_be_open',
            mock_wait_for_port_to_be_open)
        swap_os_remove = self.swap(os, 'remove', mock_os_remove_file)
        swap_os_path_exists = self.swap(os.path, 'exists', mock_os_path_exists)
        with swap_call, swap_wait_for_port_to_be_open, swap_os_remove, (
            swap_os_path_exists):
            common.start_redis_server()

        self.assertTrue(check_function_calls['os_remove_is_called'])


text:
package nl.homeserver.energie.verbruikkosten;

import nl.homeserver.DatePeriod;
import nl.homeserver.energie.meterstand.Meterstand;
import nl.homeserver.energie.meterstand.MeterstandService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Year;
import java.util.List;
import java.util.Optional;

import static java.time.Month.*;
import static java.util.stream.IntStream.range;
import static nl.homeserver.DatePeriod.aPeriodWithToDate;
import static nl.homeserver.DateTimePeriod.aPeriodWithToDateTime;
import static nl.homeserver.energie.meterstand.MeterstandBuilder.aMeterstand;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class VerbruikServiceTest {

    @InjectMocks
    VerbruikService verbruikService;

    @Mock
    MeterstandService meterstandService;
    @Mock
    VerbruikKostenOverzichtService verbruikKostenOverzichtService;
    @Mock
    ActuallyRegisteredVerbruikProvider actuallyRegisteredVerbruikProvider;

    @Test
    void whenGetVerbruikPerDagForTwoDaysThenVerbruikKostenOverzichtServiceIsCalledForBothDays() {
        // given
        final LocalDate from = LocalDate.of(2016, JANUARY, 2);
        final LocalDate to = LocalDate.of(2016, JANUARY, 4);
        final DatePeriod period = aPeriodWithToDate(from, to);

        final VerbruikKostenOverzicht verbruikKostenOverzichtForDay1 = VerbruikKostenOverzicht.builder().build();
        when(verbruikKostenOverzichtService.getVerbruikEnKostenOverzicht(
                aPeriodWithToDateTime(from.atStartOfDay(), from.atStartOfDay().plusDays(1)), actuallyRegisteredVerbruikProvider
        ))
                                           .thenReturn(verbruikKostenOverzichtForDay1);

        final VerbruikKostenOverzicht verbruikKostenOverzichtForDay2 = VerbruikKostenOverzicht.builder().build();
        when(verbruikKostenOverzichtService.getVerbruikEnKostenOverzicht(
                aPeriodWithToDateTime(from.plusDays(1).atStartOfDay(), from.plusDays(2).atStartOfDay()), actuallyRegisteredVerbruikProvider
        ))
                                           .thenReturn(verbruikKostenOverzichtForDay2);

        // when
        final List<VerbruikKostenOpDag> verbruikPerDag = verbruikService.getVerbruikPerDag(period);

        // then
        assertThat(verbruikPerDag).satisfiesExactly(
                verbruikKostenDay1 -> {
                    assertThat(verbruikKostenDay1.getDag()).isEqualTo(from);
                    assertThat(verbruikKostenDay1.getVerbruikKostenOverzicht()).isSameAs(verbruikKostenOverzichtForDay1);
                },
                verbruikKostenDay2 -> {
                    assertThat(verbruikKostenDay2.getDag()).isEqualTo(from.plusDays(1));
                    assertThat(verbruikKostenDay2.getVerbruikKostenOverzicht()).isSameAs(verbruikKostenOverzichtForDay2);
                });
    }

    @Test
    void whenGetVerbruikPerUurOpDagThenVerbruikKostenOverzichtServiceIsCalledForAllHoursInDay() {
        // given
        final LocalDate day = LocalDate.of(2016, JANUARY, 2);

        final VerbruikKostenOverzicht verbruikKostenOverzichtForHour1 = VerbruikKostenOverzicht.builder().build();
        when(verbruikKostenOverzichtService.getVerbruikEnKostenOverzicht(
                aPeriodWithToDateTime(day.atStartOfDay(), day.atStartOfDay().plusHours(1)), actuallyRegisteredVerbruikProvider
        ))
                                           .thenReturn(verbruikKostenOverzichtForHour1);

        final VerbruikKostenOverzicht verbruikKostenOverzichtForHour2 = VerbruikKostenOverzicht.builder().build();
        when(verbruikKostenOverzichtService.getVerbruikEnKostenOverzicht(
                aPeriodWithToDateTime(day.atStartOfDay().plusHours(1), day.atStartOfDay().plusHours(2)), actuallyRegisteredVerbruikProvider
        ))
                                           .thenReturn(verbruikKostenOverzichtForHour2);

        // when
        final List<VerbruikInUurOpDag> verbruikPerUurOpDag = verbruikService.getVerbruikPerUurOpDag(day);

        // then
        assertThat(verbruikPerUurOpDag).hasSize(24);

        final VerbruikInUurOpDag verbruikKostenForHour1 = verbruikPerUurOpDag.get(0);
        assertThat(verbruikKostenForHour1.getUur()).isZero();
        assertThat(verbruikKostenForHour1.getVerbruikKostenOverzicht()).isSameAs(verbruikKostenOverzichtForHour1);

        final VerbruikInUurOpDag verbruikKostenForHour2 = verbruikPerUurOpDag.get(1);
        assertThat(verbruikKostenForHour2.getUur()).isEqualTo(1);
        assertThat(verbruikKostenForHour2.getVerbruikKostenOverzicht()).isSameAs(verbruikKostenOverzichtForHour2);

        range(0, 24).forEach(hour ->
            verify(verbruikKostenOverzichtService).getVerbruikEnKostenOverzicht(
                    aPeriodWithToDateTime(day.atStartOfDay().plusHours(hour), day.atStartOfDay().plusHours(hour + 1)), actuallyRegisteredVerbruikProvider
            )
        );
    }

    @Test
    void whenGetVerbruikPerMaandInJaarThenVerbruikKostenOverzichtServiceIsCalledForAllMonthsInYear() {
        // given
        final int year = 2018;

        final VerbruikKostenOverzicht verbruikKostenOverzichtForJanuary = VerbruikKostenOverzicht.builder().build();
        when(verbruikKostenOverzichtService.getVerbruikEnKostenOverzicht(
                aPeriodWithToDateTime(LocalDate.of(year, JANUARY, 1).atStartOfDay(),
                                      LocalDate.of(year, FEBRUARY, 1).atStartOfDay()), actuallyRegisteredVerbruikProvider
        ))
                                           .thenReturn(verbruikKostenOverzichtForJanuary);

        final VerbruikKostenOverzicht verbruikKostenOverzichtForFebruary = VerbruikKostenOverzicht.builder().build();
        when(verbruikKostenOverzichtService.getVerbruikEnKostenOverzicht(
                aPeriodWithToDateTime(LocalDate.of(year, FEBRUARY, 1).atStartOfDay(),
                                      LocalDate.of(year, MARCH, 1).atStartOfDay()), actuallyRegisteredVerbruikProvider
        ))
                                           .thenReturn(verbruikKostenOverzichtForFebruary);

        // when
        final List<VerbruikInMaandInJaar> verbruikPerMaandInJaar = verbruikService.getVerbruikPerMaandInJaar(Year.of(year));

        // then
        assertThat(verbruikPerMaandInJaar).hasSize(12);

        final VerbruikInMaandInJaar verbruikKostenForMonth1 = verbruikPerMaandInJaar.get(0);
        assertThat(verbruikKostenForMonth1.getMaand()).isEqualTo(1);
        assertThat(verbruikKostenForMonth1.getVerbruikKostenOverzicht()).isSameAs(verbruikKostenOverzichtForJanuary);

        final VerbruikInMaandInJaar verbruikKostenForHour2 = verbruikPerMaandInJaar.get(1);
        assertThat(verbruikKostenForHour2.getMaand()).isEqualTo(2);
        assertThat(verbruikKostenForHour2.getVerbruikKostenOverzicht()).isSameAs(verbruikKostenOverzichtForFebruary);

        range(1, 12).forEach(month -> {
                final LocalDateTime from = LocalDate.of(year, month, 1).atStartOfDay();
                final LocalDateTime to = LocalDate.of(year, month + 1, 1).atStartOfDay();
                verify(verbruikKostenOverzichtService).getVerbruikEnKostenOverzicht(
                        aPeriodWithToDateTime(from, to), actuallyRegisteredVerbruikProvider);
            }
        );
    }

    @Test
    void givenMeterstandenExistsForTwoYearsWhenGetVerbruikPerJaarThenVerbruikKostenOverzichtServiceIsCalledForBothYears() {
        // given
        final Meterstand meterstandFor2018 = aMeterstand().withDateTime(LocalDate.of(2018, JANUARY, 1).atStartOfDay()).build();
        when(meterstandService.getOldest()).thenReturn(Optional.of(meterstandFor2018));

        final Meterstand meterstandFor2019 = aMeterstand()
                .withDateTime(LocalDate.of(2019, JANUARY, 1).atStartOfDay()).build();
        when(meterstandService.getMostRecent()).thenReturn(Optional.of(meterstandFor2019));

        final VerbruikKostenOverzicht verbruikKostenOverzichtFor2018 = VerbruikKostenOverzicht.builder().build();
        when(verbruikKostenOverzichtService.getVerbruikEnKostenOverzicht(
                aPeriodWithToDateTime(LocalDate.of(2018, JANUARY, 1).atStartOfDay(),
                                      LocalDate.of(2019, JANUARY, 1).atStartOfDay()), actuallyRegisteredVerbruikProvider
        ))
                                           .thenReturn(verbruikKostenOverzichtFor2018);

        final VerbruikKostenOverzicht verbruikKostenOverzichtFor2019 = VerbruikKostenOverzicht.builder().build();
        when(verbruikKostenOverzichtService.getVerbruikEnKostenOverzicht(
                aPeriodWithToDateTime(LocalDate.of(2019, JANUARY, 1).atStartOfDay(),
                                      LocalDate.of(2020, JANUARY, 1).atStartOfDay()), actuallyRegisteredVerbruikProvider
        ))
                                           .thenReturn(verbruikKostenOverzichtFor2019);

        // when
        final List<VerbruikInJaar> verbruikPerJaar = verbruikService.getVerbruikPerJaar();

        // then
        assertThat(verbruikPerJaar).satisfiesExactly(
                verbruikInJaar2018 -> {
                    assertThat(verbruikInJaar2018.getJaar()).isEqualTo(2018);
                    assertThat(verbruikInJaar2018.getVerbruikKostenOverzicht()).isSameAs(verbruikKostenOverzichtFor2018);
                },
                verbruikInJaar2019 -> {
                    assertThat(verbruikInJaar2019.getJaar()).isEqualTo(2019);
                    assertThat(verbruikInJaar2019.getVerbruikKostenOverzicht()).isSameAs(verbruikKostenOverzichtFor2019);
                }
        );
    }

    @Test
    void givenNoMeterstandenExistsWhenGetVerbruikPerJaarThenResultIsEmpty() {
        // given
        when(meterstandService.getOldest()).thenReturn(Optional.empty());

        // when
        final List<VerbruikInJaar> verbruikPerJaar = verbruikService.getVerbruikPerJaar();

        // then
        assertThat(verbruikPerJaar).isEmpty();
    }

    @Test
    void whenGetGemiddeldeVerbruikEnKostenInPeriodeThenAveragesAreReturned() {
        // given
        final LocalDate from = LocalDate.of(2016, JANUARY, 2);
        final LocalDate to = LocalDate.of(2016, JANUARY, 4);
        final DatePeriod period = aPeriodWithToDate(from, to);

        final VerbruikKostenOverzicht verbruikKostenOverzichtForDay1 = VerbruikKostenOverzicht.builder().build();
        when(verbruikKostenOverzichtService.getVerbruikEnKostenOverzicht(
                aPeriodWithToDateTime(from.atStartOfDay(), from.atStartOfDay().plusDays(1)), actuallyRegisteredVerbruikProvider
        ))
                                           .thenReturn(verbruikKostenOverzichtForDay1);

        final VerbruikKostenOverzicht verbruikKostenOverzichtForDay2 = VerbruikKostenOverzicht.builder().build();
        when(verbruikKostenOverzichtService.getVerbruikEnKostenOverzicht(
                aPeriodWithToDateTime(from.plusDays(1).atStartOfDay(), from.plusDays(2).atStartOfDay()), actuallyRegisteredVerbruikProvider
        ))
                                           .thenReturn(verbruikKostenOverzichtForDay2);

        // when
        final VerbruikKostenOverzicht gemiddeldeVerbruikEnKostenInPeriode =
                verbruikService.getGemiddeldeVerbruikEnKostenInPeriode(period);

        // then
        assertThat(gemiddeldeVerbruikEnKostenInPeriode).isNotNull();
    }
}


text:
$(function(){
    function myClass(){
        this.a = 5;
    };

    myClass.prototype.squarer = function(param){var v= param;
        return v*v;}

    var myObject = new myClass();

    console.log(myObject.a);
    console.log("Square of 8 is "+myObject.squarer(8));
});


text:
package lists

import (
	"fmt"
	"strings"
)

var malwaredomains = List{
	Key:         "malwaredomains.com",
	Name:        "DNS-BH – Malware Domain Blocklist",
	URL:         "http://www.malwaredomains.com/",
	Description: `The DNS-BH project creates and maintains a listing of domains that are known to be used to propagate malware and spyware. This project creates the Bind and Windows zone files required to serve fake replies to localhost for any requests to these, thus preventing many spyware installs and reporting.`,
	Iterator: TSV(
		"http://mirror1.malwaredomains.com/files/domains.txt",
		func(row []string) *Entry {
			var e *Entry
			if strings.HasPrefix(row[0], "20") {
				// row has a next validation info
				e = &Entry{
					Domain:      row[1],
					Category:    row[2],
					Description: fmt.Sprintf("%s marked it as %s", row[3], row[2]),
				}
			} else {
				// row has no next validation info, this tricks the csv parser
				e = &Entry{
					Domain:      row[0],
					Category:    row[1],
					Description: fmt.Sprintf("%s marked it as %s", row[2], row[1]),
				}
			}

			if category, ok := malwaredomainsCategories[e.Category]; ok {
				e.Category = category
				return e
			}

			return nil
		}),
}

var malwaredomainsCategories = map[string]string{
	"phishing":    "phishing",
	"malicious":   "malware",
	"attack_page": "attacker",
	"attackpage":  "attacker",
	"malware":     "malware",
	"botnet":      "botnet",
	"bedep":       "malware",
	"zeus":        "malware",
	"ransomware":  "malware",
	"malspam":     "malware",
	"simda":       "malware",
	"cryptowall":  "malware",
}

func init() {
	Lists = append(Lists, malwaredomains)
}


text:
{-# OPTIONS -XOverloadedStrings #-}

module QueueDeleteSpec (main, spec) where

import Test.Hspec
import Network.AMQP

main :: IO ()
main = hspec spec

spec :: Spec
spec = do
  describe "deleteQueue" $ do
      context "when queue exists" $ do
          it "deletes the queue" $ do
              conn <- openConnection "127.0.0.1" "/" "guest" "guest"
              ch   <- openChannel conn

              (q, _, _) <- declareQueue ch (newQueue {queueName      = "haskell-amqp.queues.to-be-deleted",
                                                      queueExclusive = True})

              n <- deleteQueue ch q
              n `shouldBe` 0

              let ex = (ChannelClosedException "NOT_FOUND - no queue 'haskell-amqp.queues.to-be-deleted' in vhost '/'")
              (declareQueue ch $ newQueue {queueName = q, queuePassive = True}) `shouldThrow` (== ex)

              closeConnection conn

          context "when queue DOES NOT exist" $ do
              it "throws an exception" $ do
                  conn <- openConnection "127.0.0.1" "/" "guest" "guest"
                  ch   <- openChannel conn

                  let q  = "haskell-amqp.queues.GmN8rozyXiz2mQYcFrQg"
                      ex = ChannelClosedException "NOT_FOUND - no queue 'haskell-amqp.queues.GmN8rozyXiz2mQYcFrQg' in vhost '/'"
                  (declareQueue ch $ newQueue {queueName = q, queuePassive = True}) `shouldThrow` (== ex)

                  closeConnection conn


text:
using System;
using System.Linq;
using FluentAssertions;
using Its.Log.Instrumentation;
using Microsoft.Its.Recipes;
using Microsoft.Owin.MockService;
using MyGetConnector.Tests.Extensions;
using Newtonsoft.Json;
using Xunit;

namespace MyGetConnector.Tests.AcceptanceTests
{
    public class PackageAddedSpecs
    {
        static PackageAddedSpecs()
        {
            Log.EntryPosted += (sender, e) => Console.WriteLine(e.LogEntry.ToString());
        }

        [Fact]
        public void When_no_trigger_callbacks_are_registered_Then_the_request_succeeds()
        {
            var packageUri = Any.Uri();

            using (var server = Microsoft.Owin.Testing.TestServer.Create<Startup>())
            {
                server.HttpClient.PostAsync("/api/MyGetWebhook/",
                    Any.MyGet.WebHooks.PackageAddedPayload(packageUri).ToJsonStringContent("application/vnd.myget.webhooks.v1+json"))
                    .Result
                    .ShouldSucceed();
            }
        }

        [Fact]
        public void When_one_trigger_callback_is_registered_Then_the_callback_is_notified_the_request_succeeds()
        {
            ConfigurationManagerExtensions.AddFakeAppServiceRuntimeSettings();

            var packageUri = Any.Uri();

            var callbackPath = Any.UriPath();

            using (var mockService = new MockService()
                .OnRequest(r => r.Path.ToString() == "/" + callbackPath)
                .RespondWith(r => r.StatusCode = 200))
            {
                var callbackUri = mockService.GetBaseAddress() + callbackPath;

                using (var server = Microsoft.Owin.Testing.TestServer.Create<Startup>())
                {
                    server.HttpClient.PutAsync(String.Format("/api/Trigger?triggerId={0}", Any.Guid()),
                            Any.Azure.AppServiceTrigger.MyGetConnectorTriggerBody(callbackUri).ToJsonStringContent())
                        .Wait();

                    server
                        .HttpClient
                        .AsMyGetTriggerSource()
                        .PostAsync("/api/MyGetWebhook/",
                            Any.MyGet.WebHooks.PackageAddedPayload(packageUri).ToJsonStringContent("application/vnd.myget.webhooks.v1+json"))
                        .Result
                        .ShouldSucceed();
                }
            }
        }

        [Fact]
        public void When_multiple_trigger_callbacks_are_registered_Then_the_callbacks_are_notified_the_request_succeeds()
        {
            ConfigurationManagerExtensions.AddFakeAppServiceRuntimeSettings();

            var packageUri = Any.Uri();

            var callbackPaths = Any.Sequence(x => Any.UriPath(1)).ToList();

            using (var mockService = new MockService())
            {
                using (var server = Microsoft.Owin.Testing.TestServer.Create<Startup>())
                {
                    foreach (var callbackPath in callbackPaths)
                    {
                        var closurePath = "/" + callbackPath;

                        mockService
                            .OnRequest(r => r.Path.ToString() == closurePath)
                            .RespondWith(r => r.StatusCode = 200);

                        var callbackUri = mockService.GetBaseAddress() + callbackPath;

                        server.HttpClient
                            .PutAsync(String.Format("/api/Trigger?triggerId={0}", Any.Guid()),
                                Any.Azure.AppServiceTrigger.MyGetConnectorTriggerBody(callbackUri).ToJsonStringContent())
                            .Wait();
                    }

                    server.HttpClient
                        .AsMyGetTriggerSource()
                        .PostAsync("/api/MyGetWebhook/",
                            Any.MyGet.WebHooks.PackageAddedPayload(packageUri).ToJsonStringContent("application/vnd.myget.webhooks.v1+json"))
                        .Result
                        .ShouldSucceed();
                }
            }
        }

        [Fact]
        public void When_one_trigger_callback_is_registered_but_target_is_not_available_Then_the_request_succeeds()
        {
            var packageUri = Any.Uri();

            ConfigurationManagerExtensions.AddFakeAppServiceRuntimeSettings();

            using (var server = Microsoft.Owin.Testing.TestServer.Create<Startup>())
            {
                server.HttpClient.PutAsync(String.Format("/api/Trigger?triggerId={0}", Any.Guid()),
                    Any.Azure.AppServiceTrigger.MyGetConnectorTriggerBody(Any.Uri().ToString()).ToJsonStringContent())
                    .Wait();

                server.HttpClient
                    .AsMyGetTriggerSource()
                    .PostAsync("/api/MyGetWebhook/",
                        Any.MyGet.WebHooks.PackageAddedPayload(packageUri).ToJsonStringContent("application/vnd.myget.webhooks.v1+json"))
                    .Result
                    .ShouldSucceed();
            }
        }

        [Fact]
        public void When_multiple_trigger_callbacks_are_registered_and_one_fails_Then_the_remaining_callbacks_are_notified_the_request_succeeds()
        {
            ConfigurationManagerExtensions.AddFakeAppServiceRuntimeSettings();

            var packageUri = Any.Uri();

            var callbackPaths = Any.Sequence(x => Any.UriPath(1)).ToList();

            using (var mockService = new MockService())
            {
                using (var server = Microsoft.Owin.Testing.TestServer.Create<Startup>())
                {
                    foreach (var callbackPath in callbackPaths)
                    {
                        var closurePath = "/" + callbackPath;

                        if (Any.Bool())
                        {
                            mockService
                                .OnRequest(r => r.Path.ToString() == closurePath)
                                .RespondWith(r => r.StatusCode = 200);
                        }

                        var callbackUri = mockService.GetBaseAddress() + callbackPath;

                        server.HttpClient.PutAsync(String.Format("/api/Trigger?triggerId={0}", Any.Guid()),
                            Any.Azure.AppServiceTrigger.MyGetConnectorTriggerBody(callbackUri)
                                .ToJsonStringContent())
                            .Wait();
                    }

                    server
                        .HttpClient
                        .AsMyGetTriggerSource()
                        .PostAsync("/api/MyGetWebhook/",
                            Any.MyGet.WebHooks.PackageAddedPayload(packageUri).ToJsonStringContent("application/vnd.myget.webhooks.v1+json"))
                        .Result
                        .ShouldSucceed();
                }
            }
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;
using SuperSocket.SocketBase;

namespace SuperSocket.QuickStart.GPSSocketServer
{
    class GPSCustomProtocol : ICustomProtocol<BinaryCommandInfo>
    {
        public ICommandReader<BinaryCommandInfo> CreateCommandReader(IAppServer appServer)
        {
            return new GPSCommandReader(appServer);
        }
    }
}


text:
from __future__ import print_function, division, absolute_import

from scipy.misc import lena
from numpy import ones
import numpy

#from numba.decorators import jit
#from numba import int32
from numba import autojit

#@jit(argtypes=[int32[:,:], int32[:,:]], restype=int32[:,:])
@autojit
def filter2d(image, filt):
    M, N = image.shape
    Mf, Nf = filt.shape
    Mf2 = Mf // 2
    Nf2 = Nf // 2
    result = numpy.zeros_like(image)
    for i in range(Mf2, M - Mf2):
        for j in range(Nf2, N - Nf2):
            num = 0.0
            for ii in range(Mf):
                for jj in range(Nf):
                    num += (filt[Mf-1-ii, Nf-1-jj] * image[i-Mf2+ii, j-Nf2+jj])
            result[i, j] = num
    return result

#image = lena()
#filter = ones((7,7), dtype='int32')
image = numpy.random.random((500, 500))
filter = ones((250, 250), dtype='int32')

import time
start = time.time()
result = filter2d(image, filter)
duration = time.time() - start

#from scipy.ndimage import convolve
from scipy import signal
start = time.time()
result = signal.fftconvolve(image, filter)
#result = convolve(image, filter)
duration2 = time.time() - start

print("Time for LLVM code = %f\nTime for convolve = %f" % (duration, duration2))

#from pylab import subplot, imshow, show, title, gray
#subplot(1,2,1)
#imshow(image)
#title('Original Image')
#gray()
#subplot(1,2,2)
#imshow(result)
#title('Filtered Image')
#gray()
#show()


text:
using Rayman;

public class ItemVO{
	public int metaId;
	public int num;

	public ItemVO(){
		metaId = -1;
		num = 0;
	}

	public ItemVO(int mid){
		metaId = mid;
		num = 0;
	}

	public ItemVO(int mid, int pnum){
		metaId = mid;
		num = pnum;
	}

	public CItemMeta meta{
		get { return CItemMetaManager.GetMeta(metaId); }
	}
}


text:
package net.i2p.data.i2cp;

/*
 * free (adj.): unencumbered; not under the control of others
 * Written by jrandom in 2003 and released into the public domain
 * with no warranty of any kind, either expressed or implied.
 * It probably won't make your computer catch on fire, or eat
 * your children, but it might.  Use at your own risk.
 *
 */

import java.io.IOException;
import java.io.InputStream;

import net.i2p.data.DataFormatException;
import net.i2p.data.DataHelper;

/**
 * Defines the message a client sends to a router when asking the
 * router to start sending a message to it.
 *
 * @author jrandom
 */
public class ReceiveMessageEndMessage extends I2CPMessageImpl {
    public final static int MESSAGE_TYPE = 7;
    private int _sessionId;
    private long _messageId;

    public ReceiveMessageEndMessage() {
        _sessionId = -1;
        _messageId = -1;
    }

    public long getSessionId() {
        return _sessionId;
    }

    /** @param id 0-65535 */
    public void setSessionId(long id) {
        _sessionId = (int) id;
    }

    public long getMessageId() {
        return _messageId;
    }

    public void setMessageId(long id) {
        _messageId = id;
    }

    @Override
    protected void doReadMessage(InputStream in, int size) throws I2CPMessageException, IOException {
        try {
            _sessionId = (int) DataHelper.readLong(in, 2);
            _messageId = DataHelper.readLong(in, 4);
        } catch (DataFormatException dfe) {
            throw new I2CPMessageException("Unable to load the message data", dfe);
        }
    }

    @Override
    protected byte[] doWriteMessage() throws I2CPMessageException, IOException {
        if ((_sessionId < 0) || (_messageId < 0))
            throw new I2CPMessageException("Unable to write out the message as there is not enough data");
        byte rv[] = new byte[2+4];
        DataHelper.toLong(rv, 0, 2, _sessionId);
        DataHelper.toLong(rv, 2, 4, _messageId);
        return rv;
    }

    public int getType() {
        return MESSAGE_TYPE;
    }

    @Override
    public String toString() {
        StringBuilder buf = new StringBuilder();
        buf.append("[ReceiveMessageEndMessage: ");
        buf.append("\n\tSessionId: ").append(_sessionId);
        buf.append("\n\tMessageId: ").append(_messageId);
        buf.append("]");
        return buf.toString();
    }
}


text:
package org.eclipse.php.internal.core.codeassist.contexts;

import java.util.ArrayList;
import java.util.List;

/**
 * This context represents the state when staying inside of a PHPDoc tag.

 * Examples:
 *
 *

 *   1. /**
 *       * @var My_|
 *
 *   2. /**
 *       * @var |
 *

 *
 * @author zhao
 */
public class PHPDocVarStartContext extends AbstractPHPDocTagStartContext {

	public static List<String> TAGS = new ArrayList<String>();

	static {
		TAGS.add("return"); //$NON-NLS-1$
		TAGS.add("see"); //$NON-NLS-1$
		TAGS.add("var"); //$NON-NLS-1$
		TAGS.add("link"); //$NON-NLS-1$
	}

	@Override
	protected List<String> getTags() {
		return TAGS;
	}

}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>de.schwellach.examples</groupId>
	<artifactId>java-raspberry-pi-gpio</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<properties>
		<version.compiler.plugin>3.1</version.compiler.plugin>

		<!-- maven-compiler-plugin -->
		<maven.compiler.target>1.8</maven.compiler.target>
		<maven.compiler.source>1.8</maven.compiler.source>

		<slf4j.version>1.7.7</slf4j.version>
		<junit.version>4.11</junit.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>${slf4j.version}</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.pi4j</groupId>
			<artifactId>pi4j-core</artifactId>
			<version>1.0</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>java-raspberry-pi-gpio</finalName>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>${version.compiler.plugin}</version>
				<configuration>
					<source>${maven.compiler.source}</source>
					<target>${maven.compiler.target}</target>
				</configuration>
			</plugin>

			<plugin>
				<artifactId>maven-assembly-plugin</artifactId>
				<configuration>
					<archive>
						<manifest>
							<mainClass>de.schwellach.examples.javaraspberrypigpio.Main</mainClass>
						</manifest>
					</archive>
					<descriptorRefs>
						<descriptorRef>jar-with-dependencies</descriptorRef>
					</descriptorRefs>
				</configuration>
				<executions>
					<execution>
						<id>make-assembly</id> <!-- this is used for inheritance merges -->
						<phase>package</phase> <!-- bind to the packaging phase -->
						<goals>
							<goal>single</goal>
						</goals>
					</execution>
				</executions>
			</plugin>

		</plugins>
	</build>
</project>


text:
package com.zw.yzk.refresh.library;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

import com.zw.yzk.refresh.library.loadmore.GridSpanLookup;
import com.zw.yzk.refresh.library.loadmore.LoadMoreViewCreator;
import com.zw.yzk.refresh.library.loadmore.WrapperAdapter;
import com.zw.yzk.refresh.library.loadmore.WrapperSpanSizeLookup;
import com.zw.yzk.refresh.library.refrsh.RefreshViewCreator;

public class PullToRefreshLayout extends LinearLayout {

    private RefreshHelper refreshHelper;
    // 刷新回调接口
    private OnRefreshListener mListener;
    private float lastY;
    // 下拉的距离。
    public float pullDownY = 0;
    private MyTimer timer;
    // 在刷新过程中滑动操作
    private boolean isTouch = false;
    //下拉布局
    private LinearLayout refreshView;
    //contentView
    private View contentView;
    // 过滤多点触碰
    private int mEvents;

    public PullToRefreshLayout(Context context) {
        this(context, null);
    }

    public PullToRefreshLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PullToRefreshLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        intiSettings(context);
    }

    //初始化设置
    private void intiSettings(Context context) {
        refreshHelper = new RefreshHelper(updateHandler);

        timer = refreshHelper.getTimer();
        setOrientation(VERTICAL);

        initRefreshLayout(context);
    }

    //初始化RefreshView
    private void initRefreshLayout(Context context) {
        refreshView = new LinearLayout(context);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
        refreshView.setGravity(Gravity.CENTER);
        refreshView.setLayoutParams(params);
        addView(refreshView, 0);
    }

    //获取refreshHelper
    public RefreshHelper getRefreshHelper() {
        return this.refreshHelper;
    }

    //设置刷新是否可用
    public void setRefreshEnable(boolean state) {
        refreshHelper.setRefreshEnable(state);
    }

    //设置上拉加载是否可用
    public void setLoadMoreEnable(boolean state) {
        refreshHelper.setLoadMoreEnable(state);
    }

    private void hide() {
        timer.schedule(5);
    }

    //设置监听事件
    public void setOnRefreshListener(final OnRefreshListener listener) {
        mListener = listener;
        if (!(contentView instanceof RecyclerView)) {
            return;
        }
        ((RecyclerView) contentView).addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (refreshHelper.getState() == State.NO_ITEM_LOADING || isLoading() || isRefreshing()) {
                    return;
                }
                if (refreshHelper.checkEndOffset(recyclerView) && mListener != null && dy > 0 && refreshHelper.isLoadMoreEnable()) {
                    mListener.onLoadMore(PullToRefreshLayout.this);
                    refreshHelper.setState(State.LOADING);
                }
            }

        });
    }

    //设置loadingView
    public void setLoadingViewCreator(LoadMoreViewCreator loadMoreViewCreator) {
        if (contentView instanceof RecyclerView) {
            RecyclerView recyclerView = (RecyclerView) contentView;
            WrapperAdapter wrapperAdapter = refreshHelper.createAdapter(recyclerView.getAdapter(), loadMoreViewCreator);
            recyclerView.setAdapter(wrapperAdapter);

            if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
                WrapperSpanSizeLookup wrapperSpanSizeLookup = new WrapperSpanSizeLookup(
                        ((GridLayoutManager) recyclerView.getLayoutManager()).getSpanSizeLookup(),
                        new GridSpanLookup(recyclerView.getLayoutManager()),
                        wrapperAdapter);
                ((GridLayoutManager) recyclerView.getLayoutManager()).setSpanSizeLookup(wrapperSpanSizeLookup);
            }
        }
    }

    //设置refreshView
    public void setRefreshViewCreator(RefreshViewCreator refreshViewCreator) {
        refreshHelper.setRefreshViewCreator(refreshViewCreator);
        if (refreshView.getChildCount() != 0) {
            refreshView.removeAllViews();
        }
        refreshView.addView(refreshHelper.getRefreshViewCreator().createView(getContext())
                , new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        refreshHelper.setState(State.INIT);
    }

    //设置header
    public void setHeader(View header) {
        if (contentView != null && contentView instanceof RecyclerView) {
            refreshHelper.setHeader(header);
        }
    }

    //移除header
    public void removeHeader() {
        refreshHelper.removeHeader();
    }

    // 设置刷新结果刷新完成后一定要调用 刷新成功: State.REFRESH_SUCCEED, 失败:State.REFRESH_FAIL,
    public void refreshFinish(State refreshResult) {
        refreshHelper.setState(refreshResult);

        if (pullDownY > 0) {
            // 刷新结果停留1秒
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    refreshHelper.setState(State.DONE);
                    hide();
                }
            }, refreshHelper.getSuccessDelay());
        } else {
            refreshHelper.setState(State.DONE);
            hide();
        }
    }

    //设置加载结果刷新完成后一定要调用 加载成功: State.LOADING_SUCCEED, 失败:State.LOADING_FAIL,没有更多:State.LOADING_FAIL
    public void loadMoreFinish(State loadResult) {
        refreshHelper.setState(loadResult);
    }

    public boolean isRefreshing() {
        return refreshHelper.getState() == State.REFRESHING;
    }

    public boolean isLoading() {
        return refreshHelper.getState() == State.LOADING;
    }

    /**
     * 设置刷新或者加载状态完成
     *
     * @param succeed 完成结果 true: 成功,false: 失败
     */
    public void finishRefreshingOrLoadingStatus(boolean succeed) {
        if (succeed) {
            if (isLoading()) {
                loadMoreFinish(State.LOADING_SUCCEED);
            } else if (isRefreshing()) {
                refreshFinish(State.REFRESH_SUCCEED);
            }
        } else {
            if (isLoading()) {
                loadMoreFinish(State.LOADING_FAIL);
            } else if (isRefreshing()) {
                refreshFinish(State.REFRESH_FAIL);
            }
        }
    }

    //是否可以下拉刷新,只有contentView本身不能下滑的时候下拉头才能开始下滑
    private boolean canPullDown() {
        return !ViewCompat.canScrollVertically(contentView, -1) && refreshHelper.getState() != State.LOADING;
    }

    // 由父控件决定是否分发事件,防止事件冲突
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (!refreshHelper.isRefreshEnable()) {
            return super.dispatchTouchEvent(ev);
        }
        switch (ev.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
                lastY = ev.getY();
                timer.cancel();
                mEvents = 0;
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
            case MotionEvent.ACTION_POINTER_UP:
                // 过滤多点触碰
                mEvents = -1;
                break;
            case MotionEvent.ACTION_MOVE:
                if (mEvents == 0) {
                    if (pullDownY > 0 || (canPullDown() && !isLoading())) {
                        // 可以下拉,正在加载时不能下拉
                        // 对实际滑动距离做缩小,造成用力拉的感觉
                        pullDownY = pullDownY + (ev.getY() - lastY) / refreshHelper.getRadio();
                        if (pullDownY < 0) {
                            pullDownY = 0;
                        }
                        if (pullDownY > getMeasuredHeight())
                            pullDownY = getMeasuredHeight();
                        if (isRefreshing()) {
                            // 正在刷新的时候触摸移动
                            isTouch = true;
                        }
                    }
                    if (refreshHelper.getState() != State.REFRESHING && pullDownY > 0f) {
                        float percent = pullDownY / refreshHelper.getRefreshDist();
                        refreshHelper.getRefreshViewCreator().stateMove(percent < 1f ? percent : 1f);
                    }
                } else {
                    mEvents = 0;
                }
                lastY = ev.getY();
                // 根据下拉距离改变比例
                refreshHelper.setRadio((float) (2 + 2 * Math.tan(Math.PI / 2 / getMeasuredHeight() * pullDownY)));
                if (pullDownY > 0) {
                    requestLayout();
                    if (pullDownY <= refreshHelper.getRefreshDist()
                            && (refreshHelper.getState() == State.RELEASE_TO_REFRESH ||
                            refreshHelper.getState() == State.DONE || refreshHelper.getState() == State.NO_ITEM_LOADING)) {
                        // 如果下拉距离没达到刷新的距离且当前状态是释放刷新,改变状态为下拉刷新
                        refreshHelper.setState(State.INIT);
                    }
                    if (pullDownY >= refreshHelper.getRefreshDist() && refreshHelper.getState() == State.INIT) {
                        // 如果下拉距离达到刷新的距离且当前状态是初始状态刷新,改变状态为释放刷新
                        refreshHelper.setState(State.RELEASE_TO_REFRESH);
                    }
                    // 取消子控件的按下事件
                    ev.setAction(MotionEvent.ACTION_CANCEL);
                }
                break;
            case MotionEvent.ACTION_UP:
                if (pullDownY > refreshHelper.getRefreshDist()) {
                    // 正在刷新时往下拉(正在加载时往上拉),释放后下拉头(上拉头)不隐藏
                    isTouch = false;
                }
                if (refreshHelper.getState() == State.RELEASE_TO_REFRESH) {
                    refreshHelper.setState(State.REFRESHING);
                    // 刷新操作
                    if (mListener != null)
                        mListener.onRefresh(this);
                }
                hide();
                break;
            case MotionEvent.ACTION_CANCEL:
                hide();
                break;
            default:
                break;
        }
        // 事件分发交给父类
        super.dispatchTouchEvent(ev);
        return true;
    }

    private class AutoRefreshAndLoadTask extends
            AsyncTask<Integer, Float, String> {
        @Override
        protected String doInBackground(Integer... params) {
            while (pullDownY < 4 / 3 * refreshHelper.getRefreshDist()) {
                pullDownY = refreshHelper.getRefreshDist();
                publishProgress(pullDownY);
                try {
                    Thread.sleep(params[0]);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            refreshHelper.setState(State.REFRESHING);
            // 刷新操作
            if (mListener != null)
                mListener.onRefresh(PullToRefreshLayout.this);
            hide();
        }

        @Override
        protected void onProgressUpdate(Float... values) {
            if (pullDownY > refreshHelper.getRefreshDist())
                refreshHelper.setState(State.RELEASE_TO_REFRESH);
            requestLayout();
        }
    }

    //设置自动刷新
    public void autoRefresh() {
        if (isRefreshing() || !refreshHelper.isRefreshEnable()) {
            return;
        }
        AutoRefreshAndLoadTask task = new AutoRefreshAndLoadTask();
        task.execute(20);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();

        contentView = getChildAt(1);

        refreshHelper.setRefreshDist(refreshView.getMeasuredHeight());
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        // 改变子控件的布局
//        refreshView.layout(0, (int) pullDownY - refreshView.getMeasuredHeight(), refreshView.getMeasuredWidth(), (int) pullDownY);
//        contentView.layout(0, (int) pullDownY, contentView.getMeasuredWidth(), (int) pullDownY
//                + contentView.getMeasuredHeight());
        refreshView.layout(0, (int) pullDownY - refreshView.getMeasuredHeight(), refreshView.getMeasuredWidth(), (int) pullDownY);
        MarginLayoutParams marginLayoutParams = (MarginLayoutParams) contentView.getLayoutParams();
        contentView.layout(marginLayoutParams.leftMargin + getPaddingLeft(), (int) pullDownY + marginLayoutParams.topMargin + getPaddingTop(),
                contentView.getMeasuredWidth() + marginLayoutParams.rightMargin + getPaddingRight(),
                (int) pullDownY + marginLayoutParams.topMargin + contentView.getMeasuredHeight() + getPaddingBottom());
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        for (int i = 0; i < getChildCount(); i++) {
            // 获取对应遍历下标的子元素
            View child = getChildAt(i);
            if (child.getVisibility() != View.GONE) {
                // 测量子元素并考量其外边距
                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
            }
        }

    }

    //执行自动回滚的handler
    Handler updateHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            // 回弹速度随下拉距离moveDeltaY增大而增大
            refreshHelper.setMoveSpeed((float) (8 + 5 * Math.tan(Math.PI / 2 / getMeasuredHeight() * (pullDownY))));
            if (!isTouch) {
                // 正在刷新,且没有往上推的话则悬停,显示"正在刷新..."
                if (isRefreshing() && pullDownY <= refreshHelper.getRefreshDist()) {
                    pullDownY = refreshHelper.getRefreshDist();
                    timer.cancel();
                }
            }
            if (pullDownY > 0) {
                pullDownY -= refreshHelper.getMoveSpeed();
            }
            if (pullDownY < 0) {
                // 已完成回弹
                pullDownY = 0;
            }
            // 刷新布局,会自动调用onLayout
            requestLayout();
            if (pullDownY == 0)
                timer.cancel();
        }
    };

    //下拉刷新、上拉加载回调接口
    public interface OnRefreshListener {
        //刷新回调接口
        void onRefresh(PullToRefreshLayout pullToRefreshLayout);

        //加载回调接口
        void onLoadMore(PullToRefreshLayout pullToRefreshLayout);
    }

}


text:
#include "stdafx.h"
#include "RuntimeClass.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

/// Instance of root runtime class.
CRuntimeClass<CObject> CObject::m_class(NULL);

/**
 * @param pBaseClass - pointer to base runtime class.
 * @return true if this class is defined from the base class.
 */
bool CBaseRuntimeClass::IsDerivedFrom(const CBaseRuntimeClass* pBaseClass) const
{
	const CBaseRuntimeClass* pClass = this;
	do
	{
		if (pClass == pBaseClass)
			return true;
		pClass = pClass->m_pBaseClass;
	}
	while (pClass != NULL);
	return false;
}


text:
package mdb;
import Jakarta.util.*;
import java.io.*;
import java.util.*;

public class Fld_decl_list extends AstList {

    public void execute () {

        super.execute();
    }

}


text:
import React from 'react';
import {List, ListItem} from 'material-ui/List';
import Divider from 'material-ui/Divider';

export default class CommentsList extends React.Component {

  render() {
    const {comments} = this.props;

    return (
      (
        <List>
          {comments && comments.map((comment, index) => {
            return (

                <ListItem
                  disabled
                  primaryText={

                      {comment.authorUsername}

                  }
                  secondaryText={

                      {comment.content}

                  }/>
                <Divider/>

            );
          })}
        </List>
      )
    );
  }
}


text:
package com.zhaomeng.study.usb;

import javax.usb.UsbException;

import org.junit.Test;

public class USBTests {
	@Test
	public void testList() throws SecurityException, UsbException{
		USBHelper.listDevices();
	}
}


text:
require_relative '../../helpers/coverage_helper'
require_relative '../../helpers/armagh_test'
require_relative '../../../lib/armagh/environment'
Armagh::Environment.init

require_relative '../../../lib/armagh/utils/processing_backoff'
require 'test/unit'

class TestProcessingBackoff < Test::Unit::TestCase

  def setup
    @max_time = 60
    @processing_backoff = Armagh::Utils::ProcessingBackoff.new(@max_time)
  end

  def test_backoff
    backoffs = []
    3.times do
      backoffs << @processing_backoff.backoff
    end

    backoffs.each do |backoff|
      assert_true backoff <= @max_time
    end

    assert_equal(3, backoffs.length)
  end

  def test_interruptable_backoff
    interrupt_time = 0.1
    backoff_time = 0

    until backoff_time >2
      start = Time.now
      backoff_time = @processing_backoff.interruptible_backoff { Time.now > start + interrupt_time }
      elapsed = Time.now - start
    end

    assert_true(elapsed < backoff_time)
  end

  def test_reset
    max_reset = 0
    100.times { max_reset = [@processing_backoff.interruptible_backoff { true }, max_reset].max }
    @processing_backoff.reset
    assert_true max_reset > @processing_backoff.interruptible_backoff { true }
  end
end