text:
require 'spec_helper'
require 'silver_lining'

describe SilverLining::Defaults do
  context "construct" do
    it "news" do
      SilverLining::Defaults.instance!([])
    end

    it "with none" do
      expect( SilverLining::Defaults.none.organization_name ).to eq( SilverLining::Defaults.instance!([]).organization_name )
    end

    it "is a singleton" do
      expect( SilverLining::Defaults.instance! ).to eq(SilverLining::Defaults.instance!)
    end
  end

  context "sington" do

    before do
      SilverLining::Defaults.reset
    end

    context "arguments" do
      ["-o", "--org"].each do |arg|
        it "finds organization with #{arg}" do
          defaults = SilverLining::Defaults.instance!([arg, "org_name"])

          expect( defaults.organization_name ).to eq("org_name")
        end
      end

      ["-v", "--vapp"].each do |vapp|
        it "finds vapp with #{vapp}" do
          defaults = SilverLining::Defaults.instance!([vapp, "vapp_name"])

          expect( defaults.vapp_name ).to eq("vapp_name")
        end
      end

      ["-n", "--network"].each do |network|
        it "finds network with #{network}" do
          defaults = SilverLining::Defaults.instance!([network, "network_name"])

          expect( defaults.network ).to eq("network_name")
        end
      end

      ["-e", "--expression"].each do |expression|
        it "finds expression with #{expression}" do
          defaults = SilverLining::Defaults.instance!([expression, "expression_value"])

          expect( defaults.expression ).to eq("expression_value")
        end
      end

      [
        ["configure", "--org", "ORG1"],
        ["--org", "ORG1", "configure"],
        ["--vapp", "VAPP1", "configure", "--org", "ORG1"],
      ].each do |argv|
        it "accepts command in position #{argv.find_index("configure")}" do
          defaults = SilverLining::Defaults.instance!(argv)

          expect( argv ).to eq(["configure"])
        end
      end
    end

    context "set a default" do
      it "sets organization name" do
        defaults = SilverLining::Defaults.instance!

        defaults.organization_name = "AN ORG"

        expect( defaults.organization_name ).to eq("AN ORG")
      end

      it "sets an invalid property" do
        expect {
          SilverLining::Defaults.instance!.defaults.invalid_property = "AN ORG"
        }.to raise_error(NoMethodError)
      end
    end

    #
    # Values can come from 2 locations
    # - command line top priority
    # - config file default at startup
    # - default command use when ever set.
    context "choose" do
      before do
        allow_any_instance_of(SilverLining::Config).to receive(:organization).and_return(nil)
        allow_any_instance_of(SilverLining::Config).to receive(:vapp_name).and_return(nil)
      end

      context "organization" do

        it "uses configured organization" do
          expect_any_instance_of(SilverLining::Config).to receive(:organization).and_return("CHOOSE CONFIG ORG")

          defaults = SilverLining::Defaults.instance!([])

          expect( defaults.choose_organization_name("") ).to eq("CHOOSE CONFIG ORG")
        end

        it "override default if parameter entered" do
          defaults = SilverLining::Defaults.instance!(["-o", "DONT CHOOSE THIS"])

          expect( defaults.choose_organization_name("CHOOSE THIS") ).to eq("CHOOSE THIS")
        end

        it "default when no parameter passed in" do
          defaults = SilverLining::Defaults.instance!(["-o", "CHOOSE THIS"])

          expect( defaults.choose_organization_name(nil) ).to eq("CHOOSE THIS")
          expect( defaults.choose_organization_name("") ).to eq("CHOOSE THIS")
        end

        it "entered value when no default" do
          defaults = SilverLining::Defaults.instance!([])

          expect( defaults.choose_organization_name("CHOOSE THIS") ).to eq("CHOOSE THIS")
        end

        it "entered value when no default even if there is none" do
          defaults = SilverLining::Defaults.instance!([])

          expect( defaults.choose_organization_name(nil) ).to eq(nil)
        end

        it "chooses invalid property" do
          defaults = SilverLining::Defaults.instance!([])

          expect( defaults.choose_invalid_property("CHOOSE THIS") ).to eq("CHOOSE THIS")
        end
      end

      context "vapp" do

        it "uses configured vapp" do
          expect_any_instance_of(SilverLining::Config).to receive(:vapp_name).and_return("CHOOSE THIS")

          defaults = SilverLining::Defaults.instance!([])

          expect( defaults.choose_vapp_name("") ).to eq("CHOOSE THIS")
        end

        it "override default if parameter available" do
          defaults = SilverLining::Defaults.instance!(["-v", "CHOOSE THIS"])

          expect( defaults.choose_vapp_name("") ).to eq("CHOOSE THIS")
        end
      end

      context "expression" do

        it "extract command line expression" do
          defaults = SilverLining::Defaults.instance!(["-e", ".vms[0].network_connection.external_ip_address"])

          expect( defaults.expression ).to eq(".vms[0].network_connection.external_ip_address")
        end
      end

      context "network" do

        it "extract network name" do
          defaults = SilverLining::Defaults.instance!(["-n", "network_name"])

          expect( defaults.network ).to eq("network_name")
        end
      end
    end
  end
end


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

using DbLinq.Data.Linq.Sugar.Expressions;

