text:
#include "tensorflow/core/distributed_runtime/preemption/preemption_sync_manager.h"

#include <memory>
#include <string>
#include <utility>

#include "grpcpp/server.h"
#include "grpcpp/server_builder.h"
#include "grpcpp/support/channel_arguments.h"
#include "absl/memory/memory.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "tensorflow/core/distributed_runtime/coordination/coordination_client.h"
#include "tensorflow/core/distributed_runtime/coordination/coordination_service.h"
#include "tensorflow/core/distributed_runtime/coordination/coordination_service_agent.h"
#include "tensorflow/core/distributed_runtime/preemption/preemption_notifier.h"
#include "tensorflow/core/distributed_runtime/rpc/async_service_interface.h"
#include "tensorflow/core/distributed_runtime/rpc/coordination/grpc_coordination_client.h"
#include "tensorflow/core/distributed_runtime/rpc/coordination/grpc_coordination_service_impl.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/status.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/threadpool.h"
#include "tensorflow/core/protobuf/cluster.pb.h"
#include "tensorflow/core/protobuf/config.pb.h"
#include "tensorflow/core/protobuf/coordination_config.pb.h"
#include "tensorflow/core/protobuf/tensorflow_server.pb.h"

namespace tensorflow {
namespace {

constexpr char kJobName[] = "test_worker";

// Send fake preemption notices at any time for testing.
class FakePreemptionNotifier : public PreemptionNotifier {
 public:
  void AnnounceDeath(absl::Time death_time) {
    mutex_lock l(mu_);
    death_time_ = death_time;
    LOG(WARNING) << "Received preemption notice with death time: "
                 << death_time_;
    NotifyRegisteredListeners();
  }

  void Reset() override {}
};

class PreemptionSyncManagerTest : public ::testing::Test {
 protected:
  PreemptionSyncManagerTest() {
    // Setup coordination service.
    StartCoordinationService();
    InitializeAndConnectCoordinationAgents();

    // Create preempt sync manager for task 1.
    auto preempt_notifier = std::make_unique<FakePreemptionNotifier>();
    preempt_notifier_ = preempt_notifier.get();
    TF_CHECK_OK(preempt_sync_mgr_->Initialize(
        Env::Default(), coord_agent_.get(), std::move(preempt_notifier)));

    // Create preempt sync manager for task 2.
    auto preempt_notifier2 = std::make_unique<FakePreemptionNotifier>();
    preempt_notifier2_ = preempt_notifier2.get();
    TF_CHECK_OK(preempt_sync_mgr2_->Initialize(
        Env::Default(), coord_agent2_.get(), std::move(preempt_notifier2)));
  }

  // `to_task1` toggles which of the two tasks receives preemption notice.
  void SendPreemptionNotice(absl::Time death_time = absl::Now(),
                            bool to_task1 = true) {
    if (to_task1) {
      preempt_notifier_->AnnounceDeath(death_time);
    } else {
      preempt_notifier2_->AnnounceDeath(death_time);
    }
    // Block main thread for a short while to allow preemption sync manager to
    // process the notice.
    Env::Default()->SleepForMicroseconds(
        absl::ToInt64Microseconds(absl::Milliseconds(1)));
  }

  // Report to coordiation service that task two is unhealthy.
  void SimulateUnhealthyTaskTwo() {
    CoordinatedTask task2;
    task2.set_job_name(kJobName);
    task2.set_task_id(2);
    TF_CHECK_OK(
        coord_service_->ReportTaskError(task2, errors::Internal("test_error")));
  }

  // Allow access to objects under test.
  std::unique_ptr<PreemptionSyncManager> preempt_sync_mgr_ =
      CreatePreemptionSyncManager();
  std::unique_ptr<PreemptionSyncManager> preempt_sync_mgr2_ =
      CreatePreemptionSyncManager();

 private:
  // Utility methods to set up coordination service and agents.
  void StartCoordinationService() {
    ::grpc::ServerBuilder builder;
    coord_service_ = EnableCoordinationService();
    coord_compute_pool_ = std::make_unique<thread::ThreadPool>(
        Env::Default(), "CoordinationServiceRpcHandler",
        /*num_threads=*/1);
    coord_rpc_service_ = std::make_unique<GrpcCoordinationServiceImpl>(
        coord_compute_pool_.get(), &builder);
    grpc_server_ = builder.BuildAndStart();
    coord_rpc_thread_ = absl::WrapUnique(Env::Default()->StartThread(
        /*thread_options=*/{}, /*name=*/"CoordinationServiceHandleRPCsLoop",
        [service = coord_rpc_service_.get()]() { service->HandleRPCsLoop(); }));
  }
  std::unique_ptr<CoordinationServiceInterface> EnableCoordinationService() {
    ServerDef server_def;
    server_def.set_protocol("grpc");
    server_def.set_job_name(kJobName);
    server_def.set_task_index(0);
    auto job_def = server_def.mutable_cluster()->add_job();
    job_def->set_name(kJobName);
    job_def->mutable_tasks()->insert({1, "TEST_ADDRESS_1"});
    job_def->mutable_tasks()->insert({2, "TEST_ADDRESS_2"});
    auto coordination_config = server_def.mutable_default_session_config()
                                   ->mutable_experimental()
                                   ->mutable_coordination_config();
    coordination_config->set_service_type("standalone");
    return CoordinationServiceInterface::EnableCoordinationService(
        "standalone", Env::Default(), server_def, /*cache=*/nullptr);
  }
  void InitializeAndConnectCoordinationAgents() {
    std::unique_ptr<CoordinationClient> coord_client =
        absl::WrapUnique(NewGrpcCoordinationClient(
            grpc_server_->InProcessChannel(::grpc::ChannelArguments())));
    std::unique_ptr<CoordinationClient> coord_client2 =
        absl::WrapUnique(NewGrpcCoordinationClient(
            grpc_server_->InProcessChannel(::grpc::ChannelArguments())));
    auto error_fn = [](const Status& status) {
      LOG(ERROR) << "Coordination service agent in error status: " << status;
    };
    TF_CHECK_OK(
        coord_agent_->Initialize(Env::Default(), kJobName, /*task_id=*/1,
                                 CoordinationServiceConfig::default_instance(),
                                 std::move(coord_client), error_fn));
    TF_CHECK_OK(
        coord_agent2_->Initialize(Env::Default(), kJobName, /*task_id=*/2,
                                  CoordinationServiceConfig::default_instance(),
                                  std::move(coord_client2), error_fn));
    TF_CHECK_OK(coord_agent_->Connect());
    TF_CHECK_OK(coord_agent2_->Connect());
  }

  // Coordination service.
  std::unique_ptr<::grpc::Server> grpc_server_;
  std::unique_ptr<CoordinationServiceInterface> coord_service_;
  std::unique_ptr<thread::ThreadPool> coord_compute_pool_;
  std::unique_ptr<AsyncServiceInterface> coord_rpc_service_;
  std::unique_ptr<Thread> coord_rpc_thread_;
  // Owned by task 1.
  std::unique_ptr<CoordinationServiceAgent> coord_agent_ =
      CreateCoordinationServiceAgent();
  FakePreemptionNotifier* preempt_notifier_;
  // Owned by task 2.
  std::unique_ptr<CoordinationServiceAgent> coord_agent2_ =
      CreateCoordinationServiceAgent();
  FakePreemptionNotifier* preempt_notifier2_;
};

/* Single task tests */
// TODO(b/230630494): Enable tests once the library is implemented.
TEST_F(PreemptionSyncManagerTest, DISABLED_NoPreemption_NoSyncPoint) {
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
}

// TODO(b/230630494): Enable tests once the library is implemented.
TEST_F(PreemptionSyncManagerTest, DISABLED_Preemption_SingleSyncPoint) {
  // Simulate task doing work and making progress.
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
  SendPreemptionNotice();

  // Since this is the only task, sync point must be reached.
  EXPECT_TRUE(preempt_sync_mgr_->ReachedSyncPoint());

  // Now, we moved past the sync point.
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
}

// TODO(b/230630494): Enable tests once the library is implemented.
TEST_F(PreemptionSyncManagerTest, DISABLED_DelayedPreemption_NoSyncPointYet) {
  // Simulate task doing work and making progress.
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
  // Send notice about scheduled preemption in an hour.
  SendPreemptionNotice(absl::Now() + absl::Hours(1));

  // Protocol didn't trigger yet, so there should be no sync point.
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
}
// TODO(b/230630494): Enable tests once the library is implemented.
TEST_F(PreemptionSyncManagerTest, DISABLED_UnhealthyTask_NoSyncPoint) {
  // Simulate task doing work and making progress.
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
  SimulateUnhealthyTaskTwo();
  SendPreemptionNotice();

  // No sync point is created since one of the tasks is unhealthy.
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
}

/* Two task tests */
// TODO(b/230630494): Enable tests once the library is implemented.
TEST_F(PreemptionSyncManagerTest, DISABLED_PreemptSlowTask) {
  // Simulate slow task 1 that is only at call #1.
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
  // Simulate fast task 3 that is already at call #3.
  EXPECT_FALSE(preempt_sync_mgr2_->ReachedSyncPoint());
  EXPECT_FALSE(preempt_sync_mgr2_->ReachedSyncPoint());
  EXPECT_FALSE(preempt_sync_mgr2_->ReachedSyncPoint());
  SendPreemptionNotice();

  // Sync point should be set at call #4.
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
  EXPECT_TRUE(preempt_sync_mgr_->ReachedSyncPoint());

  // Task 2 was already at call #3, so the next call should be the sync point.
  EXPECT_TRUE(preempt_sync_mgr2_->ReachedSyncPoint());
}

// Same as PreemptSlowTask, but we send the preemption notice to the faster
// task 2.
// TODO(b/230630494): Enable tests once the library is implemented.
TEST_F(PreemptionSyncManagerTest, DISABLED_PreemptFastTask) {
  // Simulate slow task 1 that is only at call #1.
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
  // Simulate fast task 3 that is already at call #3.
  EXPECT_FALSE(preempt_sync_mgr2_->ReachedSyncPoint());
  EXPECT_FALSE(preempt_sync_mgr2_->ReachedSyncPoint());
  EXPECT_FALSE(preempt_sync_mgr2_->ReachedSyncPoint());
  SendPreemptionNotice(absl::Now(), /*=to_task1=*/false);

  // Sync point should be set at call #4.
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
  EXPECT_FALSE(preempt_sync_mgr_->ReachedSyncPoint());
  EXPECT_TRUE(preempt_sync_mgr_->ReachedSyncPoint());

  // Task 2 was already at call #3, so the next call should be the sync point.
  EXPECT_TRUE(preempt_sync_mgr2_->ReachedSyncPoint());
}

}  // namespace
}  // namespace tensorflow


