text:
{# templates/elected_official/elected_official_edit.html #}
{% extends "template_base.html" %}

{% block title %}{% if elected_official %}{{ elected_official.elected_official_name  }}{% else %}New Politician{% endif %}{% endblock %}

{%  block content %}
{% load template_filters %}
{% load humanize %}

    < Back to Elected Officials

{% if elected_official %}Edit Elected Official "{{ elected_official.elected_official_name }}"{% else %}New Elected Official{% endif %}

{% if error_message %}
{{ error_message }}
{% endif %}

<form action="{% url "elected_official:elected_official_edit_process" %}" method="post" class="form-horizontal">
{% csrf_token %}

<input type="hidden" name="elected_official_id" value="{% if elected_official %}{{ elected_official.id }}{% else %}0{% endif %}">

    Elected Official Name

        <input type="text" name="elected_official_name" id="elected_official_name_id" class="form-control"
               value="{% if elected_official %}{{ elected_official.elected_official_name|default_if_none:"" }}{% else %}{{ elected_official_name|default_if_none:"" }}{% endif %}" />
        {% if elected_official %}
            {{ elected_official.we_vote_id }}
            (delete elected official)
        {% else %}
            {{ we_vote_id }}
        {% endif %}

    State Code

        <input type="text" name="state_code" id="state_code_id" class="form-control"
               value="{% if elected_official %}{{ elected_official.state_code|default_if_none:"" }}{% else %}{{ state_code|default_if_none:"" }}{% endif %}" />

    Elected Official Name (for Google Civic matching)

        <input type="text" name="google_civic_candidate_name" id="google_civic_candidate_name_id" class="form-control"
               value="{% if elected_official %}{{ elected_official.google_civic_candidate_name|default_if_none:"" }}{% else %}{{ google_civic_candidate_name|default_if_none:"" }}{% endif %}" />

    Twitter Handle

        <input type="text" name="elected_official_twitter_handle" id="elected_official_twitter_handle_id" class="form-control"
               value="{% if elected_official %}{{ elected_official.elected_official_twitter_handle|default_if_none:"" }}{% else %}{{ elected_official_twitter_handle|default_if_none:"" }}{% endif %}" />
    {% if elected_official.elected_official_twitter_handle %}
        (Refresh Twitter Details)

        Twitter Name: {{ elected_official.twitter_name }}

        Twitter Description: {{ elected_official.twitter_description }}

        Twitter Location: {{ elected_official.twitter_location }}

        Twitter Followers: {{ elected_official.twitter_followers_count|intcomma }}

    {% endif %}
    {% if elected_official.twitter_url %}Twitter URL (from Google Civic): {{ elected_official.twitter_url }}{% endif %}

    Elected Official Website

        <input type="text" name="elected_official_url" id="elected_official_url_id" class="form-control"
               value="{% if elected_official %}{{ elected_official.elected_official_url|default_if_none:"" }}{% else %}{{ elected_official_url|default_if_none:"" }}{% endif %}" />

    Elected Official Party

        <input type="text" name="political_party" id="political_party_id" class="form-control"
               value="{% if elected_official %}{{ elected_official.political_party|default_if_none:"" }}{% else %}{{ political_party|default_if_none:"" }}{% endif %}" />

    MapLight Id

        <input type="text" name="maplight_id" id="maplight_id_id" class="form-control"
               value="{% if elected_official %}{{ elected_official.maplight_id|default_if_none:"" }}{% else %}{{ maplight_id|default_if_none:"" }}{% endif %}" />

cancel
<input name="submit_text" type="submit" value="{% if elected_official %}Update Elected Official{% else %}Save New Elected Official{% endif %}" />

</form>

{% if elected_official %}

{% if linked_candidate_list %}

Candidates Linked to this Elected Official

            Candidate Name
            State
            Election
            Office
            Twitter Handle
            Website
            Id
            We Vote Id
            Vote Smart Id

    {% for candidate in linked_candidate_list %}

            {{ forloop.counter }}

                {% if candidate.candidate_photo_url %}

                {% endif %}

            {{ candidate.candidate_name }}
            {{ candidate.get_candidate_state }}
            {{ candidate.election.election_name }} - {{ candidate.election.google_civic_election_id }}

        {% if candidate.office %}
                {{ candidate.office.office_name }}
        {% else %}
            (office missing)
        {% endif %}

            {% if candidate.candidate_twitter_handle %}{{ candidate.candidate_twitter_handle }}

                ({{ candidate.twitter_followers_count|intcomma }} followers){% endif %}
            {% if candidate.candidate_url %}{{ candidate.candidate_url }}{% endif %}
            {% if candidate.candidate_contact_form_url %}{{ candidate.candidate_contact_form_url }}{% endif %}
            {{ candidate.id }}
            {{ candidate.we_vote_id }}
                {% if candidate.politician_we_vote_id %}
                    {{ candidate.politician_we_vote_id }}
                {% endif %}

            {{ candidate.vote_smart_id|default_if_none:"" }}

    {% endfor %}

{% else %}

(no linked candidates found)

{% endif %}

{% if related_candidate_list %}

Candidates That Might Match This Elected Official

            Candidate Name
            State
            Election
            Office
            Twitter Handle
            Website
            Id
            We Vote Id
            Vote Smart Id

    {% for candidate in related_candidate_list %}

            {{ forloop.counter }}

                {% if candidate.candidate_photo_url %}

                {% endif %}

            {{ candidate.candidate_name }}

                (match to politician)

            {{ candidate.get_candidate_state }}
            {{ candidate.election.election_name }} - {{ candidate.election.google_civic_election_id }}

        {% if candidate.office %}
                {{ candidate.office.office_name }}
        {% else %}
            (office missing)
        {% endif %}

            {% if candidate.candidate_twitter_handle %}{{ candidate.candidate_twitter_handle }}

                ({{ candidate.twitter_followers_count|intcomma }} followers){% endif %}
            {% if candidate.candidate_url %}{{ candidate.candidate_url }}{% endif %}
            {% if candidate.candidate_contact_form_url %}{{ candidate.candidate_contact_form_url }}{% endif %}
            {{ candidate.id }}
            {{ candidate.we_vote_id }}
                {% if candidate.politician_we_vote_id %}
                    {{ candidate.politician_we_vote_id }}
                {% endif %}

            {{ candidate.vote_smart_id|default_if_none:"" }}

    {% endfor %}

{% endif %}

{% if duplicate_elected_official_list %}

Possible Duplicate Elected Officials

            Elected Official Name
            State
            Twitter Handle
            Website
            Id
            We Vote Id

    {% for elected_official in duplicate_elected_official_list %}

            {{ forloop.counter }}

                {% if elected_official.photo_url %}

                {% endif %}

            {{ elected_official.elected_official_name }}
            {{ elected_official.state_code }}
            {% if elected_official.elected_official_twitter_handle %}{{ elected_official.elected_official_twitter_handle }}

                ({{ elected_official.twitter_followers_count|intcomma }} followers){% endif %}
            {% if elected_official.elected_official_url %}{{ elected_official.elected_official_url }}{% endif %}
            {{ elected_official.id }}
            {{ elected_official.we_vote_id }}

    {% endfor %}

{% endif %}

Retrieve photos

    {% if elected_official.photo_url %}

    {% endif %}

    {% if elected_official.vote_smart_id and elected_official.vote_smart_id != False and elected_official.vote_smart_id != 'False' and elected_official.vote_smart_id != None and elected_official.vote_smart_id != 'None' %}

Vote Smart Ratings

Import Vote Smart Ratings for this Elected Official

        {% if rating_list %}

                ratingId
                sigId
                ratingName
                timeSpan
                candidateId
                rating

            {% for special_interest_group_rating in rating_list %}

                {{ forloop.counter }}
                {{ special_interest_group_rating.ratingId }}

                    {{ special_interest_group_rating.sigId }}
                {{ special_interest_group_rating.ratingName }}
                {{ special_interest_group_rating.timeSpan }}
                {{ special_interest_group_rating.candidateId }}
                {{ special_interest_group_rating.rating }}

            {% endfor %}

        {% else %}

(no special interest group ratings found)

        {% endif %}
    {% endif %}{# End of if elected_official.vote_smart_id #}

    {% if elected_official.twitter_profile_image_url_https_original %}

        Twitter Image (Original)

    {% endif %}

    {% if elected_official.twitter_profile_banner_url_https %}

        Twitter Banner

    {% endif %}
{% else %}

{# Only show other elected_officials running for this office when we are entering a new elected_official #}
{% if elected_official_list %}

Existing Elected Officials

            Elected Official Name
            State
            Twitter Handle
            Website
            Id
            We Vote Id
            Vote Smart Id

    {% for elected_official in elected_official_list %}

            {{ forloop.counter }}

                {% if elected_official.photo_url %}

                {% endif %}

            {{ elected_official.elected_official_name }}
            {{ elected_official.state_code }}
            {% if elected_official.elected_official_twitter_handle %}{{ elected_official.elected_official_twitter_handle }}

                ({{ elected_official.twitter_followers_count|intcomma }} followers){% endif %}
            {% if elected_official.elected_official_url %}{{ elected_official.elected_official_url }}{% endif %}
            {{ elected_official.id }}
            {{ elected_official.we_vote_id }}
            {{ elected_official.vote_smart_id }}
            (edit)

    {% endfor %}

{% else %}
    {# Don't display anything if there aren't any other elected_officials captured for this office yet #}
{% endif %}

{% endif %}{# End of if elected_official #}

{% endblock %}


text:
import os
import unittest

from horizon.utils import secret_key

class SecretKeyTests(unittest.TestCase):
    pass

    def test_generate_secret_key(self):
        key = secret_key.generate_key(32)
        self.assertEqual(32, len(key))
        self.assertNotEqual(key, secret_key.generate_key(32))

    def test_generate_or_read_key_from_file(self):
        key_file = ".test_secret_key_store"
        key = secret_key.generate_or_read_from_file(key_file)

        # Consecutive reads should come from the already existing file:
        self.assertEqual(secret_key.generate_or_read_from_file(key_file), key)

        # Key file only be read/writable by user:
        self.assertEqual(0o600, os.stat(key_file).st_mode & 0o777)
        os.chmod(key_file, 0o644)
        self.assertRaises(secret_key.FilePermissionError,
                          secret_key.generate_or_read_from_file, key_file)
        os.remove(key_file)

redpajama_set_name: RedPajamaGithub


text:
layout: default
title: Download | Appitat
---

Developer Tools coming soon.


text:
#if !defined(XMLSUPPORTINIT_INCLUDE_GUARD_1357924680)
#define XMLSUPPORTINIT_INCLUDE_GUARD_1357924680

// Base include file.  Must be first.
#include <xalanc/XMLSupport/XMLSupportDefinitions.hpp>

#include <xalanc/PlatformSupport/PlatformSupportInit.hpp>

#include <xalanc/DOMSupport/DOMSupportInit.hpp>

XALAN_CPP_NAMESPACE_BEGIN

class XALAN_XMLSUPPORT_EXPORT XMLSupportInit
{
public:

	explicit
	XMLSupportInit(MemoryManagerType& theManager XALAN_DEFAULT_MEMMGR);

	~XMLSupportInit();

private:

	// Not implemented...
	XMLSupportInit(const XMLSupportInit&);

	XMLSupportInit&
	operator=(const XMLSupportInit&);

	static void
	initialize(MemoryManagerType& theManager);

	static void
	terminate();

	const PlatformSupportInit	m_platformSupportInit;

	const DOMSupportInit		m_domSupportInit;

	static unsigned long		s_initCounter;
};

XALAN_CPP_NAMESPACE_END

#endif	// !defined(XMLSUPPORTINIT_INCLUDE_GUARD_1357924680)


text:
FactoryGirl.define do
  factory :boat, class: Stores::Boat do
    store
    name { Faker::Lorem.word }
    color { '123321' }
  end
end


text:
export const environment = {
    envName: 'dev',
    production: false,
    API_URL: "http://localhost:4567/api/"
};


text:
package com.microsoft.bingads.v12.api.test.entities.ad_extension.review;

import java.util.Map;

import com.microsoft.bingads.internal.functionalinterfaces.BiConsumer;
import com.microsoft.bingads.internal.functionalinterfaces.Function;
import com.microsoft.bingads.internal.functionalinterfaces.Supplier;
import com.microsoft.bingads.v12.api.test.entities.BulkEntityTest;
import com.microsoft.bingads.v12.bulk.entities.BulkCampaignReviewAdExtension;

public abstract class BulkCampaignReviewAdExtensionTest extends BulkEntityTest<BulkCampaignReviewAdExtension> {
    @Override
    protected void onEntityCreation(BulkCampaignReviewAdExtension entity) {
    }

    @Override
    protected <TProperty> void testWriteProperty(
            String header,
            String expectedRowValue, TProperty propertyValue,
            BiConsumer<BulkCampaignReviewAdExtension, TProperty> setFunc
    ) {
        this.testWriteProperty(header, expectedRowValue, propertyValue, setFunc, new Supplier<BulkCampaignReviewAdExtension>() {
            @Override
            public BulkCampaignReviewAdExtension get() {
                return new BulkCampaignReviewAdExtension();
            }
        });
    }

    @Override
    protected <TProperty> void testReadProperty(
            String header,
            String input,
            TProperty expectedResult,
            Function<BulkCampaignReviewAdExtension, TProperty> actualValueFunc
    ) {
        this.testReadProperty(header, input, expectedResult, actualValueFunc, new Supplier<BulkCampaignReviewAdExtension>() {
            @Override
            public BulkCampaignReviewAdExtension get() {
                return new BulkCampaignReviewAdExtension();
            }
        });
    }

    @Override
    protected <TProperty> void testReadProperty(
            Map<String, String> rowValues,
            TProperty expectedResult,
            Function<BulkCampaignReviewAdExtension, TProperty> actualValueFunc
    ) {
        this.testReadProperty(rowValues, expectedResult, actualValueFunc, new Supplier<BulkCampaignReviewAdExtension>() {
            @Override
            public BulkCampaignReviewAdExtension get() {
                return new BulkCampaignReviewAdExtension();
            }
        });
    }
}


text:
import unittest
import filecmp
import difflib

class templateTests(unittest.TestCase):
    def test_yaml_dict(self):
        expected = 'template/test/expected.yaml'
        generated = 'template/test/generated_dict.yaml'
        with open(expected) as e, open(generated) as g:
            expected_text = e.readlines()
            generated_text = g.readlines()
            for diff in difflib.unified_diff(expected_text, generated_text, fromfile = expected, tofile = generated, n = 0):
                print(diff)
        self.assertTrue(filecmp.cmp(expected, generated))

    def test_yaml_list(self):
        expected = 'template/test/expected.yaml'
        generated = 'template/test/generated_list.yaml'
        with open(expected) as e, open(generated) as g:
            expected_text = e.readlines()
            generated_text = g.readlines()
            for diff in difflib.unified_diff(expected_text, generated_text, fromfile = expected, tofile = generated, n = 0):
                print(diff)
        self.assertTrue(filecmp.cmp(expected, generated))

if __name__ == "__main__":
    unittest.main()


text: export { default } from 'ember-ui-components/utils/calculate-position';


text:
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_VERTICAL_POSITION_CACHE_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_VERTICAL_POSITION_CACHE_H_

#include "third_party/blink/renderer/core/layout/api/line_layout_item.h"
#include "third_party/blink/renderer/platform/fonts/font_baseline.h"
#include "third_party/blink/renderer/platform/wtf/allocator/allocator.h"
#include "third_party/blink/renderer/platform/wtf/hash_map.h"

namespace blink {

// Values for vertical alignment.
const int kPositionUndefined = 0x80000000;

class VerticalPositionCache {
  STACK_ALLOCATED();

 public:
  VerticalPositionCache() = default;
  VerticalPositionCache(const VerticalPositionCache&) = delete;
  VerticalPositionCache& operator=(const VerticalPositionCache&) = delete;

  int Get(LineLayoutItem layout_object, FontBaseline baseline_type) const {
    const HashMap<LineLayoutItem, int>& map_to_check =
        baseline_type == kAlphabeticBaseline ? alphabetic_positions_
                                             : ideographic_positions_;
    const HashMap<LineLayoutItem, int>::const_iterator it =
        map_to_check.find(layout_object);
    if (it == map_to_check.end())
      return kPositionUndefined;
    return it->value;
  }

  void Set(LineLayoutItem layout_object,
           FontBaseline baseline_type,
           int position) {
    if (baseline_type == kAlphabeticBaseline)
      alphabetic_positions_.Set(layout_object, position);
    else
      ideographic_positions_.Set(layout_object, position);
  }

 private:
  HashMap<LineLayoutItem, int> alphabetic_positions_;
  HashMap<LineLayoutItem, int> ideographic_positions_;
};

}  // namespace blink

#endif  // THIRD_PARTY_BLINK_RENDERER_CORE_LAYOUT_VERTICAL_POSITION_CACHE_H_


text:
@class NSArray, NSString;

@interface XCSPortalTeam : XCSObject
{
}

+ (id)portalTeamWithTeamID:(id)arg1 teamName:(id)arg2 identityCertificateID:(id)arg3 macProgramEnabled:(BOOL)arg4 iOSProgramEnabled:(BOOL)arg5 enabledDeviceIDs:(id)arg6;
- (BOOL)_validateTeamID:(id)arg1 teamName:(id)arg2 identityCertificateID:(id)arg3 macProgramEnabled:(BOOL)arg4 iOSProgramEnabled:(BOOL)arg5 enabledDeviceIDs:(id)arg6;
- (id)_initWithTeamID:(id)arg1 teamName:(id)arg2 identityCertificateID:(id)arg3 macProgramEnabled:(BOOL)arg4 iOSProgramEnabled:(BOOL)arg5 enabledDeviceIDs:(id)arg6;
- (id)dictionaryRepresentation;
- (id)initWithContents:(id)arg1 validationErrors:(id *)arg2;

// Remaining properties
@property(copy, nonatomic) NSArray *enabledDeviceIDs; // @dynamic enabledDeviceIDs;
@property(nonatomic) BOOL iOSProgramEnabled; // @dynamic iOSProgramEnabled;
@property(copy, nonatomic) NSString *identityCertificateID; // @dynamic identityCertificateID;
@property(nonatomic) BOOL macProgramEnabled; // @dynamic macProgramEnabled;
@property(copy, nonatomic) NSString *teamID; // @dynamic teamID;
@property(copy, nonatomic) NSString *teamName; // @dynamic teamName;

@end


text:
"use strict";

var Point = require("./point.js");

var reverseDirection = function(direction) {
    return (direction + 2) % 4;
};

var WalledCell = function WalledCell(point) {
    this.location = point;
    this.clear = false;
    this.walls = [true, true, true, true];
};
// TODO Should this also set clear=false? If so, add a reset to BlockCell
WalledCell.prototype.reset = function() {
    this.walls[0] = true;
    this.walls[1] = true;
    this.walls[2] = true;
    this.walls[3] = true;
};
WalledCell.prototype.toString = function() {
    return this.location + ' [' + (this.clear ? 'clear' : 'full') + ']';
};

var WalledGrid = function(width, height) {

    this.width = width;
    this.height = height;

    this.cells = new Array(width);
    for (var x = 0; x < this.cells.length; x++) {
        this.cells[x] = new Array(height);
        for (var y = 0; y < this.cells[x].length; y++) {
            var point = new Point(x, y);
            this.cells[x][y] = new WalledCell(point);
        }
    }
};
WalledGrid.prototype.getCell = function(point) {
    if (point.x < 0 || point.x >= this.width || point.y < 0 || point.y >= this.height) {
        return null;
    }

    return this.cells[point.x][point.y];
};
WalledGrid.prototype.getAdjacentNeighbours = function(point) {
    var neighbours = [ null, null, null, null, null, null, null, null];

    neighbours[1] = this.getCell(new Point(point.x, point.y - 1));
    neighbours[3] = this.getCell(new Point(point.x + 1, point.y));
    neighbours[5] = this.getCell(new Point(point.x, point.y + 1));
    neighbours[7] = this.getCell(new Point(point.x - 1, point.y));

    return neighbours;
};
WalledGrid.prototype.getAllNeighbours = function(point) {

    var neighbours = [ null, null, null, null, null, null, null, null];

    neighbours[0] = this.getCell(new Point(point.x - 1, point.y - 1));
    neighbours[1] = this.getCell(new Point(point.x, point.y - 1));
    neighbours[2] = this.getCell(new Point(point.x + 1, point.y - 1));

    neighbours[3] = this.getCell(new Point(point.x + 1, point.y));

    neighbours[4] = this.getCell(new Point(point.x + 1, point.y + 1));
    neighbours[5] = this.getCell(new Point(point.x, point.y + 1));
    neighbours[6] = this.getCell(new Point(point.x - 1, point.y + 1));

    neighbours[7] = this.getCell(new Point(point.x - 1, point.y));

    return neighbours;
};
WalledGrid.prototype.clearCell = function(point) {
    this.cells[point.x][point.y].clear = true;
};
// TODO Pass cell or points?
WalledGrid.prototype.clearPath = function(from, to) {

    var fromCell = this.cells[from.x][from.y];
    var toCell = this.cells[to.x][to.y];

    fromCell.clear = true;
    toCell.clear = true;

    var direction;
    // TODO Check that cells are adjacent
    if (from.y > to.y) {
        direction = 0;
    } else if (from.x < to.x) {
        direction = 1;
    } else if (from.y < to.y) {
        direction = 2;
    } else { // from.x > to.x
        direction = 3;
    }

    fromCell.walls[direction] = false;
    toCell.walls[reverseDirection(direction)] = false;
};
WalledGrid.prototype.fillCell = function(point) {

    var cell = this.cells[point.x][point.y];

    // We need to fill our open wall AND our neighbours open wall
    // If a wall is gone, we know the cell exists
    if (!cell.walls[0]) {
        this.cells[cell.location.x][cell.location.y - 1].walls[reverseDirection(0)] = true;
    }
    if (!cell.walls[1]) {
        this.cells[cell.location.x + 1][cell.location.y].walls[reverseDirection(1)] = true;
    }
    if (!cell.walls[2]) {
        this.cells[cell.location.x][cell.location.y + 1].walls[reverseDirection(2)] = true;
    }
    if (!cell.walls[3]) {
        this.cells[cell.location.x - 1][cell.location.y].walls[reverseDirection(3)] = true;
    }

    cell.clear = false;
    cell.reset();
};

module.exports = WalledGrid;


text:
App Engine centric Ruby samples

## Visual Sentiment Sample

Checkout a small Sinatra app which uses the Cloud Vision API to detect joy of a
persons face.

[Visual Sentiment Sample](visual_sentiment)

## CatSwap Sample

Checkout a small Sinatra app that will Catify a human face using the Cloud
Vision API!

[CatSwap](catswap)


text:
///This file was written by Erwin Coumans

#include "btMultiBodySliderConstraint.h"
#include "btMultiBodyLinkCollider.h"
#include "BulletDynamics/Dynamics/btRigidBody.h"
#include "BulletDynamics/ConstraintSolver/btGeneric6DofSpring2Constraint.h"
#include "LinearMath/btIDebugDraw.h"

#define BTMBSLIDERCONSTRAINT_DIM 5
#define EPSILON 0.000001

btMultiBodySliderConstraint::btMultiBodySliderConstraint(btMultiBody* body, int link, btRigidBody* bodyB, const btVector3& pivotInA, const btVector3& pivotInB, const btMatrix3x3& frameInA, const btMatrix3x3& frameInB, const btVector3& jointAxis)
	:btMultiBodyConstraint(body,0,link,-1,BTMBSLIDERCONSTRAINT_DIM,false),
	m_rigidBodyA(0),
	m_rigidBodyB(bodyB),
	m_pivotInA(pivotInA),
	m_pivotInB(pivotInB),
    m_frameInA(frameInA),
    m_frameInB(frameInB),
    m_jointAxis(jointAxis)
{
    m_data.resize(BTMBSLIDERCONSTRAINT_DIM);//at least store the applied impulses
}

btMultiBodySliderConstraint::btMultiBodySliderConstraint(btMultiBody* bodyA, int linkA, btMultiBody* bodyB, int linkB, const btVector3& pivotInA, const btVector3& pivotInB, const btMatrix3x3& frameInA, const btMatrix3x3& frameInB, const btVector3& jointAxis)
	:btMultiBodyConstraint(bodyA,bodyB,linkA,linkB,BTMBSLIDERCONSTRAINT_DIM,false),
	m_rigidBodyA(0),
	m_rigidBodyB(0),
	m_pivotInA(pivotInA),
	m_pivotInB(pivotInB),
    m_frameInA(frameInA),
    m_frameInB(frameInB),
    m_jointAxis(jointAxis)
{
    m_data.resize(BTMBSLIDERCONSTRAINT_DIM);//at least store the applied impulses
}

void btMultiBodySliderConstraint::finalizeMultiDof()
{
	//not implemented yet
	btAssert(0);
}

btMultiBodySliderConstraint::~btMultiBodySliderConstraint()
{
}

int btMultiBodySliderConstraint::getIslandIdA() const
{
	if (m_rigidBodyA)
		return m_rigidBodyA->getIslandTag();

	if (m_bodyA)
	{
		if (m_linkA < 0)
		{
			btMultiBodyLinkCollider* col = m_bodyA->getBaseCollider();
			if (col)
				return col->getIslandTag();
		}
		else
		{
			if (m_bodyA->getLink(m_linkA).m_collider)
				return m_bodyA->getLink(m_linkA).m_collider->getIslandTag();
		}
	}
	return -1;
}

int btMultiBodySliderConstraint::getIslandIdB() const
{
	if (m_rigidBodyB)
		return m_rigidBodyB->getIslandTag();
	if (m_bodyB)
	{
		if (m_linkB < 0)
		{
			btMultiBodyLinkCollider* col = m_bodyB->getBaseCollider();
			if (col)
				return col->getIslandTag();
		}
		else
		{
			if (m_bodyB->getLink(m_linkB).m_collider)
				return m_bodyB->getLink(m_linkB).m_collider->getIslandTag();
		}
	}
	return -1;
}
void btMultiBodySliderConstraint::createConstraintRows(btMultiBodyConstraintArray& constraintRows, btMultiBodyJacobianData& data, const btContactSolverInfo& infoGlobal)
{
    // Convert local points back to world
    btVector3 pivotAworld = m_pivotInA;
    btMatrix3x3 frameAworld = m_frameInA;
    btVector3 jointAxis = m_jointAxis;
    if (m_rigidBodyA)
    {
        pivotAworld = m_rigidBodyA->getCenterOfMassTransform()*m_pivotInA;
        frameAworld = m_frameInA.transpose()*btMatrix3x3(m_rigidBodyA->getOrientation());
        jointAxis = quatRotate(m_rigidBodyA->getOrientation(),m_jointAxis);

    } else if (m_bodyA) {
        pivotAworld = m_bodyA->localPosToWorld(m_linkA, m_pivotInA);
        frameAworld = m_bodyA->localFrameToWorld(m_linkA, m_frameInA);
        jointAxis = m_bodyA->localDirToWorld(m_linkA, m_jointAxis);
    }
    btVector3 pivotBworld = m_pivotInB;
    btMatrix3x3 frameBworld = m_frameInB;
    if (m_rigidBodyB)
    {
        pivotBworld = m_rigidBodyB->getCenterOfMassTransform()*m_pivotInB;
        frameBworld = m_frameInB.transpose()*btMatrix3x3(m_rigidBodyB->getOrientation());

    } else if (m_bodyB) {
        pivotBworld = m_bodyB->localPosToWorld(m_linkB, m_pivotInB);
        frameBworld = m_bodyB->localFrameToWorld(m_linkB, m_frameInB);
    }

    btVector3 constraintAxis[2];
    for (int i = 0; i < 3; ++i)
    {
        constraintAxis[0] = frameAworld.getColumn(i).cross(jointAxis);
        if (constraintAxis[0].safeNorm() > EPSILON)
        {
            constraintAxis[0] = constraintAxis[0].normalized();
            constraintAxis[1] = jointAxis.cross(constraintAxis[0]);
            constraintAxis[1] = constraintAxis[1].normalized();
            break;
        }
    }

    btMatrix3x3 relRot = frameAworld.inverse()*frameBworld;
    btVector3 angleDiff;
    btGeneric6DofSpring2Constraint::matrixToEulerXYZ(relRot,angleDiff);

    int numDim = BTMBSLIDERCONSTRAINT_DIM;
    for (int i=0;i<numDim;i++)
	{
        btMultiBodySolverConstraint& constraintRow = constraintRows.expandNonInitializing();
        constraintRow.m_orgConstraint = this;
        constraintRow.m_orgDofIndex = i;
        constraintRow.m_relpos1CrossNormal.setValue(0,0,0);
        constraintRow.m_contactNormal1.setValue(0,0,0);
        constraintRow.m_relpos2CrossNormal.setValue(0,0,0);
        constraintRow.m_contactNormal2.setValue(0,0,0);
        constraintRow.m_angularComponentA.setValue(0,0,0);
        constraintRow.m_angularComponentB.setValue(0,0,0);

        constraintRow.m_solverBodyIdA = data.m_fixedBodyId;
        constraintRow.m_solverBodyIdB = data.m_fixedBodyId;

        if (m_rigidBodyA)
        {
            constraintRow.m_solverBodyIdA = m_rigidBodyA->getCompanionId();
        }
        if (m_rigidBodyB)
        {
            constraintRow.m_solverBodyIdB = m_rigidBodyB->getCompanionId();
        }

        btVector3 constraintNormalLin(0,0,0);
        btVector3 constraintNormalAng(0,0,0);
        btScalar posError = 0.0;
        if (i < 2) {
            constraintNormalLin = constraintAxis[i];
            posError = (pivotAworld-pivotBworld).dot(constraintNormalLin);
            fillMultiBodyConstraint(constraintRow, data, 0, 0, constraintNormalAng,
                                    constraintNormalLin, pivotAworld, pivotBworld,
                                    posError,
                                    infoGlobal,
                                    -m_maxAppliedImpulse, m_maxAppliedImpulse
                                    );
        }
        else { //i>=2
            constraintNormalAng = frameAworld.getColumn(i%3);
            posError = angleDiff[i%3];
            fillMultiBodyConstraint(constraintRow, data, 0, 0, constraintNormalAng,
                                    constraintNormalLin, pivotAworld, pivotBworld,
                                    posError,
                                    infoGlobal,
                                    -m_maxAppliedImpulse, m_maxAppliedImpulse, true
                                    );
        }
	}
}

void btMultiBodySliderConstraint::debugDraw(class btIDebugDraw* drawer)
{
	btTransform tr;
	tr.setIdentity();

	if (m_rigidBodyA)
	{
		btVector3 pivot = m_rigidBodyA->getCenterOfMassTransform() * m_pivotInA;
		tr.setOrigin(pivot);
		drawer->drawTransform(tr, 0.1);
	}
	if (m_bodyA)
	{
		btVector3 pivotAworld = m_bodyA->localPosToWorld(m_linkA, m_pivotInA);
		tr.setOrigin(pivotAworld);
		drawer->drawTransform(tr, 0.1);
	}
	if (m_rigidBodyB)
	{
		// that ideally should draw the same frame
		btVector3 pivot = m_rigidBodyB->getCenterOfMassTransform() * m_pivotInB;
		tr.setOrigin(pivot);
		drawer->drawTransform(tr, 0.1);
	}
	if (m_bodyB)
	{
		btVector3 pivotBworld = m_bodyB->localPosToWorld(m_linkB, m_pivotInB);
		tr.setOrigin(pivotBworld);
		drawer->drawTransform(tr, 0.1);
	}
}


text:
package monitor

import (
	"testing"
	"time"
)

func TestMonitor(t *testing.T) {
	InitMonitor([]string{"WRITE", "READ"}, 1)
	StartMonitorServer("0.0.0.0:7070")
	timeStart := time.Now()
	time.Sleep(300 * time.Millisecond)
	StatByAction("READ", timeStart)
}


text:
using System;

namespace Beyova
{
    /// <summary>
    /// class Schedule
    /// </summary>
    public class Schedule : ICloneable
    {
        #region Properties

        /// <summary>
        /// Gets or sets the recurrence.
        /// </summary>
        /// <value>The recurrence.</value>
        public TimeScope Recurrence
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the hit reference.
        /// </summary>
        /// <value>The hit reference.</value>
        public DateTime HitReference
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the start stamp.
        /// </summary>
        /// <value>The start stamp.</value>
        public DateTime? StartStamp
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the end stamp.
        /// </summary>
        /// <value>The end stamp.</value>
        public DateTime? EndStamp
        {
            get;
            set;
        }

        #endregion Properties

        /// <summary>
        /// Gets the next occurrence.
        /// </summary>
        /// <param name="nowStandardStamp">The now standard stamp.</param>
        /// <returns>System.Nullable<DateTime>.</returns>
        public DateTime? GetNextOccurrence(DateTime nowStandardStamp)
        {
            DateTime? result = null;
            DateTime tmp;
            switch (this.Recurrence)
            {
                //// Everyday
                case TimeScope.Day:
                    tmp = new DateTime(
                        nowStandardStamp.Year,
                        nowStandardStamp.Month,
                        nowStandardStamp.Day,
                        HitReference.Hour,
                        HitReference.Minute,
                        HitReference.Second);
                    if (tmp < nowStandardStamp)
                    {
                        tmp = tmp.AddDays(1);
                    }
                    result = tmp;
                    break;
                //// EveryYear
                case TimeScope.Year:
                    tmp = new DateTime(
                        nowStandardStamp.Year,
                        HitReference.Month,
                        HitReference.Day,
                        HitReference.Hour,
                        HitReference.Minute,
                        HitReference.Second);
                    if (tmp < nowStandardStamp)
                    {
                        tmp = tmp.AddYears(1);
                    }
                    result = tmp;
                    break;
                //// Weekly
                case TimeScope.Week:
                    tmp = new DateTime(
                        nowStandardStamp.Year,
                        nowStandardStamp.Month,
                        nowStandardStamp.Day,
                        HitReference.Hour,
                        HitReference.Minute,
                        HitReference.Second);
                    if (tmp < nowStandardStamp)
                    {
                        tmp = tmp.AddDays(7);
                    }
                    result = tmp;
                    break;
                //// Monthly
                case TimeScope.Month:
                    tmp = new DateTime(
                        nowStandardStamp.Year,
                        nowStandardStamp.Month,
                        HitReference.Day,
                        HitReference.Hour,
                        HitReference.Minute,
                        HitReference.Second);
                    if (tmp < nowStandardStamp)
                    {
                        tmp = tmp.AddMonths(1);
                    }
                    result = tmp;
                    break;
                //// EveryHour
                case TimeScope.Hour:
                    tmp = new DateTime(
                        nowStandardStamp.Year,
                        nowStandardStamp.Month,
                        nowStandardStamp.Day,
                        nowStandardStamp.Hour,
                        HitReference.Minute,
                        HitReference.Second);
                    if (tmp < nowStandardStamp)
                    {
                        tmp = tmp.AddHours(1);
                    }
                    result = tmp;
                    break;
                //// Once
                case TimeScope.None:
                    if (this.HitReference >= nowStandardStamp)
                    {
                        result = this.HitReference;
                    }
                    break;

                default:
                    break;
            }

            return result;
        }

        /// <summary>
        /// Creates a new object that is a copy of the current instance.
        /// </summary>
        /// <returns>A new object that is a copy of this instance.</returns>
        public object Clone()
        {
            return new Schedule
            {
                EndStamp = this.EndStamp,
                Recurrence = this.Recurrence,
                HitReference = this.HitReference,
                StartStamp = this.StartStamp
            };
        }
    }

    /// <summary>
    /// Class Schedule.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public class Schedule<T> : Schedule
    {
        /// <summary>
        /// Gets or sets the object.
        /// </summary>
        /// <value>The object.</value>
        public T Object { get; set; }
    }
}


text:
Description
===========

Cookbook containing simple library routines for role-based management of OpenStack
configuration settings.

Requirements
============

* Chef 0.8+

Attributes
==========

None

Libraries
=========

Include a depends in your `metadata.rb` file for this cookbook:

```ruby
depends "openstack-utils"
```

OpenStack Role Operations
-------------------------

To find a hash (or partial hash) of configuration information given a named Chef
role, use the `Openstack::config_by_role` routine. This routine takes as its
first parameter the name of the Chef role to look for. An optional second parameter
is the section of the node hash to return. If nil, the whole node hash is returned.

```ruby
role_name = node["openstack"]["chef_roles"]["identity_server"]
identity_conf = ::Openstack::config_by_role(role_name)
identity_conf_creds_section = ::Openstack::config_by_role(role_name, "creds")
```

URI Operations
--------------

Use the `Openstack::uri_from_hash` routine to helpfully return a `::URI::Generic`
object for a hash that contains any of the following keys:

* `host`
* `uri`
* `port`
* `path`
* `scheme`

If the `uri` key is in the hash, that will be used as the URI, otherwise the URI will be
constructed from the various parts of the hash corresponding to the keys above.

```ruby
# Suppose node hash contains the following subhash in the :identity_service key:
# {
#   :host => 'identity.example.com',
#   :port => 5000,
#   :scheme => 'https'
# }
uri = ::Openstack::uri_from_hash(node[:identity_service])
# uri.to_s would == "https://identity.example.com:5000"
```

The routine will return nil if neither a `uri` or `host` key exists in the supplied hash.

Using the library without prefixing with ::Openstack
----------------------------------------------------

Don't like prefixing calls to the library's routines with `::Openstack`? Do this:

```ruby
class ::Chef::Recipe
  include ::Openstack
end
```

in your recipe.

Testing
=====

This cookbook is using [ChefSpec](https://github.com/acrmp/chefspec) for testing.

    $ cd $repo
    $ bundle
    $ librarian-chef install
    $ ln -s ../ cookbooks/$short_repo_name # doesn't contain "cookbook-"
    $ foodcritic cookbooks/$short_repo_name
    $ bundle exec rspec cookbooks/$short_repo_name

License and Author
==================

Author:: Jay Pipes (<jaypipes@gmail.com>)

Copyright 2012, Jay Pipes

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


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/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>BSRT</groupId>
	<artifactId>SocialResearching</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SocialResearching Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<repositories>
		<repository>
			<id>JBoss repository</id>
			<url>http://repository.jboss.com/maven2/</url>
		</repository>
	</repositories>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>4.11</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>4.3.5.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>4.3.5.Final</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>5.1.2.Final</version>
		</dependency>
		<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<version>1.1.0.Final</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.6.1</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.6</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SocialResearching</finalName>
	</build>
</project>


text:
using System;
using System.Diagnostics;
using System.Security.Cryptography;
using Microsoft.Win32.SafeHandles;

namespace Internal.Cryptography
{
    internal class OpenSslCipher : BasicSymmetricCipher
    {
        private readonly bool _encrypting;
        private SafeEvpCipherCtxHandle _ctx;

        public OpenSslCipher(IntPtr algorithm, CipherMode cipherMode, int blockSizeInBytes, byte[] key, byte[] iv, bool encrypting)
            : base(cipherMode.GetCipherIv(iv), blockSizeInBytes)
        {
            Debug.Assert(algorithm != IntPtr.Zero);

            _encrypting = encrypting;

            OpenKey(algorithm, key);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (_ctx != null)
                {
                    _ctx.Dispose();
                    _ctx = null;
                }
            }

            base.Dispose(disposing);
        }

        public override unsafe int Transform(byte[] input, int inputOffset, int count, byte[] output, int outputOffset)
        {
            Debug.Assert(input != null);
            Debug.Assert(inputOffset >= 0);
            Debug.Assert(count > 0);
            Debug.Assert((count % BlockSizeInBytes) == 0);
            Debug.Assert(input.Length - inputOffset >= count);
            Debug.Assert(output != null);
            Debug.Assert(outputOffset >= 0);
            Debug.Assert(output.Length - outputOffset >= count);

            return CipherUpdate(input, inputOffset, count, output, outputOffset);
        }

        public override byte[] TransformFinal(byte[] input, int inputOffset, int count)
        {
            Debug.Assert(input != null);
            Debug.Assert(inputOffset >= 0);
            Debug.Assert(count >= 0);
            Debug.Assert((count % BlockSizeInBytes) == 0);
            Debug.Assert(input.Length - inputOffset >= count);

            byte[] output = ProcessFinalBlock(input, inputOffset, count);
            Reset();
            return output;
        }

        private unsafe byte[] ProcessFinalBlock(byte[] input, int inputOffset, int count)
        {
            byte[] output = new byte[count];
            int outputBytes = CipherUpdate(input, inputOffset, count, output, 0);

            fixed (byte* outputStart = output)
            {
                byte* outputCurrent = outputStart + outputBytes;

                int bytesWritten;
                CheckBoolReturn(Interop.Crypto.EvpCipherFinalEx(_ctx, outputCurrent, out bytesWritten));
                outputBytes += bytesWritten;
            }

            if (outputBytes == output.Length)
            {
                return output;
            }

            if (outputBytes == 0)
            {
                return Array.Empty<byte>();
            }

            byte[] userData = new byte[outputBytes];
            Buffer.BlockCopy(output, 0, userData, 0, outputBytes);
            return userData;
        }

        private unsafe int CipherUpdate(byte[] input, int inputOffset, int count, byte[] output, int outputOffset)
        {
            bool status;
            int bytesWritten;

            fixed (byte* inputStart = input)
            fixed (byte* outputStart = output)
            {
                byte* inputCurrent = inputStart + inputOffset;
                byte* outputCurrent = outputStart + outputOffset;

                status = Interop.Crypto.EvpCipherUpdate(
                    _ctx,
                    outputCurrent,
                    out bytesWritten,
                    inputCurrent,
                    count);
            }

            CheckBoolReturn(status);
            return bytesWritten;
        }

        private void OpenKey(IntPtr algorithm, byte[] key)
        {
            _ctx = Interop.Crypto.EvpCipherCreate(
                algorithm,
                key,
                IV,
                _encrypting ? 1 : 0);

            if (_ctx == null)
            {
                throw Interop.Crypto.CreateOpenSslCryptographicException();
            }

            // OpenSSL will happily do PKCS#7 padding for us, but since we support padding modes
            // that it doesn't (PaddingMode.Zeros) we'll just always pad the blocks ourselves.
            CheckBoolReturn(Interop.Crypto.EvpCipherCtxSetPadding(_ctx, 0));
        }

        private void Reset()
        {
            bool status = Interop.Crypto.EvpCipherReset(_ctx);

            CheckBoolReturn(status);
        }

        private static void CheckBoolReturn(bool returnValue)
        {
            if (!returnValue)
            {
                throw Interop.Crypto.CreateOpenSslCryptographicException();
            }
        }
    }
}


text:
ANSIBLE_METADATA = {'metadata_version': '1.1',
                    'status': ['preview'],
                    'supported_by': 'core'}

DOCUMENTATION = r'''
---
module: win_updates
version_added: "2.0"
short_description: Download and install Windows updates
description:
    - Searches, downloads, and installs Windows updates synchronously by automating the Windows Update client.
options:
    blacklist:
        description:
        - A list of update titles or KB numbers that can be used to specify
          which updates are to be excluded from installation.
        - If an available update does match one of the entries, then it is
          skipped and not installed.
        - Each entry can either be the KB article or Update title as a regex
          according to the PowerShell regex rules.
        type: list
        version_added: '2.5'
    category_names:
        description:
        - A scalar or list of categories to install updates from. To get the list
          of categories, run the module with C(state=searched). The category must
          be the full category string, but is case insensitive.
        - Some possible categories are Application, Connectors, Critical Updates,
          Definition Updates, Developer Kits, Feature Packs, Guidance, Security
          Updates, Service Packs, Tools, Update Rollups and Updates.
        type: list
        default: [ CriticalUpdates, SecurityUpdates, UpdateRollups ]
    reboot:
        description:
        - Ansible will automatically reboot the remote host if it is required
          and continue to install updates after the reboot.
        - This can be used instead of using a M(win_reboot) task after this one
          and ensures all updates for that category is installed in one go.
        - Async does not work when C(reboot=yes).
        type: bool
        default: no
        version_added: '2.5'
    reboot_timeout:
        description:
        - The time in seconds to wait until the host is back online from a
          reboot.
        - This is only used if C(reboot=yes) and a reboot is required.
        default: 1200
        version_added: '2.5'
    server_selection:
        description:
        - Defines the Windows Update source catalog.
        - C(default) Use the default search source. For many systems default is
          set to the Microsoft Windows Update catalog. Systems participating in
          Windows Server Update Services (WSUS), Systems Center Configuration
          Manager (SCCM), or similar corporate update server environments may
          default to those managed update sources instead of the Windows Update
          catalog.
        - C(managed_server) Use a managed server catalog. For environments
          utilizing Windows Server Update Services (WSUS), Systems Center
          Configuration Manager (SCCM), or similar corporate update servers, this
          option selects the defined corporate update source.
        - C(windows_update) Use the Microsoft Windows Update catalog.
        type: str
        choices: [ default, managed_server, windows_update ]
        default: default
        version_added: '2.8'
    state:
        description:
        - Controls whether found updates are downloaded or installed or listed
        - This module also supports Ansible check mode, which has the same effect as setting state=searched
        type: str
        choices: [ installed, searched, downloaded ]
        default: installed
    log_path:
        description:
        - If set, C(win_updates) will append update progress to the specified file. The directory must already exist.
        type: path
    whitelist:
        description:
        - A list of update titles or KB numbers that can be used to specify
          which updates are to be searched or installed.
        - If an available update does not match one of the entries, then it
          is skipped and not installed.
        - Each entry can either be the KB article or Update title as a regex
          according to the PowerShell regex rules.
        - The whitelist is only validated on updates that were found based on
          I(category_names). It will not force the module to install an update
          if it was not in the category specified.
        type: list
        version_added: '2.5'
    use_scheduled_task:
        description:
        - Will not auto elevate the remote process with I(become) and use a
          scheduled task instead.
        - Set this to C(yes) when using this module with async on Server 2008,
          2008 R2, or Windows 7, or on Server 2008 that is not authenticated
          with basic or credssp.
        - Can also be set to C(yes) on newer hosts where become does not work
          due to further privilege restrictions from the OS defaults.
        type: bool
        default: no
        version_added: '2.6'
notes:
- C(win_updates) must be run by a user with membership in the local Administrators group.
- C(win_updates) will use the default update service configured for the machine (Windows Update, Microsoft Update, WSUS, etc).
- C(win_updates) will I(become) SYSTEM using I(runas) unless C(use_scheduled_task) is C(yes)
- By default C(win_updates) does not manage reboots, but will signal when a
  reboot is required with the I(reboot_required) return value, as of Ansible v2.5
  C(reboot) can be used to reboot the host if required in the one task.
- C(win_updates) can take a significant amount of time to complete (hours, in some cases).
  Performance depends on many factors, including OS version, number of updates, system load, and update server load.
- Beware that just after C(win_updates) reboots the system, the Windows system may not have settled yet
  and some base services could be in limbo. This can result in unexpected behavior.
  Check the examples for ways to mitigate this.
- More information about PowerShell and how it handles RegEx strings can be
  found at U(https://technet.microsoft.com/en-us/library/2007.11.powershell.aspx).
seealso:
- module: win_chocolatey
- module: win_feature
- module: win_hotfix
- module: win_package
author:
- Matt Davis (@nitzmahone)
'''

EXAMPLES = r'''
- name: Install all security, critical, and rollup updates without a scheduled task
  win_updates:
    category_names:
      - SecurityUpdates
      - CriticalUpdates
      - UpdateRollups

- name: Install only security updates as a scheduled task for Server 2008
  win_updates:
    category_names: SecurityUpdates
    use_scheduled_task: yes

- name: Search-only, return list of found updates (if any), log to C:\ansible_wu.txt
  win_updates:
    category_names: SecurityUpdates
    state: searched
    log_path: C:\ansible_wu.txt

- name: Install all security updates with automatic reboots
  win_updates:
    category_names:
    - SecurityUpdates
    reboot: yes

- name: Install only particular updates based on the KB numbers
  win_updates:
    category_name:
    - SecurityUpdates
    whitelist:
    - KB4056892
    - KB4073117

- name: Exclude updates based on the update title
  win_updates:
    category_name:
    - SecurityUpdates
    - CriticalUpdates
    blacklist:
    - Windows Malicious Software Removal Tool for Windows
    - \d{4}-\d{2} Cumulative Update for Windows Server 2016

# One way to ensure the system is reliable just after a reboot, is to set WinRM to a delayed startup
- name: Ensure WinRM starts when the system has settled and is ready to work reliably
  win_service:
    name: WinRM
    start_mode: delayed

# Optionally, you can increase the reboot_timeout to survive long updates during reboot
- name: Ensure we wait long enough for the updates to be applied during reboot
  win_updates:
    reboot: yes
    reboot_timeout: 3600

# Search and download Windows updates
- name: Search and download Windows updates without installing them
  win_updates:
    state: downloaded
'''

RETURN = r'''
reboot_required:
    description: True when the target server requires a reboot to complete updates (no further updates can be installed until after a reboot).
    returned: success
    type: bool
    sample: true

updates:
    description: List of updates that were found/installed.
    returned: success
    type: complex
    sample:
    contains:
        title:
            description: Display name.
            returned: always
            type: str
            sample: "Security Update for Windows Server 2012 R2 (KB3004365)"
        kb:
            description: A list of KB article IDs that apply to the update.
            returned: always
            type: list of strings
            sample: [ '3004365' ]
        id:
            description: Internal Windows Update GUID.
            returned: always
            type: str (guid)
            sample: "fb95c1c8-de23-4089-ae29-fd3351d55421"
        installed:
            description: Was the update successfully installed.
            returned: always
            type: bool
            sample: true
        categories:
            description: A list of category strings for this update.
            returned: always
            type: list of strings
            sample: [ 'Critical Updates', 'Windows Server 2012 R2' ]
        failure_hresult_code:
            description: The HRESULT code from a failed update.
            returned: on install failure
            type: bool
            sample: 2147942402

filtered_updates:
    description: List of updates that were found but were filtered based on
      I(blacklist), I(whitelist) or I(category_names). The return value is in
      the same form as I(updates), along with I(filtered_reason).
    returned: success
    type: complex
    sample: see the updates return value
    contains:
        filtered_reason:
            description: The reason why this update was filtered.
            returned: always
            type: str
            sample: 'skip_hidden'

found_update_count:
    description: The number of updates found needing to be applied.
    returned: success
    type: int
    sample: 3
installed_update_count:
    description: The number of updates successfully installed or downloaded.
    returned: success
    type: int
    sample: 2
failed_update_count:
    description: The number of updates that failed to install.
    returned: always
    type: int
    sample: 0
'''


text:
using namespace std;

#include <sys/times.h>

double save_plan(const vector<PlanStep> &plan, double best_makespan, int &plan_number, string &plan_name);

int main(int argc, const char **argv) {
    ifstream file("../preprocess/output");
    if(strcmp(argv[argc-1], "-eclipserun")==0) {
	cin.rdbuf(file.rdbuf());
	cerr.rdbuf(cout.rdbuf());
	argc--;
    }

    struct tms start, search_start, search_end;
    times(&start);
    bool poly_time_method = false;

    g_greedy = false;
    bool cg_heuristic = false, cg_preferred_operators = false;
    bool cyclic_cg_heuristic = false, cyclic_cg_preferred_operators = false;
    bool no_heuristic = false;
    string plan_name = "sas_plan";
    //    bool ff_heuristic = false, ff_preferred_operators = false;
    //    bool goal_count_heuristic = false;
    //    bool blind_search_heuristic = false;
    if(argc == 1) {
	cerr << "missing argument: output file name" << endl;
	return 1;
    } else {
	plan_name = string(argv[argc - 1]);
	argc--;
    }

    for(int i = 1; i < argc; i++) {
	for(const char *c = argv[i]; *c != 0; c++) {
	    if(*c == 'g') {
	    g_greedy = true;
	    } else if(*c == 'c') {
		cg_heuristic = true;
	    } else if(*c == 'C') {
		cg_preferred_operators = true;
	    } else if(*c == 'y') {
		cyclic_cg_heuristic = true;
	    } else if(*c == 'Y') {
		cyclic_cg_preferred_operators = true;
	    } else if(*c == 'n') {
		no_heuristic = true;
	    } else {
		cerr << "Unknown option: " << *c << endl;
		return 1;
	    }
	}
    }

    if(!cg_heuristic && !cyclic_cg_heuristic && !no_heuristic) {
	cerr << "Error: you must select at least one heuristic!" << endl
		<< "If you are unsure, choose options \"yY\"." << endl;
	return 2;
    }

    cin >> poly_time_method;
    if(poly_time_method) {
	cout << "Poly-time method not implemented in this branch." << endl;
	cout << "Starting normal solver." << endl;
	// cout << "Aborting." << endl;
	// return 1;
    }

    read_everything(cin);
    g_let_time_pass = new Operator();
//    g_consistency_cache = new ConsistencyCache();

//    dump_DTGs();
//    dump_everything();
//
//    RelaxedState rs = RelaxedState(*g_initial_state);
//    buildTestState(*g_initial_state);
//    cout << "test state:" << endl;
//    g_initial_state->dump();
//    rs = RelaxedState(*g_initial_state);

    BestFirstSearchEngine *engine = new BestFirstSearchEngine;
    if(cg_heuristic || cg_preferred_operators)
	engine->add_heuristic(new CGHeuristic, cg_heuristic,
		cg_preferred_operators);
    if(cyclic_cg_heuristic || cyclic_cg_preferred_operators)
	engine->add_heuristic(new CyclicCGHeuristic, cyclic_cg_heuristic,
		cyclic_cg_preferred_operators);
    if(no_heuristic)
	engine->add_heuristic(new NoHeuristic, no_heuristic, false);

    double best_makespan = REALLYBIG;

    int plan_number = 1;
    while(true) {
	times(&search_start);
	engine->initialize();
	engine->search();
	times(&search_end);
	if(engine->found_solution()) {
	    best_makespan = save_plan(engine->get_plan(),best_makespan,plan_number,plan_name);
	    engine->fetch_next_state();
	}
	else {
	    break;
	}
    }
    engine->statistics();

    if(cg_heuristic || cg_preferred_operators) {
	cout << "Cache hits: " << g_cache_hits << endl;
	cout << "Cache misses: " << g_cache_misses << endl;
    }
    int search_ms = (search_end.tms_utime - search_start.tms_utime) * 10;
    cout << "Search time: " << search_ms / 1000.0 << " seconds" << endl;
    int total_ms = (search_end.tms_utime - start.tms_utime) * 10;
    cout << "Total time: " << total_ms / 1000.0 << " seconds" << endl;

    return engine->found_at_least_one_solution() ? 0 : 1;
}

double save_plan(const vector<PlanStep> &plan, double best_makespan, int &plan_number, string &plan_name) {

    double makespan = 0;
    for(int i = 0; i < plan.size(); i++) {
	double end_time = plan[i].start_time + plan[i].duration;
	makespan = max(makespan,end_time);
    }

    cout << "Makespan = " << makespan << endl;

    if(makespan >= best_makespan) return best_makespan;

    int len = static_cast<int>(plan_name.size() + log10(plan_number) + 10);
    char *temp_filename = (char*)malloc(len * sizeof(char));
    sprintf(temp_filename, "%s.%d.in", plan_name.c_str(), plan_number);
    char *filename = (char*)malloc(len * sizeof(char));
    sprintf(filename, "%s.%d", plan_name.c_str(), plan_number);
    len = 2*len + 30;
    char *syscall = (char*)malloc(len * sizeof(char));
    sprintf(syscall, "./search/epsilonize_plan.py < %s > %s", temp_filename, filename);
    char *syscall2 = (char*)malloc(len * sizeof(char));
    sprintf(syscall2, "rm %s", temp_filename);

//    printf("FILENAME: %s\n", temp_filename);
    FILE *file = fopen(temp_filename,"w");

    plan_number++;
    for(int i = 0; i < plan.size(); i++) {
	const PlanStep& step = plan[i];
	fprintf(file,"%.3f: (%s) [%.3f]\n", step.start_time, step.op->get_name().c_str(), step.duration);
	printf("%.3f: (%s) [%.3f]\n", step.start_time, step.op->get_name().c_str(), step.duration);
    }
    fclose(file);

    cout << "Plan length: " << plan.size() << " step(s)." << endl;
    cout << "Makespan   : " << makespan << endl;

    if(system(syscall) != 0) {
      // silence gcc warning
    }
    if(system(syscall2) != 0) {
      // silence gcc warning
    }

    free(temp_filename);
    free(filename);
    free(syscall);
    free(syscall2);

    return makespan;

}


text:
title: For Loop
localeTitle: Para loop
---
# Para loop

O loop `for` oferece uma maneira compacta de iterar em um intervalo de valores. Uma instrução básica `for` tem três partes: uma inicialização de variável, uma expressão booleana e uma expressão de incremento.

```java
for (variable initialization; boolean expression; increment expression)
 {
    // Statements
 }
```

*   `initialization` - Inicializa o loop e é executado apenas uma vez, no início.

Você pode inicializar mais de uma variável do mesmo tipo na primeira parte da declaração básica `for` loop; Cada inicialização deve ser separada por uma vírgula.

*   `expression` - avaliada no início de cada iteração. Se a `expression` avaliada como `true` , as `Statements` serão executadas.
*   `increment` - Chamado após cada iteração através do loop. Você pode aumentar / diminuir o valor das variáveis aqui. Certifique-se de que o incremento esteja funcionando em relação ao valor da expressão, para evitar um loop infinito.

Uma maneira comum `for` loop é usado é se você precisa para percorrer o seu código de um número específico de vezes. Por exemplo, se você quiser gerar os números de 0 a 10, inicialize a variável do seu contador com 0, depois verifique se o valor é menor que 10 e adicione um ao contador após cada iteração.

Observe que você deve verificar se o valor é menor que 10, não menor que ou igual a 10, pois você está iniciando o contador em 0.

```java
for (int iter_For = 0; iter_For < 10; iter_For++)
 {
    System.out.print(iter_For + " ");
    // Iterated 10 times, iter_For 0,1,2...9
 }

 System.out.println("iter_For Value: " + iter_For);
```

Nota: Também é aceitável declarar uma variável dentro do loop for como uma única instrução.

```java
for (int iter_For = 0; iter_For < 10; iter_For++)
 {
    System.out.print (iter_For + " ");
    // Iterated 10 times, iter_For 0,1,2...9
 }
```

Saída:
```
0 1 2 3 4 5 6 7 8 9
 iter_For Value: 10
```

Outro exemplo de loop for que adiciona os primeiros 50 números seria assim. i ++ significa i = i + 1.

```java
int addUntil = 50;
 int sum 0;

 for (int i = 1; i <= addUntil; i++)
 {
    sum+=i
 }

 System.out.println("The sum of the first 50 numbers is: " + 50);
```

![:rocket:](https://forum.freecodecamp.org/images/emoji/emoji_one/rocket.png?v=2 ":foguete:") [Executar código](https://repl.it/CJYr/0)

### Extras

Você não pode usar um número (antiga construção de linguagem no estilo C) ou qualquer coisa que não avalie um valor booleano como uma condição para uma instrução if ou construção de loop. Você não pode, por exemplo, dizer if (x), a menos que x seja uma variável booleana.

Além disso, é importante ter em mente que a expressão booleana deve, em algum momento, ser avaliada como verdadeira. Caso contrário, seu programa ficará preso em um loop infinito.


text:
'''
Copyright 2015 Ivan Sadikov

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''

# import libs
import unittest
import warnings
import random
# import classes
import analytics.exceptions.exceptions as ex
import analytics.algorithms.relativecomp as rc
import analytics.algorithms.rank as rank
import analytics.core.processor.processor as processor
from analytics.core.map.elementmap import ElementMap
from analytics.core.map.pulsemap import PulseMap

class RelComp_TestSequence(unittest.TestCase):
    def setUp(self):
        self.isStarted = True

    def test_relcomp_init(self):
        with self.assertRaises(ex.AnalyticsStandardError):
            a = rc._RelComp()

    def test_relcomp_alpha(self):
        self.assertEqual(rc._RelComp.alpha(), 1)

    def test_relcomp_beta(self):
        alpha = rc._RelComp.alpha()
        delta = 0.8
        with self.assertRaises(ex.AnalyticsStandardError):
            k = -1
            rc._RelComp.beta(alpha, k, delta)
        with self.assertRaises(ex.AnalyticsStandardError):
            k = 1.1
            rc._RelComp.beta(alpha, k, delta)
        k = 1
        self.assertEqual(rc._RelComp.beta(alpha, k, delta), 0)
        k = 0
        self.assertTrue(1 >= rc._RelComp.beta(alpha, k, delta) >= 0 )
        for _i in range(10):
            k = random.random();
            delta = random.randrange(1, 10)*random.random()
            self.assertTrue(1 >= rc._RelComp.beta(alpha, k, delta) >= 0)

    def test_relcomp_k(self):
        for i in range(10):
            p = random.randrange(1, 1000)
            r = p * random.random()
            rmedian = p * random.random()
            da = random.randrange(1, 100)*random.random()
            self.assertTrue(1 >= rc._RelComp.k(r, rmedian, da) >= 0)

    def test_relcomp_dr(self):
        for _i in range(10):
            p = random.randrange(1, 1000)
            r = p * random.random()
            rmedian = p * random.random()
            i = random.randrange(1, 100)
            m = random.randrange(1, 100)
            self.assertTrue(rc._RelComp.dr(r, rmedian, i, m) >= 0)

    def test_relcomp_da(self):
        a = []
        with self.assertRaises(ex.AnalyticsStandardError):
            rc._RelComp.da(a)
        # 28.03.2015: ivan sadikov - changed test according to modification
        #   [array len == 1]
        a = [random.randrange(0, 100)]
        self.assertEqual(rc._RelComp.da(a), 1.0)
        for _i in range(10):
            a = [random.randrange(0, 100) for i in range(10)]
            a = sorted(a)
            self.assertTrue(rc._RelComp.da(a) > 0)

class RelativeComparison_TestSequence(unittest.TestCase):
    def setUp(self):
        self.isStarted = True
        self._rel = rc.RelativeComparison()
        self._a = [
                {"name": "value", "desc": "value", "sample": 123, "dynamic": True, "priority": -1},
                {"name": "price", "desc": "price", "sample": 320.0, "dynamic": False, "priority": 1},
                {"name": "amount", "desc": "amount", "sample": 3, "dynamic": True}
        ]
        self._b = [
            {"id": "1","name": "#1","desc": "", "cluster": "A", "value": 100, "price": 320.0, "amount": 1},
            {"id": "2","name": "#2","desc": "", "cluster": "A", "value": 120, "price": 300.0, "amount": 4},
            {"id": "3","name": "#3","desc": "", "cluster": "A", "value": 140, "price": 199.0, "amount": 3},
            {"id": "4","name": "#4","desc": "", "cluster": "A", "value": 124, "price": 234.0, "amount": 5},
            {"id": "5","name": "#5","desc": "", "cluster": "A", "value": 150, "price": 250.0, "amount": 9},
            {"id": "6","name": "#6","desc": "", "cluster": "A", "value": 128, "price": 245.0, "amount": 3},
            {"id": "7","name": "#7","desc": "", "cluster": "A", "value": 125, "price": 230.0, "amount": 2}
        ]

    def test_relativecomp_init(self, setUp=None):
        rel = rc.RelativeComparison()
        self.assertEqual(rel._id, rc.ID)
        self.assertEqual(rel._name, rc.LONG_NAME)
        self.assertEqual(rel._short, rc.SHORT_NAME)

    def test_relativecomp_hashkeyForList(self):
        list = []
        self.assertEqual(self._rel._hashkeyForList(list), "")
        list = range(0, random.randrange(1, 20))
        random.shuffle(list)
        self.assertTrue(len(self._rel._hashkeyForList(list)) > 0)

    def test_relativecomp_threadHash(self):
        ti = 1; sti = 1
        self.assertEqual(self._rel._threadHash("", ""), "#")
        self.assertEqual(self._rel._threadHash(ti, sti), str(ti)+"#"+str(sti))

    def test_relativecomp_relcomp(self):
        self.assertEqual(self._rel._relcomp([], 1, 1), {})
        with self.assertRaises(ex.AnalyticsCheckError):
            median = random.randrange(1000, 2000)
            order = (-1)**random.randrange(0, 2)
            self._rel._relcomp(None, order, median)
        with self.assertRaises(ex.AnalyticsStandardError):
            median = random.randrange(1000, 2000)
            order = (-1)**random.randrange(0, 2)
            self._rel._relcomp([1, 2, 3], order, median)
        for i in range(10):
            a = [random.randrange(0, 100)*((-1)**random.randrange(0, 2)) for i in range(10)]
            order = (-1)**random.randrange(0, 2)
            median_index = random.randrange(0, len(a))
            median = a[median_index]
            res = self._rel._relcomp(a, order, median)
            self.assertEqual(len(res.keys()), len(set(a)))
            self.assertEqual(res[median], 1)
            for key in res.keys():
                self.assertTrue(key in a)
                self.assertTrue(1 >= res[key] >= 0)

    def test_relativecomp_frontier(self):
        map = {}
        self.assertEqual(self._rel._frontier(map), {})

        map = {}
        for _i in range(20):
            aa = [random.randrange(2, 10) for _j in range(3)]
            map[self._rel._hashkeyForList(aa)] = aa
        self.assertEqual(self._rel._frontier(map), {})

        for _k in range(10):
            map = {}
            for _i in range(20):
                aa = [random.random() for _j in range(3)]
                map[self._rel._hashkeyForList(aa)] = aa
            hashRank = self._rel._frontier(map)
            self.assertEqual(len(hashRank.keys()), len(map.keys()))
            for key in hashRank.keys():
                self.assertEqual(type(hashRank[key]), rank.Rank)
                self.assertTrue(hashRank[key] is not rank.RSYS.UND_RANK)

    def test_relativecomp_computeRank(self):
        with self.assertRaises(ex.AnalyticsCheckError):
            self._rel._computeRanks([], [], [])
        with self.assertRaises(ex.AnalyticsCheckError):
            self._rel._computeRanks({}, {}, [])
        for _kl in range(10):
            n = random.randrange(1, 3)
            orders = [(-1)**random.randrange(0, 2) for _i in range(n)]
            medians = []; a = {}
            for _i in range(20):
                aa = [random.randrange(0, 100)*random.random() for _j in range(n)]
                a[self._rel._hashkeyForList(aa)] = aa
                if _i == 5: medians = aa
            hashRank = self._rel._computeRanks(a, orders, medians)
            self.assertEqual(len(hashRank.keys()), len(a.keys()))
            for key in hashRank.keys():
                self.assertEqual(type(hashRank[key]), rank.Rank)
                self.assertNotEqual(hashRank[key], rank.RSYS.UND_RANK)

    def test_relativecomp_rankResults_err(self):
        with self.assertRaises(ex.AnalyticsCheckError):
            self._rel.rankResults({}, {})

    def test_relativecomp_rankResults(self):
        # initialise maps and idmapper
        pulses = PulseMap(); elements = ElementMap(); idmapper = {}
        idmapper = processor.parseElements(self._b, elements, idmapper)
        idmapper = processor.parsePulses(self._a, pulses, idmapper)
        # rank elements
        res = self._rel.rankResults(elements, pulses)
        self.assertEqual(len(elements._map.values()), len(self._b))
        for element in elements._map.values():
            self.assertNotEqual(element.rank()._name, rank.RSYS.UND_RANK._name)

    def test_relativecomp_rankResults_warn(self):
        # initialise maps and idmapper
        pulses = PulseMap(); elements = ElementMap(); idmapper = {}
        idmapper = processor.parseElements(self._b, elements, idmapper)
        idmapper = processor.parsePulses(self._a, pulses, idmapper)
        # make all pulses dynamic
        for pulse in pulses._map.values():
            pulse.setStatic(False)

        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter("always")
            # rank elements
            res = self._rel.rankResults(elements, pulses)
            self.assertEqual(len(elements._map.values()), len(self._b))
            for element in elements._map.values():
                self.assertNotEqual(element.rank()._name, rank.RSYS.UND_RANK._name)
            # warnings assertion
            self.assertEqual(len(w), 1)
            self.assertTrue(issubclass(w[0].category, UserWarning))

# Load test suites
def _suites():
    return [
        RelComp_TestSequence,
        RelativeComparison_TestSequence
    ]

# Load tests
def loadSuites():
    # global test suite for this module
    gsuite = unittest.TestSuite()
    for suite in _suites():
        gsuite.addTest(unittest.TestLoader().loadTestsFromTestCase(suite))
    return gsuite

if __name__ == '__main__':
    suite = loadSuites()
    print ""
    print "### Running tests ###"
    print "-" * 70
    unittest.TextTestRunner(verbosity=2).run(suite)


text:
package com.facebook.buck.util;

import com.google.common.base.Preconditions;

import java.io.InterruptedIOException;
import java.net.SocketTimeoutException;
import java.nio.channels.ClosedByInterruptException;
import java.util.Collections;
import java.util.IdentityHashMap;
import java.util.Set;

public class MoreThrowables {

  private MoreThrowables() {}

  private static InterruptedException asInterruptedException(Throwable throwable) {
    InterruptedException e = new InterruptedException();
    e.initCause(throwable);
    return e;
  }

  /**
   * Propagates an {@link InterruptedException} masquerading as another {@code Throwable}.
   */
  public static void propagateIfInterrupt(Throwable thrown) throws InterruptedException {

    // If it's already an `InterruptedException`, just rethrow it.
    if (thrown instanceof InterruptedException) {
      throw (InterruptedException) thrown;
    }

    // Thrown when a thread is interrupted while blocked on I/O.  So propagate this as
    // an `InterruptedException`.
    if (thrown instanceof ClosedByInterruptException) {
      throw asInterruptedException(thrown);
    }

    // `InterruptedIOException` can also be thrown when a thread is interrupted while blocked
    // by I/O, so propagate this -- unless it's a `SocketTimeoutException` which is thrown when
    // when a the timeout set on a socket is triggered.
    if (thrown instanceof InterruptedIOException &&
        !(thrown instanceof SocketTimeoutException)) {
      throw asInterruptedException(thrown);
    }
  }

  /**
   * If throwable has a non-empty cause, returns throwable at the bottom of the stack.
   */
  public static Throwable getInitialCause(Throwable throwable) {
    if (throwable.getCause() != null) {
      Set<Throwable> seen =
          Collections.newSetFromMap(new IdentityHashMap<Throwable, Boolean>());
      seen.add(throwable);
      return getInitialCause(throwable, seen);
    }
    return throwable;
  }

  private static Throwable getInitialCause(Throwable throwable, Set<Throwable> seen) {
    Throwable cause = throwable.getCause();
    if ((cause == null) || seen.contains(cause)) {
      return throwable;
    }
    seen.add(throwable);
    return getInitialCause(cause, seen);
  }

  /**
   * Returns string representing class, method, filename and line number that throwable was
   * thrown from
   */
  public static String getThrowableOrigin(Throwable throwable) {
    StackTraceElement[] stack = throwable.getStackTrace();
    Preconditions.checkState(stack.length > 0);
    StackTraceElement element = stack[0];
    return element.toString();
  }
}


text:
static inline time_t gmktime(struct tm *tm) {
  time_t rt = mktime(tm);
  return rt < 0 ? time_t(-1) : rt;
}

static void StringAppendStrftime(string* dst,
                                 const char* format,
                                 const struct tm* tm) {
  char space[1024];

  int result = strftime(space, sizeof(space), format, tm);

  if ((result >= 0) && (result < sizeof(space))) {
    // It fit
    dst->append(space, result);
    return;
  }

  int length = sizeof(space);
  for (int sanity = 0; sanity < 5; ++sanity) {
    length *= 2;
    char* buf = new char[length];

    result = strftime(buf, length, format, tm);
    if ((result >= 0) && (result < length)) {
      // It fit
      dst->append(buf, result);
      delete[] buf;
      return;
    }

    delete[] buf;
  }

  // sanity failure
  return;
}

// Convert a "struct tm" interpreted as *GMT* into a time_t (technically
// a long since we can't include header files in header files bla bla bla).
// This is basically filling a hole in the standard library.
//
// There are several approaches to mkgmtime() implementation on the net,
// many of them wrong.  Simply reimplementing the logic seems to be the
// simplest and most efficient, though it does reimplement calendar logic.
// The calculation is mostly straightforward; leap years are the main issue.
//
// Like gmktime() this method returns -1 on failure. Negative results
// are considered undefined by the standard so these cases are
// considered failures and thus return -1.
time_t mkgmtime(const struct tm *tm) {
  // Month-to-day offset for non-leap-years.
  static const int month_day[12] =
    {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};

  // Most of the calculation is easy; leap years are the main difficulty.
  int month = tm->tm_mon % 12;
  int year = tm->tm_year + tm->tm_mon / 12;
  if (month < 0) {   // Negative values % 12 are still negative.
    month += 12;
    --year;
  }

  // This is the number of Februaries since 1900.
  const int year_for_leap = (month > 1) ? year + 1 : year;

  time_t rt = tm->tm_sec                           // Seconds
       + 60 * (tm->tm_min                          // Minute = 60 seconds
       + 60 * (tm->tm_hour                         // Hour = 60 minutes
       + 24 * (month_day[month] + tm->tm_mday - 1  // Day = 24 hours
       + 365 * (year - 70)                         // Year = 365 days
       + (year_for_leap - 69) / 4                  // Every 4 years is leap...
       - (year_for_leap - 1) / 100                 // Except centuries...
       + (year_for_leap + 299) / 400)));           // Except 400s.
  return rt < 0 ? -1 : rt;
}

bool WallTime_Parse_Timezone(const char* time_spec,
                             const char* format,
                             const struct tm* default_time,
                             bool local,
                             WallTime* result) {
  struct tm split_time;
  if (default_time) {
     split_time = *default_time;
  } else {
     memset(&split_time, 0, sizeof(split_time));
  }
  const char* parsed = strptime(time_spec, format, &split_time);
  if (parsed == NULL) return false;

  // If format ends with "%S", match fractional seconds
  double fraction = 0.0;
  char junk;
  if ((*parsed == '.') &&
     (strcmp(format + strlen(format) - 2, "%S") == 0) &&
     (sscanf(parsed, "%lf%c",  // NOLINT(runtime/printf)
             &fraction, &junk) == 1)) {
     parsed = format + strlen(format);   // Parsed it all!
  }
  if (*parsed != '\0') return false;

  // Convert into seconds since epoch.  Adjust so it is interpreted
  // w.r.t. the daylight-saving-state at the specified time.
  split_time.tm_isdst = -1;     // Ask gmktime() to find dst imfo
  time_t ptime;
  if (local) {
    ptime = gmktime(&split_time);
  } else {
    ptime = mkgmtime(&split_time);  // Returns time in GMT instead of local.
  }

  if (ptime == -1) return false;

  *result = ptime;
  *result += fraction;
  return true;
}

WallTime WallTime_Now() {
  timespec ts;
  clock_gettime(CLOCK_REALTIME, &ts);
  return ts.tv_sec + ts.tv_nsec / static_cast<double>(1e9);
}

int32 GetDaysSinceEpoch(const char* date) {
  struct tm time;
  memset(&time, 0, sizeof(time));
  CHECK(strptime(date, "%Y-%m-%d", &time)) << "Could not parse date: " << date;
  int64 seconds_since_epoch = gmktime(&time);
  return seconds_since_epoch > 0 ? seconds_since_epoch / (60 * 60 * 24) : -1;
}

void StringAppendStrftime(string* dst,
                          const char* format,
                          time_t when,
                          bool local) {
  struct tm tm;
  bool conversion_error;
  if (local) {
    conversion_error = (localtime_r(&when, &tm) == NULL);
  } else {
    conversion_error = (gmtime_r(&when, &tm) == NULL);
  }
  if (conversion_error) {
    // If we couldn't convert the time, don't append anything.
    return;
  }
  StringAppendStrftime(dst, format, &tm);
}