namespace DbLinq.SqlServer
{
    class SqlServerExpressionTranslator : ExpressionTranslator
    {
        public override SelectExpression OuterExpression(SelectExpression e)
        {
            // Check for (from f in foo orderby f.Field select f).Count() trees
            // SQL Server doesn't support 'ORDER BY' for 'SELECT COUNT(*)'.
            if (e.Operands.Select(o => o as SpecialExpression)
                    .Where(o => o != null)
                    .Where(s => s.SpecialNodeType == SpecialExpressionType.Count)
                    .Any())
            {
                e.OrderBy.Clear();
            }
            return e;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<application generated-by="intellij" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.zeroturnaround.com" xsi:schemaLocation="http://www.zeroturnaround.com http://update.zeroturnaround.com/jrebel/rebel-2_1.xsd">

	<classpath>
		<dir name="/home/george/workspace_IDEA/CoreGAE/target/classes">
		</dir>
	</classpath>

	<web>
		<link target="/">
			<dir name="/home/george/workspace_IDEA/CoreGAE/src/main/webapp">
			</dir>
		</link>
		<link target="/WEB-INF">
			<dir name="/home/george/workspace_IDEA/CoreGAE/src/main/webapp/WEB-INF">
			</dir>
		</link>
	</web>

</application>


text:
package org.citygml4j.xml.adapter.construction;

import org.citygml4j.core.model.ade.generic.GenericADEOfDoorSurface;
import org.citygml4j.core.model.construction.ADEOfDoorSurface;
import org.citygml4j.core.model.construction.DoorSurface;
import org.citygml4j.core.model.core.AddressProperty;
import org.citygml4j.core.util.CityGMLConstants;
import org.citygml4j.xml.adapter.ade.ADEBuilderHelper;
import org.citygml4j.xml.adapter.ade.ADESerializerHelper;
import org.citygml4j.xml.adapter.core.AddressPropertyAdapter;
import org.xmlobjects.annotation.XMLElement;
import org.xmlobjects.builder.ObjectBuildException;
import org.xmlobjects.serializer.ObjectSerializeException;
import org.xmlobjects.stream.XMLReadException;
import org.xmlobjects.stream.XMLReader;
import org.xmlobjects.stream.XMLWriteException;
import org.xmlobjects.stream.XMLWriter;
import org.xmlobjects.xml.Attributes;
import org.xmlobjects.xml.Element;
import org.xmlobjects.xml.Namespaces;

import javax.xml.namespace.QName;

@XMLElement(name = "DoorSurface", namespaceURI = CityGMLConstants.CITYGML_3_0_CONSTRUCTION_NAMESPACE)
public class DoorSurfaceAdapter extends AbstractFillingSurfaceAdapter<DoorSurface> {

    @Override
    public DoorSurface createObject(QName name, Object parent) throws ObjectBuildException {
        return new DoorSurface();
    }

    @Override
    public void buildChildObject(DoorSurface object, QName name, Attributes attributes, XMLReader reader) throws ObjectBuildException, XMLReadException {
        if (CityGMLConstants.CITYGML_3_0_CONSTRUCTION_NAMESPACE.equals(name.getNamespaceURI())) {
            switch (name.getLocalPart()) {
                case "address":
                    object.getAddresses().add(reader.getObjectUsingBuilder(AddressPropertyAdapter.class));
                    return;
                case "adeOfDoorSurface":
                    ADEBuilderHelper.addADEProperty(object, GenericADEOfDoorSurface::of, reader);
                    return;
            }
        }

        super.buildChildObject(object, name, attributes, reader);
    }

    @Override
    public Element createElement(DoorSurface object, Namespaces namespaces) throws ObjectSerializeException {
        return Element.of(CityGMLConstants.CITYGML_3_0_CONSTRUCTION_NAMESPACE, "DoorSurface");
    }

    @Override
    public void writeChildElements(DoorSurface object, Namespaces namespaces, XMLWriter writer) throws ObjectSerializeException, XMLWriteException {
        super.writeChildElements(object, namespaces, writer);

        if (object.isSetAddresses()) {
            for (AddressProperty property : object.getAddresses())
                writer.writeElementUsingSerializer(Element.of(CityGMLConstants.CITYGML_3_0_CONSTRUCTION_NAMESPACE, "address"), property, AddressPropertyAdapter.class, namespaces);
        }

        for (ADEOfDoorSurface property : object.getADEProperties(ADEOfDoorSurface.class))
            ADESerializerHelper.writeADEProperty(Element.of(CityGMLConstants.CITYGML_3_0_CONSTRUCTION_NAMESPACE, "adeOfDoorSurface"), property, namespaces, writer);
    }
}


text:
package org.jetbrains.plugins.github.api;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Date;

/**
 * @author Aleksey Pivovarov
 */
@SuppressWarnings({"UnusedDeclaration", "ConstantConditions"})
class GithubPullRequestRaw implements DataConstructor {
  @Nullable public Long number;
  @Nullable public String state;
  @Nullable public String title;
  @Nullable public String body;
  @Nullable public String bodyHtml;

  @Nullable public String url;
  @Nullable public String htmlUrl;
  @Nullable public String diffUrl;
  @Nullable public String patchUrl;
  @Nullable public String issueUrl;

  @Nullable public Boolean merged;
  @Nullable public Boolean mergeable;

  @Nullable public Integer comments;
  @Nullable public Integer commits;
  @Nullable public Integer additions;
  @Nullable public Integer deletions;
  @Nullable public Integer changedFiles;

  @Nullable public Date createdAt;
  @Nullable public Date updatedAt;
  @Nullable public Date closedAt;
  @Nullable public Date mergedAt;

  @Nullable public GithubUserRaw user;

  @Nullable public LinkRaw head;
  @Nullable public LinkRaw base;

  public static class LinkRaw {
    @Nullable public String label;
    @Nullable public String ref;
    @Nullable public String sha;

    @Nullable public GithubRepoRaw repo;
    @Nullable public GithubUserRaw user;

    @NotNull
    public GithubPullRequest.Link create() {
      return new GithubPullRequest.Link(label, ref, sha, repo.createRepo(), user.createUser());
    }
  }

  @NotNull
  public GithubPullRequest createPullRequest() {
    return new GithubPullRequest(number, state, title, bodyHtml, htmlUrl, diffUrl, patchUrl, issueUrl, createdAt, updatedAt, closedAt, mergedAt,
                                 user.createUser(), head.create(), base.create());
  }

  @SuppressWarnings("unchecked")
  @NotNull
  @Override
  public <T> T create(@NotNull Class<T> resultClass) {
    if (resultClass == GithubPullRequest.class) {
      return (T)createPullRequest();
    }

    throw new ClassCastException(this.getClass().getName() + ": bad class type: " + resultClass.getName());
  }
}


text:
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/
//
// 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.

namespace Castle.Facilities.WcfIntegration
{
	using System.ServiceModel;

	public static class WcfContextChannel
	{
		public static IContextChannel For(object target)
		{
			var channelHolder = target as IWcfChannelHolder;
			return (channelHolder != null) ? channelHolder.Channel as IContextChannel : null;
		}
	}
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Machilus minutiloba S.K.Lee

### Remarks
null


text:
<?php

$loader = require __DIR__ . "/../vendor/autoload.php";
$loader->add('JobQueue\\', __DIR__);
$loader->add('JobQueue\ConsumerCommand\\', __DIR__ . '/Consumers/');


text:
Changelog
=========

> **Tags:**
> - :boom:       [Breaking Change]
> - :rocket:     [New Feature]
> - :bug:        [Bug Fix]
> - :memo:       [Documentation]
> - :house:      [Internal]
> - :nail_care:  [Polish]

## v3.18.0 (2022-03-04)

#### :boom: Breaking Change

* If an element destructor returns `true` then the element won't be destroyed

## v3.0.0-rc.210 (2021-07-07)

#### :bug: Bug Fix

* `waitForceRender` should allow the initial render of a component

## v3.0.0-rc.209 (2021-07-06)

#### :rocket: New Feature

* Added possibility to provide the element to drop via a function

## v3.0.0-rc.208 (2021-06-29)

#### :bug: Bug Fix

* Don't render empty iterables
* Fixed infinity loop with `waitForceRender`

## v3.0.0-rc.207 (2021-06-28)

#### :bug: Bug Fix

* Fixed emitting of `asyncRenderComplete`

## v3.0.0-rc.206 (2021-06-28)

#### :bug: Bug Fix

* Fixed a bug when async rendered components don't call their destructors after removing from DOM

## v3.0.0-rc.205 (2021-06-24)

#### :bug: Bug Fix

* Now all operations that are registered by asyncRender use only `async`, but not `$async`
* Fixed a bug when rendered chunk are destroyed after creation when passed a custom async group

## v3.0.0-rc.204 (2021-06-23)

#### :boom: Breaking Change

* Now to iterate objects is used `Object.entries`
* Now `filter` with a negative value removes elements from the render queue

## v3.0.0-rc.194 (2021-05-28)

#### :bug: Bug Fix

* Fixed a bug with referencing a closure' value in the `iterate` method

## v3.0.0-rc.192 (2021-05-27)

#### :rocket: New Feature

* Added a new event `asyncRenderChunkComplete`

#### :bug: Bug Fix

* Prevented the infinity loop when passing non-iterable objects to `iterate`

## v3.0.0-rc.191 (2021-05-24)

#### :rocket: New Feature

* Added overloads for infinite iterators
* Added `waitForceRender`

## v3.0.0-rc.147 (2021-02-18)

#### :rocket: New Feature

* Emit an event when async rendering is completed

## v3.0.0-rc.138 (2021-02-04)

#### :rocket: New Feature

* Added a new parameter `TaskParams.useRAF`

## v3.0.0-rc.131 (2021-01-29)

#### :house: Internal

* Now all tasks will execute on `requestAnimationFrame`

## v3.0.0-rc.112 (2020-12-18)

#### :bug: Bug Fix

* Fixed providing of render groups

## v3.0.0-rc.105 (2020-12-09)

#### :rocket: New Feature

* Added the default value to `iterate/slice`

#### :bug: Bug Fix

* Fixed a bug with redundant `v-for` invokes
* Fixed a bug when `iterate` takes the rejected promise
* Fixed the global blocking of rendering when using a filter that returns a promise

## v3.0.0-rc.100 (2020-11-17)

#### :rocket: New Feature

* Added support of filters with promises

## v3.0.0-rc.68 (2020-09-23)

#### :boom: Breaking Change

* Renamed `TaskI.list` -> `TaskI.iterable`
* Renamed `TaskOptions` -> `TaskParams`

#### :bug: Bug Fix

* Fixed rendering of arrays

## v3.0.0-rc.46 (2020-07-31)

#### :house: Internal

* Fixed ESLint warnings


text:
/**
 * @fileOverview Pagination Middleware.
 */

var __ = require('lodash');
var Promise = require('bluebird');
var cip = require('cip');
var url = require('url');
var Link = require('httplink');

var pagination = require('pagination');

/**
 * The Pagination Middleware.
 *
 * @param {Object} Crude options.
 * @contructor
 */
var Pagination = module.exports = cip.extend(function(opts) {
  this.crudeOpts = opts;
});

/**
 * Prepare and configure a pagination middleware.
 *
 * @param {CrudBase} crude The Crude Base instance.
 * @param {Object=} optObj a hash with options.
 * @return {Function} The middleware.
 */
Pagination.prototype.paginate = function(crude, optOpts) {
  var defaultOpts = {
    limit: 6,
    query: null,
  };
  var opts = __.extend(optOpts || {}, defaultOpts);

  this.crude = crude;
  return this._paginateMiddleware.bind(this, opts);
};

/**
 * First Middleware
 *
 * @param {Object} opt a hash with options.
 * @param {Object} req The request Object.
 * @param {Object} res The response Object.
 * @param {Function(Error)} next Express callback.
 * @return {Promise} A promise.
 * @private
 */
Pagination.prototype._paginateMiddleware = Promise.method(function(opts, req,
  res, next) {

  var queryShow = parseInt(req.query.show, 10);
  var page = parseInt(req.query.page, 10) || 1;
  var limit = queryShow || opts.limit;
  var skip = (page - 1) * limit;

  var query = opts.query;
  if (typeof this.crude.opts.paginateQuery === 'function') {
    query = this.crude.opts.paginateQuery(req);
  }
  if (!__.isObject(query)) {
    query = {};
  }
  if (this.crude.opts.ownUser) {
    query[this.crude.opts.ownUserSchemaProperty] =
      req[this.crude.opts.ownUserRequestProperty];
  }

  var self = this;
  return this.getLimitAndCount(query, skip, limit)
    .then(function(results) {
    var items = results[0];
    var count = results[1];

    if (!items || !__.isArray(items)) {
      items = [];
    }

    var paginator = pagination.create('search', {
      prelink: url.parse(req.url).pathname,
      current: page,
      rowsPerPage: limit,
      totalResult: count,
    });

    if (self.crude.isJson(req)) {
      var port = req.app.settings.port;
      var paginatorData = paginator.getPaginationData();

      var links = '<' + req.protocol + '://' + req.host;
      if (['80', '443'].indexOf(port + '') === -1) {
        links += ':' + port;
      }

      var link = new Link();
      var httplink = link.protocol(req.protocol)
        .data(paginatorData)
        .host(req.host)
        .port(port)
        .path(req.path)
        .rel('next')
        .show(queryShow)
        .next()
        .rel('last')
        .end()
        .get();
      res.set('Link', httplink);

      var cleanItems = self.crude.hidePrivatesArray(items);
      res.json(200, cleanItems);
      return next();
    }

    res.locals.pagination = paginator.render();
    res.locals.items = items;
    res.locals.count = count;
    next();
  }).catch(next);
});

/**
 * Get a limited set of records and the total count.
 *
 * @param {?Object} query Narrow down the set, set to null for all.
 * @param {number} skip starting position.
 * @param {number} limit how many records to fetch.
 * @return {Promise} A promise.
 */
Pagination.prototype.getLimitAndCount = function(query, skip, limit) {
  return Promise.all([
    this.crude.entity[this.crude.opts.entityReadLimit](query, skip, limit),
    this.crude.entity[this.crude.opts.entityCount](query),
  ]);
};


text:
Tasks = new Mongo.Collection('tasks');

if (Meteor.isClient) {

  // Configure the accounts UI to use usernames instead of email addresses
  Accounts.ui.config({
    passwordSignupFields: "USERNAME_ONLY"
  });

  // This code only runs on the client
  angular.module('simple-todos',['angular-meteor', 'accounts.ui']);

 angular.module('simple-todos').controller('TodosListCtrl', ['$scope', '$meteor',
    function ($scope, $meteor) {

	  $scope.$meteorSubscribe('tasks');

	  // Call the data from mongo collection database
      $scope.tasks = $meteor.collection( function() {
        return Tasks.find($scope.getReactively('query'), {sort: {createdAt: -1}})
      });

	  // Insert the data into mongo collection database	- non-secure way
	  /*
	  $scope.addTask = function (newTask) {
        $scope.tasks.push( {
          text: newTask,
          createdAt: new Date(),             // current time
          owner: Meteor.userId(),            // _id of logged in user
          username: Meteor.user().username }  // username of logged in user
        );
      };
	  */

	  // Secured way of insert, update & remove
	  $scope.addTask = function (newTask) {
        $meteor.call('addTask', newTask);
      };

      $scope.deleteTask = function (task) {
        $meteor.call('deleteTask', task._id);
      };

      $scope.setChecked = function (task) {
        $meteor.call('setChecked', task._id, !task.checked);
      };

	  $scope.setPrivate = function (task) {
        $meteor.call('setPrivate', task._id, ! task.private);
      };
	  // Mongo filter API
	  $scope.$watch('hideCompleted', function() {
        if ($scope.hideCompleted)
          $scope.query = {checked: {$ne: true}};
        else
          $scope.query = {};
      });

	  // Set Private Tasks
	  $scope.setPrivate = function (task) {
        $meteor.call('setPrivate', task._id, ! task.private);
      };

	  // Count imcomplete tasks
	   $scope.incompleteCount = function () {
        return Tasks.find({ checked: {$ne: true} }).count();
      };

    }]);
}

Meteor.methods({
  addTask: function (text) {
    // Make sure the user is logged in before inserting a task
    if (! Meteor.userId()) {
      throw new Meteor.Error('not-authorized');
    }

    Tasks.insert({
      text: text,
      createdAt: new Date(),
      owner: Meteor.userId(),
      username: Meteor.user().username
    });
  },
  deleteTask: function (taskId) {
    var task = Tasks.findOne(taskId);
    if (task.private && task.owner !== Meteor.userId()) {
      // If the task is private, make sure only the owner can check it off
      throw new Meteor.Error('not-authorized');
    }

    Tasks.update(taskId, { $set: { checked: setChecked} });
  },
  setChecked: function (taskId, setChecked) {
    Tasks.update(taskId, { $set: { checked: setChecked} });
   },
  setPrivate: function (taskId, setToPrivate) {
    var task = Tasks.findOne(taskId);

    // Make sure only the task owner can make a task private
    if (task.owner !== Meteor.userId()) {
      throw new Meteor.Error('not-authorized');
    }

    Tasks.update(taskId, { $set: { private: setToPrivate } });
  }
});

if (Meteor.isServer) {
  Meteor.publish('tasks', function () {
    return Tasks.find({
      $or: [
        { private: {$ne: true} },
        { owner: this.userId }
      ]
    });
  });
}


text:
package org.md2k.mcerebrum.UI.check_update;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;

import org.md2k.mcerebrum.ActivityMain;
import org.md2k.mcerebrum.Constants;
import org.md2k.mcerebrum.MyApplication;
import org.md2k.mcerebrum.R;
import org.md2k.mcerebrum.commons.dialog.Dialog;
import org.md2k.mcerebrum.commons.dialog.DialogCallback;
import org.md2k.mcerebrum.core.access.appinfo.AppAccess;
import org.md2k.mcerebrum.core.access.appinfo.AppBasicInfo;
import org.md2k.mcerebrum.core.constant.MCEREBRUM;
import org.md2k.mcerebrum.core.internet.download.DownloadInfo;
import org.md2k.mcerebrum.configuration.ConfigManager;
import org.md2k.mcerebrum.system.appinfo.AppInstall;
import org.md2k.mcerebrum.system.appinfo.BroadCastMessage;
import org.md2k.mcerebrum.system.update.Update;

import java.util.ArrayList;

import es.dmoral.toasty.Toasty;
import rx.Observable;
import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

import static org.md2k.mcerebrum.menu.AbstractMenu.MENU_APP_ADD_REMOVE;

public class ActivityCheckUpdate extends AppCompatActivity {
    Subscription subscription;
    Subscription subscriptionUpdate;
    Subscription subscriptionInstall;
    MaterialDialog materialDialogInstall;
    int installAllIndex = -1;
    boolean res=false;
    boolean isUpdateUI = false;
    ArrayList<String> packageNames;

    MaterialDialog materialDialog;
    boolean hasUpdate;
    String studyPackageName;
    private boolean updateYes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        updateYes=false;
        studyPackageName = getIntent().getStringExtra("STUDY");
        setContentView(R.layout.activity_check_update);
        packageNames=AppBasicInfo.get(this);
        BroadCastMessage.send(this, MCEREBRUM.APP_ACCESS.OP_DATAKIT_STOP);
        createInstallListener();
        materialDialog = new MaterialDialog.Builder(this)
                .content("Checking updates ...")
                .progress(true, 100, false)
                .show();
        subscription = Observable.just(true).subscribeOn(Schedulers.newThread()).flatMap(new Func1<Boolean, Observable<Boolean>>() {
                    @Override
                    public Observable<Boolean> call(Boolean aBoolean) {
                        return Update.checkUpdate(ActivityCheckUpdate.this).observeOn(AndroidSchedulers.mainThread());
                    }
                }).subscribe(new Observer<Boolean>() {
                    @Override
                    public void onCompleted() {
                        materialDialog.dismiss();
                        if (!hasUpdate) {
                            Toasty.success(ActivityCheckUpdate.this, "up-to-date", Toast.LENGTH_SHORT).show();
                            updateYes=false;
                            finish();
                        } else {
                            Dialog.simple(ActivityCheckUpdate.this, "Update Available", "Do you want to update?", "Yes", "Cancel", new DialogCallback() {
                                @Override
                                public void onSelected(String value) {
                                    if ("Yes".equals(value)) {
                                        updateYes=true;
                                        subscriptionUpdate = Update.checkUpdateServer(ActivityCheckUpdate.this).subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
                                                .flatMap(new Func1<Boolean, Observable<Boolean>>() {
                                                    @Override
                                                    public Observable<Boolean> call(Boolean aBoolean) {
                                                        if (aBoolean) {
                                                            return ConfigManager.updateConfigServer(MyApplication.getContext(), Constants.CONFIG_ROOT_DIR())
                                                                    .subscribeOn(Schedulers.newThread())
                                                                    .observeOn(AndroidSchedulers.mainThread()).map(new Func1<Boolean, Boolean>() {
                                                                        @Override
                                                                        public Boolean call(Boolean aBoolean) {
                                                                            return true;
                                                                        }
                                                                    });
                                                        }
                                                        else return Observable.just(true);
                                                    }
                                                }).flatMap(new Func1<Boolean, Observable<Boolean>>() {
                                                    @Override
                                                    public Observable<Boolean> call(Boolean aBoolean) {
                                                        return AppInstall.checkUpdate(ActivityCheckUpdate.this);
                                                    }
                                                }).subscribe(new Observer<Boolean>() {
                                                    @Override
                                                    public void onCompleted() {
                                                        if(res==true){
                                                            installAllIndex = 0;
                                                            downloadAndInstallAll();

                                                        }else{
                                                            updateYes=false;
                                                            finish();
                                                        }
                                                    }

                                                    @Override
                                                    public void onError(Throwable e) {
                                                        updateYes=false;
                                                        finish();
                                                    }

                                                    @Override
                                                    public void onNext(Boolean aBoolean) {
                                                        res=res | aBoolean;
                                                    }
                                                });

                                    } else {
                                        updateYes=false;
                                        finish();
                                    }
                                }
                            }).cancelable(false).show();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toasty.error(ActivityCheckUpdate.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                        materialDialog.dismiss();
                        updateYes=false;
                        finish();
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        hasUpdate = true;

                    }
                });

    }
    void installMCerebrumIfRequired() {
        String p = AppBasicInfo.getMCerebrum(this);
        String cv=AppInstall.getCurrentVersion(this, p);
        String lv=AppInstall.getLatestVersion(this, p);
        if(cv.equals(lv)){
            installAllIndex=-1;
            BroadCastMessage.send(this, MCEREBRUM.APP_ACCESS.OP_DATAKIT_STOP);
            updateYes=false;
            finish();
        }
        install(p);
    }
    void install(String packageName) {

        materialDialogInstall = new MaterialDialog.Builder(this)
                .content("Downloading " + AppBasicInfo.getTitle(this, packageName) + " ...")
                .progress(false, 100, true)
                .autoDismiss(false)
                .cancelable(false)
                .canceledOnTouchOutside(false)
                .negativeText("Cancel")
                .onNegative(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        installAllIndex=-1;
                        if(subscriptionInstall!=null && !subscriptionInstall.isUnsubscribed())
                            subscriptionInstall.unsubscribe();
                        if(materialDialogInstall!=null && materialDialogInstall.isShowing()) materialDialogInstall.dismiss();
                    }
                })
                .show();
        subscriptionInstall = AppInstall.install(this, packageName)
                .subscribeOn(Schedulers.computation())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<DownloadInfo>() {
                    @Override
                    public void onCompleted() {
                        materialDialogInstall.dismiss();
                        BroadCastMessage.send(ActivityCheckUpdate.this);
                    }

                    @Override
                    public void onError(Throwable e) {
                        Toasty.error(ActivityCheckUpdate.this, "Error: Download failed (e=" + e.toString() + ")").show();
                        materialDialogInstall.dismiss();
                        updateYes=false;
                        finish();
                    }

                    @Override
                    public void onNext(DownloadInfo downloadInfo) {
                        Log.d("abc", "total=" + downloadInfo.getTotalFileSize() + "downloaded=" + downloadInfo.getCurrentFileSize() + " progressWithBar=" + downloadInfo.getProgress());
                        materialDialogInstall.setProgress((int) downloadInfo.getProgress());
                    }
                });
    }
    void downloadAndInstallAll() {

        if (installAllIndex == -1) {

            BroadCastMessage.send(ActivityCheckUpdate.this, MCEREBRUM.APP_ACCESS.OP_DATAKIT_STOP);
            initStart();
            updateYes=false;
            finish();
            return;
        }
        installAllIndex=0;
        while (installAllIndex < packageNames.size()) {
            if (!AppInstall.hasUpdate(this, packageNames.get(installAllIndex)) || AppBasicInfo.getMCerebrum(this).equals(packageNames.get(installAllIndex)))
                installAllIndex++;
            else break;
        }
        if (installAllIndex >= packageNames.size()) {
            installMCerebrumIfRequired();
            return;
        }
        install(packageNames.get(installAllIndex));
        installAllIndex++;
/*
        downloadAndInstall(applicationManager.get()[installAllIndex].getInstallInfoController());
        applicationManager.get()[installAllIndex].getInstallInfoController().install(getActivity());
*/
/*
        if(applicationManager.get()[installAllIndex].getDownloadFromGithub()!=null || applicationManager.getAppInfos()[installAllIndex].getDownloadFromURL()!=null){
            downloadAndInstall(applicationManager.getAppInfos()[installAllIndex]);
        }
        else new AppInstall(applicationManager.getAppInfos()[installAllIndex]).install(getActivity());
*/
    }

    @Override
    public void onResume() {
        if (isUpdateUI && updateYes) {
            isUpdateUI = false;
            downloadAndInstallAll();
        }
        super.onResume();
    }
    @Override
    public void onPause(){
        super.onPause();
        if(subscriptionInstall!=null && !subscriptionInstall.isUnsubscribed())
            subscriptionInstall.unsubscribe();
        if(materialDialogInstall!=null && materialDialogInstall.isShowing())materialDialogInstall.dismiss();
        isUpdateUI=true;
    }

    @Override
    public void onDestroy(){
        unregisterReceiver(br);
        if (materialDialog != null && materialDialog.isShowing()) materialDialog.dismiss();
        if (materialDialogInstall != null && materialDialogInstall.isShowing()) materialDialogInstall.dismiss();
        if (subscriptionInstall != null && !subscriptionInstall.isUnsubscribed())
            subscriptionInstall.unsubscribe();
        if (subscription != null && !subscription.isUnsubscribed())
            subscription.unsubscribe();
        if (subscriptionUpdate != null && !subscriptionUpdate.isUnsubscribed())
            subscriptionUpdate.unsubscribe();
        if(studyPackageName!=null){
            AppAccess.launch(this, studyPackageName);
        }
        super.onDestroy();
    }
    void createInstallListener(){
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_REPLACED);
        intentFilter.addAction(Intent.ACTION_PACKAGE_CHANGED);
        intentFilter.addDataScheme("package");
        registerReceiver(br, intentFilter);
    }
    private BroadcastReceiver br = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            switch (intent.getAction()) {
                case Intent.ACTION_PACKAGE_ADDED:
                case Intent.ACTION_PACKAGE_CHANGED:
                case Intent.ACTION_PACKAGE_REPLACED:
                case Intent.ACTION_PACKAGE_REMOVED:
                    String[] temp = intent.getData().toString().split(":");
                    String packageName;
                    if (temp.length == 1)
                        packageName = temp[0];
                    else if (temp.length == 2)
                        packageName = temp[1];
                    else packageName = "";
                    AppInstall.set(getApplicationContext(), packageName);
                    try {
                        Intent i = new Intent();
                        i.setComponent(new ComponentName(packageName, "org.md2k.mcerebrum.core.access.ActivityEmpty"));
                        startActivity(i);
                    }catch(Exception e){
                    }
                    if(installAllIndex==-1)
                        BroadCastMessage.send(ActivityCheckUpdate.this, MCEREBRUM.APP_ACCESS.OP_DATAKIT_STOP);
                    isUpdateUI = true;
                    break;
            }
        }
    };
    public void initStart(){
        ArrayList<String> packageNames=AppBasicInfo.get(this);
        for(int in=0;in<packageNames.size();in++) {
            String packageName =packageNames.get(in);
            try {
                Intent i = new Intent();
                i.setComponent(new ComponentName(packageName, "org.md2k.mcerebrum.core.access.ActivityEmpty"));
                startActivity(i);
            } catch (Exception ignored) {
            }
        }

    }

}