text:
package org.ovirt.engine.core.uutils.crypto.ticket;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.security.cert.TrustAnchor;
import java.security.cert.X509Certificate;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TimeZone;

import org.apache.commons.codec.binary.Base64;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.type.TypeFactory;
import org.ovirt.engine.core.uutils.crypto.CertificateChain;

public class TicketDecoder {

    private static final String DATE_FORMAT = "yyyyMMddHHmmss";

    private final Set<TrustAnchor> trustAnchors;
    private final String eku;
    private final Certificate peer;
    private final int tollerance;

    public TicketDecoder(KeyStore trustStore, String eku, Certificate peer, int tollerance) throws KeyStoreException {
        if (trustStore == null) {
            trustAnchors = null;
        } else {
            trustAnchors = CertificateChain.keyStoreToTrustAnchors(trustStore);
        }
        this.eku = eku;
        this.peer = peer;
        this.tollerance = tollerance;
    }

    public TicketDecoder(KeyStore trustStore, String eku, Certificate peer) throws KeyStoreException {
        this(trustStore, eku, peer, 0);
    }

    public TicketDecoder(KeyStore trustStore, String eku, int tollerance) throws KeyStoreException {
        this(trustStore, eku, null, tollerance);
    }

    public TicketDecoder(Certificate peer, int tollerance) throws KeyStoreException {
        this(null, null, peer, tollerance);
    }

    public TicketDecoder(KeyStore trustStore, String eku) throws KeyStoreException {
        this(trustStore, eku, null);
    }

    public TicketDecoder(Certificate peer) throws KeyStoreException {
        this(null, null, peer);
    }

    public String decode(String ticket)
    throws GeneralSecurityException, IOException {
        Certificate cert;

        Map<String, String> map = new ObjectMapper().readValue(
            Base64.decodeBase64(ticket),
            TypeFactory.defaultInstance().constructMapType(HashMap.class, String.class, String.class)
        );

        if (peer != null) {
            cert = peer;
        } else {
            try (InputStream is = new ByteArrayInputStream(map.get("certificate").getBytes(StandardCharsets.UTF_8))) {
                cert = CertificateFactory.getInstance("X.509").generateCertificate(is);
            }
        }

        if (trustAnchors != null) {
            CertificateChain.buildCertPath(Arrays.asList(cert), trustAnchors);
        }

        if (eku != null) {
            if (!((X509Certificate)cert).getExtendedKeyUsage().contains(eku)) {
                throw new GeneralSecurityException("Certificate is not authorized for action");
            }
        }

        List<String> signedFields = Arrays.asList(map.get("signedFields").trim().split("\\s*,\\s*"));
        if (!signedFields.containsAll(Arrays.asList("salt", "data"))) {
            throw new GeneralSecurityException("Invalid ticket");
        }

        Signature sig = Signature.getInstance(String.format("%swith%s", map.get("digest"), cert.getPublicKey().getAlgorithm()));
        sig.initVerify(cert.getPublicKey());
        for (String field : signedFields) {
            byte[] buf = map.get(field).getBytes(StandardCharsets.UTF_8);
            sig.update(buf);
        }
        if (!sig.verify(Base64.decodeBase64(map.get("signature")))) {
            throw new GeneralSecurityException("Invalid ticket signature");
        }

        try {
            DateFormat df = new SimpleDateFormat(DATE_FORMAT);
            df.setTimeZone(TimeZone.getTimeZone("UTC"));
            Date validFrom = df.parse(map.get("validFrom"));
            Date validTo = df.parse(map.get("validTo"));
            Date now = new Date();
            if (! (validFrom.getTime() - tollerance <= now.getTime() && now.getTime() <= validTo.getTime() + tollerance)) {
                throw new GeneralSecurityException("Ticket lifetime expired");
            }
        } catch (ParseException e) {
            throw new GeneralSecurityException(e);
        }

        return map.get("data");
    }

}

redpajama_set_name: RedPajamaGithub


text:
;
(function ($, window, document, undefined) {
    var pluginName = "positionEditPane";
    var defaults = {
        id: "",
        parent: "",
        entity : "",
        topparent: "",
        ownerId: "",
        tabid : "",
    };

    var PositionEditPanel = function (element, options) {
        this.element = element;
        this.options = $.extend({
            id: "",
            parent: "",
            entity : "",
            topparent: "",
            ownerId: "",
            tabid : "",
        }, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.topparent = options.topparent;
        this.init(options);
    };

    PositionEditPanel.prototype.init = function (options) {
        this.loadPane(options.entity);
    };

    PositionEditPanel.prototype.loadPane = function (entity) {
        this.entity = entity;
        var mainmodalframeDiv = document.createElement("div");
        mainmodalframeDiv.className = "col-lg-12 col-md-12 col-sm-12 col-xs-12";
        mainmodalframeDiv.style.padding = "4px";
        this.element.appendChild(mainmodalframeDiv);

        // API access security key
        var mainmodalframe1 = document.createElement("div");
        mainmodalframe1.className = "panel panel-default";
        mainmodalframeDiv.appendChild(mainmodalframe1);

        // var modalframehead1 = document.createElement("div");
        // modalframehead1.className = "panel-heading";
        // mainmodalframe1.appendChild(modalframehead1);
        // modalframehead1.innerHTML = "外部应用API访问秘钥信息";

        var panelbody1 = document.createElement("div");
        panelbody1.className = "panel-body";
        mainmodalframe1.appendChild(panelbody1);

        var form = document.createElement("form");
        form.className = "form-horizontal";
        panelbody1.appendChild(form);

        // organization category
        var categroup = document.createElement("div");
        form.appendChild(categroup);
        categroup.style.padding = "2px";
        categroup.className = "form-group";

        var categoryLabel = document.createElement("label");
        categroup.appendChild(categoryLabel);
        categoryLabel.className = "col-sm-3 control-label";
        categoryLabel.innerHTML = "所属岗位/项目角色类别";

        var categorydiv = document.createElement("div");
        categorydiv.className = "col-sm-9 col-xs-12";
        categroup.appendChild(categorydiv);

        this.posCateSelect = document.createElement("select");
        this.posCateSelect.name = "orgCateSelect" + this.options.id;
        this.posCateSelect.className = "form-control";
        categorydiv.appendChild(this.posCateSelect);
        this.addOptions(this.posCateSelect, "-- 请选择岗位/项目角色分类 --", "-1", 0);
        this.posCateSelect.addEventListener("change", this, false);

        this.loading(this.options);
    };

    PositionEditPanel.prototype.loading = function (options) {
        var that = this;
        $("#progressbar").show();
        $.getJSON(service.api(39, options.ownerId), {
            catetype: "137",
            owner: options.ownerId,
        }).complete(function (data) {
            var dat = JSON.parse(data.responseText);
            for (var i = 0; i < dat.length; i++) {
                that.addOptions(that.posCateSelect, dat[i].name, dat[i].id, i + 1);
            }
            if (that.entity.categoryId != null &&
                that.entity.categoryId != undefined) {
                that.posCateSelect.value = that.entity.categoryId;
            } else {
                that.posCateSelect.value = "-1";
            }
            $("#progressbar").hide();
        });
    };

    PositionEditPanel.prototype.addOptions = function (parent, title, value, index) {
        var option = document.createElement("option");
        option.text = title;
        option.value = value;
        parent.options.add(option, index);
    };

    PositionEditPanel.prototype.handleEvent = function (e) {
        switch (e.type) {
            case "change":
                this.doChange(e);
                break;
        }
    };

    PositionEditPanel.prototype.doChange = function (evt) {
        if (this.posCateSelect.value != "-1") {
            map[this.entity.currOwner].stack.execute(new OMPositionPropChangedCmd(
                this.entity, "categoryId", this.posCateSelect.value));
        } else {
            map[this.entity.currOwner].stack.execute(new OMPositionPropChangedCmd(
                this.entity, "categoryId", null));
        }
    };

    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, pluginName)) {
                $.data(this, pluginName, new PositionEditPanel(this,
                    options));
            } else if ($.isFunction(Plugin.prototype[options])) {
                $.data(this, pluginName)[options]();
            }
        });
    };

})(jQuery, window, document);


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:padding="@dimen/margin_16px">

    <TextView
        android:id="@+id/iPoster_color_tv"
        android:layout_width="@dimen/height_90px"
        android:layout_height="@dimen/height_90px"
        android:background="#6D401C" />

</FrameLayout>


text:
// ************************************************************************************************
// The MIT License (MIT)
//
// Copyright (c) 2015 Marek Kawa (masterkawaster)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
// ************************************************************************************************
using NUnit.Framework;

namespace ObserverPattern
{
    [TestFixture]
    public class TestOPwithEvents
    {
        [Test]
        public void test()
        {
            Observable observable = new Observable();
            Observer observer = new Observer();
            observable.eventRaised += observer.HandleEventRaised;

            observable.RaiseAnEventMethod();
            observable.RaiseAnEventMethod();

            Assert.AreEqual("EE", observer.invokeList);
        }
    }
}


text:
#pragma once
#include <functional>
#include <memory>
#include "util/name_map.h"
#include "library/tactic/tactic.h"

namespace lean {
namespace inversion {
/**
   \brief When we apply the inversion tactic/procedure on a hypothesis (h : I A j), where
   I is an inductive datatpe, the hypothesis is "broken" into cases: one for each constructor.
   Some cases may be in conflict with the type (I A j) and may be suppressed.

   Example of conflict: given the vector type
      inductive vector (A : Type) : nat → Type :=
      nil {} : vector A zero,
      cons   : Π {n : nat}, A → vector A n → vector A (succ n)
   Then, (h : vector A (succ n)) is in conflict with constructor nil.

   The user may provide possible implementations (example: in the form of equations).
   Each possible implementation is associated with a case/constructor.

   The inversion tactic/procedure distributes the implementations over cases.

   The implementations may depend on hypotheses that may be modifed by the inversion procedure.
   The method update_exprs of each implementation is invoked to update the expressions of
   a given implementation.
*/
class implementation {
public:
    virtual ~implementation() {}
    virtual name const & get_constructor_name() const = 0;
    virtual void update_exprs(std::function<expr(expr const &)> const & fn) = 0;
};

typedef std::shared_ptr<implementation> implementation_ptr;
typedef list<implementation_ptr> implementation_list;

struct result {
    list<goal>                 m_goals;
    list<list<expr>>           m_args; // arguments of the constructor/intro rule
    list<implementation_list>  m_implementation_lists;
    list<rename_map>           m_renames;
    // invariant: length(m_goals) == length(m_args);
    // invariant: length(m_goals) == length(m_implementation_lists);
    // invariant: length(m_goals) == length(m_renames);
    name_generator             m_ngen;
    substitution               m_subst;
    result(list<goal> const & gs, list<list<expr>> const & args, list<implementation_list> const & imps,
           list<rename_map> const & rs, name_generator const & ngen, substitution const & subst);
};

optional<result> apply(environment const & env, io_state const & ios, type_checker & tc,
                       goal const & g, expr const & h, implementation_list const & imps,
                       bool clear_elim);
}

tactic inversion_tactic(name const & n, list<name> const & ids = list<name>());
void initialize_inversion_tactic();
void finalize_inversion_tactic();
}


