text:
var config = require("config");
var logger = require("logger").get("rpc");
var fs     = require("fs");

/*
Object hash containing all RPC methods.
*/
var methods = {};

(function() {
    function introspect() {
        return Object.keys(methods);
    }

    methods["core.introspect"] = introspect;
})();

(function() {
    function multiCall(params) {
        var methodNames = Object.keys(params);
        var result = {};

        for(var i = 0; i < methodNames.length; i++) {
            var name = methodNames[i];
            var method = methods[name];

            if(method) {
                result[name] = invoke(method, params[name]);
            } else {
                result[name].error = {
                    code: -32601,
                    message: "Method not found",
                    data: name
                };

                logger.error("Method '" + request.method + "' not found.");
            }
        }

        return result;
    }

    methods["core.multiCall"] = multiCall;
})();

(function() {
    var rpcFiles   = fs.combine(__ROOT__, "rpc");

    var files = fs.getFiles(rpcFiles);

    for(var i = 0; i < files.length; i++) {
        var rpc = require(files[i]).rpc;

        if(rpc.name && rpc.method) {
            methods[rpc.name] = rpc.method;
        }
    }
})();

logger.info("Found " + Object.keys(methods).length + " RPC method(s).");

function invoke(method, params) {
    var fn = null;

    if(params instanceof Array) {
        fn = function() { return method.apply(method, params); };
    } else {
        fn = function() { return method(params); };
    }

    return fn();
}

function handleRequest(request) {
    var method = methods[request.method];
    var response = {
        id: request.id,
        jsonrpc: "2.0"
    };

    if(method) {
        try {
            response.result = invoke(method, request.params);
        } catch(e) {
            response.result = undefined;
            response.error = {
                code: -32000,
                message: "Internal server error",
                data: {
                    name: e.name,
                    message: e.message
                }
            };

            logger.error("Error when executing RPC method '" + request.method + "': " + e);
        }
    } else {
        response.error = {
            code: -32601,
            message: "Method not found",
            data: request.method
        };

        logger.error("Method '" + request.method + "' not found.");
    }

    return response;
}

exports.handler = handleRequest;


text:
<form method="POST" action="{% url detail_tags user.id %}">
  {% csrf_token %}

    <fieldset>
    <legend style="padding-left: 0">General</legend>

	    <input type="checkbox" id="tag_crazy" name="tag"
		   {% if "crazy" in action_fields %}checked="checked"{% endif %}
		   value="crazy" />

	  <input disabled="disabled" class="fake-disabled span5"
		 {% if "crazy" in action_fields %}style="font-weight: bold"{% endif %}
		 value="Crazy" />

    </fieldset>
    {% for category, items in fields.items %}
    <fieldset>
    <legend style="padding-left: 0">{{category}}</legend>
    {% for item in items %}

	    <input type="checkbox" id="tag_{{item.0}}" name="tag"
		   {% if item.0 in action_fields %}checked="checked"{% endif %}
		   value="{{item.0}}" />

	  <input disabled="disabled" class="fake-disabled span5"
		 {% if item.0 in action_fields %}style="font-weight: bold"{% endif %}
		 value="{{item.1}}" />

    {% endfor %}
    </fieldset>
    {% endfor %}

</form>

redpajama_set_name: RedPajamaGithub


text:
package org.apache.nifi.authorization;

class RemoteShellCommands implements ShellCommandsProvider {
    // Carefully crafted command replacement string:
    private final static String remoteCommand = "ssh " +
        "-o 'StrictHostKeyChecking no' " +
        "-o 'PasswordAuthentication no' " +
        "-o \"RemoteCommand %s\" " +
        "-i %s -p %s -l root %s";

    private ShellCommandsProvider innerProvider;
    private String privateKeyPath;
    private String remoteHost;
    private Integer remotePort;

    private RemoteShellCommands() {
    }

    public static ShellCommandsProvider wrapOtherProvider(ShellCommandsProvider otherProvider, String keyPath, String host, Integer port) {
        RemoteShellCommands remote = new RemoteShellCommands();

        remote.innerProvider = otherProvider;
        remote.privateKeyPath = keyPath;
        remote.remoteHost = host;
        remote.remotePort = port;

        return remote;
    }

    public String getUsersList() {
        return String.format(remoteCommand, innerProvider.getUsersList(), privateKeyPath, remotePort, remoteHost);
    }

    public String getGroupsList() {
        return String.format(remoteCommand, innerProvider.getGroupsList(), privateKeyPath, remotePort, remoteHost);
    }

    public String getGroupMembers(String groupName) {
        return String.format(remoteCommand, innerProvider.getGroupMembers(groupName), privateKeyPath, remotePort, remoteHost);
    }