text:
<?php
#
# Portable PHP password hashing framework.
#
# Version 0.3 / elkarte.
#
# Written by Solar Designer <solar at openwall.com> in 2004-2006 and placed in
# the public domain.  Revised in subsequent years, still public domain.
#
# There's absolutely no warranty.
#
# The homepage URL for this framework is:
#
#	http://www.openwall.com/phpass/
#
# Please be sure to update the Version line if you edit this file in any way.
# It is suggested that you leave the main version number intact, but indicate
# your project name (after the slash) and add your own revision information.
#
# Please do not change the "private" password hashing method implemented in
# here, thereby making your hashes incompatible.  However, if you must, please
# change the hash type identifier (the "$P$") to something different.
#
# Obviously, since this code is in the public domain, the above are not
# requirements (there can be none), but merely suggestions.
#

class PasswordHash {
	var $itoa64;
	var $iteration_count_log2;
	var $portable_hashes;
	var $random_state;

	public function __construct( $iteration_count_log2, $portable_hashes )
	{
		$this->itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

		if ($iteration_count_log2 < 4 || $iteration_count_log2 > 31)
			$iteration_count_log2 = 8;
		$this->iteration_count_log2 = $iteration_count_log2;

		$this->portable_hashes = $portable_hashes;

		$this->random_state = microtime() . uniqid(rand(), TRUE);
	}