text:
  var XDeck = undefined;

  (function() {
    // The polyfill needs to take precedence or else it will reference the wrong document!
    if(document._currentScript) {
      var localDoc = document._currentScript.ownerDocument;
    } else {
      var localDoc = document.currentScript.ownerDocument;
    }
    var proto = Object.create(HTMLElement.prototype);

    proto.createdCallback = function() {
      if(this.createShadowRoot) {
        this._root = this.createShadowRoot();
      } else {
        this._root = this.webkitCreateShadowRoot();
      }

      var tplContent = localDoc.querySelector("template#deck").content;
      this._root.appendChild(tplContent.cloneNode(true));
    };

    var changeSlide = function(direction) {
        var currentSlideIndex = parseInt(document.location.hash.slice(1), 10) || 1;
        var slideShown     = document.querySelector("x-slide.active"),
            slideToBeShown = slideShown;

        var transitFunc = (direction == "next" ? function(node) { return node.nextSibling;     }
                                               : function(node) { return node.previousSibling; });

        while((slideToBeShown = transitFunc(slideToBeShown)) && slideToBeShown.tagName !== "X-SLIDE");

        if(!slideToBeShown) return;

        slideToBeShown.classList.add("active");
        slideShown.classList.remove("active");

    }

    var addKeyboardListener = function() {
      document.addEventListener("keyup", function(event) {
        var currentSlideIndex = parseInt(document.location.hash.slice(1), 10) || 1;

        if(event.keyCode == 37) {         // left
          document.location.hash = --currentSlideIndex;
          changeSlide("previous");
        } else if(event.keyCode == 39 ) { // right
          document.location.hash = ++currentSlideIndex;
          changeSlide("next");
        } else { return; }
      });
    }

    var addTouchListener = function() {
      var slides = document.querySelectorAll("x-slide");

      for(var i=0;i<slides.length;i++) {
        Hammer(slides[i]).on("swipeleft", function(event) {
          console.log("Touchy");
          var currentSlideIndex = parseInt(document.location.hash.slice(1), 10) || 1;
          document.location.hash = ++currentSlideIndex;
          changeSlide("next");
          e.stopPropagation();
        });

        Hammer(slides[i]).on("swiperight", function(event) {
          console.log("Touchy");
          var currentSlideIndex = parseInt(document.location.hash.slice(1), 10) || 1;
          document.location.hash = --currentSlideIndex;
          changeSlide("prev");
          e.stopPropagation();
        });

      }
    }

    proto.attachedCallback = function() {
      var self = this;
      var currentSlideIndex = parseInt(document.location.hash.slice(1), 10) || 1;
      document.location.hash = "#" + currentSlideIndex;

      self.querySelector("x-slide:nth-child(" + currentSlideIndex + ")").classList.add("active");

      addKeyboardListener();
      addTouchListener();
    };

    XDeck = document.registerElement("x-deck", { prototype: proto });
  })();


text:
MEDUSA_BEGIN;

class IFont :public IResource
{
public:
	IFont(const FontId& fontId);
	virtual ~IFont(void);
public:
	virtual ResourceType Type()const { return ResourceType::Font; }
	static ResourceType ClassGetResourceType() { return ResourceType::Font; }

	virtual bool IsBitmap()const = 0;

	StringRef FamilyName() const { return mFamilyName; }
	void SetFamilyName(const StringRef& val) { mFamilyName = val; }

	StringRef StyleName() const { return mStyleName; }
	void SetStyleName(const StringRef& val) { mStyleName = val; }

	void AddChar(FontChar* fontChar);
	void AddKerning(FontKerning* pair);
	const FontChar* GetChar(wchar_t c)const;
	FontChar* GetChar(wchar_t c);

	const FontChar* TryLoadChar(wchar_t c);

	const FontId& GetFontId() const { return mFontId; }
	FontId& MutableFontId() { return mFontId; }

	void SetFontId(const FontId& val) { mFontId = val; OnUpdateFontId(); }

	uint Size() const { return mFontId.Size(); }

	uintp LineHeight() const { return mLineHeight; }
	void SetLineHeight(uintp val) { mLineHeight = val; }

	uint TotalCharCount() const { return mTotalCharCount; }
	void SetTotalCharCount(uint val) { mTotalCharCount = val; }

	uint KerningPairsCount() const { return static_cast<uint>(mKernings.Count()); }

	intp Ascender() const { return mAscender; }
	void SetAscender(intp val) { mAscender = val; }

	intp Descender() const { return mDescender; }
	void SetDescender(intp val) { mDescender = val; }

	uint SpaceWidth() const { return mSpaceFontChar->HAdvance; }
	const FontChar* SpaceFontChar() const { return mSpaceFontChar; }
	void SetSpaceFontChar(const FontChar* val) { mSpaceFontChar = val; }

	const FontKerning* GetKerning(int prev, int next)const;
	FontKerning* GetKerning(int prev, int next);
	const FontKerning* TryLoadKerning(int prev, int next);

	bool HasKerning()const { return MEDUSA_FLAG_HAS(mFlags, FontFlags::HasKerning); }

	bool HasSinglePage()const;
	virtual bool IsFixed()const { return true; }

	bool IsBold() const { return MEDUSA_FLAG_HAS(mFlags, FontFlags::IsBold); }
	void SetIsBold(bool val) { MEDUSA_FLAG_ENABLE(mFlags, FontFlags::IsBold, val); }

	bool IsItalic() const { return MEDUSA_FLAG_HAS(mFlags, FontFlags::IsItalic); }
	void SetIsItalic(bool val) { MEDUSA_FLAG_ENABLE(mFlags, FontFlags::IsItalic, val); }

	bool IsPacked() const { return mIsPacked; }
	void SetIsPacked(bool val) { mIsPacked = val; }

	void SetOutlineThickness(uint val) { mFontId.SetOutlineThickness(val); }

	const Padding4I& Padding() const { return mPadding; }
	void SetPadding(const Padding4I& val) { mPadding = val; }

	Point2I Spacing() const { return mSpacing; }
	void SetSpacing(Point2I val) { mSpacing = val; }

	const Size2U& ImageSize() const { return mImageSize; }
	void SetImageSize(Size2U val) { mImageSize = val; }

	Color4F Channel() const { return mChannel; }
	void SetChannel(Color4F val) { mChannel = val; }

	FontFlags Flags() const { return mFlags; }
	void SetFlags(FontFlags val) { mFlags = val; }
	uint OriginalSize() const { return mOriginalSize; }
	void SetOriginalSize(uint val) { mOriginalSize = val; }

	const Share<TextureAtlas>& Atlas() const { return mAtlas; }
	void SetAtlas(const Share<TextureAtlas>& val);

	virtual uint Preload(const WStringRef& str) { return 0; }
protected:
	virtual const FontChar* OnLoadChar(wchar_t c) { return nullptr; }
	virtual const FontKerning* OnLoadKerning(int prev, int next) { return nullptr; }
	virtual bool OnUpdateFontId() { return true; }
protected:
	FontId mFontId;
	uint mTotalCharCount = 0;
	HeapString mFamilyName;
	HeapString mStyleName;
	FontFlags mFlags;
	uint mOriginalSize = 0;

	Padding4I mPadding;	//	The padding for each character (up, right, down, left).
	Point2I mSpacing;	//	The spacing for each character (horizontal, vertical).
	Size2U mImageSize;

	bool mIsPacked = false;	//Set to 1 if the monochrome characters have been packed into each of the texture channels. In this case alphaChnl describes what is stored in each channel.
	Color4F mChannel;	//Set to 0 if the channel holds the glyph data, 1 if it holds the outline, 2 if it holds the glyph and the outline, 3 if its set to zero, and 4 if its set to one.

	//layout
	uintp mLineHeight = 0;
	intp mAscender = 0;	//height above base line
	intp mDescender = 0;	//height below base line
	Size2U mMaxAdvance;

	intp mUnderlinePosition = 0;
	uintp mUnderlineTickness = 0;

	//contents
	Share<TextureAtlas> mAtlas;

	Dictionary<wchar_t, FontChar*> mChars;
	Dictionary<uint64, FontKerning*> mKernings;

	const FontChar* mSpaceFontChar = nullptr;

	//const static char* mASCIIChars;
	const static char* mNEHEChars;

};

MEDUSA_END;


text:
<?php

namespace backend\models\form;

use backend\components\ExcelExchange;
use common\models\Message;
use common\models\SourceMessage;
use Yii;
use yii\base\Model;
use yii\helpers\FileHelper;

/**
 * Class ExcelExchangeForm
 * @package backend\models\form
 */
class ExcelExchangeForm extends Model
{
    public $languages; // 'uk', 'en' or 'ru'
    public $is_rewrite = false;
    public $type_end; // 'backend' or 'frontend';
    public $category; // 'admin' or 'app'
    public $file;
    public $errors;