    public String getSystemCheck() {
        return String.format(remoteCommand, innerProvider.getSystemCheck(), privateKeyPath, remotePort, remoteHost);
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?><!--

 Copyright 2003 - 2014 The eFaps Team

 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.

 Author:          The eFaps Team

-->
<datamodel-statusgroup xmlns="http://www.efaps.org/xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
    <uuid>d6fc1f05-8094-427b-916a-0b44e03c48e8</uuid>
    <file-application>eFapsApp-Sales</file-application>
    <definition>
        <version-expression>(version==latest)</version-expression>
        <name>Sales_AcquisitionCostingStatus</name>
        <parent>Sales_DocumentStatus</parent>
        <status key="Draft">
            <description>AcquisitionCosting was drafted and is still editable. (Borrador)</description>
        </status>
        <status key="Open">
            <description>AcquisitionCosting was printed (Pendiente)</description>
        </status>
        <status key="Closed">
            <description>AcquisitionCosting is terminated. (Cerrado)</description>
        </status>
        <status key="Canceled">
            <description>Canceled. AcquisitionCosting was canceled. (Anulado)
            </description>
        </status>
    </definition>
</datamodel-statusgroup>


text:
<html>
 <head>
  <title>QUnit TestSuite for sap.ui.table</title>
  <script src="../../../../../resources/sap/ui/qunit/qunit-redirect.js"></script>
  <script>

  /**
   * Add test pages to this test suite function.
   * Please order alphabetically
   */
  function suite() {
    var suite = new parent.jsUnitTestSuite();
    var contextPath = "/" + window.location.pathname.split("/")[1];
    suite.addTestPage(contextPath + "/test-resources/sap/ui/suite/qunit/VerticalProgressIndicator.qunit.html");
    suite.addTestPage(contextPath + "/test-resources/sap/ui/suite/qunit/TaskCircle.qunit.html");
    return suite;
  }

  </script>
 </head>
 <body>
 </body>
</html>


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.uminho.di.gsd.gossip.service.operations;

import org.apache.log4j.Logger;
import org.uminho.di.gsd.common.ApplicationServiceConstants;
import org.uminho.di.gsd.common.Constants;
import org.uminho.di.gsd.gossip.service.repo.MessagesProcessor;
import org.ws4d.java.message.SOAPHeader;
import org.ws4d.java.schema.Attribute;
import org.ws4d.java.schema.ComplexType;
import org.ws4d.java.schema.Element;
import org.ws4d.java.schema.SchemaUtil;
import org.ws4d.java.service.Operation;
import org.ws4d.java.service.parameter.ParameterValue;
import org.ws4d.java.structures.List;
import org.ws4d.java.types.EndpointReference;
import org.ws4d.java.types.QName;
import org.ws4d.java.types.URI;

/**
 *
 * @author fjoc
 */
public abstract class GossipOperation extends Operation {

    static Logger logger = Logger.getLogger(GossipOperation.class);

    protected MessagesProcessor processor;

    public GossipOperation(String operationName, QName operationType) {
        super(operationName, operationType);
    }

    public void setProcessor(MessagesProcessor proc) {
        this.processor = proc;
    }

    protected abstract void initInput();

    protected abstract void initOutput();

    protected Element getSvcEprElement() {
        Element svcEprElement = new Element(Constants.SvcEprElementQName, SchemaUtil.getSchemaType(SchemaUtil.TYPE_ANYURI));

        return svcEprElement;
    }

    protected Element getTimeIntervalElement() {
        Element timeIntervalElement = new Element(Constants.TimeIntervalElementQName);

        ComplexType timeIntervalType = new ComplexType(ComplexType.CONTAINER_SEQUENCE);
        Attribute msAttribute = new Attribute(Constants.MillisecondsAttributeQName);
        msAttribute.setType(SchemaUtil.getSchemaType(SchemaUtil.TYPE_UNSIGNED_LONG));
        msAttribute.setUse(Attribute.USE_REQUIRED);
        timeIntervalType.addAttribute(msAttribute);

        timeIntervalElement.setType(timeIntervalType);

        return timeIntervalElement;
    }

    protected Element getIdentifiersListElement() {
        Element identifiersList = new Element(Constants.IdentifiersListElementQName);

        ComplexType messagesListType = new ComplexType(ComplexType.CONTAINER_SEQUENCE);
        Element identifier = getMessageIdentifierElement();
        identifier.setMaxOccurs(-1);
        messagesListType.addElement(identifier);

        identifiersList.setType(messagesListType);

        return identifiersList;
    }

    protected Element getMessagesInfoListElement() {
        Element messagesInfoList = new Element(Constants.MessagesInfoListElementQName);

        ComplexType messagesInfoListType = new ComplexType(ComplexType.CONTAINER_SEQUENCE);
        Element messageInfo = getMessageInfoElement();
        messageInfo.setMaxOccurs(-1);
        messagesInfoListType.addElement(messageInfo);

        messagesInfoList.setType(messagesInfoListType);

        return messagesInfoList;
    }

    protected Element getMessageInfoElement() {
        Element messageInfo = new Element(Constants.MessageInfoElementQName);

        ComplexType messageInfoType = new ComplexType(Constants.MessageInfoTypeQName, ComplexType.CONTAINER_SEQUENCE);
        messageInfoType.addElement(getMessageIdentifierElement());
        messageInfoType.addElement(getMessageActionElement());

        messageInfo.setType(messageInfoType);

        return messageInfo;
    }

    protected Element getMessageIdentifierElement() {
        Element identifier = new Element(Constants.MessageIdentifierElementQName, SchemaUtil.getSchemaType(SchemaUtil.TYPE_ANYURI));

        return identifier;
    }

    protected Element getMessagesListElement() {
        Element messagesList = new Element(Constants.MessagesListElementQName);

        ComplexType messagesListType = new ComplexType(Constants.MessagesListTypeQName, ComplexType.CONTAINER_SEQUENCE);
        Element messageContainer = getMessageContainerElement();
        messageContainer.setMaxOccurs(-1);
        messagesListType.addElement(messageContainer);

        messagesList.setType(messagesListType);

        return messagesList;
    }

    protected Element getMessageContainerElement() {
        Element messageContainer = new Element(Constants.MessageContainerElementQName);

        ComplexType messageContainerType = new ComplexType(Constants.MessageContainerTypeQName, ComplexType.CONTAINER_SEQUENCE);

        messageContainerType.addElement(getMessageIdentifierElement());
        messageContainerType.addElement(getMessageActionElement());
        messageContainerType.addElement(getRoundsElement());
        messageContainerType.addElement(getMessageElement());

        messageContainer.setType(messageContainerType);

        return messageContainer;
    }

    protected Element getRoundsElement()
    {
        Element roundsElement = new Element(Constants.RoundsElementQName, SchemaUtil.getSchemaType(SchemaUtil.TYPE_UNSIGNED_LONG));

        return roundsElement;
    }

//    protected Element getMessageActionContainerElement() {
//        Element messageActionContainer = new Element(Constants.MessageActionContainerElementQName);
//
//        ComplexType messageActionContainerType = new ComplexType(Constants.MessageActionContainerTypeQName, ComplexType.CONTAINER_SEQUENCE);
//
//        messageActionContainerType.addElement(getMessageIdentifierElement());
//        messageActionContainerType.addElement(getMessageActionElement());
//
//        Element rounds = getRoundsElement();
//        rounds.setMinOccurs(0);
//        messageActionContainerType.addElement(rounds);
//
//        messageActionContainer.setType(messageActionContainerType);
//
//        return messageActionContainer;
//    }

    protected Element getMessageActionElement() {
        Element action = new Element(Constants.ActionElementQName, SchemaUtil.getSchemaType(SchemaUtil.TYPE_ANYURI));

        return action;
    }

    protected Element getMessageElement() {
        Element message = new Element(Constants.MessageElementQName, SchemaUtil.getSchemaType(SchemaUtil.TYPE_STRING));

//        ComplexType cType = new ComplexType(ComplexType.CONTAINER_SEQUENCE);
//        Element infoTemp = new Element(ApplicationServiceConstants.infoTempValueElementQName, SchemaUtil.getSchemaType(SchemaUtil.TYPE_DOUBLE));
//        cType.addElement(infoTemp);
//        message.setType(cType);

        return message;
    }

    protected Element getPullMessagesSyncElement()
    {
        Element pullMessages = new Element(Constants.FetchSyncOperationQName);

        ComplexType pullMessagesType = new ComplexType(ComplexType.CONTAINER_SEQUENCE);
        pullMessagesType.addElement(getIdentifiersListElement());

        pullMessages.setType(pullMessagesType);

        return pullMessages;
    }

    protected ComplexType getPushMessageType()
    {
        ComplexType pushMessageType = new ComplexType(Constants.PushMessageTypeQName, ComplexType.CONTAINER_SEQUENCE);
        pushMessageType.addElement(getMessagesListElement());

        return pushMessageType;
    }

    protected Element getPushElement()
    {
        ComplexType pushMessageType = new ComplexType(Constants.PushMessageTypeQName, ComplexType.CONTAINER_SEQUENCE);
        pushMessageType.addElement(getMessagesListElement());

        Element push = new Element(Constants.PushOperationQName, pushMessageType);

        return push;
    }

    protected Element getPushIdsElement()
    {
        Element pushIds = new Element(Constants.PushIdsOperationQName);

        ComplexType pushIdsType = new ComplexType(ComplexType.CONTAINER_SEQUENCE);
        pushIdsType.addElement(getMessagesInfoListElement());
        Element svcEPR = getSvcEprElement();
        svcEPR.setMinOccurs(0);
        svcEPR.setMaxOccurs(1);
        pushIdsType.addElement(svcEPR);

        pushIds.setType(pushIdsType);

        return pushIds;
    }

    protected URI getSender(SOAPHeader header, ParameterValue pv)
    {
        String svcEprStr = null;
        if(header != null)
        {
            // UDP
            EndpointReference replyTo = header.getReplyTo();
            if(replyTo != null)
                svcEprStr = header.getReplyTo().toString();
        }
        else
        {
            // TCP
            svcEprStr = pv.getValue(Constants.SvcEprElementName);
        }

        return new URI(svcEprStr);
    }

    public List getRecentMessages(long now, long interval)
    {
        return processor.getRecentMessages(now - interval);
    }

    public List getRecentMessages(long now, ParameterValue pv)
    {
        long timeInterval = 0;
        // retirar TimeInterval de pv
        String timeIntervalStr = pv.getAttributeValue(Constants.MillisecondsAttributeName, Constants.TimeIntervalElementName);
        logger.info("getRecentMessages invoked! TimeInterval:" + timeIntervalStr + "; pv=" + pv.toString());

        if (timeIntervalStr != null) {
            try {
                timeInterval = new Long(timeIntervalStr);
                logger.debug("now=" + now + "; timeInterval=" + timeInterval + "; now-timeInterval=" + (now - timeInterval));
            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            }
        } else {
            logger.error("timeIntervalStr has become null somehow!");
        }

        return processor.getRecentMessages(now - timeInterval);
    }
}


text:
namespace Stone{

class FunctionWrapper
{
public:
	FunctionWrapper() = default;

	template<typename FunctionType>
	FunctionWrapper(FunctionType&& f) noexcept
		:impl(new Impl<FunctionType>(std::move(f)))
	{
	}

	FunctionWrapper(FunctionWrapper&& other) noexcept
		:impl(std::move(other.impl))
	{
	}

	void operator()()
	{
		if(impl)
		{
			return impl->call();
		}
	}

	FunctionWrapper& operator=(FunctionWrapper&& other)
	{
		impl=std::move(other.impl);
		return *this;
	}

	FunctionWrapper(const FunctionWrapper&)=delete;
	FunctionWrapper(FunctionWrapper&)=delete;
	FunctionWrapper& operator=(const FunctionWrapper&)=delete;

private:
	struct Base
	{
		virtual void call()=0;
		virtual ~Base() {}
	};

	template<typename FunctionType>
	struct Impl: Base
	{
		FunctionType F_;
		Impl(FunctionType&& f): F_(std::move(f)) {}
		void call() { return F_(); }
	};

	std::unique_ptr<Base> impl;
};

class ThreadPool : private Noncopyable
{
public:
	explicit ThreadPool(const std::string& name = "ThreadPool");
	~ThreadPool();
	void SetThreadInitCallback(const std::function<void ()>& cb){ ThreadInitCallback_ = cb; }

	template<typename FunctionType>
	std::future<typename std::result_of<FunctionType()>::type>
	Submit(FunctionType f)
	{
		typedef typename std::result_of<FunctionType()>::type ResultType;
		std::packaged_task<ResultType()> task(std::move(f));
		std::future<ResultType> res(task.get_future());

#ifdef ESSIE_SPORT_MODE
		while(!Tasks_.SinglePut(std::move(task)))
		{
			std::this_thread::yield();
		}
#else
		if(!Tasks_.SinglePut(std::move(task)))
		{
			std::unique_lock<std::mutex> lk(MutexHasFreeSpace_);
			HasFreeSpace_.wait(lk, [&]{return Tasks_.SinglePut(std::move(task));});
		}

		std::lock_guard<std::mutex> lk(MutexHasData_);
		HasData_.notify_one();
#endif

		return res;
	}

private:
	void start(int numThreads);
	void stop();
	void run(std::string thread);
	FunctionWrapper take(const std::string& thread);

private:
	std::string Name_;
	std::vector<std::thread> Threads_;
	std::function<void()> ThreadInitCallback_;
	bool Running_;

	std::mutex MutexHasData_;
	std::mutex MutexHasFreeSpace_;
	std::condition_variable HasData_;
	std::condition_variable HasFreeSpace_;

	AsyncQueue<FunctionWrapper> Tasks_;
};

}

#endif


text:
package bezier.gui.menubar;

import bezier.EditorUI;

public class ExitMenuItem extends AbstractMenuItem {
  public ExitMenuItem(EditorUI editor) {
    super ("Exit", editor);
  }

  @Override
  protected void doAction(EditorUI editor) {
    editor.exit();
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PlayFab.Json
{
  /// <summary>
  /// Specifies null value handling options for the <see cref="JsonSerializer"/>.
  /// </summary>
  public enum NullValueHandling
  {
    /// <summary>
    /// Include null values when serializing and deserializing objects.
    /// </summary>
    Include = 0,
    /// <summary>
    /// Ignore null values when serializing and deserializing objects.
    /// </summary>
    Ignore = 1
  }
}
#endif


text:
package com.keeps.core.model.listener;

import com.keeps.tools.exception.CapecException;
import com.keeps.core.service.SoftService;

public abstract interface SaveOrUpdateListener extends ModelListener {
	public abstract void onSaveOrUpdate(SoftService paramSoftService) throws CapecException;
}


text:
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <dials/algorithms/spot_prediction/reflection_predictor.h>

namespace dials { namespace algorithms { namespace boost_python {

  using namespace boost::python;

  void export_scan_static_reflection_predictor() {
    typedef ScanStaticReflectionPredictor Predictor;

    class_<Predictor>("ScanStaticReflectionPredictor", no_init)
      .def(init<const boost::shared_ptr<BeamBase>,
                const Detector&,
                const Goniometer&,
                const Scan&,
                const cctbx::uctbx::unit_cell&,
                const cctbx::sgtbx::space_group_type&,
                double,
                double,
                double>())
      .def("for_ub_old_index_generator", &Predictor::for_ub_old_index_generator)
      .def("for_ub", &Predictor::for_ub)
      .def("for_hkl", &Predictor::for_hkl)
      .def("for_hkl", &Predictor::for_hkl_with_individual_ub)
      .def("for_reflection_table", &Predictor::for_reflection_table)
      .def("for_reflection_table", &Predictor::for_reflection_table_with_individual_ub);
  }

  void export_scan_varying_reflection_predictor() {
    typedef ScanVaryingReflectionPredictor Predictor;

    class_<Predictor>("ScanVaryingReflectionPredictor", no_init)
      .def(init<const boost::shared_ptr<BeamBase>,
                const Detector&,
                const Goniometer&,
                const Scan&,
                const cctbx::sgtbx::space_group_type&,
                double,
                std::size_t,
                double>())
      .def("for_ub", &Predictor::for_ub)
      .def("for_ub_on_single_image", &Predictor::for_ub_on_single_image)
      .def("for_varying_models", &Predictor::for_varying_models)
      .def("for_varying_models_on_single_image",
           &Predictor::for_varying_models_on_single_image)
      .def("for_reflection_table", &Predictor::for_reflection_table);
  }

  void export_stills_delta_psi_reflection_predictor() {
    typedef StillsDeltaPsiReflectionPredictor Predictor;

    af::reflection_table (Predictor::*predict_all)() const = &Predictor::operator();

    af::reflection_table (Predictor::*predict_observed)(
      const af::const_ref<cctbx::miller::index<> >&) = &Predictor::operator();

    af::reflection_table (Predictor::*predict_observed_with_panel)(
      const af::const_ref<cctbx::miller::index<> >&, std::size_t) =
      &Predictor::operator();

    af::reflection_table (Predictor::*predict_observed_with_panel_list)(
      const af::const_ref<cctbx::miller::index<> >&,
      const af::const_ref<std::size_t>&) = &Predictor::operator();

    class_<Predictor>("StillsDeltaPsiReflectionPredictor", no_init)
      .def(init<const boost::shared_ptr<BeamBase>,
                const Detector&,
                mat3<double>,
                const cctbx::uctbx::unit_cell&,
                const cctbx::sgtbx::space_group_type&,
                const double&>())
      .def("__call__", predict_all)
      .def("for_ub", &Predictor::for_ub)
      .def("__call__", predict_observed)
      .def("__call__", predict_observed_with_panel)
      .def("__call__", predict_observed_with_panel_list)
      .def("for_reflection_table", &Predictor::for_reflection_table)
      .def("for_reflection_table", &Predictor::for_reflection_table_with_individual_ub);
  }

  void export_nave_stills_reflection_predictor() {
    typedef NaveStillsReflectionPredictor Predictor;

    af::reflection_table (Predictor::*predict_all)() const = &Predictor::operator();

    af::reflection_table (Predictor::*predict_observed)(
      const af::const_ref<cctbx::miller::index<> >&) = &Predictor::operator();

    af::reflection_table (Predictor::*predict_observed_with_panel)(
      const af::const_ref<cctbx::miller::index<> >&, std::size_t) =
      &Predictor::operator();

    af::reflection_table (Predictor::*predict_observed_with_panel_list)(
      const af::const_ref<cctbx::miller::index<> >&,
      const af::const_ref<std::size_t>&) = &Predictor::operator();

    class_<Predictor>("NaveStillsReflectionPredictor", no_init)
      .def(init<const boost::shared_ptr<BeamBase>,
                const Detector&,
                mat3<double>,
                const cctbx::uctbx::unit_cell&,
                const cctbx::sgtbx::space_group_type&,
                const double&,
                const double&,
                const double&>())
      .def("__call__", predict_all)
      .def("for_ub", &Predictor::for_ub)
      .def("__call__", predict_observed)
      .def("__call__", predict_observed_with_panel)
      .def("__call__", predict_observed_with_panel_list)
      .def("for_reflection_table", &Predictor::for_reflection_table)
      .def("for_reflection_table", &Predictor::for_reflection_table_with_individual_ub);
  }

  void export_spherical_relp_stills_reflection_predictor() {
    typedef SphericalRelpStillsReflectionPredictor Predictor;

    af::reflection_table (Predictor::*predict_all)() const = &Predictor::operator();

    af::reflection_table (Predictor::*predict_observed)(
      const af::const_ref<cctbx::miller::index<> >&) = &Predictor::operator();

    af::reflection_table (Predictor::*predict_observed_with_panel)(
      const af::const_ref<cctbx::miller::index<> >&, std::size_t) =
      &Predictor::operator();

    af::reflection_table (Predictor::*predict_observed_with_panel_list)(
      const af::const_ref<cctbx::miller::index<> >&,
      const af::const_ref<std::size_t>&) = &Predictor::operator();

    class_<Predictor>("SphericalRelpStillsReflectionPredictor", no_init)
      .def(init<const boost::shared_ptr<BeamBase>,
                const Detector&,
                mat3<double>,
                const cctbx::uctbx::unit_cell&,
                const cctbx::sgtbx::space_group_type&,
                const double&>())
      .def("__call__", predict_all)
      .def("for_ub", &Predictor::for_ub)
      .def("__call__", predict_observed)
      .def("__call__", predict_observed_with_panel)
      .def("__call__", predict_observed_with_panel_list)
      .def("for_reflection_table", &Predictor::for_reflection_table)
      .def("for_reflection_table", &Predictor::for_reflection_table_with_individual_ub);
  }

  void export_reflection_predictor() {
    export_scan_static_reflection_predictor();
    export_scan_varying_reflection_predictor();
    export_stills_delta_psi_reflection_predictor();
    export_nave_stills_reflection_predictor();
    export_spherical_relp_stills_reflection_predictor();
  }

}}}  // namespace dials::algorithms::boost_python


text:
Services provide stable endpoints for Pods based on a set of labels.

In this lab you will create the `monolith` service and "expose" the `secure-monolith` Pod externally. You will learn how to:

* Create a service
* Use label selectors to expose a limited set of Pods externally

## Tutorial: Create a Service

Explore the monolith service configuration file:

```
cat services/monolith.yaml
```

Modify the monolith service to expose it externally as a Load Balancer:

```bash
vim services/monolith.yaml
```

Change `type: NodePorts` to a load balancer, so it will be exposed publicly:
```yaml
type: LoadBalancer
```

Now create the service using kubectl:

```
kubectl create -f services/monolith.yaml
```
<!--
Use the `gcloud compute firewall-rules` command to allow traffic to the `monolith` service:

```
gcloud compute firewall-rules create allow-monolith-nodeport \
  --allow=tcp:31000
``` -->

## Exercise: Interact with the Monolith Service Remotely

### Hints

```
kubectl get services
```

```
curl -k https://<EXTERNAL_IP>
```

### Quiz

* Why are you unable to get a response from the `monolith` service?

## Exercise: Explore the monolith Service

### Hints

```
kubectl get services monolith
```

```
kubectl describe services monolith
```

### Quiz

* How many endpoints does the `monolith` service have?
* What labels must a Pod have to be picked up by the `monolith` service?

## Tutorial: Add Labels to Pods

Currently the `monolith` service does not have any endpoints. One way to troubleshoot an issue like this is to use the `kubectl get pods` command with a label query.

```
kubectl get pods -l "app=monolith"
```

```
kubectl get pods -l "app=monolith,secure=enabled"
```

> Notice this label query does not print any results

Use the `kubectl label` command to add the missing `secure=enabled` label to the `secure-monolith` Pod.

```
kubectl label pods secure-monolith 'secure=enabled'
```

View the list of endpoints on the `monolith` service:

```
kubectl describe services monolith
```

### Quiz

* How many endpoints does the `monolith` service have?

## Exercise: Interact with the Monolith Service Remotely

### Hints

```
kubectl get services monolith
```

```
curl -k https://<EXTERNAL_IP>
```

## Tutorial: Remove Labels from Pods

In this exercise you will observe what happens when a required label is removed from a Pod.

Use the `kubectl label` command to remove the `secure` label from the `secure-monolith` Pod.

```
kubectl label pods secure-monolith secure-
```

View the list of endpoints on the `monolith` service:

```
kubectl describe services monolith
```

### Quiz

* How many endpoints does the `monolith` service have?

## Summary

In this lab you learned how to expose Pods using services and labels.


text:
# Dumping structure for table tbl_constant
DROP TABLE IF EXISTS `tbl_constant`;
CREATE TABLE IF NOT EXISTS `tbl_constant` (
  `ConstantName` varchar(255) NOT NULL DEFAULT '',
  `ConstantValue` text,
  `ConstantDesc` text,
  `ConstantGroup` varchar(255) NOT NULL DEFAULT '',
  PRIMARY KEY (`ConstantName`),
  UNIQUE KEY `ConstantName` (`ConstantName`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

# Dumping data for table tbl_constant: 1 rows
DELETE FROM `tbl_constant`;
/*!40000 ALTER TABLE `tbl_constant` DISABLE KEYS */;
INSERT INTO `tbl_constant` (`ConstantName`, `ConstantValue`, `ConstantDesc`, `ConstantGroup`)
VALUES ('URCHINCODE', '0', 'Google Analytics Code. 0 - no code', 'misc');
/*!40000 ALTER TABLE `tbl_constant` ENABLE KEYS */;


text:
A Python project to analyze my Fitbit sleep data.

## Overview
![Spring quarter sleep durations versus bedtimes](sample-image.png?raw=true)

This is a Python 3 project to obtain and analyze data on my sleep patterns, which has been collected nightly since July 2015 on my Fitbit Charge HR. The first part of the project is a script to access my nightly sleep logs; this script can be used by anyone hoping to access their data. The second part is the data analysis, in which I look into my spring sleep habits. This README focuses on the first part only.

Goals of this project included:
 * Learning to use Fitbit's API
 * Learning about the OAuth 2.0 protocol
 * Introducing myself to data analysis in Python
 * Gaining insight into my sleep patterns

Note: Fitbit is a registered trademark and service mark of Fitbit, Inc. My sleep analysis project is designed for personal use with the Fitbit platform. This product is not put out by Fitbit, and Fitbit does not service or warrant the functionality of this product.

## Part 1: Obtaining Minute-by-Minute Sleep Data
The first part of this project involves accessing my nightly, minute-by-minute sleep data from Fitbit's servers. Fitbit does not usually provide this through their smartphone or desktop apps; users can only generally see summary statistics. In order to access this data, I had to use Fitbit's API myself.

### Instructions
Clone the repo. Go to the [Fitbit Developers website](https://dev.fitbit.com/), register for an account, and register an app with them. The app will be for "Personal" use, which gives access to intraday sleep data.

Create a file in a new directory, `credentials/client_secret.json`. (Note that this directory is listed in `.gitignore`.) This file should have:
```
{
  "web": {
    "client_id": "",
    "client_secret": "",
    "redirect_uris": [ "" ],
    "auth_uri": "https://api.fitbit.com/1/user/[client_id]/sleep/date",
    "token_uri": "https://api.fitbit.com/oauth2/token"
  }
}
```
Fill in the `client_id`, `client_secret`, and `redirect_uris` according to what you see on the Fitbit Developers console. Replace `[client_id]` with your client ID in `auth_uri`, and leave `token_uri` as is.

Finally, you are ready to run the app from the command line as `python fitbit.py <start date>`, with `<start date>` being optional, formatted as `yyyy-mm-dd`. This will write up to 150 days' worth of minute-by-minute sleep data to the directory `/logs/`.

### How Data Access Works
Accessing the data roughly follows this flow:
 * Try to read an access token from a file.
 * If no access token exists, generate a new one (this requires the user to authorize the script, which occurs in `get_token()`).
 * Try to read sleep data using this token. If the token has expired (this would happen if it was read from a file created some time ago), use the refresh token to generate and save a new one.
 * Read the sleep data with the new token.

The files are saved to a directory `logs` with names `yyyy-mm-dd.json`.

### Usage Notes
Fitbit limits API usage to 150 requests per hour. If you have more than 150 days of data, the script will write 150, then exit and tell you the start date for the top of the next hour.

If the start date is not entered, a default date of 150 days ago is chosen.

## Part 2: Data Analysis
Refer to `spring-sleep-analysis.ipynb` for the data analysis. This was done through a Jupyter notebook, making use of my spring quarter sleep data. Further detail is provided in that file; the image above is taken from the notebook.


text:
@implementation OHToolbarItem

@end


text:
#ifndef BINARYHEAP_H
#define BINARYHEAP_H

#include <iostream>
#include <vector>
#include "../Heap.h"
#include "../Exceptions.h"

namespace altrusian {
    namespace Heaps {
        namespace D_Ary_Heap {

            class D_ary_Heap : public Heap {

                Heaps::EmptyHeapException emptyHeapException;
                Heaps::IndexOutOfBounds indexOutOfBoundsException;

            protected:
                int d;
                virtual long int parentIndex(long int const &keyIndex);
                virtual long int firstChildIndex(long int const &keyIndex);
                virtual long int firstNodeIndex();
                virtual long int lastNodeIndex();
                virtual bool isCapableToShiftUp(long int const &keyIndex) = 0;
                virtual bool isCapableToShiftDown(long int const &keyIndex) = 0;
                virtual void shiftUp(long int const &keyIndex);
                virtual void shiftDown(long int const &keyIndex);
                virtual long int maxChildIndex(long int const &keyIndex) = 0;
                virtual void bubbleUp(long int keyIndex);
                virtual void bubbleDown(long int keyIndex);
                virtual bool isFirstNode(long int const &keyIndex);
                virtual bool isLeafNode(long int const &keyIndex);
                virtual bool indexNotInBounds(long int const &keyIndex);
                virtual long int dThChildIndex(long int const &firstChildIndex);
                virtual long int distanceFromFirstChild(long int const &keyIndex);

            public:
                int max();
                int extractMax();
                void insert(int value);
                void heapify();
                void update(long int const &keyIndex, int const &value);
                void mergeWith(Heap *heap);
                bool isEmpty();
                long int size();
                heapIterator it_begin();
                heapIterator it_end();

                static Heap *mergeHeaps(Heap *heap1, Heap *heap2, Heap *heap, std::vector<int> &vector);

            };

        }
    }
}

#endif //BINARYHEAP_H


text:
namespace aria2 {

class RequestGroupTest : public CppUnit::TestFixture {

  CPPUNIT_TEST_SUITE(RequestGroupTest);
  CPPUNIT_TEST(testGetFirstFilePath);
  CPPUNIT_TEST(testCreateDownloadResult);
  CPPUNIT_TEST_SUITE_END();
private:
  std::shared_ptr<Option> option_;
public:
  void setUp()
  {
    option_.reset(new Option());
  }

  void testGetFirstFilePath();
  void testCreateDownloadResult();
};

CPPUNIT_TEST_SUITE_REGISTRATION( RequestGroupTest );

void RequestGroupTest::testGetFirstFilePath()
{
  std::shared_ptr<DownloadContext> ctx
    (new DownloadContext(1024, 1024, "/tmp/myfile"));

  RequestGroup group(GroupId::create(), option_);
  group.setDownloadContext(ctx);

  CPPUNIT_ASSERT_EQUAL(std::string("/tmp/myfile"), group.getFirstFilePath());

  group.markInMemoryDownload();

  CPPUNIT_ASSERT_EQUAL(std::string("[MEMORY]myfile"), group.getFirstFilePath());
}

void RequestGroupTest::testCreateDownloadResult()
{
  std::shared_ptr<DownloadContext> ctx
    (new DownloadContext(1024, 1024*1024, "/tmp/myfile"));
  RequestGroup group(GroupId::create(), option_);
  group.setDownloadContext(ctx);
  group.initPieceStorage();
  {
    std::shared_ptr<DownloadResult> result = group.createDownloadResult();

    CPPUNIT_ASSERT_EQUAL(std::string("/tmp/myfile"),
                         result->fileEntries[0]->getPath());
    CPPUNIT_ASSERT_EQUAL((int64_t)1024*1024,
                         result->fileEntries.back()->getLastOffset());
    CPPUNIT_ASSERT_EQUAL((uint64_t)0, result->sessionDownloadLength);
    CPPUNIT_ASSERT_EQUAL((int64_t)0, result->sessionTime);
    // result is UNKNOWN_ERROR if download has not completed and no specific
    // error has been reported
    CPPUNIT_ASSERT_EQUAL(error_code::UNKNOWN_ERROR, result->result);

    // if haltReason is set to RequestGroup::USER_REQUEST, download
    // result will become REMOVED.
    group.setHaltRequested(true, RequestGroup::USER_REQUEST);
    result = group.createDownloadResult();
    CPPUNIT_ASSERT_EQUAL(error_code::REMOVED, result->result);
    // if haltReason is set to RequestGroup::SHUTDOWN_SIGNAL, download
    // result will become IN_PROGRESS.
    group.setHaltRequested(true, RequestGroup::SHUTDOWN_SIGNAL);
    result = group.createDownloadResult();
    CPPUNIT_ASSERT_EQUAL(error_code::IN_PROGRESS, result->result);
  }
  {
    group.setLastErrorCode(error_code::RESOURCE_NOT_FOUND);

    std::shared_ptr<DownloadResult> result = group.createDownloadResult();

    CPPUNIT_ASSERT_EQUAL(error_code::RESOURCE_NOT_FOUND, result->result);
  }
  {
    group.getPieceStorage()->markAllPiecesDone();

    std::shared_ptr<DownloadResult> result = group.createDownloadResult();

    CPPUNIT_ASSERT_EQUAL(error_code::FINISHED, result->result);
  }
}

} // namespace aria2


text:
<?php

use Illuminate\Database\Seeder;

use Synthesise\Seminar;

class SeminarTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {

        DB::table('seminars')->delete();

        // AHEW

        Seminar::create(array(
            'name' => 'Grundfragen pädagogischen Denkens und Handelns',
            'subject' => 'Allgemeine und Historische Erziehungswissenschaft',
            'description' => 'Hier geht es um die Grundfragen zu Erziehung und Bildung.',
            'module' => 'M1',
            'author' => 'Apl. Prof. Dr. Timo Hoyer',
            'contact' => 'hoyer@ph-karlsruhe.de',
            'authorized_editors' => ["dozent", "root"],
            'image_path' => 'storage/seminars/2f85bce36f69738b5fa85b25e6e9a728.jpg',
            'info_intro' => '

            Die Lehrveranstaltung »Erziehungswissenschaftliche Grundfragen pädagogischen Denkens und Handelns« führt in Themen und Fragestellungen der Allgemeinen und Historischen Erziehungswissenschaft ein. Sie setzt sich folgendermaßen zusammen:
',
            'info_lections' => '

                Die online-Lektionen vermitteln in verdichteter, visualisierter Form Theoriezugänge zu elementaren Themenfeldern und Forschungszweigen der Allgemeinen und Historischen Erziehungswissenschaft.

                Die einzelnen Lektionen werden in festgelegten, zumeist wöchentlichen Abständen zugänglich gemacht (Daten der Freischaltung siehe unter »Zugänglich ab« in der Tabelle weiter unten). Die einmal freigeschalteten Lektionen bleiben bis zum Tag der Prüfung geöffnet und können jederzeit angeschaut werden.

                An den mit roten Fähnchen gekennzeichneten Stellen der online-Lektionen können Sie individuelle Notizen (Stichworte, kurze Erläuterungen, Eselsbrücken, Querverweise etc.) einfügen, die automatisch gespeichert werden und als PDF ausdruckbar sind.

                Die Lektionen sind urheberrechtlich geschützt und ausschließlich im vorgegebenen Rahmen der Lehrveranstaltung zu nutzen. Der Download oder die Verbreitung in irgendeiner Form ist nicht gestattet.

',
            'info_texts' => '

            Digitalisierte Medien sind eine Erweiterung herkömmlicher Lehr-Lern-Medien, sollen diese aber nicht zum Verschwinden bringen. Wissenschaftliche, hermeneutische Textarbeit bleibt eine bedeutsame Praxis, die Studierende gerade in stark von Theoriedebatten geprägten Fächern, wie die Erziehungswissenschaft, erlernen und ausüben müssen.

            Zu jeder online-Lektion gibt es (mindestens) einen prüfungsrelevanten Text (Primär- oder Sekundärliteratur), der die in der Lektion angesprochenen Themen mit neuen Gesichtspunkten ergänzt, vertieft oder weiterführt.

            Den Texten sind Bearbeitungsaufgaben und Fragen beigefügt (Hinweise zur Bearbeitung der Texte).

            In den wöchentlichen Veranstaltungen (Mentoriate) besteht die Gelegenheit, die Inhalte zu reflektieren, Verknüpfungen zwischen Lektion und Text herzustellen sowie Abweichungen, Widersprüche und eigene Erfahrungen zu diskutieren.

            Allgemeine und weiterführende Literaturhinweise zu den vier großen Themenblöcken der Vorlesung bieten die Möglichkeiten, sich über die Veranstaltung hinaus mit den darin angesprochenen Fragen auseinanderzusetzen.

',
            'info_exam' => '

            Die Modul 1-Veranstaltung wird in der Prüfungswoche mit einer 90minütigen schriftlichen Klausur abgeschlossen, die aus zwei gleichwertigen Teilen besteht: Allgemeine/Historische Erziehungswissenschaft und Schulpädagogik.

            Der Teil der Allgemeinen und Historischen Erziehungswissenschaft setzt sich aus Single Choice- und Multiple Choice-Aufgaben zusammen. Die Klausurmodalitäten werden rechtzeitig in einer Vorlesung (siehe Präsenzveranstaltungen) besprochen.

            Weitere allgemeine Informationen zur Akademischen Vorprüfung finden Sie auf der Website des Prüfungsamts.

',
            'info_dates' => NULL,
            'info_path' => NULL,
            'available_from' => '2016-10-25',
            'available_to' => '2017-02-08',
            'disqus_shortname' => NULL,
        ));

        // FRÜHPÄDAGOGIK
        Seminar::create(array(
            'name' => 'Geschichte(n) und Theorien (früh-)kindlicher Bildung und Entwicklung',
            'subject' => 'Frühpädagogik',
            'description' => 'Hier geht es um die frühpädagogischen Grundlagen von Erziehung und Bildung.',
            'module' => 'M1',
            'author' => 'Prof. Dr. Ulrich Wehner',
            'contact' => 'wehner@ph-karlsruhe.de',
            'authorized_editors' => ["dozent", "root"],
            'image_path' => 'storage/seminars/59d1c268a763eb7d28cdefa5274b1d2a.jpg',
            'info_intro' => NULL,
            'info_lections' => NULL,
            'info_texts' => NULL,
            'info_exam' => NULL,
            'info_dates' => NULL,
            'info_path' => NULL,
            'available_from' => '2016-10-30',
            'available_to' => '2017-03-01',
            'disqus_shortname' => NULL
        ));

        // MATHEMATIK
        Seminar::create(array(
            'name' => 'Zahlentheorie und Zahlbereiche',
            'subject' => 'Mathematik',
            'description' => 'Hier geht es um die Einfühung in die Grundlagen der Mathematik.',
            'module' => 'M1',
            'author' => 'Prof. Dr. Mutfried Hartmann',
            'contact' => 'mutfried.hartmann@ph-karlsruhe.de',
            'authorized_editors' => ["root"],
            'image_path' => 'storage/seminars/63377e139e0464e8244d0b026efd0b84.jpg',
            'info_intro' => NULL,
            'info_lections' => NULL,
            'info_texts' => NULL,
            'info_exam' => NULL,
            'info_dates' => NULL,
            'info_path' => NULL,
            'available_from' => '2016-10-30',
            'available_to' => '2017-03-01',
            'disqus_shortname' => 'etpm'
        ));

    }
}


text:
from collections import defaultdict
from datetime import timedelta
from enum import IntEnum, auto

from libmozdata import utils as lmdutils

from auto_nag import utils
from auto_nag.bzcleaner import BzCleaner
from auto_nag.constants import HIGH_PRIORITY, HIGH_SEVERITY
from auto_nag.user_activity import UserActivity, UserStatus
from auto_nag.utils import plural

RECENT_BUG_LIMIT = lmdutils.get_date("today", timedelta(weeks=5).days)
RECENT_NEEDINFO_LIMIT = lmdutils.get_date("today", timedelta(weeks=2).days)

class NeedinfoAction(IntEnum):
    FORWARD = auto()
    CLEAR = auto()
    CLOSE_BUG = auto()

    def __str__(self):
        return self.name.title().replace("_", " ")

class InactiveNeedinfoPending(BzCleaner):
    def __init__(self):
        super(InactiveNeedinfoPending, self).__init__()
        self.max_actions = utils.get_config(self.name(), "max_actions", 7)

    def get_max_actions(self):
        return self.max_actions

    def description(self):
        return "Bugs with needinfo pending on inactive people"

    def columns(self):
        return [
            "id",
            "summary",
            "inactive_ni",
            "inactive_ni_count",
            "action",
            "triage_owner",
        ]

    def get_bugs(self, *args, **kwargs):
        bugs = super().get_bugs(*args, **kwargs)
        bugs = self.handle_inactive_requestee(bugs)

        # Resolving https://github.com/mozilla/relman-auto-nag/issues/1300 should clean this
        # including improve the wording in the template (i.e., "See the search query on Bugzilla").
        self.query_url = utils.get_bz_search_url({"bug_id": ",".join(bugs.keys())})

        return bugs

    def handle_inactive_requestee(self, bugs):
        """
        Detect inactive users and filter bugs to keep only the ones with needinfo pending on
        inactive users.
        """
        requestee_bugs = defaultdict(list)
        for bugid, bug in bugs.items():
            for flag in bug["needinfo_flags"]:
                if "requestee" not in flag:
                    flag["requestee"] = ""

                requestee_bugs[flag["requestee"]].append(bugid)

        user_activity = UserActivity(include_fields=["groups"])
        needinfo_requestees = set(requestee_bugs.keys())
        triage_owners = {bug["triage_owner"] for bug in bugs.values()}
        inactive_users = user_activity.check_users(needinfo_requestees | triage_owners)

        inactive_requestee_bugs = {
            bugid
            for requestee, bugids in requestee_bugs.items()
            if requestee in inactive_users
            for bugid in bugids
        }

        def has_canconfirm_group(user_email):
            for group in inactive_users[user_email].get("groups", []):
                if group["name"] == "canconfirm":
                    return True
            return False

        def get_inactive_ni(bug):
            return [
                {
                    "id": flag["id"],
                    "setter": flag["setter"],
                    "requestee": flag["requestee"],
                    "requestee_status": user_activity.get_string_status(
                        inactive_users[flag["requestee"]]["status"]
                    ),
                    "requestee_canconfirm": has_canconfirm_group(flag["requestee"]),
                }
                for flag in bug["needinfo_flags"]
                if flag["requestee"] in inactive_users
                and (
                    # Exclude recent needinfos to allow some time for external
                    # users to respond.
                    flag["modification_date"] < RECENT_NEEDINFO_LIMIT
                    or inactive_users[flag["requestee"]]["status"]
                    in [UserStatus.DISABLED, UserStatus.UNDEFINED]
                )
            ]

        res = {}
        skiplist = self.get_auto_ni_skiplist()
        for bugid, bug in bugs.items():
            if (
                bugid not in inactive_requestee_bugs
                or bug["triage_owner"] in inactive_users
                or bug["triage_owner"] in skiplist
            ):
                continue

            inactive_ni = get_inactive_ni(bug)
            if len(inactive_ni) == 0:
                continue

            bug = {
                **bug,
                "inactive_ni": inactive_ni,
                "inactive_ni_count": len(inactive_ni),
                "action": self.get_action_type(bug, inactive_ni),
            }
            res[bugid] = bug
            self.add_action(bug)

        return res

    @staticmethod
    def get_action_type(bug, inactive_ni):
        """
        Determine if should forward needinfos to the triage owner, clear the
        needinfos, or close the bug.
        """

        if (
            bug["priority"] in HIGH_PRIORITY
            or bug["severity"] in HIGH_SEVERITY
            or bug["last_change_time"] >= RECENT_BUG_LIMIT
        ):
            return NeedinfoAction.FORWARD

        if (
            len(bug["needinfo_flags"]) == 1
            and bug["type"] == "defect"
            and inactive_ni[0]["requestee"] == bug["creator"]
            and not inactive_ni[0]["requestee_canconfirm"]
            and not any(
                attachment["content_type"] == "text/x-phabricator-request"
                and not attachment["is_obsolete"]
                for attachment in bug["attachments"]
            )
        ):
            return NeedinfoAction.CLOSE_BUG

        if bug["severity"] == "--":
            return NeedinfoAction.FORWARD

        return NeedinfoAction.CLEAR

    @staticmethod
    def _clear_inactive_ni_flags(bug):
        return [
            {
                "id": flag["id"],
                "status": "X",
            }
            for flag in bug["inactive_ni"]
        ]

    @staticmethod
    def _needinfo_triage_owner_flag(bug):
        return [
            {
                "name": "needinfo",
                "requestee": bug["triage_owner"],
                "status": "?",
                "new": "true",
            }
        ]

    @staticmethod
    def _request_from_triage_owner(bug):
        reasons = []
        if bug["priority"] in HIGH_PRIORITY:
            reasons.append("high priority")
        if bug["severity"] in HIGH_SEVERITY:
            reasons.append("high severity")
        if bug["last_change_time"] >= RECENT_BUG_LIMIT:
            reasons.append("recent activity")

        if len(reasons) == 0 and bug["severity"] == "--":
            return "since the bug doesn't have a severity set, could you please set the severity or close the bug?"

        comment = []
        if reasons:
            comment.append(f"since the bug has {utils.english_list(reasons)}")

        if (
            len(bug["inactive_ni"]) == 1
            and bug["inactive_ni"][0]["setter"] == bug["triage_owner"]
        ):
            comment.append(
                "could you please find another way to get the information or close the bug as `INCOMPLETE` if it is not actionable?"
            )
        else:
            comment.append("could you have a look please?")

        return ", ".join(comment)

    def add_action(self, bug):
        users_num = len(set([flag["requestee"] for flag in bug["inactive_ni"]]))

        if bug["action"] == NeedinfoAction.FORWARD:
            autofix = {
                "flags": (
                    self._clear_inactive_ni_flags(bug)
                    + self._needinfo_triage_owner_flag(bug)
                ),
                "comment": {
                    "body": (
                        f'Redirect { plural("a needinfo that is", bug["inactive_ni"], "needinfos that are") } pending on { plural("an inactive user", users_num, "inactive users") } to the triage owner.'
                        f'\n:{ bug["triage_owner_nic"] }, {self._request_from_triage_owner(bug)}'
                    )
                },
            }

        elif bug["action"] == NeedinfoAction.CLEAR:
            autofix = {
                "flags": self._clear_inactive_ni_flags(bug),
                "comment": {
                    "body": (
                        f'Clear { plural("a needinfo that is", bug["inactive_ni"], "needinfos that are") } pending on { plural("an inactive user", users_num, "inactive users") }.'
                        "\n\nInactive users most likely will not respond; "
                        "if the missing information is essential and cannot be collected another way, "
                        "the bug maybe should be closed as `INCOMPLETE`."
                    ),
                },
            }

        elif bug["action"] == NeedinfoAction.CLOSE_BUG:
            autofix = {
                "flags": self._clear_inactive_ni_flags(bug),
                "status": "RESOLVED",
                "resolution": "INCOMPLETE",
                "comment": {
                    "body": "A needinfo is requested from the reporter, however, the reporter is inactive on Bugzilla. Closing the bug as incomplete."
                },
            }

        autofix["comment"]["body"] += f"\n\n{self.get_documentation()}\n"
        self.add_prioritized_action(bug, bug["triage_owner"], autofix=autofix)

    def get_bug_sort_key(self, bug):
        return (
            bug["action"],
            utils.get_sort_by_bug_importance_key(bug),
        )

    def handle_bug(self, bug, data):
        bugid = str(bug["id"])
        triage_owner_nic = (
            bug["triage_owner_detail"]["nick"] if "triage_owner_detail" in bug else ""
        )
        data[bugid] = {
            "priority": bug["priority"],
            "severity": bug["severity"],
            "creation_time": bug["creation_time"],
            "last_change_time": utils.get_last_no_bot_comment_date(bug),
            "creator": bug["creator"],
            "type": bug["type"],
            "attachments": bug["attachments"],
            "triage_owner": bug["triage_owner"],
            "triage_owner_nic": triage_owner_nic,
            "needinfo_flags": [
                flag for flag in bug["flags"] if flag["name"] == "needinfo"
            ],
        }

        return bug

    def get_bz_params(self, date):
        fields = [
            "type",
            "attachments.content_type",
            "attachments.is_obsolete",
            "triage_owner",
            "flags",
            "priority",
            "severity",
            "creation_time",
            "comments",
            "creator",
        ]

        params = {
            "include_fields": fields,
            "resolution": "---",
            "f1": "flagtypes.name",
            "o1": "equals",
            "v1": "needinfo?",
        }

        # Run monthly on all bugs and weekly on recently changed bugs
        if lmdutils.get_date_ymd(date).day > 7:
            params.update(
                {
                    "f2": "anything",
                    "o2": "changedafter",
                    "v2": "-1m",
                }
            )

        return params

if __name__ == "__main__":
    InactiveNeedinfoPending().run()


text:
layout: post

title: BCrypt: Hash Passwords Correctly
author: Matthew James Davis
category: blog
thumb: blog/2016-1-28-bcrypt.jpg
blurb: How to leverage the BCrypt algorithm to enhance your application's security
tags: security hacking bcrypt node javascript c# .NET python

published: true
---
On 11 Jan 2016, [Milq](http://www.milq.com) was [hacked](https://twitter.com/data_siph0n/status/686070270419931136). Their database was stolen, the user table dumped to a text file, and shared to the internet. In fact, this is a very common occurrence, with a very simple solution: BCrypt.

> Bcrypt has the best kind of repute that can be achieved for a cryptographic algorithm: it has been around for quite some time, used quite widely, "attracted attention", and yet remains unbroken to date.

Implementing the BCrypt algorithm is basically done for you; there are libraries in almost every language that handle everything for you. Let's look at how to use them.

# .NET (C#)

There are a few out BCrypt libraries in NuGet, and I personally use [BCrypt.NET](https://www.nuget.org/packages/BCrypt-Official/). You can install this through Visual Studio by

1. right clicking your solution,
2. clicking "Manage NuGet Packages for Solution..."
3. clicking the "Browse" tab in the NuGet window
4. setting "Package source" in the upper right to "nuget.org"
5. searching for "bcrypt"
6. selecting BCrypt-Official
7. ticking the checkbox of the project you to install it in on the right
8. and clicking install.

Now you're ready to use it. Here's an example of how to use it in code. Easy.

```csharp
// hash and save a password
hashedPassword = BCrypt.Net.BCrypt.HashPassword(submittedPassword);

// check a password
bool validPassword = BCrypt.Net.BCrypt.Verify(submittedPassword, hashedPassword);
```

# node.js (javascript)

There are a few BCrypt libraries in npm as well, and I personally use [bcryptjs](https://www.npmjs.com/package/bcryptjs). You can install this through npm by running `npm install bcryptjs --save` from your project's root directory.

Here's an example of how to use it in code. Again, easy.

```javascript
// first, require it in
var bcrypt = require('bcryptjs');

// hash and save a password
hashedPassword = bcrypt.hashSync(submittedPassword, 10);

// check a password
bool validPassword = bcrypt.compareSync(submittedPassword, hashedPassword)
```

# python

Python has only one widely used BCrypt library that I know of, aptly named [bcrypt](https://pypi.python.org/pypi/bcrypt/2.0.0). You can install this by running `pip install bcrypt`.

Here's an example of how to use it in code. This is a bit different from the previous two examples, but still straightforward.

```python
# first, import it
import bcrypt

# hash and save a password
hashedPassword = bcrypt.hashpw(submittedPassword, bcrypt.gensalt(10))

# check a password
validPassword = bcrypt.hashpw(password, hashed) == hashed
```

# Migrating to BCrypt
Okay, so implementing BCrypt is very easy. But your mature application, like Milq, is using a very primitive hashing algorithm, and you can't exactly recover the passwords to BCryptify them. But there are options, and if you've ever receieved an email from a website urging you to log in for "security reasons," you've probably seen them in practice.

The strategy here is to *assume* everything is already BCrypt; when BCrypt libraries find non-BCrypt passwords, they throw errors. By migrating your current password code into the catch block of such an error, you can check for valid passwords using your old algorithm and update the passwords on the fly to BCrypt. Here's an example in C#:

```csharp
bool validPassword = false;

try
{
	// check the password using bcrypt
    validPassword = BCrypt.Net.BCrypt.Verify(submittedPassword, hashedPassword);
}

// if a salt parse exception is thrown, the password has not been updated
// check against the old algorithm and update if the password is valid
catch (BCrypt.Net.SaltParseException)
{
    validPassword = OldCheckPasswordFunction(submittedPassword, hashedPassword))
    if (validPassword)
    {
        user.Password = BCrypt.Net.BCrypt.HashPassword(login.Password);
    }
}
```

As easy as that, your database will record-by-record be updated to BCrypt as users log in, with your users none the wiser.

# The Cost Parameter

In the node.js and python examples above, you may have noticed the number 10 in a few spots. This number is the cost parameter. The cost parameter is used to increase the time required to complete one hash. If the cost parameter is very high, it will take longer to complete a hash. For a user with a single password, a wait of 500 ms is not noticeable; for an attacker with billions or more of passwords, cracking the system will become impossible.

Since computers become faster over time, the cost parameter was introduced as a variable. What might have taken 500ms in 2001 might require only 5ms today. Therefore, this number can be increased to fit your application's particular needs. Here's how to do it:

#### c\#
```csharp
int costParameter = 12;
hashedPassword = BCrypt.Net.BCrypt.HashPassword(login.Password, costParameter);
```

#### node.js
```javascript
var costParameter = 12;
hashedPassword = bcrypt.hashSync(submittedPassword, costParameter);
```

#### python
```python
costParameter = 12;
hashedPassword = bcrypt.hashpw(submittedPassword, bcrypt.gensalt(costParameter));
```

# Why is BCrypt better?

![A BCrypt Hash](/images/blog/2016-1-28-bcrypt-1.png "A BCrypt Hash")

BCrypt is not the best algorithm out there; however, it is sufficient for the large majority of use cases, and it is just as easy to implement, if not easier, than the basic hash-and-salt method. What sets BCrypt apart is that instead of the more typical SHA-* algorithm, it leverages the [Blowfish](https://en.wikipedia.org/wiki/Blowfish_%28cipher%29) algorithm, which has the advantage of being much *slower* in parallel. Since users log in one-at-a-time, this makes it much harder for attackers, who will test numerous passwords, to beat the algorithm.

# Links
[OWASP Password Storage Cheat Sheat](https://www.owasp.org/index.php/Password_Storage_Cheat_Sheet)

[In-Depth Explanation of BCrypt](http://security.stackexchange.com/questions/4781/do-any-security-experts-recommend-bcrypt-for-password-storage)

[60% of the Milq passwords were deciphered](https://twitter.com/kyhwana/status/686431850441474048)


text:
package com.egzosn.pay.common.http;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;

import static com.egzosn.pay.common.http.UriVariables.getMapToParameters;

import com.egzosn.pay.common.util.str.StringUtils;

/**
 * 请求实体,包含请求头,内容类型,编码类型等
 *
 * @author egan
 * <pre>
 *               email egzosn@gmail.com
 *               date 2017/12/20
 *           </pre>
 */
public class HttpStringEntity extends StringEntity {
    /**
     * 请求头
     */
    private List<Header> headers;
    /**
     * 是否为空的请求实体
     */
    private boolean isEmpty = false;

    public boolean isEmpty() {
        return isEmpty;
    }

    public void setEmpty(boolean empty) {
        isEmpty = empty;
    }

    public void requestIsEmpty(Map<String, Object> request) {
        if (null == request || request.isEmpty()) {
            this.isEmpty = true;
        }
    }

    public void requestIsEmpty(String request) {
        if (StringUtils.isEmpty(request)) {
            this.isEmpty = true;
        }

    }

    /**
     * 构造器
     *
     * @param request 请求体
     * @param headers 请求头
     * @throws UnsupportedEncodingException 不支持默认的HTTP字符集
     */
    public HttpStringEntity(Map<String, Object> request, Header... headers) throws UnsupportedEncodingException {
        this(getMapToParameters(request), headers);
        requestIsEmpty(request);

    }

    /**
     * 构造器
     *
     * @param request 请求体
     * @param headers 请求头
     * @throws UnsupportedEncodingException 不支持默认的HTTP字符集
     */
    public HttpStringEntity(Map<String, Object> request, Map<String, String> headers) throws UnsupportedEncodingException {
        this(getMapToParameters(request), headers);
        requestIsEmpty(request);

    }

    /**
     * 构造器
     *
     * @param request     请求体
     * @param contentType 内容类型
     */
    public HttpStringEntity(Map<String, Object> request, ContentType contentType) {
        super(getMapToParameters(request), contentType);
        requestIsEmpty(request);
    }

    /**
     * 构造器
     *
     * @param request 请求体
     * @param charset 字符类型
     */
    public HttpStringEntity(Map<String, Object> request, String charset) {
        super(getMapToParameters(request), charset);
        requestIsEmpty(request);
    }

    /**
     * 构造器
     *
     * @param request 请求体
     * @param charset 字符类型
     */
    public HttpStringEntity(Map<String, Object> request, Charset charset) {
        super(getMapToParameters(request), charset);
        requestIsEmpty(request);
    }

    /**
     * 构造器
     *
     * @param request 请求体
     * @throws UnsupportedEncodingException 不支持默认的HTTP字符集
     */
    public HttpStringEntity(Map<String, Object> request) throws UnsupportedEncodingException {
        super(getMapToParameters(request));
        requestIsEmpty(request);
    }

    /**
     * 构造器
     *
     * @param request     请求体
     * @param contentType 内容类型
     * @throws UnsupportedCharsetException 不支持默认的HTTP字符集
     */
    public HttpStringEntity(String request, ContentType contentType) throws UnsupportedCharsetException {
        super(request, contentType);
        requestIsEmpty(request);
    }

    /**
     * 构造器
     *
     * @param request 请求体
     * @param charset 字符类型
     * @throws UnsupportedCharsetException 不支持默认的HTTP字符集
     */
    public HttpStringEntity(String request, String charset) throws UnsupportedCharsetException {
        super(request, charset);
        requestIsEmpty(request);
    }

    /**
     * 构造器
     *
     * @param request 请求体
     * @param charset 字符类型
     */
    public HttpStringEntity(String request, Charset charset) {
        super(request, charset);
        requestIsEmpty(request);
    }

    /**
     * 构造器
     *
     * @param request 请求体
     * @param headers 请求头
     * @throws UnsupportedEncodingException 不支持默认的HTTP字符集
     */
    public HttpStringEntity(String request, Header... headers) throws UnsupportedEncodingException {
        super(request);
        requestIsEmpty(request);
        if (null != headers) {
            this.headers = Arrays.asList(headers);
        }
    }

    /**
     * 构造器
     *
     * @param request 请求体
     * @param headers 请求头
     * @throws UnsupportedEncodingException 不支持默认的HTTP字符集
     */
    public HttpStringEntity(String request, Map<String, String> headers) throws UnsupportedEncodingException {
        super(request);
        requestIsEmpty(request);
        this.headers = new ArrayList<>();
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            addHeader(new BasicHeader(entry.getKey(), entry.getValue()));
        }
    }

    /**
     * 获取请求头集
     *
     * @return 请求头集
     */
    public List<Header> getHeaders() {
        return headers;
    }

    /**
     * 添加请求头
     *
     * @param header 请求头
     */
    public void addHeader(Header header) {
        if (null == this.headers) {
            this.headers = new ArrayList<>();
        }
        this.headers.add(header);
    }

    /**
     * 设置请求头集
     *
     * @param headers 请求头集
     */
    public void setHeaders(List<Header> headers) {
        this.headers = headers;
    }

    /**
     * 设置请求头集
     *
     * @param headers 请求头集
     */
    public void setHeaders(Map<String, String> headers) {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            addHeader(new BasicHeader(entry.getKey(), entry.getValue()));
        }
    }

    /**
     * 设置请求头
     *
     * @param header 请求头
     * @see com.egzosn.pay.common.http.HttpHeader
     */
    public void setHeaders(HttpHeader header) {
        this.headers = header.getHeaders();
    }

}


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

/******************************************************************************
 * This file is auto-generated from a template file by the GenerateTests.csx  *
 * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make    *
 * changes, please update the corresponding template and run according to the *
 * directions listed in the file.                                             *
 ******************************************************************************/

using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Intrinsics;

namespace JIT.HardwareIntrinsics.General
{
    public static partial class Program
    {
        private static void CreateElementUInt32()
        {
            var test = new VectorCreate__CreateElementUInt32();

            // Validates basic functionality works
            test.RunBasicScenario();

            // Validates calling via reflection works
            test.RunReflectionScenario();

            if (!test.Succeeded)
            {
                throw new Exception("One or more scenarios did not complete as expected.");
            }
        }
    }

    public sealed unsafe class VectorCreate__CreateElementUInt32
    {
        private static readonly int LargestVectorSize = 32;

        private static readonly int ElementCount = Unsafe.SizeOf<Vector256<UInt32>>() / sizeof(UInt32);

        public bool Succeeded { get; set; } = true;

        public void RunBasicScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario));

            UInt32[] values = new UInt32[ElementCount];

            for (int i = 0; i < ElementCount; i++)
            {
                values[i] = TestLibrary.Generator.GetUInt32();
            }

            Vector256<UInt32> result = Vector256.Create(values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7]);

            ValidateResult(result, values);
        }

        public void RunReflectionScenario()
        {
            TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario));

            Type[] operandTypes = new Type[ElementCount];
            UInt32[] values = new UInt32[ElementCount];

            for (int i = 0; i < ElementCount; i++)
            {
                operandTypes[i] = typeof(UInt32);
                values[i] = TestLibrary.Generator.GetUInt32();
            }

            object result = typeof(Vector256)
                                .GetMethod(nameof(Vector256.Create), operandTypes)
                                .Invoke(null, new object[] { values[0], values[1], values[2], values[3], values[4], values[5], values[6], values[7] });

            ValidateResult((Vector256<UInt32>)(result), values);
        }

        private void ValidateResult(Vector256<UInt32> result, UInt32[] expectedValues, [CallerMemberName] string method = "")
        {
            UInt32[] resultElements = new UInt32[ElementCount];
            Unsafe.WriteUnaligned(ref Unsafe.As<UInt32, byte>(ref resultElements[0]), result);
            ValidateResult(resultElements, expectedValues, method);
        }

        private void ValidateResult(UInt32[] resultElements, UInt32[] expectedValues, [CallerMemberName] string method = "")
        {
            bool succeeded = true;

            for (var i = 0; i < ElementCount; i++)
            {
                if (resultElements[i] != expectedValues[i])
                {
                    succeeded = false;
                    break;
                }
            }

            if (!succeeded)
            {
                TestLibrary.TestFramework.LogInformation($"Vector256.Create(UInt32): {method} failed:");
                TestLibrary.TestFramework.LogInformation($"   value: ({string.Join(", ", expectedValues)})");
                TestLibrary.TestFramework.LogInformation($"  result: ({string.Join(", ", resultElements)})");
                TestLibrary.TestFramework.LogInformation(string.Empty);

                Succeeded = false;
            }
        }
    }
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCommentsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('author_id')->unsigned()->index();
            $table->string('commentable_type');
            $table->integer('commentable_id')->unsigned();
            $table->integer('parent_id')->unsigned()->nullable();
            $table->string('title')->nullable();
            $table->text('content');
            $table->timestamps();
            $table->softDeletes();

            $table->foreign('author_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('parent_id')->references('id')->on('comments');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('comments');
    }
}


text:
'use strict';

/**
 * @ngdoc directive
 * @name dreFrontendApp.directive:inputEquals
 * @description
 * # inputEquals
 */
angular.module('dreFrontendApp')
    .directive('inputEqualsValidator', function () {
        return {
            restrict: 'A', // only activate on element attribute
            require: '?ngModel', // get a hold of NgModelController
            link: function (scope, elem, attrs, ngModel) {
                if (ngModel) { // do nothing if no ng-model

                    // watch own value and re-validate on change
                    scope.$watch(attrs.ngModel, function () {
                        validate();
                    });

                    // observe the other value and re-validate on change
                    attrs.$observe('inputEqualsValidator', function () {
                        validate();
                    });

                    var validate = function () {
                        // values
                        var val1 = ngModel.$viewValue;
                        var val2 = attrs.inputEqualsValidator;

                        // set validity
                        ngModel.$setValidity('equals', val1 === val2);
                    };
                }
            }
        };
    });


text:
<book>
  <chapter>
    <section>
      <subsection>
	<note>A note here</note>
	<note>And here</note>
      </subsection>
      <subsection>
      </subsection>
    </section>
  </chapter>
  <chapter>
    <note>And another note here</note>
  </chapter>
</book>


text:
module TfIdfSimilarity
  class BM25Model < Model
    # Return the term's inverse document frequency.
    #
    # @param [String] term a term
    # @return [Float] the term's inverse document frequency
    def inverse_document_frequency(term)
      df = @model.document_count(term)
      log((documents.size - df + 0.5) / (df + 0.5))
    end
    alias_method :idf, :inverse_document_frequency

    # Returns the term's frequency in the document.
    #
    # @param [Document] document a document
    # @param [String] term a term
    # @return [Float] the term's frequency in the document
    #
    # @note Like Lucene, we use a b value of 0.75 and a k1 value of 1.2.
    def term_frequency(document, term)
      if @model.average_document_size.zero?
        Float::NAN
      else
        tf = document.term_count(term)
        (tf * 2.2) / (tf + 0.3 + 0.9 * document.size / @model.average_document_size)
      end
    end
    alias_method :tf, :term_frequency
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.NRefactory.CSharp.Resolver;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;

namespace SharpKit.Compiler
{
    class NotifyNavigator : IResolveVisitorNavigator
    {
        #region IResolveVisitorNavigator Members

        ResolveVisitorNavigationMode IResolveVisitorNavigator.Scan(AstNode node)
        {
            return ResolveVisitorNavigationMode.Resolve;
        }

        public Action<AstNode, ResolveResult> Resolved { get; set; }
        void IResolveVisitorNavigator.Resolved(AstNode node, ResolveResult result)
        {
            if (Resolved != null)
                Resolved(node, result);
        }

        public Action<Expression, ResolveResult, Conversion, IType> ProcessConversion { get; set; }
        void IResolveVisitorNavigator.ProcessConversion(Expression expression, ResolveResult result, Conversion conversion, IType targetType)
        {
            if (ProcessConversion != null)
                ProcessConversion(expression, result, conversion, targetType);
        }

        #endregion
    }
}


text:
> BUILD REAL-TIME IOT SOLUTIONS WITH EASE. Now you can connect the unconnected. With the Structure IoT developer platform your devices and data come together to create the Internet of Things solution you need.

- [Structure IoT Development Platform Homepage](https://www.getstructure.io/)
- [Structure IoT Development Platform Kit](https://www.getstructure.io/kit)

## PlatformIO Library

```sh
[ 253 ] Structure        arduino, atmelavr, atmelsam, timsp430, titiva, teensy, freescalekinetis, ststm32, nordicnrf51, nxplpc, espressif, siliconlabsefm32, linux_arm, native "Structure": Arduino SDK for connecting embedded devices to the Structure IoT developer platform
...
xe1gyq@jessie:~/nodemcu$ platformio lib install 253
Installing library [ 253 ]:
Downloading  [####################################]  100%
Unpacking  [####################################]  100%
The library #253 'Structure' has been successfully installed!
xe1gyq@jessie:~/nodemcu$
```

## Welcome

- [Welcome](https://app.getstructure.io/#/welcome)

> CREATE APPLICATION. Devices are registered, and workflows are created, all within the context of an application. First, let's name your new application.

- Applications
  - Create Application
  - Name: MyNodeMCU
  - + New Application

> DEVICES, DEVICES, DEVICES! This is your application's device list. From here you can view and filter all of your various things. Add a device now and start building!


text:
package com.stripe.model;

public class Summary extends StripeObject {
	Integer chargeFees;
	Integer net;
	Integer refundGross;
	Integer adjustmentGross;
	Integer refundFees;
	Integer validationCount;
	Integer validationFees;
	Integer refundCount;
	Integer adjustmentCount;
	Integer chargeCount;
	Integer chargeGross;

	public Integer getChargeFees() {
		return chargeFees;
	}

	public void setChargeFees(Integer chargeFees) {
		this.chargeFees = chargeFees;
	}

	public Integer getNet() {
		return net;
	}

	public void set(Integer net) {
		this.net = net;
	}

	public Integer getRefundGross() {
		return refundGross;
	}

	public void setRefundGross(Integer refundGross) {
		this.refundGross = refundGross;
	}

	public Integer getAdjustmentGross() {
		return adjustmentGross;
	}

	public void setAdjustmentGross(Integer adjustmentGross) {
		this.adjustmentGross = adjustmentGross;
	}

	public Integer getRefundFees() {
		return refundFees;
	}

	public void setRefundFees(Integer refundFees) {
		this.refundFees = refundFees;
	}

	public Integer getValidationCount() {
		return validationCount;
	}

	public void setValidationCount(Integer validationCount) {
		this.validationCount = validationCount;
	}

	public Integer getValidationFees() {
		return validationFees;
	}

	public void setValidationFees(Integer validationFees) {
		this.validationFees = validationFees;
	}

	public Integer getRefundCount() {
		return refundCount;
	}

	public void setRefundCount(Integer refundCount) {
		this.refundCount = refundCount;
	}

	public Integer getAdjustmentCount() {
		return adjustmentCount;
	}

	public void setAdjustmentCount(Integer adjustmentCount) {
		this.adjustmentCount = adjustmentCount;
	}

	public Integer getChargeCount() {
		return chargeCount;
	}

	public void setChargeCount(Integer chargeCount) {
		this.chargeCount = chargeCount;
	}

	public Integer getChargeGross() {
		return chargeGross;
	}

	public void setChargeGross(Integer chargeGross) {
		this.chargeGross = chargeGross;
	}
}


text:
package oneapi.model;

import java.util.Arrays;

import oneapi.model.common.ResourceReference;

public class SendMessageResult {

	private String clientCorrelator;
	private SendMessageResultItem[] sendMessageResults;
	private ResourceReference resourceReference;

	public SendMessageResult() {
		super();
	}

	public String getClientCorrelator() {
		return clientCorrelator;
	}

	public void setClientCorrelator(String clientCorrelator) {
		this.clientCorrelator = clientCorrelator;
	}

	public SendMessageResultItem[] getSendMessageResults() {
		return sendMessageResults;
	}

	public void setSendMessageResults(SendMessageResultItem[] sendMessageResults) {
		this.sendMessageResults = sendMessageResults;
	}

	public ResourceReference getResourceReference() {
		return resourceReference;
	}

	public void setResourceReference(ResourceReference resourceReference) {
		this.resourceReference = resourceReference;
	}

	@Override
	public String toString() {
		return "SendMessageResult {clientCorrelator=" + clientCorrelator
				+ ", sendMessageResults=" + Arrays.toString(sendMessageResults)
				+ ", resourceReference=" + resourceReference + "}";
	}
}


text:
package recommender

import org.apache.spark.mllib.clustering.KMeans
import org.apache.spark.rdd.RDD

/**
 * Created by Ondra Fiedler on 30.7.14.
 */

/**
 * Basis for algorithms that speed up k-NN algorithm by clustering
 * @param vectorsRDD Vectors representing a set of users. Ratings of users are taken from the Recommender's dataHolder if this field is not specified.
 * @param numberOfClusters Number of clusters
 * @param numberOfNeighbors Number of considered neighbors by the k-NN algorithm
 * @param distanceMetric Metric which determines similarity between users in k-NN
 */
abstract class ClusteredKnnRecommender(vectorsRDD: RDD[UserVector], numberOfClusters: Int, numberOfNeighbors: Int, distanceMetric: DistanceMetric = CosineDistance) extends RecommenderWithUserVectorRepresentation(vectorsRDD) with Serializable {

  def this(numberOfClusters: Int, numberOfNeighbors: Int, distanceMetric: DistanceMetric = CosineDistance) = this(UserSparseVector.convertRatingsFromHolderToUserSparseVectors(MainHolder.getDataHolder()), numberOfClusters, numberOfNeighbors, distanceMetric)

  //Get centroids and clusters
  val (centroids, arrayOfClustersRDDs) = clustering()

  //One k-nn recommender per cluster
  val KnnRecommenders = arrayOfClustersRDDs.map(v => new KnnRecommender(v, numberOfNeighbors, distanceMetric))

  //"Recommender" for choosing nearest centroids
  val centroidsRDD = spark.sparkEnvironment.sc.parallelize(centroids).persist()
  val nearestCentroidsRecommender = new KnnRecommender(centroidsRDD, numberOfClusters, distanceMetric)

  /**
   * Groups vectors into clusters
   * @return Sequence of RDDs. Each RDD contains UserVectors corresponding to one cluster
   **/
  protected def clustering(): (Array[UserVector], Seq[RDD[UserVector]])

  override def recommend(userVector: UserVector, numberOfRecommendedProducts: Int) = {

    val nearestCentroids = nearestCentroidsRecommender.getNearestNeighbors(userVector)
    val nearestCentroidsIDs = nearestCentroids.map(v => v.getUserID())

    //TODO iterate more nearest clusters
    val nearestRecommender = KnnRecommenders(nearestCentroidsIDs(0))
    nearestRecommender.recommend(userVector, numberOfRecommendedProducts)
  }
}

/**
 * ClusteredKnnRecommender using k-Means algorithm from MLlib for clustering
 * @param vectorsRDD Vectors representing a set of users. Ratings of users are taken from the Recommender's dataHolder if this field is not specified.
 * @param numberOfClusters Number of clusters
 * @param numberOfKMeansIterations Number of k-Means algorithm
 * @param numberOfNeighbors Number of considered neighbors by the k-nn algorithm
 * @param distanceMetric Metric which determines similarity between users in k-NN
 */
class KMeansClusteredKnnRecommender(vectorsRDD: RDD[UserVector], numberOfClusters: Int, numberOfKMeansIterations: Int, numberOfNeighbors: Int, distanceMetric: DistanceMetric = CosineDistance) extends ClusteredKnnRecommender(vectorsRDD, numberOfClusters, numberOfNeighbors, distanceMetric) with Serializable {

  def this(numberOfClusters: Int, numberOfKMeansIterations: Int, numberOfNeighbors: Int, distanceMetric: DistanceMetric = CosineDistance) = this(UserSparseVector.convertRatingsFromHolderToUserSparseVectors(MainHolder.getDataHolder()), numberOfClusters, numberOfKMeansIterations, numberOfNeighbors, distanceMetric)

  override def clustering(): (Array[UserVector], Seq[RDD[UserVector]]) = {
    KMeansClustering.clustering(vectorsRDD, numberOfClusters, numberOfKMeansIterations)
  }
}

/**
 * Clustering by MLlib's k-Means
 */
object KMeansClustering {
  def clustering(vectorsRDD: RDD[UserVector], numberOfClusters: Int, numberOfKMeansIterations: Int): (Array[UserVector], Seq[RDD[UserVector]]) = {
    val mllibVectorsRDD = vectorsRDD.map(v => v.toMLlibVector())

    val kmeans = new KMeans().setK(numberOfClusters).setMaxIterations(numberOfKMeansIterations)
    val model = kmeans.run(mllibVectorsRDD)

    val predictedClusters = model.predict(mllibVectorsRDD)
    val vectorsWithClusterNumbersRDD = predictedClusters.zip(vectorsRDD)

    val centroidsMLlibVectors = model.clusterCenters
    val centroidsUserVector: Array[UserVector] = centroidsMLlibVectors.zipWithIndex.map { case (v, i) => new UserDenseVector(i, v.toArray)}

    val arrayOfClustersRDDsBeforeRepartition = (0 until numberOfClusters).map(i => vectorsWithClusterNumbersRDD.filter { case (j, cluster) => (i == j)}.map { case (j, vec) => vec})

    val numberOfVectorsInOriginalRDD = vectorsRDD.count()
    val numberOfOriginalPartitions = vectorsRDD.partitions.length

    val seqOfClustersRDDs = arrayOfClustersRDDsBeforeRepartition.map(rdd => {
      val ratioBetweenVectorsInThisClustersAndAllClusters = rdd.count().toDouble / numberOfVectorsInOriginalRDD
      val numberOfPartitions = (numberOfOriginalPartitions * ratioBetweenVectorsInThisClustersAndAllClusters).ceil.toInt
      rdd.repartition(numberOfPartitions).persist()
    })

    (centroidsUserVector, seqOfClustersRDDs)
  }
}


text:
(function() {
if (!window.GLOBALS) { window.GLOBALS = {}; };

var swipeThrottlingTime = 1;
var stopPoints = [2.70, 5.37, 13.23, 14.73, 19.33, 22.00, 28.70, 35.83, 38.20];

window.GLOBALS.stopPoints = stopPoints;
window.GLOBALS.swipeThrottlingTime = swipeThrottlingTime;
if (window.GLOBALS.scrubber) { window.GLOBALS.scrubber.stopPoints = stopPoints; };
})();


text:
'use strict';

angular.module('pollioApp')
    .factory('poll', function(pollQuestion, pollRecipient, uniqueid) {

        function Poll() {

            this._id = this._id || uniqueid.create();
            this.slug = this._id;

            if (this.questions) {
            	this.questions = this.questions.map(pollQuestion.create);
            } else {
            	this.questions = [];
            }

            if (this.recipients) {
            	this.recipients = this.recipients.map(pollRecipient.create);
            } else {
            	this.recipients = [];
            }

            this.addQuestion = function() {
                this.questions.push(pollQuestion.create());
            };

            this.removeQuestion = function($index) {
                this.questions.splice($index, 1);
            };
            this.addRecipient = function() {
                this.recipients.push(pollRecipient.create());
            };

            this.removeRecipient = function($index) {
                this.recipients.splice($index, 1);
            };

            this.addWeblink = function() {

                var recipient = pollRecipient.create();
                recipient.type = 'Public Link';
                recipient.value = ['http://polli.com', this.slug].join('/');

                this.recipients.push(recipient);

            };
        }

        return {
            create: function(source) {
                if (source) {
                    Poll.call(source);
                    return source;
                }
                return new Poll();
            }
        };

    });


text:
@protocol PZPhotoViewDelegate;

@interface PZPhotoView : UIScrollView

@property (assign, nonatomic) IBOutlet id<PZPhotoViewDelegate> photoViewDelegate;

- (void)prepareForReuse;
- (void)displayImage:(UIImage *)image;

- (void)startWaiting;
- (void)stopWaiting;

- (void)updateZoomScale:(CGFloat)newScale;
- (void)updateZoomScale:(CGFloat)newScale withCenter:(CGPoint)center;

@end

@protocol PZPhotoViewDelegate <NSObject>

@optional

- (void)photoViewDidSingleTap:(PZPhotoView *)photoView;
- (void)photoViewDidDoubleTap:(PZPhotoView *)photoView;
- (void)photoViewDidTwoFingerTap:(PZPhotoView *)photoView;
- (void)photoViewDidDoubleTwoFingerTap:(PZPhotoView *)photoView;

@end


text:
<?php

/**
 * LoggerAppenderMailEvent appends individual log events via email.
 *
 * This appender is similar to LoggerAppenderMail, except that it sends each
 * each log event in an individual email message at the time when it occurs.
 *
 * This appender uses a layout.
 *
 * ## Configurable parameters: ##
 *
 * - **to** - Email address(es) to which the log will be sent. Multiple email
 *     addresses may be specified by separating them with a comma.
 * - **from** - Email address which will be used in the From field.
 * - **subject** - Subject of the email message.
 * - **smtpHost** - Used to override the SMTP server. Only works on Windows.
 * - **port** - Used to override the default SMTP server port. Only works on
 *     Windows.
 *
 * @version $Revision$
 * @package log4php
 * @subpackage appenders
 * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link http://logging.apache.org/log4php/docs/appenders/mail-event.html Appender documentation
 */
class LoggerAppenderMailEvent extends LoggerAppender {

	/**
	 * Email address to put in From field of the email.
	 * @var string
	 */
	protected $from;

	/**
	 * Mail server port (widnows only).
	 * @var integer
	 */
	protected $port = 25;

	/**
	 * Mail server hostname (windows only).
	 * @var string
	 */
	protected $smtpHost;

	/**
	 * The subject of the email.
	 * @var string
	 */
	protected $subject = 'Log4php Report';

	/**
	 * One or more comma separated email addresses to which to send the email.
	 * @var string
	 */
	protected $to = null;

	/**
	 * Indiciates whether this appender should run in dry mode.
	 * @deprecated
	 * @var boolean
	 */
	protected $dry = false;

	public function activateOptions() {
		if (empty($this->to)) {
			$this->warn("Required parameter 'to' not set. Closing appender.");
			$this->close = true;
			return;
		}

		$sendmail_from = ini_get('sendmail_from');
		if (empty($this->from) and empty($sendmail_from)) {
			$this->warn("Required parameter 'from' not set. Closing appender.");
			$this->close = true;
			return;
		}

		$this->closed = false;
	}

	public function append(LoggerLoggingEvent $event) {
		$smtpHost = $this->smtpHost;
		$prevSmtpHost = ini_get('SMTP');
		if(!empty($smtpHost)) {
			ini_set('SMTP', $smtpHost);
		}

		$smtpPort = $this->port;
		$prevSmtpPort= ini_get('smtp_port');
		if($smtpPort > 0 and $smtpPort < 65535) {
			ini_set('smtp_port', $smtpPort);
		}

		// On unix only sendmail_path, which is PHP_INI_SYSTEM i.e. not changeable here, is used.

		$addHeader = empty($this->from) ? '' : "From: {$this->from}\r\n";

		if(!$this->dry) {
			$result = mail($this->to, $this->subject, $this->layout->getHeader() . $this->layout->format($event) . $this->layout->getFooter($event), $addHeader);
		} else {
			echo "DRY MODE OF MAIL APP.: Send mail to: ".$this->to." with additional headers '".trim($addHeader)."' and content: ".$this->layout->format($event);
		}

		ini_set('SMTP', $prevSmtpHost);
		ini_set('smtp_port', $prevSmtpPort);
	}

	/** Sets the 'from' parameter. */
	public function setFrom($from) {
		$this->setString('from', $from);
	}

	/** Returns the 'from' parameter. */
	public function getFrom() {
		return $this->from;
	}

	/** Sets the 'port' parameter. */
	public function setPort($port) {
		$this->setPositiveInteger('port', $port);
	}

	/** Returns the 'port' parameter. */
	public function getPort() {
		return $this->port;
	}

	/** Sets the 'smtpHost' parameter. */
	public function setSmtpHost($smtpHost) {
		$this->setString('smtpHost', $smtpHost);
	}

	/** Returns the 'smtpHost' parameter. */
	public function getSmtpHost() {
		return $this->smtpHost;
	}

	/** Sets the 'subject' parameter. */
	public function setSubject($subject) {
		$this->setString('subject',  $subject);
	}

	/** Returns the 'subject' parameter. */
	public function getSubject() {
		return $this->subject;
	}

	/** Sets the 'to' parameter. */
	public function setTo($to) {
		$this->setString('to',  $to);
	}

	/** Returns the 'to' parameter. */
	public function getTo() {
		return $this->to;
	}

	/** Enables or disables dry mode. */
	public function setDry($dry) {
		$this->setBoolean('dry', $dry);
	}
}


text:
package unnamed.utils.io;

import net.minecraft.nbt.NBTTagCompound;

public interface INbtReader<T> {
    T readFromNBT(NBTTagCompound tag, String name);
}


text:
<?php echo Form::open(array("class"=>"form-horizontal")); ?>

	<fieldset>

			<?php echo Form::label('Name', 'name', array('class'=>'control-label')); ?>

				<?php echo Form::input('name', Input::post('name', isset($plant) ? $plant->name : ''), array('class' => 'col-md-4 form-control', 'placeholder'=>'Name')); ?>

			<?php echo Form::label('Scientific name', 'scientific_name', array('class'=>'control-label')); ?>

				<?php echo Form::textarea('scientific_name', Input::post('scientific_name', isset($plant) ? $plant->scientific_name : ''), array('class' => 'col-md-8 form-control', 'rows' => 8, 'placeholder'=>'Scientific name')); ?>

			<?php echo Form::label('Common names', 'common_names', array('class'=>'control-label')); ?>

				<?php echo Form::textarea('common_names', Input::post('common_names', isset($plant) ? $plant->common_names : ''), array('class' => 'col-md-8 form-control', 'rows' => 8, 'placeholder'=>'Common names')); ?>

			<?php echo Form::label('Vernacular names', 'vernacular_names', array('class'=>'control-label')); ?>

				<?php echo Form::textarea('vernacular_names', Input::post('vernacular_names', isset($plant) ? $plant->vernacular_names : ''), array('class' => 'col-md-8 form-control', 'rows' => 8, 'placeholder'=>'Vernacular names')); ?>

			<?php echo Form::label('Properties', 'properties', array('class'=>'control-label')); ?>

				<?php echo Form::textarea('properties', Input::post('properties', isset($plant) ? $plant->properties : ''), array('class' => 'col-md-8 form-control', 'rows' => 8, 'placeholder'=>'Properties')); ?>

			<?php echo Form::label('Usage', 'usage', array('class'=>'control-label')); ?>

				<?php echo Form::textarea('usage', Input::post('usage', isset($plant) ? $plant->usage : ''), array('class' => 'col-md-8 form-control', 'rows' => 8, 'placeholder'=>'Usage')); ?>

			<?php echo Form::submit('submit', 'Save', array('class' => 'btn btn-primary')); ?>

	</fieldset>
<?php echo Form::close(); ?>


text:
using System.Threading.Tasks;

namespace Vulcan.Core.DataAccess.Migrations.MigrationProviders
{
    public interface IMigrationProvider
    {
        Task Process(DataDefinitionContext ddc);
    }
}


text:
<!DOCTYPE html>

        <title>My Resources Javascript</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="libs/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>

My resources Javascript

Custom modal dialogs

Draw canvas

Scroll to text

Resize the image on the canvas