	protected function get_random_bytes($count)
	{
		$output = '';
		if (@is_readable('/dev/urandom') &&
		    ($fh = @fopen('/dev/urandom', 'rb'))) {
			$output = fread($fh, $count);
			fclose($fh);
		}

		if (strlen($output) < $count) {
			$output = '';
			for ($i = 0; $i < $count; $i += 16) {
				$this->random_state =
				    md5(microtime() . $this->random_state);
				$output .=
				    pack('H*', md5($this->random_state));
			}
			$output = substr($output, 0, $count);
		}

		return $output;
	}

	protected function encode64($input, $count)
	{
		$output = '';
		$i = 0;
		do {
			$value = ord($input[$i++]);
			$output .= $this->itoa64[$value & 0x3f];
			if ($i < $count)
				$value |= ord($input[$i]) << 8;
			$output .= $this->itoa64[($value >> 6) & 0x3f];
			if ($i++ >= $count)
				break;
			if ($i < $count)
				$value |= ord($input[$i]) << 16;
			$output .= $this->itoa64[($value >> 12) & 0x3f];
			if ($i++ >= $count)
				break;
			$output .= $this->itoa64[($value >> 18) & 0x3f];
		} while ($i < $count);

		return $output;
	}

	protected function gensalt_private($input)
	{
		$output = '$P$';
		$output .= $this->itoa64[min($this->iteration_count_log2 +
			((PHP_VERSION >= '5') ? 5 : 3), 30)];
		$output .= $this->encode64($input, 6);

		return $output;
	}

	protected function crypt_private($password, $setting)
	{
		$output = '*0';
		if (substr($setting, 0, 2) == $output)
			$output = '*1';

		$id = substr($setting, 0, 3);
		# We use "$P$", phpBB3 uses "$H$" for the same thing
		if ($id != '$P$' && $id != '$H$')
			return $output;

		$count_log2 = strpos($this->itoa64, $setting[3]);
		if ($count_log2 < 7 || $count_log2 > 30)
			return $output;

		$count = 1 << $count_log2;

		$salt = substr($setting, 4, 8);
		if (strlen($salt) != 8)
			return $output;

		# We're kind of forced to use MD5 here since it's the only
		# cryptographic primitive available in all versions of PHP
		# currently in use.  To implement our own low-level crypto
		# in PHP would result in much worse performance and
		# consequently in lower iteration counts and hashes that are
		# quicker to crack (by non-PHP code).
		if (PHP_VERSION >= '5') {
			$hash = md5($salt . $password, TRUE);
			do {
				$hash = md5($hash . $password, TRUE);
			} while (--$count);
		} else {
			$hash = pack('H*', md5($salt . $password));
			do {
				$hash = pack('H*', md5($hash . $password));
			} while (--$count);
		}

		$output = substr($setting, 0, 12);
		$output .= $this->encode64($hash, 16);

		return $output;
	}

	protected function gensalt_extended($input)
	{
		$count_log2 = min($this->iteration_count_log2 + 8, 24);
		# This should be odd to not reveal weak DES keys, and the
		# maximum valid value is (2**24 - 1) which is odd anyway.
		$count = (1 << $count_log2) - 1;

		$output = '_';
		$output .= $this->itoa64[$count & 0x3f];
		$output .= $this->itoa64[($count >> 6) & 0x3f];
		$output .= $this->itoa64[($count >> 12) & 0x3f];
		$output .= $this->itoa64[($count >> 18) & 0x3f];

		$output .= $this->encode64($input, 3);

		return $output;
	}

	protected function gensalt_blowfish($input)
	{
		# This one needs to use a different order of characters and a
		# different encoding scheme from the one in encode64() above.
		# We care because the last character in our encoded string will
		# only represent 2 bits.  While two known implementations of
		# bcrypt will happily accept and correct a salt string which
		# has the 4 unused bits set to non-zero, we do not want to take
		# chances and we also do not want to waste an additional byte
		# of entropy.
		$itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

		$output = '$2a$';
		$output .= chr(ord('0') + $this->iteration_count_log2 / 10);
		$output .= chr(ord('0') + $this->iteration_count_log2 % 10);
		$output .= '$';

		$i = 0;
		do {
			$c1 = ord($input[$i++]);
			$output .= $itoa64[$c1 >> 2];
			$c1 = ($c1 & 0x03) << 4;
			if ($i >= 16) {
				$output .= $itoa64[$c1];
				break;
			}

			$c2 = ord($input[$i++]);
			$c1 |= $c2 >> 4;
			$output .= $itoa64[$c1];
			$c1 = ($c2 & 0x0f) << 2;

			$c2 = ord($input[$i++]);
			$c1 |= $c2 >> 6;
			$output .= $itoa64[$c1];
			$output .= $itoa64[$c2 & 0x3f];
		} while (1);

		return $output;
	}

	public function HashPassword($password)
	{
		if ( strlen( $password ) > 4096 )
			return '*';

		$random = '';

		if (CRYPT_BLOWFISH == 1 && !$this->portable_hashes) {
			$random = $this->get_random_bytes(16);
			$hash =
			    crypt($password, $this->gensalt_blowfish($random));
			if (strlen($hash) == 60)
				return $hash;
		}

		if (CRYPT_EXT_DES == 1 && !$this->portable_hashes) {
			if (strlen($random) < 3)
				$random = $this->get_random_bytes(3);
			$hash =
			    crypt($password, $this->gensalt_extended($random));
			if (strlen($hash) == 20)
				return $hash;
		}

		if (strlen($random) < 6)
			$random = $this->get_random_bytes(6);
		$hash =
		    $this->crypt_private($password,
		    $this->gensalt_private($random));
		if (strlen($hash) == 34)
			return $hash;

		# Returning '*' on error is safe here, but would _not_ be safe
		# in a crypt(3)-like function used _both_ for generating new
		# hashes and for validating passwords against existing hashes.
		return '*';
	}

	public function CheckPassword($password, $stored_hash)
	{
		if ( strlen( $password ) > 4096 )
			return false;

		$hash = $this->crypt_private($password, $stored_hash);
		if ($hash[0] == '*')
			$hash = crypt($password, $stored_hash);

		return $this->_hash_equals($hash, $stored_hash);
	}

	/**
	 * Timing attack safe string comparison
	 *
	 * Unlike normal === comparisons where the function returns after the
	 * first non match, here the time taken is independent of the number of
	 * characters that match.
	 *
	 * @see http://php.net/manual/en/function.hash-equals.php#117101
	 *
	 * This function should be used to mitigate timing attacks; for instance,
	 * when testing crypt() password hashes.
	 *
	 * @param string $a
	 * @param string $b
	 *
	 * @return bool
	 */
	protected function _hash_equals($a, $b)
	{
		// PHP 5.6+
		if (function_exists('hash_equals'))
		{
			return hash_equals($a, $b);
		}

		$ret = strlen($a) ^ strlen($b);
		$ret |= array_sum(unpack("C*", $a ^ $b));

		return !$ret;
	}
}


text:
package de.nava.mlsample.domain;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.Collection;

@XmlRootElement(name = "products")
@XmlAccessorType(XmlAccessType.NONE)
public class Products {

    private Collection<Product> products;

    @XmlElement(name = "product")
    public Collection<Product> getProducts() {
        return products;
    }

    public void setProducts(Collection<Product> products) {
        this.products = products;
    }
}


text:
#define GLOBAL_OSandPlatform
#include "OSandPlatform.h"

#include "debug_shell.h"
#include "instr_task.h"

xTaskHandle *xLED1TaskHandle;
xTaskHandle *xStackTaskHandle;
xTaskHandle *xUSBCDCACMTaskHandle;
xTaskHandle *xDebugShellTaskHandle;
xTaskHandle *xInstrumentTaskHandle;

extern portTASK_FUNCTION(vUSBCDCACMTask, pvParameters); //in cdcacm.c
extern portTASK_FUNCTION(vStackTask, pvParamaters);
extern portTASK_FUNCTION(vInstrumentTask, pvParameters);
static portTASK_FUNCTION(vLEDTask1, pvParameters)
{
  (void)(pvParameters);//unused params
  while(1) {
    if (USBConfigured) {
      redOn(0);
      greenOn(1);
      delayms(50);
      greenOn(0);
      delayms(100);
      greenOn(1);
      delayms(50);
      greenOn(0);
      delayms(800);
    } else {
      redOn(1);
      taskYIELD();
    }
  }
}

int main(void)
{
  portBASE_TYPE qStatus = pdPASS;   // = 1, this, and pdFAIL = 0, are in projdefs.h

  // Now setup the clocks ...
  setupClocks();

  // Setup GPIOs
  setupGPIOs();

  redOn(1); greenOn(1);
  Delay(0x1FFFFF);
  redOn(0); greenOn(0);

  init_hiresTimer();
  setupTimers(); //HV turn-off timer

  //Fixup NVIC for FreeRTOS ...
  setupNVIC();

  // Create tasks
  // remember, stack size is in 32-bit words and is allocated from the heap ...

  qStatus = xTaskCreate(vUSBCDCACMTask, "USB Serial Task", 256, NULL, (tskIDLE_PRIORITY + 1UL),
                        (xTaskHandle *) &xUSBCDCACMTaskHandle);

  qStatus = xTaskCreate(vLEDTask1, "LED Task 1", 64, NULL, (tskIDLE_PRIORITY + 1UL),
                        (xTaskHandle *) &xLED1TaskHandle);

  qStatus = xTaskCreate(vStackTask, "Stacklight", 128, NULL, (tskIDLE_PRIORITY + 1UL),
                        (xTaskHandle *) &xStackTaskHandle);

  qStatus = xTaskCreate(vDebugShell, "Debug shell", 1024, NULL, (tskIDLE_PRIORITY + 1UL),
                        (xTaskHandle *) &xDebugShellTaskHandle);

  qStatus = xTaskCreate(vInstrumentTask, "Instrument task", 1024, NULL,  (tskIDLE_PRIORITY + 1UL),
                        (xTaskHandle *) &xInstrumentTaskHandle);

  (void) qStatus;

  // start the scheduler
  vTaskStartScheduler();

  /* Control should never come here */
  //DEBUGSTR("Scheduler Failure\n");
  while (1) {}
}