    protected $translation_;
    protected $fileName;
    protected $filePath;
    protected $formats = [
        'xls'  => 'Excel5',
        'xlsx' => 'Excel2007',
    ];

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['languages', 'is_rewrite'], 'required'],
            ['is_rewrite', 'boolean'],
            ['type_end', 'in', 'range' => ['backend', 'frontend']],
            ['category', 'in', 'range' => ['admin', 'app']],
            [
                'file', 'file', 'skipOnEmpty'            => true,
                                   'extensions'             => ['xls', 'xlsx'],
                                   'maxSize'                => 1024 * 1024 * 10,
                                   'enableClientValidation' => false,
                                    'on' => 'export'
            ]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'languages'  => Yii::t('admin', 'Languages'),
            'is_rewrite' => Yii::t('admin', 'Is rewrite'),
        ];
    }

    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();

        $this->languages = $this->category === 'admin' ? ['ru'] : ['en', 'uk'];
        $this->type_end = $this->category === 'admin' ? 'backend' : 'frontend';
    }

    /**
     * @inheritdoc
     */
    public function import()
    {
        /** @var Message $model */
        $model = Message::getByCategory($this->category);
        /** @var ExcelExchange $excel */
        $excel = new ExcelExchange();
        /** @var ExcelExchange $PHPExcel */
        $PHPExcel = $excel->createExcel($this->type_end);

        // set title columns
        $this->setHeader($PHPExcel);
        // new row
        $PHPExcel->newRow();
        // set value
        foreach ($model as $row) {
            $this->setValue($PHPExcel, $row);
        }
        // set filter
        $this->setFilter($PHPExcel->PHPExcel);
        // set style
        $this->setStyle($PHPExcel->PHPExcel);
        // get file to download
        $PHPExcel->getContentDownload('translations_' . $this->type_end);
    }

    public function export()
    {
        /** @var \PHPExcel_Reader_IReader $objReader */
        $objReader = \PHPExcel_IOFactory::createReader($this->formats[$this->file->extension]);
        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($this->filePath . $this->fileName);
        $objWorksheet = $objPHPExcel->getActiveSheet();

        $highestRow = $objWorksheet->getHighestRow();
        //$highestColumn = $objWorksheet->getHighestColumn();
        //$highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);

        for ($row = 2; $row <= $highestRow; ++$row) {
            if ($this->category !== $objWorksheet->getCellByColumnAndRow(1, $row)->getValue()) {
                $this->errors[] = Yii::t('admin', 'Incorrect category! Need {need}, given {given}', [
                    'need' => $this->category,
                    'given' => $objWorksheet->getCellByColumnAndRow(1, $row)->getValue()
                ]);
            } else {
                $model = SourceMessage::findOne([
                    'category' => $this->category,
                    'message'  => $objWorksheet->getCellByColumnAndRow(2, $row)->getValue()
                ]);

                if (!$model) {
                    $this->insertTranslation($objWorksheet, $row);
                } else {
                    $this->updateTranslation($objWorksheet, $row, $model);
                }
            }
        }

        unlink($this->filePath . $this->fileName);

        return true;
    }

    /**
     * @return bool
     */
    public function upload()
    {
        $this->filePath = FileHelper::normalizePath(Yii::getAlias('@statics/web/uploads/temp')) . DIRECTORY_SEPARATOR;

        if ($this->validate()) {
            if (!file_exists($this->filePath)) {
                mkdir($this->filePath, 0777, true);
            }

            $this->fileName = md5($this->file->baseName . time()) . '.' . $this->file->extension;
            $this->file->saveAs($this->filePath . $this->fileName);

            return true;
        } else {
            return false;
        }
    }

    /**
     * @param ExcelExchange $PHPExcel
     */
    protected function setHeader(ExcelExchange $PHPExcel)
    {
        $PHPExcel->setColumn('ID');
        $PHPExcel->setColumn('Category');
        $PHPExcel->setColumn('Source');

        if ($this->category === 'admin') {
            $PHPExcel->setColumn('Message RU');
        } else {
            $PHPExcel->setColumn('Message EN');
            $PHPExcel->setColumn('Message UA');
        }
    }

    /**
     * @param ExcelExchange $PHPExcel
     * @param Message $row
     */
    protected function setValue(ExcelExchange $PHPExcel, Message $row)
    {
        if ($row->language === 'en') {
            $this->translation_ = $row->translation;
        } else {
            $PHPExcel->setColumn($row->id);
            $PHPExcel->setColumn($row->sourceMessage->category);
            $PHPExcel->setColumn($row->sourceMessage->message);
            $this->category !== 'admin' && $PHPExcel->setColumn($this->translation_);
            $PHPExcel->setColumn($row->translation);
            $PHPExcel->newRow();
        }
    }

    /**
     * @param \PHPExcel $PHPExcel
     */
    protected function setFilter(\PHPExcel $PHPExcel)
    {
        $PHPExcel->getActiveSheet()->setAutoFilter(
            'A1:'
            . $PHPExcel->setActiveSheetIndex(0)->getHighestColumn()
            . $PHPExcel->setActiveSheetIndex(0)->getHighestRow()
        );
    }

    /**
     * @param \PHPExcel $PHPExcel
     */
    protected function setStyle(\PHPExcel $PHPExcel)
    {
        // set auto-size
        foreach(range('A',$PHPExcel->setActiveSheetIndex(0)->getHighestColumn()) as $columnID)
        {
            $PHPExcel->getActiveSheet()->getColumnDimension($columnID)
                ->setAutoSize(true);
        }

        // set first row bold
        $PHPExcel->getActiveSheet()->getStyle(
            'A1:'
            . $PHPExcel->setActiveSheetIndex(0)->getHighestColumn()
            . '1'
        )->getFont()->setBold(true);
    }

    /**
     * @param \PHPExcel_Worksheet $objWorksheet
     * @param $row
     * @return bool
     * @throws \Exception
     * @throws \yii\db\Exception
     */
    protected function insertTranslation(\PHPExcel_Worksheet $objWorksheet, $row)
    {
        $transaction = SourceMessage::getDb()->beginTransaction();

        try {
            $sourceMessage = new SourceMessage();
            $sourceMessage->category = $this->category;
            $sourceMessage->message = $objWorksheet->getCellByColumnAndRow(2, $row)->getValue();
            $sourceMessage->save();

            if ($this->category === 'admin') {
                $message = new Message();
                $message->id = $sourceMessage->id;
                $message->language = 'ru';
                $message->translation = $objWorksheet->getCellByColumnAndRow(3, $row)->getValue();
                $message->save();
            } else {
                foreach ([3 => 'en', 4 => 'uk'] as $index => $lang) {
                    $message = new Message();
                    $message->id = $sourceMessage->id;
                    $message->language = $lang;
                    $message->translation = $objWorksheet->getCellByColumnAndRow($index, $row)->getValue();
                    $message->save();
                }
            }

            $transaction->commit();

            return true;

        } catch(\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }

    /**
     * @param \PHPExcel_Worksheet $objWorksheet
     * @param $row
     * @param SourceMessage $sourceMessage
     * @return bool
     */
    protected function updateTranslation(\PHPExcel_Worksheet $objWorksheet, $row, SourceMessage $sourceMessage)
    {
        foreach ([3 => 'en', 4 => 'uk'] as $index => $lang) {
            foreach ($sourceMessage->messages as $message) {
                if ($message->language === $lang) {
                    if ($message->translation !== $objWorksheet->getCellByColumnAndRow($index, $row)->getValue()) {
                        $message->language = $lang;
                        $message->translation = $objWorksheet->getCellByColumnAndRow($index, $row)->getValue();
                        $this->is_rewrite && $message->save();
                    }
                }
            }
        }

        return true;
    }
}


text:
import * as React from 'react';
import CloseOnEscape from 'react-close-on-escape';

const onEscapeCallback = () => {};

// $ExpectError
const missingRequired = <CloseOnEscape />;

// $ExpectError
const invalidExample = <CloseOnEscape onEscape={true} />;

const validExample = <CloseOnEscape onEscape={onEscapeCallback} />;


text:
import phonenumbers
import requests
import dateutil.parser

from django.core.files.temp import NamedTemporaryFile
from django.contrib.auth.models import User
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.forms import model_to_dict

from rfnumplan.utils import read_csv_num_plan, map_instances_by_name, range_to_prefix
from django.utils.translation import ugettext_lazy as _

from .settings import MAX_PREFIX_LENGTH

class ModelDiffMixin(object):
    """
    A model mixin that tracks model fields' values and provide some useful api
    to know what fields have been changed.
    """

    def __init__(self, *args, **kwargs):
        super(ModelDiffMixin, self).__init__(*args, **kwargs)
        self.__initial = self._dict

    @property
    def diff(self):
        d1 = self.__initial
        d2 = self._dict
        diffs = [(k, (v, d2[k])) for k, v in d1.items() if v != d2[k]]
        return dict(diffs)

    @property
    def has_changed(self):
        return bool(self.diff)

    @property
    def changed_fields(self):
        return self.diff.keys()

    def get_field_diff(self, field_name):
        """
        Returns a diff for field if it's changed and None otherwise.
        """
        return self.diff.get(field_name, None)

    def save(self, *args, **kwargs):
        """
        Saves model and set initial state.
        """
        super(ModelDiffMixin, self).save(*args, **kwargs)
        self.__initial = self._dict

    @property
    def _dict(self):
        return model_to_dict(self, fields=[field.name for field in self._meta.fields])

class Operator(models.Model):
    name = models.CharField(_('operator name'), max_length=255, unique=True)

    class Meta:
        verbose_name = _('operator')
        verbose_name_plural = _('operators')
        ordering = ['name']

    def __str__(self):
        return self.name

class Region(models.Model):
    name = models.CharField(_('region name'), max_length=255, unique=True)

    class Meta:
        verbose_name = _('region')
        verbose_name_plural = _('regions')
        ordering = ['name']

    def __str__(self):
        return self.name

class NumberingPlan(ModelDiffMixin, models.Model):
    name = models.CharField(_('numbering plan'), max_length=128, help_text=_('e.g. rossviaz 4xx'))
    prefix = models.PositiveIntegerField(_('prefix'), help_text=_('e.g. 7'))
    plan_uri = models.URLField(_('url'), blank=True)
    loaded = models.BooleanField(_('loaded'), default=False)
    last_modified = models.DateTimeField(_('last modified'), blank=True, null=True)

    class Meta:
        verbose_name = _('numbering plan')
        verbose_name_plural = _('numbering plans')
        ordering = ['name']

    def __str__(self):
        return self.name

    def do_import(self, force=False):
        head = requests.head(self.plan_uri).headers
        lm = dateutil.parser.parse(head.get('Last-Modified'))
        if self.last_modified and self.last_modified >= lm and not force and self.loaded:
            return []

        response = requests.get(self.plan_uri)
        tmp = NamedTemporaryFile(delete=True)
        tmp.write(response.content)
        tmp.flush()

        parsed = read_csv_num_plan(tmp.name)
        operators = map_instances_by_name(Operator, parsed['operators'])
        regions = map_instances_by_name(Region, parsed['regions'])
        NumberingPlanRange.objects.filter(numbering_plan=self).delete()

        bulk = []
        for bundle in parsed['data']:
            bulk.append(
                NumberingPlanRange(
                    numbering_plan=self,
                    prefix=bundle['prefix'],
                    range_start='1%s' % bundle['range_start'],
                    range_end='1%s' % bundle['range_end'],
                    range_capacity=bundle['range_capacity'],
                    operator=operators[bundle['operator']],
                    region=regions[bundle['region']],
                )
            )

        self.last_modified = lm
        self.loaded = True
        return NumberingPlanRange.objects.bulk_create(bulk)

    def save(self, *args, **kwargs):
        cf = self.changed_fields
        res = super(NumberingPlan, self).save()

        if not self.loaded or self.plan_uri in cf:
            self.do_import()
            self.save()

        return res

    def range_prefixes(self):
        return self.ranges.order_by('prefix').values_list('prefix').annotate(cnt=models.Count('prefix'))