void vApplicationStackOverflowHook( xTaskHandle xTask __attribute__(( unused )), signed char *pcTaskName __attribute__(( unused )) )
{
  while (1) {
  }
  return;
}

void vApplicationMallocFailedHook( void ) {
  while (1) {
  }
  return;
}

//	vApplicationIdleHook() ...
//
//  will only be called if configUSE_IDLE_HOOK is set to 1 in FreeRTOSConfig.h.
//  It will be called on each iteration of the idle task.
//
//	It is essential that code added to this hook function never attempts
//	to block in any way (for example, call xQueueReceive() with a block time
//	specified, or call vTaskDelay()).  If the application makes use of the
//	vTaskDelete() API function (as this demo application does) then it is also
//	important that vApplicationIdleHook() is permitted to return to its calling
//	function, because it is the responsibility of the idle task to clean up
//	memory allocated by the kernel to any task that has since been deleted.
//
void vApplicationIdleHook( void ) {
  // jjones:  I have configured to use the IdleHook, but don't
  //          really have anything for it do do... yet.
  //          The default behavior is just to surrender to the tick ...
  __WFI();
  // What is shown below is from an LWIP and USB-CDC demo, where the idle task
  // lazy-dumps characters out the USB port.  I include it as a tutorial on
  // using the TickCount (or some other higher-res timer) to  prevent the
  // idle task from churning, or sending any faster than necessary.

  //  static portTickType xLastTx = 0;
  //  char cTxByte;
  //
  //  /* The idle hook simply sends a string of characters to the USB port.
  //  	 The characters will be buffered and sent once the port is connected. */
  //  if( ( xTaskGetTickCount() - xLastTx ) > mainUSB_TX_FREQUENCY ) {
  //  	xLastTx = xTaskGetTickCount();
  //  	for( cTxByte = mainFIRST_TX_CHAR; cTxByte <= mainLAST_TX_CHAR; cTxByte++ ) {
  //  	  vUSBSendByte( cTxByte );
  //  	}
  //  }
} // end vApplicationIdleHook

// FreeRTOS application tick hook
void vApplicationTickHook(void)
{}

void _exit(int status __attribute__(( unused )) )
{
  //TRIG_HARDFAULT;
  while (1) ;
}


text:
The github repository of Tfe RSS has moved to Framagit.

[New repostiroy here!](https://git.framasoft.org/tfeserver/tfe-rss)


text:
package io.cattle.platform.engine.process;

import io.cattle.platform.engine.manager.impl.ProcessRecord;
import io.cattle.platform.lock.definition.LockDefinition;

import java.util.Map;

public interface ProcessState {

    String getResourceId();

    Object getResource();

    LockDefinition getProcessLock();

    String getState();

    ProcessPhase getPhase();

    void setPhase(ProcessPhase phase);

    Map<String,Object> getData();

    boolean shouldCancel(ProcessRecord record);

    boolean isDone(boolean schedule);

    boolean isStart(ProcessRecord record);

    boolean isTransitioning();

    void reload();

    String setTransitioning();

    String setDone();

    Map<String,Object> convertData(Object data);

    void applyData(Map<String,Object> data);

}


text:
title: eSpeak text to speech
date: 2016-06-21 17:46:46
tags:
- Text to Speech
- General Tools
- Communication
- Accessing the Web
- Alternative Access
- Learning and Education
- General Tools

---

{% alert info no-icon %}
eSpeak is a compact free and open source software speech synthesizer for English and other languages, for Linux and Windows.
{% endalert %}

From the developer:
-------------------

 eSpeak uses a ""formant synthesis"" method. This allows many languages to be provided in a small size. The speech is clear, and can be used at high speeds, but is not as natural or smooth as larger synthesizers which are based on human speech recordings.

 eSpeak is available as:

- A command line program (Linux and Windows) to speak text from a file or from stdin.
- A shared library version for use by other programs. (On Windows this is a DLL).
- A SAPI5 version for Windows, so it can be used with screen-readers and other programs that support the Windows SAPI5 interface.
- eSpeak has been ported to other platforms, including Solaris and Mac OSX.

### Features.

- Includes different Voices, whose characteristics can be altered.
- Can produce speech output as a WAV file.
- SSML (Speech Synthesis Markup Language) is supported (not complete), and also HTML.
- Compact size. The program and its data, including many languages, totals about 1.4 Mbytes.
- **Can be used as a front-end to MBROLA diphone voices,** see mbrola.html. eSpeak converts text to phonemes with pitch and length information.
- Can translate text into phoneme codes, so it could be adapted as a front end for another speech synthesis engine.
- Potential for other languages. Several are included in varying stages of progress. Help from native speakers for these or other languages is welcome.
- Development tools are available for producing and tuning phoneme data.

### Links:
- Contact Address
- Project Home Page

### Download: http://espeak.sourceforge.net/download.html


text:
package user

import (
	"context"
	"fmt"
	"io"
	"os"
	"path/filepath"

	"github.com/influxdata/influx-cli/v2/pkg/tabwriter"
	"github.com/influxdata/influxdb/v2"
	"github.com/influxdata/influxdb/v2/bolt"
	"github.com/influxdata/influxdb/v2/logger"
	"github.com/influxdata/influxdb/v2/tenant"
	"github.com/spf13/cobra"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

func NewUserCommand() *cobra.Command {
	base := &cobra.Command{
		Use:   "user",
		Short: "On-disk user management commands, for recovery",
		Args:  cobra.NoArgs,
		Run: func(cmd *cobra.Command, args []string) {
			cmd.PrintErrf("See '%s -h' for help\n", cmd.CommandPath())
		},
	}

	base.AddCommand(NewUserListCommand())
	base.AddCommand(NewUserCreateCommand())

	return base
}

type userListCommand struct {
	logger   *zap.Logger
	boltPath string
	out      io.Writer
}

func NewUserListCommand() *cobra.Command {
	var userCmd userListCommand
	cmd := &cobra.Command{
		Use:   "list",
		Short: "List users",
		RunE: func(cmd *cobra.Command, args []string) error {
			config := logger.NewConfig()
			config.Level = zapcore.InfoLevel

			newLogger, err := config.New(cmd.ErrOrStderr())
			if err != nil {
				return err
			}
			userCmd.logger = newLogger
			userCmd.out = cmd.OutOrStdout()
			return userCmd.run()
		},
	}

	defaultPath := filepath.Join(os.Getenv("HOME"), ".influxdbv2", "influxd.bolt")

	cmd.Flags().StringVar(&userCmd.boltPath, "bolt-path", defaultPath, "Path to the BoltDB file.")

	return cmd
}

func (cmd *userListCommand) run() error {
	ctx := context.Background()
	store := bolt.NewKVStore(cmd.logger.With(zap.String("system", "bolt-kvstore")), cmd.boltPath)
	if err := store.Open(ctx); err != nil {
		return err
	}
	defer store.Close()
	tenantStore := tenant.NewStore(store)
	tenantService := tenant.NewService(tenantStore)
	filter := influxdb.UserFilter{}
	users, _, err := tenantService.FindUsers(ctx, filter)
	if err != nil {
		return err
	}

	return PrintUsers(ctx, cmd.out, users)
}

type userCreateCommand struct {
	logger   *zap.Logger
	boltPath string
	out      io.Writer
	username string
	password string
}

func NewUserCreateCommand() *cobra.Command {
	var userCmd userCreateCommand
	cmd := &cobra.Command{
		Use:   "create",
		Short: "Create new user",
		RunE: func(cmd *cobra.Command, args []string) error {
			config := logger.NewConfig()
			config.Level = zapcore.InfoLevel

			newLogger, err := config.New(cmd.ErrOrStderr())
			if err != nil {
				return err
			}
			userCmd.logger = newLogger
			userCmd.out = cmd.OutOrStdout()
			return userCmd.run()
		},
	}

	defaultPath := filepath.Join(os.Getenv("HOME"), ".influxdbv2", "influxd.bolt")
	cmd.Flags().StringVar(&userCmd.boltPath, "bolt-path", defaultPath, "Path to the BoltDB file")
	cmd.Flags().StringVar(&userCmd.username, "username", "", "Name of the user")
	cmd.Flags().StringVar(&userCmd.password, "password", "", "Password for new user")

	return cmd
}

func (cmd *userCreateCommand) run() error {
	ctx := context.Background()
	store := bolt.NewKVStore(cmd.logger.With(zap.String("system", "bolt-kvstore")), cmd.boltPath)
	if err := store.Open(ctx); err != nil {
		return err
	}
	defer store.Close()
	tenantStore := tenant.NewStore(store)
	tenantService := tenant.NewService(tenantStore)

	if cmd.username == "" {
		return fmt.Errorf("must provide --username")
	}
	if cmd.password == "" {
		return fmt.Errorf("must provide --password")
	}

	user := influxdb.User{
		Name: cmd.username,
	}

	if err := tenantService.CreateUser(ctx, &user); err != nil {
		return err
	}

	if err := tenantService.SetPassword(ctx, user.ID, cmd.password); err != nil {
		// attempt to delete new user because password failed
		if delErr := tenantService.DeleteUser(ctx, user.ID); delErr != nil {
			fmt.Fprintf(cmd.out, "Could not delete bad user %q after password set failed: %s", cmd.username, delErr)
		}
		return err
	}

	// Print all users now that we have added one
	filter := influxdb.UserFilter{}
	users, _, err := tenantService.FindUsers(ctx, filter)
	if err != nil {
		return err
	}
	return PrintUsers(ctx, cmd.out, users)
}

func PrintUsers(ctx context.Context, w io.Writer, v []*influxdb.User) error {
	headers := []string{"ID", "Name"}

	var rows []map[string]interface{}
	for _, u := range v {
		row := map[string]interface{}{
			"ID":   u.ID,
			"Name": u.Name,
		}
		rows = append(rows, row)
	}

	writer := tabwriter.NewTabWriter(w, false)
	defer writer.Flush()
	if err := writer.WriteHeaders(headers...); err != nil {
		return err
	}
	for _, row := range rows {
		if err := writer.Write(row); err != nil {
			return err
		}
	}
	return nil
}


text:
package io.debezium.connector.oracle.junit;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Marker annotation used togehter with {@link SkipTestDependingOnAdapterNameRule} JUnit rule, that allows
 * tests to not be skipped based on the adapter name that is being used for testing.
 *
 * @author Chris Cranford
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.TYPE })
public @interface SkipWhenAdapterNameIsNot {

    SkipWhenAdapterNameIsNot.AdapterName value();

    /**
     * Returns the reason why the test should be skipped.
     */
    String reason() default "";

    enum AdapterName {
        XSTREAM {
            @Override
            boolean isNotEqualTo(String adapterName) {
                return !adapterName.equalsIgnoreCase("xstream");
            }
        },
        LOGMINER {
            @Override
            boolean isNotEqualTo(String adapterName) {
                return !adapterName.equalsIgnoreCase("logminer");
            }
        };

        abstract boolean isNotEqualTo(String adapterName);
    }
}


text:
using System.Collections.Generic;
using FacetedWorlds.Reversi.Model;

namespace FacetedWorlds.Reversi.Client.NavigationModels
{
    public class RemoteMoveComparer : IComparer<Move>
    {
        public int Compare(Move x, Move y)
        {
            if (x.Index < y.Index)
                return -1;
            else if (x.Index > y.Index)
                return 1;
            else
                return 0;
        }
    }
}


text:
package com.sequenceiq.it.cloudbreak.action.v4.stack;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.recipe.AttachRecipeV4Response;
import com.sequenceiq.it.cloudbreak.CloudbreakClient;
import com.sequenceiq.it.cloudbreak.action.Action;
import com.sequenceiq.it.cloudbreak.context.TestContext;
import com.sequenceiq.it.cloudbreak.dto.stack.StackTestDto;
import com.sequenceiq.it.cloudbreak.log.Log;

public class StackAttachRecipeAction implements Action<StackTestDto, CloudbreakClient> {

    private static final Logger LOGGER = LoggerFactory.getLogger(StackAttachRecipeAction.class);

    @Override
    public StackTestDto action(TestContext testContext, StackTestDto testDto, CloudbreakClient client) throws Exception {
        Log.whenJson(LOGGER, " attach recipe to stack request:\n", testDto.getAttachRecipeV4Request());
        AttachRecipeV4Response response = client.getDefaultClient().stackV4Endpoint().attachRecipe(
                client.getWorkspaceId(),
                testDto.getAttachRecipeV4Request(),
                testDto.getName(),
                testContext.getActingUserCrn().getAccountId());
        Log.whenJson(LOGGER, " attach recipe to stack response:\n", response);
        return testDto;
    }
}


text:
name: Optimization
# add a short one line description of your project
desc: Implement a framework for model optimization
requirements:
# Student requirements:
 - Python
 - Basic familiarity with neural networks
difficulty: medium
issues:
# Related issues (if any)  to this project.
 - https://github.com/ctlearn-project/ctlearn/issues/89
mentors:
# First person in contact; mentors may change before project starts.
 - nietootein
 - bryankim96
 - rlopezcoto
initiatives:
 - GSOC
tags:
# Different technologies needed
 - python
 - tensorflow
collaborating_projects:
# suborganisation(s) to which this project belongs.
 - ctlearn
---

#### Description

CTLearn is a Python package for using deep learning to perform
analysis tasks on data from imaging atmospheric Cherenkov telescopes
(IACTs). These tasks may be either classification or regression
problems. This project would enable automated model optimization in
CTLearn.

The sensitivity of IACTs is mostly driven by our capability of
distinguishing gamma-ray induced events from cosmic-ray induced
events. The better our deep learning models are in telling these two
populations apart the better our reach in the gamma-ray Universe will
be. Therefore, optimizing our deep learning models has the potential
to make a difference in our view of the Universe at these energies.

In this project, the student will first learn how to use CTLearn to
train classification models that tell gamma-ray images from cosmic-ray
images apart and why this is important in the context of IACTs. Then,
the student will implement tools that will enable automated model
optimization in CTLearn, and will implement iterative grid and random
searches as a basic optimization procedure. Finally, the student will
run iterative, grid and random-search based optimizations for two of the
currently implemented models.

#### Milestones

##### GSOC CODING STARTS

* Install CTLearn and train a pre-existing benchmark model to verify that it runs correctly.
* Understand the technical and scientific goals of the project.

##### GSOC MIDTERM

* Implement the calculation of useful metrics from a prediction file.
* Implement iterative grid and random searches in (a)the hyperparameter (sub)space.
* Have all code and documentation in GitHub.

##### GSOC FINAL

* Complete coarse iterative grid and random searches for the single_tel model.
* Complete coarse iterative grid and random searches for the cnn_rnn model.
* Implement other optimization searches, e.g., random search, genetic algorithms, Bayesian optimization, etc. (time permitting).
* Have all code, documentation, and plots in GitHub.


text:
package org.everit.jetty.server.component.ecm.internal.servletcontext;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * Abstract manager class for ServletContext component.
 *
 * @param <KEY>
 *          The type of the key of the ServletContext element. E.g.: ServletKey
 * @param <ELEMENT>
 *          The type of the ServletContext element. E.g.: Servlet
 */
public abstract class AbstractServletContextElementManager<KEY, ELEMENT> {

  private Map<KEY, Integer> previousKeysWithPosition = Collections.emptyMap();

  protected abstract ELEMENT createNewElement(KEY newKey);

  protected abstract ELEMENT[] createNewElementArray(int length);

  /**
   * Generates a new Array for the new keys in the way that if there are keys from the old array,
   * those elements are re-used.
   *
   * @param newKeys
   *          The new key array.
   * @param previousElements
   *          The previous element array that was used by the ServletContext component.
   * @return The new element array.
   */
  public ELEMENT[] generateUpgradedElementArray(final KEY[] newKeys,
      final ELEMENT[] previousElements) {

    ELEMENT[] result = createNewElementArray(newKeys.length);

    for (int i = 0; i < newKeys.length; i++) {
      KEY newKey = newKeys[i];
      if ((previousElements == null) || (previousElements.length == 0)) {
        // The length of previousElements can be zero if the ServletHandler is freshly created
        result[i] = createNewElement(newKey);
      } else {
        Integer position = previousKeysWithPosition.get(newKey);
        if (position != null) {
          result[i] = previousElements[position];
        } else {
          result[i] = createNewElement(newKey);
        }
      }
    }

    return result;
  }

  /**
   * Updates the previous key array in the manager.
   *
   * @param keys
   *          The keys that are getting that are currently used in the ServletContext component (so
   *          next time they will be previous).
   */
  public void updatePrviousKeys(final KEY[] keys) {
    Map<KEY, Integer> updated = new HashMap<>(keys.length);
    for (int i = 0; i < keys.length; i++) {
      updated.put(keys[i], i);
    }
    previousKeysWithPosition = updated;
  }
}


text:
layout: post
title: Using form_for for nested resources in rails
categories: ruby-on-rails
---

Using object with `form_for` in rails in really nice things. But, it can get tricky when we need a form for nested resources. For example, we could have a `@result` resource, inside a `@course` resource. What should be done in these cases?