class NumberingPlanRange(models.Model):
    numbering_plan = models.ForeignKey(NumberingPlan, verbose_name=_('numbering plan'), related_name='ranges')
    prefix = models.PositiveIntegerField(_('prefix'), help_text=_('e.g. 495'))
    range_start = models.PositiveIntegerField(_('range start'), help_text=_('`1`-prefixed range start'))
    range_end = models.PositiveIntegerField(_('range end'), help_text=_('`1`-prefixed range end'))
    range_capacity = models.PositiveIntegerField(_('range capacity'))

    operator = models.ForeignKey(Operator, verbose_name=_('operator'))
    region = models.ForeignKey(Region, verbose_name=_('region'))

    class Meta:
        verbose_name = _('numbering plan range')
        verbose_name_plural = _('numbering plan ranges')
        ordering = ['numbering_plan_id', 'prefix', 'range_start']

    def __str__(self):
        return '%s [%s; %s]' % (self.numbering_plan.name, str(self.range_start)[1:], str(self.range_end)[1:])

    @staticmethod
    def find(phone_number: str):
        """
        7 9 252123399
        7 92 52123399
        7 925 2123399
        7 9252 123399
        79 2 52123399
        79 25 2123399
        79 252 123399
        79 2521 23399
        792 5 2123399
        792 52 123399
        792 521 23399
        792 5212 3399
        7925 2 123399
        7925 21 23399
        7925 212 3399
        7925 2123 399
        :param phone_number:
        :return:
        """

        number = phonenumbers.parse(phone_number, region='RU')
        if not phonenumbers.is_valid_number(number):
            raise ValueError(_('Wrong number %s') % phone_number)

        e164_number = phonenumbers.format_number(number, phonenumbers.PhoneNumberFormat.E164).lstrip('+')

        lookup = models.Q()

        for i in range(1, min(MAX_PREFIX_LENGTH, len(e164_number))):
            plan_prefix = e164_number[:i]
            rest = e164_number[i:]

            for j in range(1, min(MAX_PREFIX_LENGTH, len(rest))):
                pr_prefix = rest[:j]
                local_phone = rest[j:]
                lookup |= models.Q(
                    numbering_plan__prefix=plan_prefix, prefix=pr_prefix,
                    range_start__lte='1%s' % local_phone, range_end__gte='1%s' % local_phone
                )
        return NumberingPlanRange.objects.filter(lookup).select_related('operator', 'region')

    @staticmethod
    def range_prefixes():
        return NumberingPlanRange.objects.order_by('prefix').values_list('prefix').annotate(cnt=models.Count('prefix'))

    def to_prefix_list(self):
        start = ''.join(map(str, [self.numbering_plan.prefix, self.prefix, str(self.range_start)[1:]]))
        end = ''.join(map(str, [self.numbering_plan.prefix, self.prefix, str(self.range_end)[1:]]))

        for prefix in range_to_prefix(start, end):
            yield str(prefix)

    def get_display(self):
        return '+%s (%s) [%s - %s] x%s' % (
            self.numbering_plan.prefix,
            self.prefix,
            str(self.range_start)[1:],
            str(self.range_end)[1:],
            self.range_capacity
        )


text:
package org.kuali.hr;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.log4j.Logger;
import org.kuali.kpme.core.rice.test.lifecycles.KPMEXmlDataLoaderLifecycle;
import org.kuali.kpme.core.util.ClearDatabaseLifecycle;
import org.kuali.kpme.core.util.DatabaseCleanupDataLifecycle;
import org.kuali.kpme.core.util.HrContext;
import org.kuali.kpme.core.util.LoadDatabaseDataLifeCycle;
import org.kuali.rice.core.api.config.property.Config;
import org.kuali.rice.core.api.config.property.ConfigContext;
import org.kuali.rice.core.api.lifecycle.BaseLifecycle;
import org.kuali.rice.core.api.lifecycle.Lifecycle;
import org.kuali.rice.core.impl.services.CoreImplServiceLocator;
import org.kuali.rice.krad.UserSession;
import org.kuali.rice.krad.util.GlobalVariables;
import org.kuali.rice.krad.util.MessageMap;
import org.kuali.rice.test.RiceInternalSuiteDataTestCase;
import org.kuali.rice.test.TransactionalLifecycle;
import org.kuali.rice.test.lifecycles.JettyServerLifecycle;
import org.kuali.rice.test.lifecycles.JettyServerLifecycle.ConfigMode;
import org.springframework.cache.CacheManager;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.WebClient;

/**
 *  Default test base for a full KPME unit test.
 */
public abstract class KPMEWebTestCase extends RiceInternalSuiteDataTestCase {

	private static final String FILE_PREFIX = System.getProperty("user.dir") + "/../db/src/main/resources/org/kuali/kpme/kpme-db/workflow/";

	private static final String RELATIVE_WEBAPP_ROOT = "/src/main/webapp";

	private TransactionalLifecycle transactionalLifecycle;
    private WebClient webClient;

	@Override
	protected String getModuleName() {
		return "kpme";
	}

	@Override
	public void setUp() throws Exception {
	    if (System.getProperty("basedir") == null) {
	        System.setProperty("basedir", System.getProperty("user.dir") + "/");
	    }

		super.setUp();

		GlobalVariables.setMessageMap(new MessageMap());

		final boolean needsSpring = false;
		if (needsSpring) {
			transactionalLifecycle = new TransactionalLifecycle();
			//transactionalLifecycle.setTransactionManager(KRADServiceLocatorInternal.getTransactionManager());
			transactionalLifecycle.start();
		}

	    new ClearDatabaseLifecycle().start();

		new LoadDatabaseDataLifeCycle(this.getClass()).start();

	    //lets try to create a user session
	    GlobalVariables.setUserSession(new UserSession("admin"));
        setWebClient(new WebClient(BrowserVersion.FIREFOX_17));
        getWebClient().getOptions().setJavaScriptEnabled(true);
        getWebClient().getOptions().setTimeout(0);
	}

	@Override
	public void tearDown() throws Exception {
	    // runs custom SQL at the end of each test.
	    // useful for difficult to reset test additions, not handled by
	    // our ClearDatabaseLifecycle.
        HrContext.clearTargetUser();
        getWebClient().closeAllWindows();
	    new DatabaseCleanupDataLifecycle(this.getClass()).start();

		final boolean needsSpring = true;
		if (needsSpring) {
		    if ( (transactionalLifecycle != null) && (transactionalLifecycle.isStarted()) ) {
		        transactionalLifecycle.stop();
		    }
		}

		GlobalVariables.setMessageMap(new MessageMap());

		super.tearDown();
	}

    @Override
    protected List<Lifecycle> getPerTestLifecycles() {
        List<Lifecycle> lifecycles = super.getPerTestLifecycles();
        lifecycles.add(new ClearCacheLifecycle());
        return lifecycles;
    }