Rails guide gives us a hint at [here](guides.rubyonrails.org/form_helpers.html#relying-on-record-identification). The answer from this [StackOverflow question](http://stackoverflow.com/questions/2034700/form-for-with-nested-resources) also suggests same. But it has a gotcha!

I was trying to use the same form for a smart-join table (a join table with identifying objects). The table is `results` and both `students` and `courses` has many of them. So, I want a two-way implementation of inputting result.

1. Going from course side and inputting result for all of the enrolled students for that course

2. From Student side and inputting results for all courses of that particular student.

And **I want to use the same form**. Here, the problem arise. Should I use `form_for([@course, @result])` or `form_form([@student, @result])`?

The problem is solved by using just the object for the form, i.e `@result` and using url: option to fix route.

So, I finally used

    {% highlight ruby %}
    form_for(@result, url: {action: "create"})
    {% endhighlight %}

Which is much more convenient. I wish, I had known this before!

Hope, this helps some other rails folks!


text:
.powerPathNavigator .helm button.pressedButton, /* comment 1 */
.powerPathNavigator .helm button:active:not(.disabledButton),
.powerPathNavigator table.powerPathInfo th:active,
.powerPathNavigator table.powerPathInfo th:active + th:last-child {
}

/* comment 2 */
.powerPathNavigator .helm button.pressedButton,
.powerPathNavigator .helm button:active:not(.disabledButton) {
}

.foo,
/* comment 3 */
.bar {
   display: block;
}

/* comment 4 */
/* comment 5 */ .field /* comment 6 */
/* comment 7 */
/* comment 8 */ { /* comment 9 */
    /* comment 10 */
    background: green;
    /* comment 11 */
/* comment 12 */ } /* comment 13 */
/* comment 14 */

/* comment 15 */ .element /* comment 16 */ , /* comment 17 */ .element /* comment 18 */ {}
/* comment 19 */
.element
/* comment 20 */
,
/* comment 21 */
.element
/* comment 22 */
{}

/* comment 23 */ .element /* comment 24 */ .element /* comment 25 */ {}
/* comment 26 */
.element
/* comment 27 */
.element
/* comment 28 */
{}

/* comment 29 */ .element /* comment 30 */ > /* comment 31 */ .element /* comment 32 */ {}
/* comment 33 */
.element
/* comment 34 */
>
/* comment 35 */
.element
/* comment 36 */
{}

/* comment 37 */ .element /* comment 38 */ + /* comment 39 */ .element /* comment 40 */ {}
/* comment 41 */
.element
/* comment 42 */
+
/* comment 43 */
.element
/* comment 44 */
{}

/* comment 45 */ .element /* comment 46 */ ~ /* comment 47 */ .element /* comment 48 */ {}
/* comment 49 */
.element
/* comment 50 */
~
/* comment 51 */
.element
/* comment 52 */
{}

/* comment 53 */ .element /* comment 54 */ >>> /* comment 55 */ .element /* comment 56 */ {}
/* comment 57 */
.element
/* comment 58 */
>>>
/* comment 59 */
.element
/* comment 60 */
{}

a[/* comment 61 */target/* comment 62 */] {}
a[/* comment 63 */target/* comment 64 */=/* comment 65 */"_blank"/* comment 66 */] {}
a[/* comment 67 */target/* comment 68 */~=/* comment 69 */"_blank"/* comment 70 */] {}
a[/* comment 71 */target/* comment 72 */|=/* comment 73 */"_blank"/* comment 74 */] {}
a[/* comment 75 */target/* comment 76 */^=/* comment 77 */"_blank"/* comment 78 */] {}
a[/* comment 79 */target/* comment 80 */$=/* comment 81 */"_blank"/* comment 82 */] {}
a[/* comment 83 */target/* comment 84 */*=/* comment 85 */"_blank"/* comment 86 */] {}

[/* comment 87 */foo/* comment 88 */|/* comment 89 */att/* comment 90 */=/* comment 91 */val/* comment 92 */] {}
[/* comment 93 */*/* comment 94 */|/* comment 95 */att/* comment 96 */] {}
[/* comment 97 */|/* comment 98 */att/* comment 99 */] {}

a/* comment 100 */:/* comment 101 */active {}

a/* comment 102 */::/* comment 103 */after {}

p:lang(/* comment 104 */it/* comment 105 */) {}

span:nth-child(/* comment 106 */2n/* comment 107 */+/* comment 108 */1/* comment 109 */) {}

/* comment 110 */::-webkit-progress-bar {}

/* comment 111 */:matches(/* comment 112 */section/* comment 113 */,/* comment 114 */ article/* comment 115 */) /* comment 116 */ h1 {}

/* comment 117 */*/* comment 118 */ {}

/* comment 119 */#container/* comment 120 */{}

/* comment 121 */.error/* comment 122 */{}

/* comment 123 */a/* comment 124 */{}

input:not(/* comment 125 */[/* comment 126 */disabled/* comment 127 */]/* comment 128 */) {}

/* comment 129 */h1/* comment 130 */, /* comment 131 */h2/* comment 132 */,/* comment 133 */ h3/* comment 134 */ {}

/* comment 135 */.phone/* comment 136 */ { /* comment 137 */
        /* comment 138 */&_title/* comment 139 */ { /* comment 140 */
        width: 500px;
        /* comment 141 */body.is_dark/* comment 142 */ & /* comment 143 */{ /* comment 144 */
            color: white;
        /* comment 145 */ } /* comment 146 */
    /* comment 147 */ } /* comment 148 */

    /* comment 149 */ img/* comment 150 */ { /* comment 151 */
        display: block;
    /* comment 152 */ } /* comment 153 */
/* comment 154 */
} /* comment 155 */

@media (max-width: 500px) {
    /* comment 156 */ a /* comment 157 */ { /* comment 158 */
        /* comment 159 */b/* comment 160 */ {/* comment 161 */} /* comment 162 */
    /* comment 163 */ } /* comment 164 */
/* comment 165 */ } /* comment 166 */

/* comment 167 */ article /* comment 168 */ :--heading /* comment 169 */ + /* comment 170 */ p /* comment 171 */ {}

/* comment 172 */ .foo /* comment 173 */ :global /* comment 174 */.bar /* comment 175 */{}
/* comment 176 */ .foo /* comment 177 */ :global(/* comment 178 */.bar/* comment 179 */) /* comment 180 */ .baz /* comment 181 */ {}

/* comment 182 */ .foo /* comment 183 */ :local /* comment 184 */ .bar /* comment 185 */ {}
/* comment 186 */ .foo /* comment 187 */ :local(/* comment 188 */.foo/* comment 189 */) /* comment 190 */ .bar /* comment 191 */ {}

/* custom properties set & @apply rule */
:root {
    /* comments 192 */ --centered /* comments 193 */ : /* comments 194 */ {
        display: flex;
        align-items: center;
        justify-content: center;
    };
}


text:
<?php

namespace WindowsAzure\MediaServices\Templates;
use WindowsAzure\Common\Internal\Validate;
use WindowsAzure\Common\Internal\Utilities;

/**
 * Represents TokenVerificationKey abstract class used in media services
 *
 * @category  Microsoft
 * @package   WindowsAzure\MediaServices\Templates
 * @author    Azure PHP SDK <azurephpsdk@microsoft.com>
 * @copyright Microsoft Corporation
 * @license   http://www.apache.org/licenses/LICENSE-2.0  Apache License 2.0
 * @version   Release: 0.4.2_2016-04
 * @link      https://github.com/windowsazure/azure-sdk-for-php
 */
abstract class TokenVerificationKey
{

}


text:
using System.IO.Pipelines;
using Microsoft.AspNetCore.Http.Features;
using Microsoft.Extensions.Logging;

namespace Microsoft.AspNetCore.Http.Connections.Internal.Transports;

internal sealed partial class ServerSentEventsServerTransport : IHttpTransport
{
    private readonly PipeReader _application;
    private readonly string _connectionId;
    private readonly ILogger _logger;
    private readonly HttpConnectionContext? _connection;

    public ServerSentEventsServerTransport(PipeReader application, string connectionId, ILoggerFactory loggerFactory)
        : this(application, connectionId, connection: null, loggerFactory)
    { }

    public ServerSentEventsServerTransport(PipeReader application, string connectionId, HttpConnectionContext? connection, ILoggerFactory loggerFactory)
    {
        _application = application;
        _connectionId = connectionId;
        _connection = connection;

        // We create the logger with a string to preserve the logging namespace after the server side transport renames.
        _logger = loggerFactory.CreateLogger("Microsoft.AspNetCore.Http.Connections.Internal.Transports.ServerSentEventsTransport");
    }

    public async Task ProcessRequestAsync(HttpContext context, CancellationToken cancellationToken)
    {
        context.Response.ContentType = "text/event-stream";
        context.Response.Headers.CacheControl = "no-cache,no-store";
        context.Response.Headers.Pragma = "no-cache";

        // Make sure we disable all response buffering for SSE
        var bufferingFeature = context.Features.GetRequiredFeature<IHttpResponseBodyFeature>();
        bufferingFeature.DisableBuffering();

        context.Response.Headers.ContentEncoding = "identity";

        try
        {
            // Workaround for a Firefox bug where EventSource won't fire the open event
            // until it receives some data
            await context.Response.WriteAsync(":\r\n", cancellationToken);
            await context.Response.Body.FlushAsync(cancellationToken);
            while (true)
            {
                var result = await _application.ReadAsync(cancellationToken);
                var buffer = result.Buffer;

                try
                {
                    if (result.IsCanceled)
                    {
                        break;
                    }

                    if (!buffer.IsEmpty)
                    {
                        Log.SSEWritingMessage(_logger, buffer.Length);

                        _connection?.StartSendCancellation();
                        await ServerSentEventsMessageFormatter.WriteMessageAsync(buffer, context.Response.Body, _connection?.SendingToken ?? default);
                    }
                    else if (result.IsCompleted)
                    {
                        break;
                    }
                }
                finally
                {
                    _connection?.StopSendCancellation();
                    _application.AdvanceTo(buffer.End);
                }
            }
        }
        catch (OperationCanceledException)
        {
            // Closed connection
        }
    }

    private static partial class Log
    {
        [LoggerMessage(1, LogLevel.Trace, "Writing a {Count} byte message.", EventName = "SSEWritingMessage")]
        public static partial void SSEWritingMessage(ILogger logger, long count);
    }
}


text:
"use strict";

var Animation = require("./Animation");
var RequestAnimationFrame = require("./injectable/RequestAnimationFrame");
var CancelAnimationFrame = require("./injectable/CancelAnimationFrame");

import type { AnimationConfig, EndCallback } from "./Animation";

type DecayAnimationConfigSingle = AnimationConfig & {
  velocity: number,
  deceleration?: number
};

class DecayAnimation extends Animation {
  _startTime: number;
  _lastValue: number;
  _fromValue: number;
  _deceleration: number;
  _velocity: number;
  _onUpdate: (value: number) => void;
  _animationFrame: any;

  constructor(config: DecayAnimationConfigSingle) {
    super();
    this._deceleration =
      config.deceleration !== undefined ? config.deceleration : 0.998;
    this._velocity = config.velocity;
    this.__isInteraction =
      config.isInteraction !== undefined ? config.isInteraction : true;
  }

  start(
    fromValue: number,
    onUpdate: (value: number) => void,
    onEnd: ?EndCallback
  ): void {
    this.__active = true;
    this._lastValue = fromValue;
    this._fromValue = fromValue;
    this._onUpdate = onUpdate;
    this.__onEnd = onEnd;
    this._startTime = Date.now();
    this._animationFrame = RequestAnimationFrame.current(
      this.onUpdate.bind(this)
    );
  }

  onUpdate(): void {
    var now = Date.now();

    var value =
      this._fromValue +
      this._velocity /
        (1 - this._deceleration) *
        (1 - Math.exp(-(1 - this._deceleration) * (now - this._startTime)));

    this._onUpdate(value);

    if (Math.abs(this._lastValue - value) < 0.1) {
      this.__debouncedOnEnd({ finished: true });
      return;
    }

    this._lastValue = value;
    if (this.__active) {
      this._animationFrame = RequestAnimationFrame.current(
        this.onUpdate.bind(this)
      );
    }
  }

  stop(): void {
    this.__active = false;
    CancelAnimationFrame.current(this._animationFrame);
    this.__debouncedOnEnd({ finished: false });
  }
}

module.exports = DecayAnimation;


text:
<html>

<head>
    {% block head %}
    <title> {% block title %}{% endblock %} - My Application</title>
    {% endblock %}
</head>
{% block body %} {% endblock %}

</html>


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>Objective Chipmunk: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css"/>

Main Page

Related Pages

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Hierarchy

Class Members

ChipmunkStaticSegmentShape Member List

This is the complete list of members for ChipmunkStaticSegmentShape, including all inherited members.

	a	ChipmunkSegmentShape

- 	addToSpace: (defined in <ChipmunkBaseObject>)	<ChipmunkBaseObject>

	b	ChipmunkSegmentShape

	bb	ChipmunkShape

	body	ChipmunkShape

- 	cacheBB	ChipmunkShape

- 	chipmunkObjects	<ChipmunkObject>

	collisionType	ChipmunkShape

	data	ChipmunkShape

	data	ChipmunkShape

	elasticity	ChipmunkShape

	friction	ChipmunkShape

	group	ChipmunkShape

- 	initWithBody:from:to:radius:	ChipmunkSegmentShape

	layers	ChipmunkShape

	normal	ChipmunkSegmentShape

- 	pointQuery:	ChipmunkShape

	radius	ChipmunkSegmentShape

- 	removeFromSpace: (defined in <ChipmunkBaseObject>)	<ChipmunkBaseObject>

+ 	segmentWithBody:from:to:radius:	ChipmunkSegmentShape	 [static]

	sensor	ChipmunkShape

	shape	ChipmunkShape

	surfaceVel	ChipmunkShape

 All Classes Functions Properties

<address class="footer">Generated on Mon Dec 13 2010 18:43:39 for Objective Chipmunk by

 1.7.1 </address>


text:
<?php

include __DIR__.'./../../../src/chain_of_responsibility/FluffycatCom/ChianOfResponsibility/AbstractBookTopic.php';
include __DIR__.'./../../../src/chain_of_responsibility/FluffycatCom/ChianOfResponsibility/BookTopic.php';

use FluffycatCom\ChainOfResponsibility\BookTopic;

$b  = new BookTopic('a');
echo $b->getTopic(), PHP_EOL;


text:
import os, sublime, sublime_plugin, subprocess

# Array of required Node packages
packages = [

]

def conf_error(me):
    sublime.error_message("No packages specified in config")

def npm_error(me):
    import sys, webbrowser

    if sublime.ok_cancel_dialog("Some package dependencies could not be installed automatically. Please refer to the installation guide to resolve this problem.\n\nDo you want to open the website for this package?", "Open website"):
        webbrowser.open("https://packagecontrol.io/packages/"+me)
    sys.exit()

def plugin_loaded():
    from package_control import events
    from subprocess import check_call

    # Get name of package
    me = os.path.basename(os.path.dirname(os.path.realpath(__file__)))

    if events.install(me) or events.post_upgrade(me):

        # Get absolute package path
        package_path = sublime.packages_path() + '/' + me

        # Install packages specified in the array
        if len(packages) > 0:
            for package in packages:
                if package:
                    try:
                        os.chdir(package_path)
                        sublime.status_message("[%s] npm install -g %s" % ( me, package))
                        check_call(['npm', 'install', '-g',  package])
                        sublime.status_message("[%s] Completed" % me)

                    except subprocess.CalledProcessError:
                        npm_error(me)

                else:
                    conf_error(me)

        # Install packages from package.json
        elif len(packages) is 0 and os.path.isfile(package_path + "/package.json"):

            try:
                os.chdir(package_path)
                sublime.status_message("[%s] npm install" % me)
                check_call(['npm', 'install', '-g', '--production'])
                sublime.status_message("[%s] Completed" % me)

            except subprocess.CalledProcessError:
                npm_error(me)


text:
package com.hisun.loganalysis.controller;

import java.util.Collections;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hisun.index.PageQueryResult;
import com.hisun.loganalysis.service.HostMonitorService;
import com.hisun.util.StringUtil;

/**
 * 主机监测查询、统计
 * @author tdz
 * @company hisunpay 高阳通联
 * @website http://www.hisunpay.com
 * @date 2016年11月17日 下午3:45:26
 *
 */
@Controller
@RequestMapping("/hostMonitor")
public class HostMonitorController extends BaseController {

	/**
	 * 主机监测服务
	 */
	private HostMonitorService hostMonitorService;

	@Resource(name = "hostMonitorService")
	public void setHostMonitorService(HostMonitorService hostMonitorService) {
		this.hostMonitorService = hostMonitorService;
	}

	/**
	 * 查询主机监测日志
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping(value = "/listData")
	@ResponseBody
	public Map<String, Object> listData(HttpServletRequest req, HttpServletResponse resp) {

		String db = req.getParameter("db");
		String table = req.getParameter("table");
		String hostname = req.getParameter("hostname");
		String ipAddr = req.getParameter("ipAddr");
		String hwAddr = req.getParameter("hwAddr");
		String cpuUsage = req.getParameter("cpuUsage");
		String cpuUsageOpt = req.getParameter("cpuUsageOpt");
		String totalMemUsed = req.getParameter("totalMemUsed");
		String totalMemUsedOpt = req.getParameter("totalMemUsedOpt");
		String startTime = req.getParameter("startTime");
		String endTime = req.getParameter("endTime");
		Integer pageNo = Integer.parseInt(StringUtil.nvl(req.getParameter("pageNo"), DEFAULT_PAGE_NO));
		Integer pageSize = Integer.parseInt(StringUtil.nvl(req.getParameter("pageSize"), DEFAULT_PAGE_SIZE));
		String sortField = req.getParameter("sortField");
		String sort = req.getParameter("sort");

		try {
			String[] dbs = prepareDb(db, startTime, endTime, true);
			Long start = 0L;
			Long end = 0L;
			if(!StringUtil.isEmpty(startTime)) start = DEFAULT_SDF.parse(startTime).getTime();
			if(!StringUtil.isEmpty(startTime)) end = DEFAULT_SDF.parse(endTime).getTime();

			PageQueryResult ret = hostMonitorService.queryData(dbs, table, hostname, ipAddr, hwAddr,
					cpuUsage, cpuUsageOpt, totalMemUsed, totalMemUsedOpt,
					start, end, pageNo, pageSize, sortField, sort);
			logger.info("hostMonitorQuery,size:" + ret.getTotalSize() + ",used:" + ret.getUsetime());
			logger.debug("hostMonitorStat,ret:" + ret.getResultSet());
			return ret.toMap();
		} catch (Exception e) {
			errLogger.error("hostMonitorQuery error,msg:" + e.getMessage(), e);
		}

		return Collections.EMPTY_MAP;
	}

	/**
	 * 统计主机监测日志
	 * @param req
	 * @param resp
	 * @return
	 */
	@RequestMapping(value = "/statData")
	@ResponseBody
	public Map<Object, Object> statData(HttpServletRequest req, HttpServletResponse resp) {

		String db = req.getParameter("db");
		String table = req.getParameter("table");
		String hostname = req.getParameter("hostname");
		String ipAddr = req.getParameter("ipAddr");
		String hwAddr = req.getParameter("hwAddr");
		String startTime = req.getParameter("startTime");
		String endTime = req.getParameter("endTime");

		String[] dbs = prepareDb(db, startTime, endTime, true);
		Map<Object, Object> ret = Collections.EMPTY_MAP;

		try {
			long start = System.currentTimeMillis();
			ret =hostMonitorService.statData(dbs, table, hostname, ipAddr, hwAddr, startTime, endTime);
			logger.info("hostMonitorStat,used:" + (System.currentTimeMillis() - start));
			logger.debug("hostMonitorStat,ret:" + ret);
		} catch (Exception e) {
			errLogger.error("hostMonitorStat error,msg:" + e.getMessage(), e);
		}

		return ret;
	}
}


text:
import {Dispatcher} from 'flux';
class AppDispatcher extends Dispatcher{
    dispatch(action = {}) {
        console.log("Dispatched", action);
        super.dispatch(action);
    }
}

export default new AppDispatcher();


text:
package com.yofc.odn.production.dao.impl;

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

import com.yofc.odn.production.dao.SpecificationDao;
import com.yofc.odn.production.model.Specificationnum;

import javax.annotation.Resource;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;

@Component(value = "productionSpecificationDao")
public class SpecificationDaoImpl implements SpecificationDao{

	private SessionFactory sessionFactory;

	@Resource(name="sessionFactory")
	public void setSesionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	public Session getSession(){
		return this.sessionFactory.getCurrentSession();
	}

	@Override
	public List<Specificationnum> findUnfinishedByContractNum(String contractNum){
		String hql = "from productionSpecificationnum  where contract.contractNum = :contractNum and isFinished=:isFinished" ;
		List<Specificationnum> specificationnums = new ArrayList<Specificationnum>();
		specificationnums = this.getSession().createQuery(hql).setString("contractNum", contractNum).setInteger("isFinished", 0).list();
		return specificationnums;
	}

	@Override
	public Specificationnum findOneBySpecificationNumId(int specificationNumId) {
		String hql = "from productionSpecificationnum where specificationNumId = :specificationNumId" ;
		List<Specificationnum> sf = new ArrayList<Specificationnum>();
		sf = this.getSession().createQuery(hql).setInteger("specificationNumId", specificationNumId).list();
		return (sf != null && sf.size() > 0) ? sf.get(0) : null;
	}

	@Override
	public void updateSpecificationnum(Specificationnum specificationnum) {
		Session s = this.getSession();
		s.update(specificationnum);
		s.flush();
	}

	@Override
	public List<Specificationnum> findByFiberType(int contractId, char typeNameFlag) {
		if(contractId!=0){
			String hql = "from productionSpecificationnum  where contract.contractId = :contractId and fibertype.typeNameFlag = :typeNameFlag";
			List<Specificationnum> specificationnums = new ArrayList<Specificationnum>();
			specificationnums = this.getSession().createQuery(hql).setInteger("contractId", contractId).setCharacter("typeNameFlag", typeNameFlag).list();
			return specificationnums;
		}else{
			String hql = "from productionSpecificationnum  where fibertype.typeNameFlag = :typeNameFlag";
			List<Specificationnum> specificationnums = new ArrayList<Specificationnum>();
			specificationnums = this.getSession().createQuery(hql).setCharacter("typeNameFlag", typeNameFlag).list();
			return specificationnums;
		}

	}

}


text:
import { verifyJWTToken } from './libs/auth'

/*
  Verifies whether required arguments are passed with HTTP request
  • list: array - [String]
    - item: string
      * bot_id:params
*/
export function paramCheck(list)
{
  return (req, res, next) =>
  {
    const filterList = list.filter((el, index) =>
    {
      // split if possible - if not, set as array
      const _el = (el.includes(':')) ? el.split(':') : [el, 'query']
      const _paramList = req[_el[1]]

      return (Object.keys(_paramList).includes(_el[0]))
    })

    if (filterList.length !== list.length)
    {
      return res.status(400)
              .json({
                message: `Missing arguments`
              })
    }

    next()
  }
}

export function verifyJWT(req, res, next)
{
  let token = req.body.token || req.query.token

  verifyJWTToken(token)
    .then((decodedToken) =>
    {
      req.user = decodedToken.data
      next()
    })
    .catch((err) =>
    {
      res.status(400)
        .json({message: "Invalid auth token provided."})
    })
}


text:
package org.radargun.stages.test;

import java.util.concurrent.TimeUnit;

import org.radargun.utils.TimeService;
import org.radargun.utils.Utils;

/**
 * Time-based limitation of the stress test.
 *
 * @author Mircea Markus <Mircea.Markus@jboss.com>
 */
public class TimeStressorCompletion extends AbstractCompletion {

   private volatile long lastPrint = -1;
   private final long duration;
   private final long logFrequency = TimeUnit.SECONDS.toNanos(20);

   /**
    * @param duration Duration of the test in nanoseconds.
    */
   public TimeStressorCompletion(long duration, long requestPeriod) {
      super(requestPeriod);
      this.duration = TimeUnit.MILLISECONDS.toNanos(duration);
   }

   @Override
   public boolean moreToRun(int opNumber) {
      // Synchronize the start until someone is ready
      // we don't care about the race condition here
      long now = TimeService.nanoTime();
      if (startTime == -1) {
         startTime = now;
      }
      waitForNextRequest(opNumber, now);
      return now < startTime + duration;
   }

   @Override
   public void logProgress(int executedOps) {
      long now = TimeService.nanoTime();
      //make sure this info is not printed more frequently than 20 secs
      if (lastPrint < 0 || (now - lastPrint) < logFrequency) {
         return;
      }
      synchronized (this) {
         if (now - lastPrint < logFrequency) return;
         lastPrint = now;
         //make sure negative durations are not printed
         long remaining = Math.max(0, (startTime + duration) - now);
         log.infof(PROGRESS_STRING, executedOps, Utils.getNanosDurationString(now - startTime),
               Utils.getNanosDurationString(remaining), Utils.getNanosDurationString(duration));
      }
   }
}


text:
package com.github.mvollebregt.wildmock.fluentinterface;

import com.github.mvollebregt.wildmock.function.ActionABC;
import com.github.mvollebregt.wildmock.function.FunctionABC;

public class TriggerABC<A, B, C> extends Trigger {

    public TriggerABC(ActionABC<A, B, C> expectedCalls, Class<A> a, Class<B> b, Class<C> c) {
        super(expectedCalls, a, b, c);
    }

    public TriggerABC<A, B, C> with(FunctionABC<A, B, C, Boolean> predicate) {
        return new TriggerABC<>(this, predicate);
    }

    public void then(ActionABC<A, B, C> behaviour) {
        super.then(behaviour);
    }

    private TriggerABC(TriggerABC<A, B, C> source, FunctionABC<A, B, C, Boolean> predicate) {
        super(source, predicate);
    }
}


text:
package com.ditcherj.contextio.responses;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

/**
 * Created by Jonathan Ditcher on 02/04/2017.
 */
@JsonIgnoreProperties(ignoreUnknown=true)
public class SimpleResponse extends BaseResponse {

    private Boolean success;

    public SimpleResponse() {
    }

    public Boolean getSuccess() {
        return success;
    }

    public void setSuccess(Boolean success) {
        this.success = success;
    }

    @Override
    public String toString() {
        return "PostMessageResponse{" +
                "success=" + success +
                "} " + super.toString();
    }
}