	@Override
	protected List<Lifecycle> getSuiteLifecycles() {
		List<Lifecycle> lifecycles = super.getPerTestLifecycles();
	    lifecycles.add(new Lifecycle() {
			boolean started = false;

			public boolean isStarted() {
				return this.started;
			}

			public void start() throws Exception {
				setModuleName(getModuleName());
				setBaseDirSystemProperty(getModuleName());
				Config config = getTestHarnessConfig();
				ConfigContext.init(config);
				this.started = true;
			}

			public void stop() throws Exception {
				this.started = false;
			}
		});
	    /**
	     * Loads the TestHarnessSpringBeans.xml file which obtains connections to the DB for us
	     */
/*	    lifecycles.add(getTestHarnessSpringResourceLoader());*/

	    /**
	     * Establishes the TestHarnessServiceLocator so that it has a reference to the Spring context
	     * created from TestHarnessSpringBeans.xml
	     */
/*	    lifecycles.add(new BaseLifecycle() {
	        @Override
	        public void start() throws Exception {
	            TestHarnessServiceLocator.setContext(getTestHarnessSpringResourceLoader().getContext());
	            super.start();
	        }
	    });*/

	    lifecycles.add(new Lifecycle() {
			private JettyServerLifecycle jettyServerLifecycle;

			public boolean isStarted() {
				return jettyServerLifecycle.isStarted();
			}

			public void start() throws Exception {
	            System.setProperty("web.bootstrap.spring.file", "classpath:TestHarnessSpringBeans.xml");
	            jettyServerLifecycle = new JettyServerLifecycle(getPort(), getContext(), RELATIVE_WEBAPP_ROOT);
	            jettyServerLifecycle.setConfigMode(ConfigMode.OVERRIDE);
				jettyServerLifecycle.start();
			}

			public void stop() throws Exception {
				this.jettyServerLifecycle.stop();
			}
		});

	    ClearDatabaseLifecycle clearDatabaseLifecycle = new ClearDatabaseLifecycle();
	    clearDatabaseLifecycle.getAlternativeTablesToClear().add("KREW_RULE_T");
	    clearDatabaseLifecycle.getAlternativeTablesToClear().add("KREW_RULE_RSP_T");
	    clearDatabaseLifecycle.getAlternativeTablesToClear().add("KREW_DLGN_RSP_T");
	    clearDatabaseLifecycle.getAlternativeTablesToClear().add("KREW_RULE_ATTR_T");
	    clearDatabaseLifecycle.getAlternativeTablesToClear().add("KREW_RULE_TMPL_T");
	    clearDatabaseLifecycle.getAlternativeTablesToClear().add("KREW_DOC_TYP_T");
	    lifecycles.add(clearDatabaseLifecycle);

	    File[] folders = new File(FILE_PREFIX).listFiles();

	    if (folders != null) {
            Arrays.sort(folders);
            for (File folder : folders) {
            	if (folder.getName().startsWith("00")) {
            		File[] files = new File(FILE_PREFIX + folder.getName()).listFiles();
            		if (files != null) {
                        // Arrays.sort(files);
                        for (File file : files) {
                        	if (file.getName().endsWith(".xml")) {
                        		lifecycles.add(new KPMEXmlDataLoaderLifecycle(FILE_PREFIX + folder.getName() + "/" + file.getName()));
                        	}
                        }
    		        }
	            }
            }
	    }
		return lifecycles;
	}

/*	public void futureEffectiveDateValidation(String baseUrl) throws Exception {
	  	HtmlPage page = HtmlUnitUtil.gotoPageAndLogin(getWebClient(), baseUrl);
	  	Assert.assertNotNull(page);

	  	HtmlForm form = page.getFormByName("KualiForm");
	  	Assert.assertNotNull("Search form was missing from page.", form);
	  	// use past dates
	    setFieldValue(page, "document.newMaintainableObject.effectiveDate", "04/01/2011");
	    HtmlInput  input  = HtmlUnitUtil.getInputContainingText(form, "methodToCall.route");
	    Assert.assertNotNull("Could not locate submit button", input);
	  	page = ((HtmlButtonInput)page.getElementByName("methodToCall.route")).click();
	  	Assert.assertTrue("page text does not contain:\n" + HrTestConstants.EFFECTIVE_DATE_ERROR, page.asText().contains(HrTestConstants.EFFECTIVE_DATE_ERROR));
	  	LocalDate futureDate = LocalDate.now().plusYears(2); // 2 years in the future
	  	String futureDateString = "01/01/" + Integer.toString(futureDate.getYear());

	  	// use dates 2 years in the future
	    setFieldValue(page, "document.newMaintainableObject.effectiveDate", futureDateString);
	  	page = ((HtmlButtonInput)page.getElementByName("methodToCall.route")).click();
	  	Assert.assertTrue("page text does not contain:\n" + HrTestConstants.EFFECTIVE_DATE_ERROR, page.asText().contains(HrTestConstants.EFFECTIVE_DATE_ERROR));
	  	LocalDate validDate = LocalDate.now().plusMonths(5); // 5 month in the future
	  	String validDateString = Integer.toString(validDate.getMonthOfYear()) + '/' + Integer.toString(validDate.getDayOfMonth())
	  		+ '/' + Integer.toString(validDate.getYear());
	  	setFieldValue(page, "document.newMaintainableObject.effectiveDate", validDateString);
	  	page = ((HtmlElement)page.getElementByName("methodToCall.route")).click();
	  	Assert.assertFalse("page text contains:\n" + HrTestConstants.EFFECTIVE_DATE_ERROR, page.asText().contains(HrTestConstants.EFFECTIVE_DATE_ERROR));
	}
*/
    public class ClearCacheLifecycle extends BaseLifecycle {
        private final Logger LOG = Logger.getLogger(ClearCacheLifecycle.class);

        @Override
        public void start() throws Exception {
            long startTime = System.currentTimeMillis();
            LOG.info("Starting cache flushing");
            List<CacheManager> cms = new ArrayList<CacheManager>(CoreImplServiceLocator.getCacheManagerRegistry().getCacheManagers());
            for (CacheManager cm : cms) {
                for (String cacheName : cm.getCacheNames()) {
                    //LOG.info("Clearing cache: " + cacheName);
                    cm.getCache(cacheName).clear();
                }
            }
            long endTime = System.currentTimeMillis();
            LOG.info("Caches cleared in " + (endTime - startTime) + "ms");
        }

        @Override
        public void stop() throws Exception {
            super.stop();
        }

    }

    public WebClient getWebClient() {
        return this.webClient;
    }

    public void setWebClient(WebClient webClient) {
        this.webClient = webClient;
    }

    public static String getBaseURL() {
	    return ConfigContext.getCurrentContextConfig().getProperty("application.url");
    }

    public static String getContext() {
    	return "/" + ConfigContext.getCurrentContextConfig().getProperty("app.context.name");
    }

    public static String getTempDir() {
	return ConfigContext.getCurrentContextConfig().getProperty("temp.dir");
    }

    public static Integer getPort() {
	    return new Integer(ConfigContext.getCurrentContextConfig().getProperty("kns.test.port"));
    }

    /*protected List<String> getConfigLocations() {
        List<String> configLocations = new ArrayList<String>();
        //configLocations.add(getRiceMasterDefaultConfigFile());
        configLocations.add("classpath:META-INF/kpme-test-config.xml");

        //module specific overrides:
        configLocations.add(getModuleTestConfigLocation());
        return configLocations;
    }*/

}


text:
desc "compress ARCHIVE [TO]", "Compress files in an archive which match on a certain criterion"
option 'aggressive', :aliases=>'-a', :type=>'boolean', :desc=>"Aggressive mode: compress identical files even if they don't have the same paths"
option 'dryrun',     :aliases=>'-D', :type=>'boolean', :desc=>"Dryrun; don't actually delete files"
option "force",      :aliases=>'-f', :type=>'boolean', :desc=>"Overwrite existing to directory"
option 'link',       :aliases=>'-l', :type=>'boolean',  :desc=>"Create symlinks for duplicate files?"
option 'quiet',      :aliases=>'-q', :type=>'boolean', :desc=>"Quiet mode"

long_desc <<-EOT
Compress archive.
Removes files in an archive which have identical content, and compresses directories of the form
path/to/file_<DATETIME>/tape... to path/to/file, provided there's only one tape.

If the compression of tapes described above results in more than one version of the target file,
then they are named path/to/file.V1, path/to/file.V2, etc. (If the file has an extension, this is
appended after the "v1", etc.)

The --aggressive parameter controls what files are flagged as duplicates, and how they are handled.
With --Aggressive, ALL files with duplicate content are deleted, except for the oldest one, regardless
of whether all the files have the same target path. Without it, only duplicate versions with exactly
the same target path are deleted.

The --link parameter causes duplicate files (regardless of whether they have the same target path or
not) to be replaced with a symlink to the oldest file with the same content. Note that this only
matters with --no-delete.

As illustration for the above, consider the following example: Three files file1/tape.ar001.0001,
file1/tape.ar002.0002, and file2/tape.ar003.0003 all have identical content. Assume the files above
are listed in order of creation. Then:

Flag                        Meaning                             Action
--no-aggressive, --no-link  Delete duplicates with identical    Deletes file1/tape.ar002.0002. Creates
                            target paths. Keep all other        the other two files. No symlinks are
                            duplicates. Do not create symlinks  created.
                            (This is the default.)

--aggressive,    --no-link  Delete all duplicates, even if      Deletes file1/tape.ar002.0002 and
                            they have different target paths.   file2/tape.ar003.0003. No symlinks
                            Do not create symlinks.             are created.

--no-aggressive, --link     Delete duplicates with identical    Deletes file1/tape.ar002.0002
                            target paths. Replace all dup-      Replaces file2/tape.ar003.0003 with a symlink to
                            licate files with symlinks to the   file1/tape.ar001.0001
                            oldest identical file.

--aggressive,    --link     Delete all duplicates, even if      Deletes file1/tape.ar002.0002 and
                            they have different target paths.   and file2/tape.ar003.0003. No duplicate
                            No links are left to be created.    files are left to be symlinked.
EOT
def compress(archive, to=nil)
  check_for_unknown_options(archive, to)
  Archive.compress(archive, to, options)
end


text:
package main

import (
	"fmt"
	"net/url"
	"os"

	vers "github.com/treeder/functions/api/version"
	functions "github.com/iron-io/functions_go"
	"github.com/urfave/cli"
)

func version() cli.Command {
	r := versionCmd{VersionApi: functions.NewVersionApi()}
	return cli.Command{
		Name:   "version",
		Usage:  "displays fn and functions daemon versions",
		Action: r.version,
	}
}

type versionCmd struct {
	*functions.VersionApi
}

func (r *versionCmd) version(c *cli.Context) error {
	apiURL := os.Getenv("API_URL")
	if apiURL == "" {
		apiURL = "http://localhost:8080"
	}

	u, err := url.Parse(apiURL)
	if err != nil {
		return err
	}
	r.Configuration.BasePath = u.String()

	fmt.Println("Client version:", vers.Version)
	v, _, err := r.VersionGet()
	if err != nil {
		return err
	}
	fmt.Println("Server version", v.Version)
	return nil
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>User</title>
<meta name="date" content="2015-10-14">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

com.markdavidhansen.cs240.shared.model

Class User

java.lang.Object

com.markdavidhansen.cs240.shared.model.User

public class User
extends java.lang.Object

Field Summary

Fields

Modifier and Type
Field and Description

private java.lang.String
email

private java.lang.String
firstName

private int
inedexedRecords

private java.lang.String
lastName

private java.lang.String
passwordHash

private int
userID

private java.lang.String
userName

Constructor Summary

Constructors

Modifier
Constructor and Description

User()

private
User(java.lang.String userName,
    java.lang.String firstName,
    java.lang.String lastName,
    java.lang.String email,
    java.lang.String passwordHash,
    int inedexedRecords)

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

java.lang.String
getEmail()

java.lang.String
getFirstName()

int
getInedexedRecords()

java.lang.String
getLastName()

java.lang.String
getPasswordHash()

static User
getUser(int userID)

int
getUserID()

java.lang.String
getUserName()

boolean
saveUser(java.lang.String userName,
        java.lang.String firstName,
        java.lang.String lastName,
        java.lang.String email,
        java.lang.String passwordHash,
        int inedexedRecords)

void
setEmail(java.lang.String email)

void
setFirstName(java.lang.String firstName)

void
setInedexedRecords(int inedexedRecords)

void
setLastName(java.lang.String lastName)

void
setPasswordHash(java.lang.String passwordHash)

void
setUserID(int userID)

void
setUserName(java.lang.String userName)

static boolean
validateUser(java.lang.String username,
            java.lang.String passwordHash)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

userID

private int userID

userName

private java.lang.String userName

firstName

private java.lang.String firstName

lastName

private java.lang.String lastName

email

private java.lang.String email

passwordHash

private java.lang.String passwordHash

inedexedRecords

private int inedexedRecords

Constructor Detail

User

public User()

User

private User(java.lang.String userName,
             java.lang.String firstName,
             java.lang.String lastName,
             java.lang.String email,
             java.lang.String passwordHash,
             int inedexedRecords)

Method Detail

getUserID

public int getUserID()

setUserID

public void setUserID(int userID)

getUserName

public java.lang.String getUserName()

setUserName

public void setUserName(java.lang.String userName)

getFirstName

public java.lang.String getFirstName()

setFirstName

public void setFirstName(java.lang.String firstName)

getLastName

public java.lang.String getLastName()

setLastName

public void setLastName(java.lang.String lastName)

getEmail

public java.lang.String getEmail()

setEmail

public void setEmail(java.lang.String email)

getPasswordHash

public java.lang.String getPasswordHash()

setPasswordHash

public void setPasswordHash(java.lang.String passwordHash)

getInedexedRecords

public int getInedexedRecords()

setInedexedRecords

public void setInedexedRecords(int inedexedRecords)

saveUser

public boolean saveUser(java.lang.String userName,
                        java.lang.String firstName,
                        java.lang.String lastName,
                        java.lang.String email,
                        java.lang.String passwordHash,
                        int inedexedRecords)

getUser

public static User getUser(int userID)

validateUser

public static boolean validateUser(java.lang.String username,
                                   java.lang.String passwordHash)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text:
require 'barton/data'
require 'yaml'

describe Barton::Data do
  describe 'csv2yaml' do
    it "should only accept a csv file" do
      proc { Barton::Data.csv2yaml('no_such_file.txt') }.must_raise Errno::ENOENT
    end

    it "should convert each csv row to a yaml list item" do
      yaml = Barton::Data.csv2yaml 'spec/raw/StateRepsCSV.csv'
      #File.open('spec/raw/test.yaml', 'w') { |file| file.write yaml }
      #puts yaml
      parsed = ''
      proc { parsed = YAML.load yaml }.must_be_silent
      parsed.size.must_equal 9
      first = parsed.first.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
      first[:surname].must_equal 'Brodtmann'
      first[:electorate].must_equal 'Canberra'
    end
  end

  describe 'csv2hash' do
    it "should only accept a csv file" do
      proc { Barton::Data.csv2hash('no_such_file.txt') }.must_raise Errno::ENOENT
    end

    it "should convert each csv row to hash" do
      results = Barton::Data.csv2hash 'spec/raw/StateRepsCSV.csv'
      results.size.must_equal 9
      five = results[4]
      five.must_be_instance_of Hash
      five[:surname].must_equal'Alexander'
      five[:electorate].must_equal 'Bennelong'
    end
  end

  describe "parse_name" do
    it "should return a string" do
      Barton::Data.parse_name(:surname => 'Smith').must_be_kind_of String
    end

    it "should parse a name from valid hash keys" do
      Barton::Data.parse_name(:surname => 'Smith', :firstname => 'Bob').must_equal 'Bob Smith'
      Barton::Data.parse_name(:surname => 'Smith', :first => 'Robert', :preferred_name => 'Bob').must_equal "Robert 'Bob' Smith"
      Barton::Data.parse_name(:surname => 'Smith', :initials => 'R.A.').must_equal "R.A. Smith"
    end
  end

  describe "merge" do
    it "merge 2 yaml files and return a string" do
      merged = Barton::Data.merge :source => 'raw/qld-la.yaml', :target => 'spec/data/qld-state.yaml', :electorate => 'electorate'
      parsed = ''
      proc { parsed = YAML.load merged }.must_be_silent
    end
  end
end


text:
require 'json'
require 'restclient'
require 'nokogiri'

module Github
  module API

    module Transport

      def fetch_html(url, wait = 1)
        Nokogiri::HTML(fetch(url, wait))
      end

      def fetch_json(url, wait = 1)
        JSON.parse(fetch(url, wait))
      end

      def fetch(url, wait)
        sleep(wait);
        puts "ALFRED: fetching #{url}"
        RestClient.get(url).body
      rescue Exception => e
        puts e.backtrace
      end

    end # module Transport

    include Transport

    def watchers(user, repo, nr_of_watchers)
      nr_of_pages = (nr_of_watchers / 20.0).ceil
      (1..nr_of_pages).inject([]) do |result, page_num|
        watchers_page = fetch_html(watchers_url(user, repo, page_num))
        result + watchers_page.css(watchers_content_selector).inject([]) do |watchers, a|
          watchers << a.content
        end
      end
    end

    def watchers_url(user, repo, page_num)
      "#{root}/#{user}/#{repo}/watchers?page=#{page_num}"
    end

    def watchers_content_selector
      '#watchers li a:nth-child(2)'
    end

  end # module API

  extend API

end # module Github


text:
from __future__ import absolute_import

from google.cloud.oslogin_v1 import types
from google.cloud.oslogin_v1.gapic import enums
from google.cloud.oslogin_v1.gapic import os_login_service_client

class OsLoginServiceClient(os_login_service_client.OsLoginServiceClient):
    __doc__ = os_login_service_client.OsLoginServiceClient.__doc__
    enums = enums

__all__ = ("enums", "types", "OsLoginServiceClient")


text:
require 'spec_helper'

describe PostDecorator do
  let(:decorator) { PostDecorator.new(object) }
  let(:object) { Post.create }

  it 'can use built-in helpers' do
    expect(decorator.truncated).to eq 'Once upon a...'
  end

  it 'can use built-in private helpers' do
    expect(decorator.html_escaped).to eq ''
  end

  it 'can use user-defined helpers from app/helpers' do
    expect(decorator.hello_world).to eq 'Hello, world!'
  end

  it 'can be passed to path helpers' do
    expect(helpers.post_path(decorator)).to eq "/posts/#{object.id}"
  end

  it 'can use path helpers with its model' do
    expect(decorator.path_with_model).to eq "/posts/#{object.id}"
  end

  it 'can use path helpers with its id' do
    expect(decorator.path_with_id).to eq "/posts/#{object.id}"
  end

  it 'can be passed to url helpers' do
    expect(helpers.post_url(decorator)).to eq "http://test.host/posts/#{object.id}"
  end

  it 'can use url helpers with its model' do
    expect(decorator.url_with_model).to eq "http://test.host/posts/#{object.id}"
  end

  it 'can use url helpers with its id' do
    expect(decorator.url_with_id).to eq "http://test.host/posts/#{object.id}"
  end

  it 'can be passed implicitly to url_for' do
    expect(decorator.link).to eq "#{object.id}"
  end

  it 'serializes overriden attributes' do
    expect(decorator.serializable_hash['updated_at']).to be :overridden
  end

  it 'serializes to JSON' do
    json = decorator.to_json
    expect(json).to include('"updated_at":"overridden"')
  end

  it 'serializes to XML' do
    pending('Rails < 3.2 does not use `serializable_hash` in `to_xml`') if Rails.version.to_f < 3.2

    xml = Capybara.string(decorator.to_xml)
    expect(xml).to have_css 'post > updated-at', text: 'overridden'
  end

  it 'uses a test view context from ApplicationController' do
    expect(Drape::ViewContext.current.controller).to be_an ApplicationController
  end
end


text:
<?php

namespace Symfony\Component\DependencyInjection;

use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\ServiceCircularReferenceException;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;

/**
 * ContainerInterface is the interface implemented by service container classes.
 *
 * @author Fabien Potencier <fabien@symfony.com>
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 *
 * @api
 */
interface ContainerInterface
{
    const EXCEPTION_ON_INVALID_REFERENCE = 1;
    const NULL_ON_INVALID_REFERENCE = 2;
    const IGNORE_ON_INVALID_REFERENCE = 3;
    const SCOPE_CONTAINER = 'container';
    const SCOPE_PROTOTYPE = 'prototype';

    /**
     * Sets a service.
     *
     * Note: The $scope parameter is deprecated since version 2.8 and will be removed in 3.0.
     *
     * @param string $id      The service identifier
     * @param object $service The service instance
     * @param string $scope   The scope of the service
     *
     * @api
     */
    public function set($id, $service, $scope = self::SCOPE_CONTAINER);

    /**
     * Gets a service.
     *
     * @param string $id              The service identifier
     * @param int    $invalidBehavior The behavior when the service does not exist
     *
     * @return object The associated service
     *
     * @throws ServiceCircularReferenceException When a circular reference is detected
     * @throws ServiceNotFoundException          When the service is not defined
     *
     * @see Reference
     *
     * @api
     */
    public function get($id, $invalidBehavior = self::EXCEPTION_ON_INVALID_REFERENCE);

    /**
     * Returns true if the given service is defined.
     *
     * @param string $id The service identifier
     *
     * @return bool true if the service is defined, false otherwise
     *
     * @api
     */
    public function has($id);

    /**
     * Check for whether or not a service has been initialized.
     *
     * @param string $id
     *
     * @return bool true if the service has been initialized, false otherwise
     */
    public function initialized($id);

    /**
     * Gets a parameter.
     *
     * @param string $name The parameter name
     *
     * @return mixed The parameter value
     *
     * @throws InvalidArgumentException if the parameter is not defined
     *
     * @api
     */
    public function getParameter($name);

    /**
     * Checks if a parameter exists.
     *
     * @param string $name The parameter name
     *
     * @return bool The presence of parameter in container
     *
     * @api
     */
    public function hasParameter($name);

    /**
     * Sets a parameter.
     *
     * @param string $name  The parameter name
     * @param mixed  $value The parameter value
     *
     * @api
     */
    public function setParameter($name, $value);

    /**
     * Enters the given scope.
     *
     * @param string $name
     *
     * @api
     *
     * @deprecated since version 2.8, to be removed in 3.0.
     */
    public function enterScope($name);

    /**
     * Leaves the current scope, and re-enters the parent scope.
     *
     * @param string $name
     *
     * @api
     *
     * @deprecated since version 2.8, to be removed in 3.0.
     */
    public function leaveScope($name);

    /**
     * Adds a scope to the container.
     *
     * @param ScopeInterface $scope
     *
     * @api
     *
     * @deprecated since version 2.8, to be removed in 3.0.
     */
    public function addScope(ScopeInterface $scope);

    /**
     * Whether this container has the given scope.
     *
     * @param string $name
     *
     * @return bool
     *
     * @api
     *
     * @deprecated since version 2.8, to be removed in 3.0.
     */
    public function hasScope($name);

    /**
     * Determines whether the given scope is currently active.
     *
     * It does however not check if the scope actually exists.
     *
     * @param string $name
     *
     * @return bool
     *
     * @api
     *
     * @deprecated since version 2.8, to be removed in 3.0.
     */
    public function isScopeActive($name);
}


text:
<component name="ProjectDictionaryState">
  <dictionary name="pcrx4317">
    <words>
      <w>ragab</w>
    </words>
  </dictionary>
</component>


text:
// Popup.cs, 10.06.2019
// Copyright (C) Dominic Beger 17.06.2019

using System;
using System.Drawing;
using System.Windows.Forms;

namespace nUpdate.Administration.UI.Popups
{
    public class Popup
    {
        /// <summary>
        ///     Shows a new popup-window.
        /// </summary>
        /// <param name="popupIcon">The icons of the popup.</param>
        /// <param name="title">The title of the popup.</param>
        /// <param name="infoMessage">The info message of the popup.</param>
        /// <param name="buttons">The buttons to show for the user-interaction.</param>
        public static DialogResult ShowPopup(Icon popupIcon, string title, string infoMessage, PopupButtons buttons)
        {
            var popupWindow = new PopupDialog
            {
                PopupIcon = popupIcon,
                Title = title,
                InfoMessage = infoMessage,
                Buttons = buttons,
                StartPosition = FormStartPosition.CenterParent
            };

            return popupWindow.ShowDialog();
        }

        /// <summary>
        ///     Shows a new popup-window.
        /// </summary>
        /// <param name="popupIcon">The icons of the popup.</param>
        /// <param name="title">The title of the popup.</param>
        /// <param name="ex">The exception to handle in the popup-information.</param>
        /// <param name="buttons">The buttons to show for the user-interaction.</param>
        public static DialogResult ShowPopup(Icon popupIcon, string title, Exception ex, PopupButtons buttons)
        {
            var popupWindow = new PopupDialog
            {
                PopupIcon = popupIcon,
                Title = title,
                InfoMessage = ex.Message,
                Buttons = buttons,
                StartPosition = FormStartPosition.CenterParent,
                Exception = ex
            };

            return popupWindow.ShowDialog();
        }

        /// <summary>
        ///     Shows a new popup-window.
        /// </summary>
        /// <param name="owner">The owner of the modal popup dialog.</param>
        /// <param name="popupIcon">The icons of the popup.</param>
        /// <param name="title">The title of the popup.</param>
        /// <param name="infoMessage">The info message of the popup.</param>
        /// <param name="buttons">The buttons to show for the user-interaction.</param>
        public static DialogResult ShowPopup(IWin32Window owner, Icon popupIcon, string title, string infoMessage,
            PopupButtons buttons)
        {
            var popupWindow = new PopupDialog
            {
                PopupIcon = popupIcon,
                Title = title,
                InfoMessage = infoMessage,
                Buttons = buttons,
                StartPosition = FormStartPosition.CenterParent
            };

            return popupWindow.ShowDialog(owner);
        }

        /// <summary>
        ///     Shows a new popup-window.
        /// </summary>
        /// <param name="owner">The owner of the modal popup dialog.</param>
        /// <param name="popupIcon">The icons of the popup.</param>
        /// <param name="title">The title of the popup.</param>
        /// <param name="exception">The exception to handle in the popup-information.</param>
        /// <param name="buttons">The buttons to show for the user-interaction.</param>
        public static DialogResult ShowPopup(IWin32Window owner, Icon popupIcon, string title, Exception exception,
            PopupButtons buttons)
        {
            var popupWindow = new PopupDialog
            {
                PopupIcon = popupIcon,
                Title = title,
                InfoMessage = exception.Message,
                StartPosition = FormStartPosition.CenterParent,
                Buttons = buttons,
                Exception = exception
            };

            return popupWindow.ShowDialog();
        }
    }
}


text:
Third-view is a opensource project which help students to understand basic concepts in a better way.

It uses 3D library threejs to create scenes do demonstrate the topic.

 List of technologies/ framework and third party references used

 threejs

Three.js allows the creation of GPU-accelerated 3D animations using the JavaScript
                            language with the help of WebGL.

                        Try yourself

{ } TypeScript

TypeScript is a typed superset of JavaScript that compiles to plain JavaScript.
                            Any browser. Any host. Any OS. By Microsoft

                        Get started

Angular2

Angular2 takes a web component-based approach to building powerful single page applications                            for the web.

                        Learn more

 Bootstrap: Lean more

 jQuery: Lean more

 dat.gui: Lean more

 sprintf: Lean more

 YUI: Lean more


text:
var moduleX = require('./main');
moduleX.currentUrl = 'http://google.com';
console.log('current url: ' + moduleX.currentUrl);


text:
'use strict';
var inspect = require('util').inspect;
var Q = require('q');

module.exports = function () {
    var service = {};
    service.imap = require('imap');

    service.compile = function (objects, errors) {
        objects.forEach(function (obj) {
            var imapConfig = obj.imapConfig;
            if (imapConfig) {
                service.imapConfig = imapConfig;
            }
        });
    };

    service.fetchInboundEmails = function () {
        var future = Q.defer();

        var imap = new service.imap({
            user: service.imapConfig.user,
            password: service.imapConfig.password,
            host: service.imapConfig.host || 'imap.gmail.com',
            port: service.imapConfig.port || 993,
            tls: service.imapConfig.tls || true
        });

        function openInbox(cb) {
            imap.openBox('INBOX', true, cb);
        }

        imap.once('ready', function() {
            openInbox(function(err, box) {
                if (err) throw err;
                console.log('uid validity = %s', box.uidvalidity);
                console.log('uid next = %s', box.uidnext);
                var f = imap.seq.fetch(box.messages.total + ':*', { bodies: [''] });
                f.on('message', function(msg, seqno) {
                    console.log('Message #%d', seqno);
                    var prefix = '(#' + seqno + ') ';
                    msg.on('body', function(stream, info) {
                        if (info.which === 'TEXT')
                            console.log(prefix + 'Body [%s] found, %d total bytes', inspect(info.which), info.size);
                        var buffer = '', count = 0;
                        stream.on('data', function(chunk) {
                            count += chunk.length;
                            buffer += chunk.toString('utf8');
                            if (info.which === 'TEXT')
                                console.log(prefix + 'Body [%s] (%d/%d)', inspect(info.which), count, info.size);
                        });
                        stream.once('end', function() {
                            console.log('INFO = %s', inspect(info));
                            if (info.which !== 'TEXT')
                                console.log(prefix + 'Parsed header: %s', inspect(service.imap.parseHeader(buffer)));
                            else
                                console.log(prefix + 'Body [%s] Finished', inspect(info.which));
                                console.log(prefix + 'Body itself: %s', buffer);
                        });
                    });
                    msg.once('attributes', function(attrs) {
                        console.log(prefix + 'Attributes: %s', inspect(attrs, false, 8));
                    });
                    msg.once('end', function() {
                        console.log(prefix + 'Finished');
                    });
                });
                f.once('error', function(err) {
                    console.log('Fetch error: ' + err);
                });
                f.once('end', function() {
                    console.log('Done fetching all messages!');
                    imap.end();
                });
            });
        });

        imap.once('error', function(err) {
            console.log(err);
            future.reject(err);
        });

        imap.once('end', function() {
            future.resolve('TODO: Here must be fetched data...');
            console.log('Connection ended');
        });

        imap.connect();

        return future.promise;
    };

    return service;
};


text:
<!DOCTYPE html>

  <title>Angular Switching Toolbar Demo</title>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <link href="../bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="../dist/chameleon-navbar.css" rel="stylesheet">

        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
          Toggle navigation

        </button>
        Project name

Home

About

Contact

            Dropdown

Action

Another action

Something else here

Nav header

Separated link

One more separated link

Default

This example is a quick exercise to illustrate how the default, static and fixed to top navbar work. It includes the responsive CSS and HTML, so it also adapts to your viewport and device.

To see the difference between static and fixed top navbars, just scroll.

        View navbar docs »

Dark Grey

This example is a quick exercise to illustrate how the default, static and fixed to top navbar work. It includes the responsive CSS and HTML, so it also adapts to your viewport and device.

To see the difference between static and fixed top navbars, just scroll.

        View navbar docs »

Dark Red

This example is a quick exercise to illustrate how the default, static and fixed to top navbar work. It includes the responsive CSS and HTML, so it also adapts to your viewport and device.

To see the difference between static and fixed top navbars, just scroll.

        View navbar docs »


text:
package com.b2international.snowowl.core.attachments;

import java.nio.file.Path;

import com.b2international.snowowl.core.client.TransportConfiguration;
import com.b2international.snowowl.core.config.SnowOwlConfiguration;
import com.b2international.snowowl.core.plugin.Component;
import com.b2international.snowowl.core.setup.Environment;
import com.b2international.snowowl.core.setup.Plugin;
import com.b2international.snowowl.eventbus.IEventBus;

/**
 * @since 7.0
 */
@Component
public final class AttachmentPlugin extends Plugin {

	private static final String ATTACHMENTS_FOLDER = "attachments";

	@Override
	public void preRun(SnowOwlConfiguration configuration, Environment env) throws Exception {
		final IEventBus bus = env.service(IEventBus.class);

		if (env.isServer()) {
			final Path attachmentsPath = env.getDataPath().resolve(ATTACHMENTS_FOLDER);
			final DefaultAttachmentRegistry attachmentRegistry = new DefaultAttachmentRegistry(attachmentsPath);
			attachmentRegistry.register(bus);
			env.services().registerService(AttachmentRegistry.class, attachmentRegistry);
		} else {

			TransportConfiguration transportConfig = env.service(SnowOwlConfiguration.class).getModuleConfig(TransportConfiguration.class);

			env.services().addServiceListener(IEventBus.class, (oldBus, newBus) -> {
				final AttachmentRegistryClient attachmentRegistryClient = new AttachmentRegistryClient(newBus, transportConfig.getUploadChunkSize(), transportConfig.getDownloadChunkSize());
				env.services().registerService(AttachmentRegistry.class, attachmentRegistryClient);
			});

		}
	}
}


text:
title: Classic film
image: /images/elibrary/rear-window.jpg
alt: 1950s poster of Alfred Hitchcock's Rear Window
service: Kanopy
category: film
---

A collection of classics from the Kanopy service to stream for free, including Rear Window, Black Orpheus, A Farewell to Arms, A Star is Born, Carnival of Souls and many Sherlock Holmes classics.


text:
<?php

namespace FSi\Bundle\AdminSecurityBundle\Token;

interface TokenGeneratorInterface
{
    /**
     * @return string
     */
    public function generateToken();
}