text:
layout: project
title:  "Use my jekyll theme"
date:   2016-09-19 22:10:00 +0200
tags: ['english', 'jekyll', 'theme']
author: "Lukas Himsel"
---

## Hints

If you want to use my jekyll theme, follow the instructions and host it yourself. Easily setup as a Github page.

To add pages (for example a portfolio, an extra about page, and so on), you need to link them to the `index.html` manually. Required to configure in this dimensions is a bit of html and jekyll know-how. Reading the [Jekyll docs](http://jekyllrb.com/docs/pages/) could help. All other things are easy to edit and configure, even without much jekyll experience.

#### Theme features
- Projects showcase
- RSS and ATOM feed
- Blogpost pagination
- SEO meta tags, *schema.org* structured data
- [twitter](https://dev.twitter.com/cards/getting-started) cards
- made with MaterializeCSS
- Disqus comments

## Setup

### 1. Get the sources

#### 1.1 Clone

Clone the repository from github:
[https://github.com/lukas-h/material-theme.git](https://github.com/lukas-h/material-theme.git)

#### 1.2 or download
[https://github.com/lukas-h/material-theme/archive/gh-pages.zip](https://github.com/lukas-h/material-theme/archive/gh-pages.zip)

### 2. Configure
- Replace all the configuration in `_config.yml` and `_data/projects.yml` by your own data. Change the name, email address, configure your your language settings.
And most important: change the site's URL! Optionally add your google analytics ID.

- Put your address and legal info into `imprint.html`.

- Change the icon `images/favicon.png`.

- Replace the domain name in the `robots.txt`

- Don't forget the `README.md`.

### 3. Start writing posts
Replace the existing example post and then add your own!
Have a look at the [Jekyll docs](http://jekyllrb.com/docs/posts/)
about how to write blog posts.
To add tags to your posts, look into the example, you'll see that there is
a line starting with `tags:`. Add your keywords there.

### 4. You're done
Take a stop on the Github project page. Feel free to give a star and share it with others!
You have questions, feedback or something to improve, mail me or open issues on github. Contributions are always welcome.
Thanks to them who have already [helped](https://github.com/lukas-h/material-theme/graphs/contributors) to improve, especially [@varundey](https://github.com/varundey)!
See the [Github Project](https://github.com/lukas-h/material-theme)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FarseerPhysics.Dynamics;
using FarseerPhysics.Dynamics.Contacts;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace AITW
{
    internal class NPC : IBodyInfo
    {
        private Physics Physics { get; set; }
        private Level Level { get; set; }
        private Player Player { get; set; }
        private GameTime GameTime { get; set; }
        private int Damage { get; set; }
        private int Health { get; set; }

        private Vector2 Position { get; set; }

        private Character _character;

        private SpriteEffects _effect;
        private String _action;
        private String _facing;

        private Timer _timer;
        private Helpers _helpers;

        private const float MeterInPixels = 64f;

        public NPC(Level level, Physics physics, Player player, int damage, Vector2 position)
        {
            Physics = physics;
            Position = position;
            Player = player;
            Damage = damage;
            Level = level;
            _timer = new Timer(new TimeSpan(0, 1, 0, 0));
            _timer.TimerTick += TimerOnTimerTick;
            _helpers = new Helpers();
        }

        private void TimerOnTimerTick(object sender, EventArgs eventArgs)
        {
            try
            {
                Physics.SomeBodyCircle.ApplyLinearImpulse(new Vector2(0, -5), Physics.SomeBodyCircle.Position);

                _action = "stand";
                _facing = "right";
                _effect = SpriteEffects.None;
                _character.Update_Stand(GameTime);
            }
            catch
            {
            }

        }

        public Vector2 GetPosition()
        {
            try
            {
                return Physics.SomeBodyRectangle.Position*MeterInPixels;
            }
            catch
            {
                Console.WriteLine("Не удалось получить позицию NPC");
                return Vector2.Zero;
            }

        }

        public void LoadContent(ContentManager content, string characterName = "Dummy")
        {
            _character = new Character(characterName, content); // 32x64 -> 0.5m x 1m
        }

        public void CreateBody(Vector2 position)
        {
            var bodyPosition = new Vector2(position.X/MeterInPixels, position.Y/MeterInPixels);
            Physics.AddSomeBody(bodyPosition, Physics.TYPE_NPC);

            Physics.SomeBodyRectangle.OnCollision += SomeBodyRectangleOnOnCollision;
            Physics.SomeBodyCircle.OnSeparation += SomeBodyCircleOnOnSeparation;
        }

        private bool SomeBodyRectangleOnOnCollision(Fixture f1, Fixture f2, Contact contact)
        {
            if (f1.Body.UserData == Physics.TYPE_PLAYER || f2.Body.UserData == Physics.TYPE_PLAYER)
            {
                Player.Hurt(Damage);
            }
            return true;
        }

        public void SomeBodyCircleOnOnSeparation(Fixture f1, Fixture f2)
        {

        }

        public void Update(GameTime gameTime)
        {
            GameTime = gameTime;
            var xDist = Physics.DistanceBetweenBodies(Physics.SomeBodyRectangle, Physics.PlayerRectBody).X * MeterInPixels;
            if (Math.Abs(xDist) >= 128)
            {
                Console.WriteLine(xDist);
                if (xDist < 0)
                {
                    Physics.SomeBodyCircle.ApplyForce(new Vector2(10, 0),
                  Physics.SomeBodyCircle.Position);
                }
                else if (xDist > 0)
                {
                    Physics.SomeBodyCircle.ApplyForce(new Vector2(-10, 0),
                  Physics.SomeBodyCircle.Position);
                }

                _action = "stand";
                _facing = "right";
                _effect = SpriteEffects.None;
                _character.Update_Stand(GameTime);
            }

            _timer.Update(gameTime, Timer.TimerType.TenSeconds);
        }

        public void Draw(SpriteBatch batch)
        {
            var npcPos = Physics.SomeBodyRectangle.Position*MeterInPixels;
            _character.Draw(batch, npcPos, _effect, _action);
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
console.log('Hello SW123!');
const cacheName = 'cache';
self.addEventListener('install', function (e) {

    e.waitUntil(caches.open(cacheName).then(function (cache) {
        return cache.addAll([
            '/',
            '/index.html',
            '/bundle.js',
            '/vendors.js'
        ]);
    }));
});

self.addEventListener('fetch', function (event) {
    // let go non GET requests
    if (event.request.method !== 'GET' || event.request.url.startsWith('chrome-extension://')) {
        return;
    }

    event.respondWith(
        caches.match(event.request).then(function (response) {
            if (response) {
                event.waitUntil(update(event.request));
                return response;
            }

            return fetch(event.request).then(function (response) {
                return caches.open(cacheName).then(function (cache) {
                    cache.put(event.request, response.clone());
                    return response;
                });
            });
        }));
})

function update(request) {
    return caches.open(cacheName).then(function (cache) {
        return fetch(request).then(function (response) {
            return cache.put(request, response);
        });
    });
}


text:
package org.emooti.emootibantransformer;

import java.util.ArrayList;

public class EmootiDesign {
	String design = "ampel";
	String num = "3";

	private ArrayList<Emooti> emootis=new ArrayList<Emooti>();

    public String getDesign()
    {
        return design;
    }

    public void setDesign(String design)
    {
        this.design = design;
    }
    public String getNum()
    {
        return num;
    }

    public void setNum(String num)
    {
        this.num = num;
    }

    public ArrayList<Emooti> getEmooti()
    {
        return emootis;
    }
    public void setEmooti(ArrayList<Emooti> emootis)
    {
        this.emootis = emootis;
    }

}


text:
<?php
add_action( 'ninja_forms_edit_field_ul', 'ninja_forms_edit_field_output_ul' );
function ninja_forms_edit_field_output_ul( $form_id ){
	$fields = ninja_forms_get_fields_by_form_id( $form_id );
	?>

		<input class="button-primary menu-save ninja-forms-save-data" id="ninja_forms_save_data_top" type="submit" value="<?php _e('Save Field Settings', 'ninja-forms'); ?>" />

	  		<?php
				if( is_array( $fields ) AND !empty( $fields ) ){
					foreach( $fields as $field ){
						ninja_forms_edit_field( $field['id'] );
					}
				}
			?>

	<?php
}


text:
import django.db.models.deletion
from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ("shipping", "0026_shippingzone_description"),
    ]

    operations = [
        migrations.RenameModel(
            old_name="ShippingMethodZipCodeRule",
            new_name="ShippingMethodPostalCodeRule",
        ),
        migrations.AddField(
            model_name="shippingmethodpostalcoderule",
            name="inclusion_type",
            field=models.CharField(
                choices=[
                    ("include", "Shipping method should include postal code rule"),
                    ("exclude", "Shipping method should exclude postal code rule"),
                ],
                default="exclude",
                max_length=32,
            ),
        ),
        migrations.AlterField(
            model_name="shippingmethodpostalcoderule",
            name="shipping_method",
            field=models.ForeignKey(
                on_delete=django.db.models.deletion.CASCADE,
                related_name="postal_code_rules",
                to="shipping.shippingmethod",
            ),
        ),
    ]


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!--URLs-->
    <string name="link_backpack_tf" translatable="false">https://backpack.tf/profiles/</string>
    <string name="link_bazaar_tf" translatable="false">https://bazaar.tf/profiles/</string>
    <string name="link_steamrep" translatable="false">https://steamrep.com/profiles/</string>
    <string name="link_rep_tf" translatable="false">https://rep.tf/</string>
    <string name="link_steam_community" translatable="false">https://steamcommunity.com/profiles/</string>
    <string name="link_search_bazaar" translatable="false">https://bazaar.tf/search/</string>

    <!--links with env vars-->
    <string name="link_steam_login" translatable="false">/bptf/openid</string>

    <string name="gcm_sender_id" translatable="false">999648321586</string>

</resources>


text:
package io.cattle.platform.agent.connection.event;

import io.cattle.platform.agent.server.connection.AgentConnection;
import io.cattle.platform.agent.server.connection.AgentConnectionFactory;
import io.cattle.platform.core.model.Agent;
import io.cattle.platform.eventing.EventService;

import java.io.IOException;

import javax.inject.Inject;

public class AgentEventingConnectionFactory implements AgentConnectionFactory {

    private static final String PROTOCOL = "event://";

    EventService eventService;

    @Override
    public AgentConnection createConnection(Agent agent) throws IOException {
        String uri = agent.getUri();
        if ( uri == null || ! uri.startsWith(PROTOCOL) ) {
            return null;
        }

        return new AgentEventingConnection(agent.getId(), agent.getUri(), eventService);
    }

    public EventService getEventService() {
        return eventService;
    }

    @Inject
    public void setEventService(EventService eventService) {
        this.eventService = eventService;
    }

}


text:
class IOHandle1D {

public:
    IOHandle1D(){};
    IOHandle1D(Params1D* _p);
    ~IOHandle1D(){};
    void cache_flush( const thrust::host_vector<cuDoubleComplex>& v);
private:

    string filename = "framedata.h5";
    const size_t c_size = 100;
    thrust::host_vector<double> real_cache;
    thrust::host_vector<double> img_cache;
    // Require all the nececarry handles
    hid_t file;
    hid_t dataspace, dataset;
    hid_t filespace, memspace;
    hid_t prop;
    // Also size information will be
    // necessary
    hsize_t size;
    hsize_t offset;
    hsize_t dim1;

    void overwrite( const thrust::host_vector<cuDoubleComplex>& v);
    void savechunkt();
    void initfile();
};


text:
package sub

import (
	"bytes"
	"sync"
	"time"

	"github.com/go-mangos/mangos"
)

type sub struct {
	sock mangos.ProtocolSocket
	subs [][]byte
	raw  bool
	sync.Mutex
}

func (s *sub) Init(sock mangos.ProtocolSocket) {
	s.sock = sock
	s.subs = [][]byte{}
	s.sock.SetSendError(mangos.ErrProtoOp)
}

func (*sub) Shutdown(time.Time) {} // No sender to drain.

func (s *sub) receiver(ep mangos.Endpoint) {

	rq := s.sock.RecvChannel()
	cq := s.sock.CloseChannel()

	for {
		var matched = false

		m := ep.RecvMsg()
		if m == nil {
			return
		}

		s.Lock()
		for _, sub := range s.subs {
			if bytes.HasPrefix(m.Body, sub) {
				// Matched, send it up.  Best effort.
				matched = true
				break
			}
		}
		s.Unlock()

		if !matched {
			m.Free()
			continue
		}

		select {
		case rq <- m:
		case <-cq:
			m.Free()
			return
		default: // no room, drop it
			m.Free()
		}
	}
}

func (*sub) Number() uint16 {
	return mangos.ProtoSub
}

func (*sub) PeerNumber() uint16 {
	return mangos.ProtoPub
}

func (*sub) Name() string {
	return "sub"
}

func (*sub) PeerName() string {
	return "pub"
}

func (s *sub) AddEndpoint(ep mangos.Endpoint) {
	go s.receiver(ep)
}

func (*sub) RemoveEndpoint(mangos.Endpoint) {}

func (s *sub) SetOption(name string, value interface{}) error {
	s.Lock()
	defer s.Unlock()

	var vb []byte
	var ok bool

	// Check names first, because type check below is only valid for
	// subscription options.
	switch name {
	case mangos.OptionRaw:
		if s.raw, ok = value.(bool); !ok {
			return mangos.ErrBadValue
		}
		return nil
	case mangos.OptionSubscribe:
	case mangos.OptionUnsubscribe:
	default:
		return mangos.ErrBadOption
	}

	switch v := value.(type) {
	case []byte:
		vb = v
	case string:
		vb = []byte(v)
	default:
		return mangos.ErrBadValue
	}
	switch name {
	case mangos.OptionSubscribe:
		for _, sub := range s.subs {
			if bytes.Equal(sub, vb) {
				// Already present
				return nil
			}
		}
		s.subs = append(s.subs, vb)
		return nil

	case mangos.OptionUnsubscribe:
		for i, sub := range s.subs {
			if bytes.Equal(sub, vb) {
				s.subs[i] = s.subs[len(s.subs)-1]
				s.subs = s.subs[:len(s.subs)-1]
				return nil
			}
		}
		// Subscription not present
		return mangos.ErrBadValue

	default:
		return mangos.ErrBadOption
	}
}

func (s *sub) GetOption(name string) (interface{}, error) {
	switch name {
	case mangos.OptionRaw:
		return s.raw, nil
	default:
		return nil, mangos.ErrBadOption
	}
}

// NewSocket allocates a new Socket using the SUB protocol.
func NewSocket() (mangos.Socket, error) {
	return mangos.MakeSocket(&sub{}), nil
}


text:
function ajaxlookup(resourcetype, lookin) {
  new Ajax.Updater('lookup', '', { method: 'get', onLoading: createProgressBar('lookupfiles'), onComplete: sorttable.reinit, parameters: {lookup: 'true', 'yanel.resource.viewid': 'source', lookin: lookin, 'resource-type': resourcetype} });
}


text:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
import io.nuclio.Context;
import io.nuclio.Event;
import io.nuclio.EventHandler;
import io.nuclio.Response;

public class JsonParser implements EventHandler {

    @Override
    public Response handleEvent(Context context, Event event) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            TypeReference< HashMap < String, String > > typeRef = new TypeReference < HashMap < String, String > >() {
            };

            Map< String, String > request = mapper.readValue(event.getBody(), typeRef);
            return new Response().setBody(request.get("return_this"));
        } catch (Throwable err) {
            return new Response().setBody(err.toString()).setStatusCode(500);
        }
    }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lmo.tcp.bridge;

import lmo.tcp.bridge.conf.ConfigName;

/**
 *
 * @author LMO-PC
 */
public class BridgeClientConfig {

    //shost sport srcid srcpass dstid dstpass rhost rport lport
    @ConfigName(required = true)
    public static int port;

    @ConfigName(required = true)
    public static String shost;
    @ConfigName(required = true)
    public static int sport;
    @ConfigName(required = true)
    public static int srcid;
    public static String srcpass;

    @ConfigName(required = true)
    public static int dstid;
    public static String dstpass;
    @ConfigName(required = true)
    public static String rhost;
    @ConfigName(required = true)
    public static int rport;
}


text:
namespace v8 {
namespace internal {

// Non-templatized base class for {OrderedHashTable}s.
// TODO(hash): Unify this with the HashTableBase above.
class OrderedHashTableBase : public FixedArray {
 public:
  static const int kNotFound = -1;
  static const int kMinCapacity = 4;

  static const int kNumberOfElementsIndex = 0;
  // The next table is stored at the same index as the nof elements.
  static const int kNextTableIndex = kNumberOfElementsIndex;
  static const int kNumberOfDeletedElementsIndex = kNumberOfElementsIndex + 1;
  static const int kNumberOfBucketsIndex = kNumberOfDeletedElementsIndex + 1;
  static const int kHashTableStartIndex = kNumberOfBucketsIndex + 1;
  static const int kRemovedHolesIndex = kHashTableStartIndex;

  static constexpr const int kNumberOfElementsOffset =
      FixedArray::OffsetOfElementAt(kNumberOfElementsIndex);
  static constexpr const int kNextTableOffset =
      FixedArray::OffsetOfElementAt(kNextTableIndex);
  static constexpr const int kNumberOfDeletedElementsOffset =
      FixedArray::OffsetOfElementAt(kNumberOfDeletedElementsIndex);
  static constexpr const int kNumberOfBucketsOffset =
      FixedArray::OffsetOfElementAt(kNumberOfBucketsIndex);
  static constexpr const int kHashTableStartOffset =
      FixedArray::OffsetOfElementAt(kHashTableStartIndex);

  static const int kLoadFactor = 2;

  // NumberOfDeletedElements is set to kClearedTableSentinel when
  // the table is cleared, which allows iterator transitions to
  // optimize that case.
  static const int kClearedTableSentinel = -1;
};

// OrderedHashTable is a HashTable with Object keys that preserves
// insertion order. There are Map and Set interfaces (OrderedHashMap
// and OrderedHashTable, below). It is meant to be used by JSMap/JSSet.
//
// Only Object* keys are supported, with Object::SameValueZero() used as the
// equality operator and Object::GetHash() for the hash function.
//
// Based on the "Deterministic Hash Table" as described by Jason Orendorff at
// https://wiki.mozilla.org/User:Jorend/Deterministic_hash_tables
// Originally attributed to Tyler Close.
//
// Memory layout:
//   [0]: element count
//   [1]: deleted element count
//   [2]: bucket count
//   [3..(3 + NumberOfBuckets() - 1)]: "hash table", where each item is an
//                            offset into the data table (see below) where the
//                            first item in this bucket is stored.
//   [3 + NumberOfBuckets()..length]: "data table", an array of length
//                            Capacity() * kEntrySize, where the first entrysize
//                            items are handled by the derived class and the
//                            item at kChainOffset is another entry into the
//                            data table indicating the next entry in this hash
//                            bucket.
//
// When we transition the table to a new version we obsolete it and reuse parts
// of the memory to store information how to transition an iterator to the new
// table:
//
// Memory layout for obsolete table:
//   [0]: bucket count
//   [1]: Next newer table
//   [2]: Number of removed holes or -1 when the table was cleared.
//   [3..(3 + NumberOfRemovedHoles() - 1)]: The indexes of the removed holes.
//   [3 + NumberOfRemovedHoles()..length]: Not used
//
template <class Derived, int entrysize>
class OrderedHashTable : public OrderedHashTableBase {
 public:
  // Returns an OrderedHashTable with a capacity of at least |capacity|.
  static Handle<Derived> Allocate(Isolate* isolate, int capacity,
                                  PretenureFlag pretenure = NOT_TENURED);

  // Returns an OrderedHashTable (possibly |table|) with enough space
  // to add at least one new element.
  static Handle<Derived> EnsureGrowable(Isolate* isolate,
                                        Handle<Derived> table);

  // Returns an OrderedHashTable (possibly |table|) that's shrunken
  // if possible.
  static Handle<Derived> Shrink(Isolate* isolate, Handle<Derived> table);

  // Returns a new empty OrderedHashTable and records the clearing so that
  // existing iterators can be updated.
  static Handle<Derived> Clear(Isolate* isolate, Handle<Derived> table);

  // Returns true if the OrderedHashTable contains the key
  static bool HasKey(Isolate* isolate, Derived* table, Object* key);

  // Returns a true value if the OrderedHashTable contains the key and
  // the key has been deleted. This does not shrink the table.
  static bool Delete(Isolate* isolate, Derived* table, Object* key);

  int NumberOfElements() const {
    return Smi::ToInt(get(kNumberOfElementsIndex));
  }

  int NumberOfDeletedElements() const {
    return Smi::ToInt(get(kNumberOfDeletedElementsIndex));
  }

  // Returns the number of contiguous entries in the data table, starting at 0,
  // that either are real entries or have been deleted.
  int UsedCapacity() const {
    return NumberOfElements() + NumberOfDeletedElements();
  }

  int NumberOfBuckets() const { return Smi::ToInt(get(kNumberOfBucketsIndex)); }

  // Returns an index into |this| for the given entry.
  int EntryToIndex(int entry) {
    return kHashTableStartIndex + NumberOfBuckets() + (entry * kEntrySize);
  }

  int HashToBucket(int hash) { return hash & (NumberOfBuckets() - 1); }

  int HashToEntry(int hash) {
    int bucket = HashToBucket(hash);
    Object* entry = this->get(kHashTableStartIndex + bucket);
    return Smi::ToInt(entry);
  }

  int KeyToFirstEntry(Isolate* isolate, Object* key) {
    // This special cases for Smi, so that we avoid the HandleScope
    // creation below.
    if (key->IsSmi()) {
      uint32_t hash = ComputeUnseededHash(Smi::ToInt(key));
      return HashToEntry(hash & Smi::kMaxValue);
    }
    HandleScope scope(isolate);
    Object* hash = key->GetHash();
    // If the object does not have an identity hash, it was never used as a key
    if (hash->IsUndefined(isolate)) return kNotFound;
    return HashToEntry(Smi::ToInt(hash));
  }

  int FindEntry(Isolate* isolate, Object* key) {
    int entry = KeyToFirstEntry(isolate, key);
    // Walk the chain in the bucket to find the key.
    while (entry != kNotFound) {
      Object* candidate_key = KeyAt(entry);
      if (candidate_key->SameValueZero(key)) break;
      entry = NextChainEntry(entry);
    }

    return entry;
  }

  int NextChainEntry(int entry) {
    Object* next_entry = get(EntryToIndex(entry) + kChainOffset);
    return Smi::ToInt(next_entry);
  }

  // use KeyAt(i)->IsTheHole(isolate) to determine if this is a deleted entry.
  Object* KeyAt(int entry) {
    DCHECK_LT(entry, this->UsedCapacity());
    return get(EntryToIndex(entry));
  }

  bool IsObsolete() { return !get(kNextTableIndex)->IsSmi(); }

  // The next newer table. This is only valid if the table is obsolete.
  Derived* NextTable() { return Derived::cast(get(kNextTableIndex)); }

  // When the table is obsolete we store the indexes of the removed holes.
  int RemovedIndexAt(int index) {
    return Smi::ToInt(get(kRemovedHolesIndex + index));
  }

  static const int kEntrySize = entrysize + 1;
  static const int kChainOffset = entrysize;

  static const int kMaxCapacity =
      (FixedArray::kMaxLength - kHashTableStartIndex) /
      (1 + (kEntrySize * kLoadFactor));

 protected:
  static Handle<Derived> Rehash(Isolate* isolate, Handle<Derived> table,
                                int new_capacity);

  void SetNumberOfBuckets(int num) {
    set(kNumberOfBucketsIndex, Smi::FromInt(num));
  }

  void SetNumberOfElements(int num) {
    set(kNumberOfElementsIndex, Smi::FromInt(num));
  }

  void SetNumberOfDeletedElements(int num) {
    set(kNumberOfDeletedElementsIndex, Smi::FromInt(num));
  }

  // Returns the number elements that can fit into the allocated buffer.
  int Capacity() { return NumberOfBuckets() * kLoadFactor; }

  void SetNextTable(Derived* next_table) { set(kNextTableIndex, next_table); }

  void SetRemovedIndexAt(int index, int removed_index) {
    return set(kRemovedHolesIndex + index, Smi::FromInt(removed_index));
  }
};

class OrderedHashSet : public OrderedHashTable<OrderedHashSet, 1> {
 public:
  DECL_CAST(OrderedHashSet)

  static Handle<OrderedHashSet> Add(Isolate* isolate,
                                    Handle<OrderedHashSet> table,
                                    Handle<Object> value);
  static Handle<FixedArray> ConvertToKeysArray(Isolate* isolate,
                                               Handle<OrderedHashSet> table,
                                               GetKeysConversion convert);
  static HeapObject* GetEmpty(ReadOnlyRoots ro_roots);
  static inline RootIndex GetMapRootIndex();
  static inline bool Is(Handle<HeapObject> table);
};

class OrderedHashMap : public OrderedHashTable<OrderedHashMap, 2> {
 public:
  DECL_CAST(OrderedHashMap)

  // Returns a value if the OrderedHashMap contains the key, otherwise
  // returns undefined.
  static Handle<OrderedHashMap> Add(Isolate* isolate,
                                    Handle<OrderedHashMap> table,
                                    Handle<Object> key, Handle<Object> value);
  Object* ValueAt(int entry);

  static Object* GetHash(Isolate* isolate, Object* key);

  static HeapObject* GetEmpty(ReadOnlyRoots ro_roots);
  static inline RootIndex GetMapRootIndex();
  static inline bool Is(Handle<HeapObject> table);

  static const int kValueOffset = 1;
};

// This is similar to the OrderedHashTable, except for the memory
// layout where we use byte instead of Smi. The max capacity of this
// is only 254, we transition to an OrderedHashTable beyond that
// limit.
//
// Each bucket and chain value is a byte long. The padding exists so
// that the DataTable entries start aligned. A bucket or chain value
// of 255 is used to denote an unknown entry.
//
// Memory layout: [ Header ]  [ Padding ] [ DataTable ] [ HashTable ] [ Chains ]
//
// The index are represented as bytes, on a 64 bit machine with
// kEntrySize = 1, capacity = 4 and entries = 2:
//
// [ Header ]  :
//    [0] : Number of elements
//    [1] : Number of deleted elements
//    [2] : Number of buckets
//
// [ Padding ] :
//    [3 .. 7] : Padding
//
// [ DataTable ] :
//    [8  .. 15] : Entry 1
//    [16 .. 23] : Entry 2
//    [24 .. 31] : empty
//    [32 .. 39] : empty
//
// [ HashTable ] :
//    [40] : First chain-link for bucket 1
//    [41] : empty
//
// [ Chains ] :
//    [42] : Next chain link for bucket 1
//    [43] : empty
//    [44] : empty
//    [45] : empty
//
template <class Derived>
class SmallOrderedHashTable : public HeapObject {
 public:
  // Offset points to a relative location in the table
  typedef int Offset;

  // ByteIndex points to a index in the table that needs to be
  // converted to an Offset.
  typedef int ByteIndex;

  void Initialize(Isolate* isolate, int capacity);

  static Handle<Derived> Allocate(Isolate* isolate, int capacity,
                                  PretenureFlag pretenure = NOT_TENURED);

  // Returns a true if the OrderedHashTable contains the key
  bool HasKey(Isolate* isolate, Handle<Object> key);

  // Returns a true value if the table contains the key and
  // the key has been deleted. This does not shrink the table.
  static bool Delete(Isolate* isolate, Derived* table, Object* key);

  // Returns an SmallOrderedHashTable (possibly |table|) with enough
  // space to add at least one new element. Returns empty handle if
  // we've already reached MaxCapacity.
  static MaybeHandle<Derived> Grow(Isolate* isolate, Handle<Derived> table);

  static Handle<Derived> Rehash(Isolate* isolate, Handle<Derived> table,
                                int new_capacity);

  // Iterates only fields in the DataTable.
  class BodyDescriptor;

  // Returns total size in bytes required for a table of given
  // capacity.
  static int SizeFor(int capacity) {
    DCHECK_GE(capacity, kMinCapacity);
    DCHECK_LE(capacity, kMaxCapacity);

    int data_table_size = DataTableSizeFor(capacity);
    int hash_table_size = capacity / kLoadFactor;
    int chain_table_size = capacity;
    int total_size = kDataTableStartOffset + data_table_size + hash_table_size +
                     chain_table_size;

    return RoundUp(total_size, kPointerSize);
  }

  // Returns the number elements that can fit into the allocated table.
  int Capacity() const {
    int capacity = NumberOfBuckets() * kLoadFactor;
    DCHECK_GE(capacity, kMinCapacity);
    DCHECK_LE(capacity, kMaxCapacity);

    return capacity;
  }

  // Returns the number elements that are present in the table.
  int NumberOfElements() const {
    int nof_elements = getByte(kNumberOfElementsOffset, 0);
    DCHECK_LE(nof_elements, Capacity());

    return nof_elements;
  }

  int NumberOfDeletedElements() const {
    int nof_deleted_elements = getByte(kNumberOfDeletedElementsOffset, 0);
    DCHECK_LE(nof_deleted_elements, Capacity());

    return nof_deleted_elements;
  }

  int NumberOfBuckets() const { return getByte(kNumberOfBucketsOffset, 0); }

  DECL_VERIFIER(SmallOrderedHashTable)

  static const int kMinCapacity = 4;
  static const byte kNotFound = 0xFF;

  // We use the value 255 to indicate kNotFound for chain and bucket
  // values, which means that this value can't be used a valid
  // index.
  static const int kMaxCapacity = 254;
  STATIC_ASSERT(kMaxCapacity < kNotFound);

  // The load factor is used to derive the number of buckets from
  // capacity during Allocation. We also depend on this to calaculate
  // the capacity from number of buckets after allocation. If we
  // decide to change kLoadFactor to something other than 2, capacity
  // should be stored as another field of this object.
  static const int kLoadFactor = 2;

  // Our growth strategy involves doubling the capacity until we reach
  // kMaxCapacity, but since the kMaxCapacity is always less than 256,
  // we will never fully utilize this table. We special case for 256,
  // by changing the new capacity to be kMaxCapacity in
  // SmallOrderedHashTable::Grow.
  static const int kGrowthHack = 256;

 protected:
  void SetDataEntry(int entry, int relative_index, Object* value);

  // TODO(gsathya): Calculate all the various possible values for this
  // at compile time since capacity can only be 4 different values.
  Offset GetBucketsStartOffset() const {
    int capacity = Capacity();
    int data_table_size = DataTableSizeFor(capacity);
    return kDataTableStartOffset + data_table_size;
  }

  Address GetHashTableStartAddress(int capacity) const {
    return FIELD_ADDR(this, kDataTableStartOffset + DataTableSizeFor(capacity));
  }

  void SetFirstEntry(int bucket, byte value) {
    DCHECK_LE(static_cast<unsigned>(bucket), NumberOfBuckets());
    setByte(GetBucketsStartOffset(), bucket, value);
  }

  int GetFirstEntry(int bucket) const {
    DCHECK_LE(static_cast<unsigned>(bucket), NumberOfBuckets());
    return getByte(GetBucketsStartOffset(), bucket);
  }

  // TODO(gsathya): Calculate all the various possible values for this
  // at compile time since capacity can only be 4 different values.
  Offset GetChainTableOffset() const {
    int nof_buckets = NumberOfBuckets();
    int capacity = nof_buckets * kLoadFactor;
    DCHECK_EQ(Capacity(), capacity);

    int data_table_size = DataTableSizeFor(capacity);
    int hash_table_size = nof_buckets;
    return kDataTableStartOffset + data_table_size + hash_table_size;
  }

  void SetNextEntry(int entry, int next_entry) {
    DCHECK_LT(static_cast<unsigned>(entry), Capacity());
    DCHECK_GE(static_cast<unsigned>(next_entry), 0);
    DCHECK(next_entry <= Capacity() || next_entry == kNotFound);
    setByte(GetChainTableOffset(), entry, next_entry);
  }

  int GetNextEntry(int entry) const {
    DCHECK_LT(entry, Capacity());
    return getByte(GetChainTableOffset(), entry);
  }

  Object* GetDataEntry(int entry, int relative_index) {
    DCHECK_LT(entry, Capacity());
    DCHECK_LE(static_cast<unsigned>(relative_index), Derived::kEntrySize);
    Offset entry_offset = GetDataEntryOffset(entry, relative_index);
    return READ_FIELD(this, entry_offset);
  }

  Object* KeyAt(int entry) const {
    DCHECK_LT(entry, Capacity());
    Offset entry_offset = GetDataEntryOffset(entry, Derived::kKeyIndex);
    return READ_FIELD(this, entry_offset);
  }

  int HashToBucket(int hash) const { return hash & (NumberOfBuckets() - 1); }

  int HashToFirstEntry(int hash) const {
    int bucket = HashToBucket(hash);
    int entry = GetFirstEntry(bucket);
    DCHECK(entry < Capacity() || entry == kNotFound);
    return entry;
  }

  void SetNumberOfBuckets(int num) { setByte(kNumberOfBucketsOffset, 0, num); }

  void SetNumberOfElements(int num) {
    DCHECK_LE(static_cast<unsigned>(num), Capacity());
    setByte(kNumberOfElementsOffset, 0, num);
  }

  void SetNumberOfDeletedElements(int num) {
    DCHECK_LE(static_cast<unsigned>(num), Capacity());
    setByte(kNumberOfDeletedElementsOffset, 0, num);
  }

  int FindEntry(Isolate* isolate, Object* key) {
    DisallowHeapAllocation no_gc;
    Object* hash = key->GetHash();

    if (hash->IsUndefined(isolate)) return kNotFound;
    int entry = HashToFirstEntry(Smi::ToInt(hash));

    // Walk the chain in the bucket to find the key.
    while (entry != kNotFound) {
      Object* candidate_key = KeyAt(entry);
      if (candidate_key->SameValueZero(key)) return entry;
      entry = GetNextEntry(entry);
    }
    return kNotFound;
  }

  static const Offset kNumberOfElementsOffset = kHeaderSize;
  static const Offset kNumberOfDeletedElementsOffset =
      kNumberOfElementsOffset + kOneByteSize;
  static const Offset kNumberOfBucketsOffset =
      kNumberOfDeletedElementsOffset + kOneByteSize;
  static const constexpr Offset kDataTableStartOffset =
      RoundUp<kPointerSize>(kNumberOfBucketsOffset);

  static constexpr int DataTableSizeFor(int capacity) {
    return capacity * Derived::kEntrySize * kPointerSize;
  }

  // This is used for accessing the non |DataTable| part of the
  // structure.
  byte getByte(Offset offset, ByteIndex index) const {
    DCHECK(offset < kDataTableStartOffset || offset >= GetBucketsStartOffset());
    return READ_BYTE_FIELD(this, offset + (index * kOneByteSize));
  }

  void setByte(Offset offset, ByteIndex index, byte value) {
    DCHECK(offset < kDataTableStartOffset || offset >= GetBucketsStartOffset());
    WRITE_BYTE_FIELD(this, offset + (index * kOneByteSize), value);
  }

  Offset GetDataEntryOffset(int entry, int relative_index) const {
    DCHECK_LT(entry, Capacity());
    int offset_in_datatable = entry * Derived::kEntrySize * kPointerSize;
    int offset_in_entry = relative_index * kPointerSize;
    return kDataTableStartOffset + offset_in_datatable + offset_in_entry;
  }

  int UsedCapacity() const {
    int used = NumberOfElements() + NumberOfDeletedElements();
    DCHECK_LE(used, Capacity());

    return used;
  }

 private:
  friend class OrderedHashMapHandler;
  friend class OrderedHashSetHandler;
  friend class CodeStubAssembler;
};

class SmallOrderedHashSet : public SmallOrderedHashTable<SmallOrderedHashSet> {
 public:
  DECL_CAST(SmallOrderedHashSet)

  DECL_PRINTER(SmallOrderedHashSet)

  static const int kKeyIndex = 0;
  static const int kEntrySize = 1;

  // Adds |value| to |table|, if the capacity isn't enough, a new
  // table is created. The original |table| is returned if there is
  // capacity to store |value| otherwise the new table is returned.
  static MaybeHandle<SmallOrderedHashSet> Add(Isolate* isolate,
                                              Handle<SmallOrderedHashSet> table,
                                              Handle<Object> key);
  static inline bool Is(Handle<HeapObject> table);
  static inline RootIndex GetMapRootIndex();
};

class SmallOrderedHashMap : public SmallOrderedHashTable<SmallOrderedHashMap> {
 public:
  DECL_CAST(SmallOrderedHashMap)

  DECL_PRINTER(SmallOrderedHashMap)

  static const int kKeyIndex = 0;
  static const int kValueIndex = 1;
  static const int kEntrySize = 2;

  // Adds |value| to |table|, if the capacity isn't enough, a new
  // table is created. The original |table| is returned if there is
  // capacity to store |value| otherwise the new table is returned.
  static MaybeHandle<SmallOrderedHashMap> Add(Isolate* isolate,
                                              Handle<SmallOrderedHashMap> table,
                                              Handle<Object> key,
                                              Handle<Object> value);
  static inline bool Is(Handle<HeapObject> table);
  static inline RootIndex GetMapRootIndex();
};

// TODO(gsathya): Rename this to OrderedHashTable, after we rename
// OrderedHashTable to LargeOrderedHashTable. Also set up a
// OrderedHashSetBase class as a base class for the two tables and use
// that instead of a HeapObject here.
template <class SmallTable, class LargeTable>
class OrderedHashTableHandler {
 public:
  typedef int Entry;

  static Handle<HeapObject> Allocate(Isolate* isolate, int capacity);
  static bool Delete(Handle<HeapObject> table, Handle<Object> key);
  static bool HasKey(Isolate* isolate, Handle<HeapObject> table,
                     Handle<Object> key);

  // TODO(gsathya): Move this to OrderedHashTable
  static const int OrderedHashTableMinSize =
      SmallOrderedHashTable<SmallTable>::kGrowthHack << 1;
};

class OrderedHashMapHandler
    : public OrderedHashTableHandler<SmallOrderedHashMap, OrderedHashMap> {
 public:
  static Handle<HeapObject> Add(Isolate* isolate, Handle<HeapObject> table,
                                Handle<Object> key, Handle<Object> value);
  static Handle<OrderedHashMap> AdjustRepresentation(
      Isolate* isolate, Handle<SmallOrderedHashMap> table);
};

class OrderedHashSetHandler
    : public OrderedHashTableHandler<SmallOrderedHashSet, OrderedHashSet> {
 public:
  static Handle<HeapObject> Add(Isolate* isolate, Handle<HeapObject> table,
                                Handle<Object> key);
  static Handle<OrderedHashSet> AdjustRepresentation(
      Isolate* isolate, Handle<SmallOrderedHashSet> table);
};

class JSCollectionIterator : public JSObject {
 public:
  // [table]: the backing hash table mapping keys to values.
  DECL_ACCESSORS(table, Object)

  // [index]: The index into the data table.
  DECL_ACCESSORS(index, Object)

  // Dispatched behavior.
  DECL_PRINTER(JSCollectionIterator)

  static const int kTableOffset = JSObject::kHeaderSize;
  static const int kIndexOffset = kTableOffset + kPointerSize;
  static const int kSize = kIndexOffset + kPointerSize;

 private:
  DISALLOW_IMPLICIT_CONSTRUCTORS(JSCollectionIterator);
};

// OrderedHashTableIterator is an iterator that iterates over the keys and
// values of an OrderedHashTable.
//
// The iterator has a reference to the underlying OrderedHashTable data,
// [table], as well as the current [index] the iterator is at.
//
// When the OrderedHashTable is rehashed it adds a reference from the old table
// to the new table as well as storing enough data about the changes so that the
// iterator [index] can be adjusted accordingly.
//
// When the [Next] result from the iterator is requested, the iterator checks if
// there is a newer table that it needs to transition to.
template <class Derived, class TableType>
class OrderedHashTableIterator : public JSCollectionIterator {
 public:
  // Whether the iterator has more elements. This needs to be called before
  // calling |CurrentKey| and/or |CurrentValue|.
  bool HasMore();

  // Move the index forward one.
  void MoveNext() { set_index(Smi::FromInt(Smi::ToInt(index()) + 1)); }

  // Returns the current key of the iterator. This should only be called when
  // |HasMore| returns true.
  inline Object* CurrentKey();

 private:
  // Transitions the iterator to the non obsolete backing store. This is a NOP
  // if the [table] is not obsolete.
  void Transition();

  DISALLOW_IMPLICIT_CONSTRUCTORS(OrderedHashTableIterator);
};

}  // namespace internal
}  // namespace v8

#include "src/objects/object-macros-undef.h"

#endif  // V8_OBJECTS_ORDERED_HASH_TABLE_H_


text:
from django.conf.urls import url

from monitor.views import SummaryView, memory_data, swap_data, cpu_data, net_data

urlpatterns = [
    url(r'^$', SummaryView.as_view(), name='monitor-summary'),
    url(r'^memory/$', memory_data, name='monitor-memory_data'),
    url(r'^swap/$', swap_data, name='monitor-swap_data'),
    url(r'^cpu/$', cpu_data, name='monitor-cpu_data'),
    url(r'^net/$', net_data, name='monitor-net_data')
]


text:
namespace downgrade {

SnapshotItemDetails::SnapshotItemDetails(base::FilePath path,
                                         ItemType item_type,
                                         uint64_t data_types,
                                         SnapshotItemId id)
    : path(std::move(path)),
      is_directory(item_type == ItemType::kDirectory),
      data_types(data_types),
      id(id) {}

// Returns a list of items to snapshot that should be directly under the user
// data  directory.
std::vector<SnapshotItemDetails> CollectUserDataItems() {
  std::vector<SnapshotItemDetails> user_data_items{
      SnapshotItemDetails(base::FilePath(chrome::kLocalStateFilename),
                          SnapshotItemDetails::ItemType::kFile, 0,
                          SnapshotItemId::kLocalState),
      SnapshotItemDetails(base::FilePath(profiles::kHighResAvatarFolderName),
                          SnapshotItemDetails::ItemType::kDirectory, 0,
                          SnapshotItemId::kHighResAvatar)};
#if BUILDFLAG(IS_WIN)
  user_data_items.emplace_back(base::FilePath(web_app::kLastBrowserFilename),
                               SnapshotItemDetails::ItemType::kFile, 0,
                               SnapshotItemId::kLastBrowser);
#endif  // BUILDFLAG(IS_WIN)
  return user_data_items;
}

// Returns a list of items to snapshot that should be under a profile directory.
std::vector<SnapshotItemDetails> CollectProfileItems() {
  // Data mask to delete the pref files if any of the following types is
  // deleted. When cookies are deleted, the kZeroSuggestCachedResults and
  // kZeroSuggestCachedResultsWithURL prefs have to be reset. When history and
  // isolated origins are deleted, the kPrefLastLaunchTime and
  // kUserTriggeredIsolatedOrigins prefs have to be reset. When data type
  // content is deleted, blocklisted sites are deleted from the translation
  // prefs.
  uint64_t pref_data_type =
      content::BrowsingDataRemover::DATA_TYPE_COOKIES |
      chrome_browsing_data_remover::DATA_TYPE_ISOLATED_ORIGINS |
      chrome_browsing_data_remover::DATA_TYPE_HISTORY |
      chrome_browsing_data_remover::DATA_TYPE_CONTENT_SETTINGS;
  std::vector<SnapshotItemDetails> profile_items{
      // General Profile files
      SnapshotItemDetails(base::FilePath(chrome::kPreferencesFilename),
                          SnapshotItemDetails::ItemType::kFile, pref_data_type,
                          SnapshotItemId::kPreferences),
      SnapshotItemDetails(base::FilePath(chrome::kSecurePreferencesFilename),
                          SnapshotItemDetails::ItemType::kFile, pref_data_type,
                          SnapshotItemId::kSecurePreferences),
      // History files
      SnapshotItemDetails(base::FilePath(history::kHistoryFilename),
                          SnapshotItemDetails::ItemType::kFile,
                          chrome_browsing_data_remover::DATA_TYPE_HISTORY,
                          SnapshotItemId::kHistory),
      SnapshotItemDetails(base::FilePath(history::kFaviconsFilename),
                          SnapshotItemDetails::ItemType::kFile,
                          chrome_browsing_data_remover::DATA_TYPE_HISTORY,
                          SnapshotItemId::kFavicons),
      SnapshotItemDetails(base::FilePath(history::kTopSitesFilename),
                          SnapshotItemDetails::ItemType::kFile,
                          chrome_browsing_data_remover::DATA_TYPE_HISTORY,
                          SnapshotItemId::kTopSites),
      // Bookmarks
      SnapshotItemDetails(base::FilePath(bookmarks::kBookmarksFileName),
                          SnapshotItemDetails::ItemType::kFile,
                          chrome_browsing_data_remover::DATA_TYPE_BOOKMARKS,
                          SnapshotItemId::kBookmarks),
      // Tab Restore and sessions
      // TODO(crbug.com/1103458): Remove legacy snapshots in M89
      SnapshotItemDetails(
          base::FilePath(sessions::kLegacyCurrentTabSessionFileName),
          SnapshotItemDetails::ItemType::kFile,
          chrome_browsing_data_remover::DATA_TYPE_HISTORY,
          SnapshotItemId::kLegacyCurrentTabSession),
      SnapshotItemDetails(
          base::FilePath(sessions::kLegacyCurrentSessionFileName),
          SnapshotItemDetails::ItemType::kFile,
          chrome_browsing_data_remover::DATA_TYPE_HISTORY,
          SnapshotItemId::kLegacyCurrentSession),
      SnapshotItemDetails(base::FilePath(sessions::kSessionsDirectory),
                          SnapshotItemDetails::ItemType::kDirectory,
                          chrome_browsing_data_remover::DATA_TYPE_HISTORY,
                          SnapshotItemId::kSessions),
      // Sign-in state
      SnapshotItemDetails(base::FilePath(profiles::kGAIAPictureFileName),
                          SnapshotItemDetails::ItemType::kFile, 0,
                          SnapshotItemId::kGAIAPicture),
      // Password / Autofill
      SnapshotItemDetails(
          base::FilePath(password_manager::kAffiliationDatabaseFileName),
          SnapshotItemDetails::ItemType::kFile,
          chrome_browsing_data_remover::DATA_TYPE_PASSWORDS |
              chrome_browsing_data_remover::DATA_TYPE_FORM_DATA,
          SnapshotItemId::kAffiliationDatabase),
      SnapshotItemDetails(
          base::FilePath(password_manager::kLoginDataForProfileFileName),
          SnapshotItemDetails::ItemType::kFile,
          chrome_browsing_data_remover::DATA_TYPE_PASSWORDS |
              chrome_browsing_data_remover::DATA_TYPE_FORM_DATA,
          SnapshotItemId::kLoginDataForProfile),
      SnapshotItemDetails(
          base::FilePath(password_manager::kLoginDataForAccountFileName),
          SnapshotItemDetails::ItemType::kFile,
          chrome_browsing_data_remover::DATA_TYPE_PASSWORDS |
              chrome_browsing_data_remover::DATA_TYPE_FORM_DATA,
          SnapshotItemId::kLoginDataForAccount),
      SnapshotItemDetails(base::FilePath(kWebDataFilename),
                          SnapshotItemDetails::ItemType::kFile,
                          chrome_browsing_data_remover::DATA_TYPE_PASSWORDS |
                              chrome_browsing_data_remover::DATA_TYPE_FORM_DATA,
                          SnapshotItemId::kWebData),
      SnapshotItemDetails(base::FilePath(autofill::kStrikeDatabaseFileName),
                          SnapshotItemDetails::ItemType::kDirectory,
                          chrome_browsing_data_remover::DATA_TYPE_PASSWORDS |
                              chrome_browsing_data_remover::DATA_TYPE_FORM_DATA,
                          SnapshotItemId::kStrikeDatabase),
      // Cookies
      SnapshotItemDetails(base::FilePath(chrome::kCookieFilename),
                          SnapshotItemDetails::ItemType::kFile,
                          content::BrowsingDataRemover::DATA_TYPE_COOKIES,
                          SnapshotItemId::kCookie)};

#if BUILDFLAG(IS_WIN)
  // Sign-in state
  profile_items.emplace_back(base::FilePath(profiles::kProfileIconFileName),
                             SnapshotItemDetails::ItemType::kFile, 0,
                             SnapshotItemId::kProfileIcon);
#endif  // BUILDFLAG(IS_WIN)
  return profile_items;
}

}  // namespace downgrade


text:
function _addHiddenInput(form, name, val) {
    var element = document.createElement('input');
    element.type = 'hidden';
    element.name = name;
    element.value = val;
    form.appendChild(element);
}

/* When a workflow action button is clicked, either show a modal or make a POST request to the workflow action view */
function ActivateWorkflowActionsForDashboard(csrfToken) {
    document.querySelectorAll('[data-workflow-action-url]').forEach(function (buttonElement) {
        buttonElement.addEventListener('click', function (e) {
            // Stop the button from submitting the form
            e.preventDefault();
            e.stopPropagation();

            if ('launchModal' in buttonElement.dataset) {
                ModalWorkflow({
                    'url': buttonElement.dataset.workflowActionUrl,
                    'onload': {
                        'action': function(modal, jsonData) {
                            var nextElement = document.createElement('input');
                            nextElement.type = 'hidden';
                            nextElement.name = 'next';
                            nextElement.value = window.location;
                            $('form', modal.body).append(nextElement);
                            modal.ajaxifyForm($('form', modal.body));
                        },
                        'success': function(modal, jsonData) {
                            window.location.href = jsonData['redirect'];
                        }
                    },
                });
            } else {
                // if not opening a modal, submit a POST request to the action url
                var formElement = document.createElement('form');

                formElement.action = buttonElement.dataset.workflowActionUrl;
                formElement.method = 'POST';

                _addHiddenInput(formElement, 'csrfmiddlewaretoken', csrfToken);
                _addHiddenInput(formElement, 'next', window.location);

                document.body.appendChild(formElement);
                formElement.submit();
            }
        }, {capture: true});
    });
}

function ActivateWorkflowActionsForEditView(formSelector) {
    var form = $(formSelector).get(0);

    document.querySelectorAll('[data-workflow-action-name]').forEach(function (buttonElement) {
        buttonElement.addEventListener('click', function (e) {
            if ('workflowActionModalUrl' in buttonElement.dataset) {
                // This action requires opening a modal to collect additional data.
                // Stop the button from submitting the form
                e.preventDefault();
                e.stopPropagation();

                // open the modal at the given URL
                ModalWorkflow({
                    'url': buttonElement.dataset.workflowActionModalUrl,
                    'onload': {
                        'action': function(modal, jsonData) {
                            modal.ajaxifyForm($('form', modal.body));
                        },
                        'success': function(modal, jsonData) {
                            // a success response includes the additional data to submit with the edit form
                            _addHiddenInput(form, 'action-workflow-action', 'true')
                            _addHiddenInput(form, 'workflow-action-name', buttonElement.dataset.workflowActionName)
                            _addHiddenInput(form, 'workflow-action-extra-data', JSON.stringify(jsonData['cleaned_data']))
                            // note: need to submit via jQuery (as opposed to form.submit()) so that the onsubmit handler
                            // that disables the dirty-form prompt doesn't get bypassed
                            $(form).submit();
                        }
                    },
                });

            } else {
                // no modal, so let the form submission to the edit view proceed, with additional
                // hidden inputs to tell it to perform our action
                _addHiddenInput(form, 'action-workflow-action', 'true')
                _addHiddenInput(form, 'workflow-action-name', buttonElement.dataset.workflowActionName)
            }
        }, {capture: true});
    });
}


text:
#ifndef _WIN32
	#define DLLExport
#endif

#ifdef _WIN32
	#ifdef ENGINE_DLL_EXPORTS
		#define DLLExport __declspec(dllexport)
	#else
		#define DLLExport __declspec(dllimport)
	#endif

	// Disable the warning C4251 which is triggered by stl classes in
	// Ceres' public interface. To quote MSDN: "C4251 can be ignored "
	// "if you are deriving from a type in the Standard C++ Library"
	#pragma warning( push )
	#pragma warning( disable : 4251 )

	// Disable C4250 - inheritance via dominance
	#pragma warning( disable : 4250 )

	#pragma warning( disable : 4099 )

#endif


text:
if ENV["TRAVIS"]
  require 'simplecov'
  SimpleCov.start

  require 'codecov'
  SimpleCov.formatter = SimpleCov::Formatter::Codecov
end


text:
package com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.instancegroup;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.sequenceiq.cloudbreak.api.endpoint.v4.recipes.responses.RecipeV4Response;
import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.base.InstanceGroupV4Base;
import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.instancegroup.instancemetadata.InstanceMetaDataV4Response;
import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.instancegroup.network.InstanceGroupNetworkV4Response;
import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.instancegroup.securitygroup.SecurityGroupV4Response;
import com.sequenceiq.cloudbreak.api.endpoint.v4.stacks.response.instancegroup.template.InstanceTemplateV4Response;
import com.sequenceiq.cloudbreak.doc.ModelDescriptions;
import com.sequenceiq.cloudbreak.doc.ModelDescriptions.InstanceGroupModelDescription;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

@ApiModel
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
public class InstanceGroupV4Response extends InstanceGroupV4Base {

    @ApiModelProperty(ModelDescriptions.ID)
    private Long id;

    @ApiModelProperty(InstanceGroupModelDescription.METADATA)
    private Set<InstanceMetaDataV4Response> metadata = new HashSet<>();

    @ApiModelProperty(InstanceGroupModelDescription.TEMPLATE)
    private InstanceTemplateV4Response template;

    @ApiModelProperty(InstanceGroupModelDescription.SECURITYGROUP)
    private SecurityGroupV4Response securityGroup;

    private List<RecipeV4Response> recipes;

    @ApiModelProperty(InstanceGroupModelDescription.AVAILABILITY_ZONES)
    private Set<String> availabilityZones = new HashSet<>();

    @ApiModelProperty(InstanceGroupModelDescription.NETWORK)
    private InstanceGroupNetworkV4Response network;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Set<InstanceMetaDataV4Response> getMetadata() {
        return metadata;
    }

    public void setMetadata(Set<InstanceMetaDataV4Response> metadata) {
        this.metadata = metadata;
    }

    public InstanceTemplateV4Response getTemplate() {
        return template;
    }

    public void setTemplate(InstanceTemplateV4Response template) {
        this.template = template;
    }

    public SecurityGroupV4Response getSecurityGroup() {
        return securityGroup;
    }

    public void setSecurityGroup(SecurityGroupV4Response securityGroup) {
        this.securityGroup = securityGroup;
    }

    public List<RecipeV4Response> getRecipes() {
        return recipes;
    }

    public void setRecipes(List<RecipeV4Response> recipes) {
        this.recipes = recipes;
    }

    public InstanceGroupNetworkV4Response getNetwork() {
        return network;
    }

    public void setNetwork(InstanceGroupNetworkV4Response network) {
        this.network = network;
    }

    public Set<String>  getAvailabilityZones() {
        return availabilityZones;
    }

    public void setAvailabilityZones(Set<String>  availabilityZones) {
        this.availabilityZones = availabilityZones;
    }
}


text:
exports = module.exports = Tunnel;

var net = require('net');
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var SubTunnel = require('./sub-tunnel');

// [流程]
inherits(Tunnel, EventEmitter);

function Tunnel() {
	// 隧道类型 cipher 或 decipher
	this.type = undefined;

	// 本地监听所用的地址和端口
	this.localHost = undefined;
	this.localPort = undefined;

	// 远程地址和端口
	this.remoteHost = undefined;
	this.remotePort = undefined;

	// 传输密钥
	this.key = undefined;

	// 当前状态
	// undefined - 从未开始
	// start - 已经开始
	// stop - 已经结束
	this.status = undefined;

	// 执行结果
	this.success = undefined;
	this.errorText = undefined;

	// 内部变量
	this.server = undefined;
	this.subTunnelList = undefined;
}

Tunnel.prototype.start = function() {
	var self = this;

	// 参数检查
	// TODO

	// 不允许重入
	if (self.status === 'start') {
		return false;
	}

	// 通知订阅者
	self.status = 'start';
	self.emit('start');

	self.subTunnelList = [];

	self.server = net.createServer();
	self.server.on('connection', onConnection);
	self.server.on('error', onError);
	self.server.on('close', onClose);
	self.server.listen(self.localPort, self.localHost);

	function onConnection(clientSocket) {
		var subTunnel = new SubTunnel();
		subTunnel.clientSocket = clientSocket;
		subTunnel.serverHost = self.remoteHost;
		subTunnel.serverPort = self.remotePort;
		subTunnel.type =self.type;
		subTunnel.key = self.key;

		// 注意:这里没有考虑释放的问题
		// 因此会造成内存的泄漏

		subTunnel.start();
	}

	function onError(err) {
		// 停止所有子隧道
		stopAllSubTunnel();

		self.status = 'stop';
		self.success = false;
		self.errorText = err.toString();
		self.emit('stop');
	}

	function onClose() {
		// 停止所有子隧道
		stopAllSubTunnel();

		// 如果 close 事件发生时还没有停止
		// 说明一直没出错
		if (self.status === 'start') {
			self.status = 'stop';
			self.success = true;
			self.errorText = undefined;
			self.emit('stop');
		}
	}

	function stopAllSubTunnel() {
		if (Array.isArray(self.subTunnelList)) {
			self.subTunnelList.forEach(function(subTunnel) {
				subTunnel.stop();
			});
		}
	}
}

Tunnel.prototype.stop = function() {
	var self = this;

	if (self.status === 'start') {
		self.server.close();
	}
}


text:
package ua.riaval.quiztest.dao;

import javax.ejb.Local;

import ua.riaval.quiztest.entity.QuestionType;

@Local
public interface QuestionTypeDAO extends DAO<QuestionType> {

	public QuestionType findByTypeName(String typeName);

}


text:
/**
 * Created by mkg on 11/5/2016.
 */
import React, { Component } from 'react';
import {
    AppRegistry,
    Dimensions,
    ListView,
    StyleSheet,
    Text,
    View
} from 'react-native';

class EventView extends Component {
    constructor(props) {
        super(props);
        this.state = this.props.store.getState();
        this.camIndex = ((this.props.route.passProps.camIndex!=null) ? this.props.route.passProps.camIndex : -1 );
        this.unsubscribe = this.props.store.subscribe(()=>{
            this.setState(this.props.store.getState());
            }
            ,this)
    }

    componentWillUnmount(){
        this.unsubscribe();
    }

    render() {
        var events = this.state.events;
        if (this.camIndex!=-1){
            events = events.filter((t)=> {
                    return t.camIndex==this.camIndex;
                }
            , this);
        }
        var eventLog = events.map(
            (data, i) => {
                return(
                    <Text key={i}>{this.state.cameras[data.camIndex].state.name}: {data.eventType}</Text>
                );
            }
        , this);
        return (
            <View>
                {eventLog}
            </View>
        );
    }
}

const styles = StyleSheet.create({

});

export default EventView;


text:
'use strict';

const View = require('@scola/view');

class CheckboxView extends View.Abstract {
  constructor() {
    super();
    this.isChecked = false;
  }

  build() {
    this
      .element('wrapper', 'div')
      .style({
        position: 'relative'
      });

    this
      .element('input', 'input')
      .properties({
        type: 'checkbox'
      })
      .style({
        opacity: 0
      })
      .listen({
        click: this.handleClick,
        check: this.handleCheck
      }, this)
      .appendTo(
        this.element('wrapper')
      );

    this
      .element('outer', 'div')
      .style({
        border: '0.3em solid #FFF',
        background: '#FFF',
        cursor: 'pointer',
        height: '1.5em',
        left: 0,
        position: 'absolute',
        textAlign: 'center',
        top: 0,
        width: '1.5em'
      })
      .listen({
        click: this.handleClick
      }, this)
      .appendTo(
        this.element('wrapper')
      );

    this
      .element('inner', 'div')
      .style({
        bottom: 0,
        left: 0,
        position: 'absolute',
        right: 0,
        top: 0
      })
      .appendTo(
        this.element('outer')
      );
  }

  render() {
    return this.element('wrapper');
  }

  checked() {
    return this.element('input').get().checked;
  }

  handleClick() {
    const element = this.element('input').get();

    this.isChecked = !this.isChecked;
    element.checked = this.isChecked;

    this.element('input').emit('check', {
      view: this,
      checked: this.isChecked
    });
  }

  handleCheck(event) {
    event
      .view
      .element('inner')
      .style({
        background: event.checked ? '#000' : 'none'
      });
  }
}

module.exports = CheckboxView;


text:
layout: page
title: Twin Enterprises Conference
date: 2016-05-24
author: Douglas Dillon
tags: weekly links, java
status: published
summary: Pellentesque tincidunt iaculis tellus, a eleifend felis viverra.
banner: images/banner/leisure-03.jpg
booking:
  startDate: 10/01/2016
  endDate: 10/05/2016
  ctyhocn: LAXVLHX
  groupCode: TEC
published: true
---
Fusce dignissim tincidunt ex et aliquet. Integer sed consequat leo. Fusce congue sem ante, varius ultricies enim rutrum quis. Proin quis pulvinar magna, at fringilla ligula. Etiam hendrerit non justo eget sollicitudin. Maecenas et turpis vel dui gravida ultricies. Morbi tincidunt metus ac lacus porttitor, vel fermentum enim dapibus.

* Sed non felis eu eros dictum vulputate
* Curabitur faucibus sapien non sapien gravida, ut aliquam dui tincidunt
* Nullam maximus elit at nulla fringilla mattis.

Nulla porta felis augue, at tempus ipsum lobortis et. Vestibulum velit risus, iaculis eu laoreet ac, rhoncus nec diam. Curabitur at felis justo. Nullam ac urna id massa congue placerat scelerisque sed ante. Nulla ultricies augue eu sem lobortis, et fermentum felis rhoncus. Sed vestibulum, purus non congue finibus, eros lacus maximus purus, sit amet ullamcorper augue nisl ut lectus. Nunc vel nibh feugiat, aliquet mauris quis, dignissim risus. Donec eget dolor nec metus ornare rhoncus ut quis tortor. In eget viverra ipsum. Vestibulum faucibus fermentum sem, quis venenatis augue egestas sit amet. Pellentesque libero dui, iaculis sit amet tincidunt a, pharetra quis tellus. Aliquam tempus vel est eget viverra. Donec eu felis vitae risus semper euismod eget non magna. Ut rutrum id magna id sagittis. Cras sapien mi, facilisis vitae consectetur vitae, suscipit at diam. Morbi mi magna, consequat et diam eu, maximus malesuada ligula.


text:
package com.angkorteam.framework.wicket.markup.html.form;
/**
 * Created by Khauv Socheat on 4/14/2016.
 */

import com.angkorteam.framework.wicket.resource.CodeMirrorResourceReference;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.model.IModel;

public class HtmlTextArea extends TextArea<String> {
    public HtmlTextArea(String id) {
        super(id);
    }

    public HtmlTextArea(String id, IModel<String> model) {
        super(id, model);
    }

    protected void onInitialize() {
        super.onInitialize();
        this.setOutputMarkupId(true);
    }

    public void renderHead(IHeaderResponse response) {
        super.renderHead(response);
        String markupId = this.getMarkupId(true);
        response.render(CssHeaderItem.forReference(CodeMirrorResourceReference.CODE_MIRROR_STYLE));
        response.render(CssHeaderItem.forReference(CodeMirrorResourceReference.SHOW_HINT_STYLE));
        response.render(CssHeaderItem.forReference(CodeMirrorResourceReference.FULLSCREEN_STYLE));
        response.render(CssHeaderItem.forReference(CodeMirrorResourceReference.THEME_NIGHT_STYLE));
        response.render(JavaScriptHeaderItem.forReference(CodeMirrorResourceReference.CODE_MIRROR_JAVASCRIPT));
        response.render(JavaScriptHeaderItem.forReference(CodeMirrorResourceReference.SHOW_HINT_JAVASCRIPT));
        response.render(JavaScriptHeaderItem.forReference(CodeMirrorResourceReference.CSS_HINT_JAVASCRIPT));
        response.render(JavaScriptHeaderItem.forReference(CodeMirrorResourceReference.HTML_HINT_JAVASCRIPT));
        response.render(JavaScriptHeaderItem.forReference(CodeMirrorResourceReference.XML_JAVASCRIPT));
        response.render(JavaScriptHeaderItem.forReference(CodeMirrorResourceReference.SCRIPT_JAVASCRIPT));
        response.render(JavaScriptHeaderItem.forReference(CodeMirrorResourceReference.CSS_JAVASCRIPT));
        response.render(JavaScriptHeaderItem.forReference(CodeMirrorResourceReference.VB_JAVASCRIPT));
        response.render(JavaScriptHeaderItem.forReference(CodeMirrorResourceReference.HTML_JAVASCRIPT));
        response.render(JavaScriptHeaderItem.forReference(CodeMirrorResourceReference.FULLSCREEN_JAVASCRIPT));
        response.render(OnDomReadyHeaderItem.forScript("CodeMirror.fromTextArea(document.getElementById('" + markupId + "'), { indentUnit: 4, lineNumbers: true, theme: 'night', extraKeys: {'Ctrl-Space': 'autocomplete', 'F11': function(cm) { cm.setOption('fullScreen', !cm.getOption('fullScreen')); }, 'Esc': function(cm) { if (cm.getOption('fullScreen')) cm.setOption('fullScreen', false); }}, mode: {name: 'htmlmixed', globalVars: true} })"));
    }
}


text:
package example.repo;

import example.model.Customer349;

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface Customer349Repository extends CrudRepository<Customer349, Long> {

	List<Customer349> findByLastName(String lastName);
}


text:
//******************************************************************************************************
//  CommandFrame.cs - Gbtc
//
//  Copyright © 2012, Grid Protection Alliance.  All Rights Reserved.
//
//  Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See
//  the NOTICE file distributed with this work for additional information regarding copyright ownership.
//  The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT
//
//  Unless agreed to in writing, the subject software distributed under the License is distributed on an
//  "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the
//  License for the specific language governing permissions and limitations.
//
//  Code Modification History:
//  ----------------------------------------------------------------------------------------------------
//  04/27/2009 - J. Ritchie Carroll
//       Generated original version of source code.
//  09/15/2009 - Stephen C. Wills
//       Added new header and license agreement.
//  12/17/2012 - Starlynn Danyelle Gilliam
//       Modified Header.
//
//******************************************************************************************************

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using GSF.IO.Checksums;
using GSF.Parsing;

namespace GSF.PhasorProtocols.SelFastMessage
{
    /// <summary>
    /// Represents the SEL Fast Message implementation of a <see cref="ICommandFrame"/> that can be sent or received.
    /// </summary>
    /// <remarks>
    /// SEL Fast Message command frames are designed only to be sent to a device, not received from a device. As a result
    /// this frame does not implement <see cref="ISupportFrameImage{TTypeIdentifier}"/> for automated frame parsing. This class
    /// exposes a constructor that accepts a binary image in order to manually parse a command frame.
    /// </remarks>
    [Serializable]
    public class CommandFrame : CommandFrameBase
    {
        #region [ Members ]

        // Fields
        private MessagePeriod m_messagePeriod;

        #endregion

        #region [ Constructors ]

        /// <summary>
        /// Creates a new <see cref="CommandFrame"/> from the given <paramref name="buffer"/>.
        /// </summary>
        /// <param name="buffer">Binary image to parse.</param>
        /// <param name="startIndex">Start index into <paramref name="buffer"/> to begin parsing.</param>
        /// <param name="length">Length of valid data within <paramref name="buffer"/>.</param>
        /// <remarks>
        /// This constructor is used by a consumer to parse a received SEL Fast Message command frame. Typically
        /// command frames are sent to a device. This constructor would used if this code was being used
        /// inside of a phasor measurement device.
        /// </remarks>
        /// <exception cref="ArgumentOutOfRangeException"><paramref name="length"/> is not large enough to parse frame.</exception>
        public CommandFrame(byte[] buffer, int startIndex, int length)
            : base(new CommandCellCollection(0), PhasorProtocols.DeviceCommand.ReservedBits)
        {
            if (length < 16)
                throw new ArgumentOutOfRangeException(nameof(length));

            // Validate check-sum
            if (!ChecksumIsValid(buffer, startIndex))
                throw new InvalidOperationException($"Invalid binary image detected - check sum of {GetType().Name} did not match");

            // Validate SEL Fast Message data image
            if (buffer[startIndex] != Common.HeaderByte1 || buffer[startIndex + 1] != Common.HeaderByte2)
                throw new InvalidOperationException($"Bad data stream, expected header bytes 0xA546 as first bytes in SEL Fast Message command frame, got 0x{buffer[startIndex].ToString("X").PadLeft(2, '0')}{buffer[startIndex + 1].ToString("X").PadLeft(2, '0')}");

            Command = (DeviceCommand)buffer[startIndex + 9];

            if (Command == DeviceCommand.EnableUnsolicitedMessages)
                m_messagePeriod = (MessagePeriod)BigEndian.ToUInt16(buffer, startIndex + 14);

            // Validate check-sum
            int sumLength = FrameSize - 2;

            if (BigEndian.ToUInt16(buffer, startIndex + sumLength) != CalculateChecksum(buffer, startIndex, sumLength))
                throw new InvalidOperationException($"Invalid binary image detected - check sum of {GetType().Name} did not match");
        }

        /// <summary>
        /// Creates a new <see cref="CommandFrame"/> from specified parameters.
        /// </summary>
        /// <param name="command">The <see cref="PhasorProtocols.DeviceCommand"/> for this <see cref="CommandFrame"/>.</param>
        /// <param name="messagePeriod">The desired <see cref="SelFastMessage.MessagePeriod"/> for SEL device connection.</param>
        /// <remarks>
        /// This constructor is used by a consumer to generate an SEL Fast Message command frame.
        /// </remarks>
        public CommandFrame(PhasorProtocols.DeviceCommand command, MessagePeriod messagePeriod)
            : base(new CommandCellCollection(0), command)
        {
            if (command != PhasorProtocols.DeviceCommand.EnableRealTimeData && command != PhasorProtocols.DeviceCommand.DisableRealTimeData)
                throw new ArgumentException($"SEL Fast Message does not support {command} device command.", nameof(command));

            m_messagePeriod = messagePeriod;
        }

        /// <summary>
        /// Creates a new <see cref="CommandFrame"/> from serialization parameters.
        /// </summary>
        /// <param name="info">The <see cref="SerializationInfo"/> with populated with data.</param>
        /// <param name="context">The source <see cref="StreamingContext"/> for this deserialization.</param>
        protected CommandFrame(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            // Deserialize command frame
            m_messagePeriod = (MessagePeriod)info.GetValue("messagePeriod", typeof(MessagePeriod));
        }

        #endregion

        #region [ Properties ]

        /// <summary>
        /// Gets or sets the <see cref="DeviceCommand"/> for this <see cref="CommandFrame"/>.
        /// </summary>
        public new DeviceCommand Command
        {
            // Interpret SEL specific device command
            get
            {
                return base.Command switch
                {
                    PhasorProtocols.DeviceCommand.EnableRealTimeData => DeviceCommand.EnableUnsolicitedMessages,
                    PhasorProtocols.DeviceCommand.DisableRealTimeData => DeviceCommand.DisableUnsolicitedMessages,
                    _ => DeviceCommand.Undefined,
                };
            }
            set
            {
                base.Command = value switch
                {
                    DeviceCommand.EnableUnsolicitedMessages => PhasorProtocols.DeviceCommand.EnableRealTimeData,
                    DeviceCommand.DisableUnsolicitedMessages => PhasorProtocols.DeviceCommand.DisableRealTimeData,
                    _ => PhasorProtocols.DeviceCommand.ReservedBits,
                };
            }
        }

        /// <summary>
        /// Gets or sets the desired message period for the SEL device.
        /// </summary>
        public MessagePeriod MessagePeriod
        {
            get => m_messagePeriod;
            set => m_messagePeriod = value;
        }

        /// <summary>
        /// Gets frame size based on <see cref="Command"/>.
        /// </summary>
        public byte FrameSize => (byte)(Command == DeviceCommand.EnableUnsolicitedMessages ? 18 : 16);

        /// <summary>
        /// Gets the length of the <see cref="HeaderImage"/>.
        /// </summary>
        protected override int HeaderLength => 9;

        /// <summary>
        /// Gets the binary header image of the <see cref="DataFrame"/> object.
        /// </summary>
        protected override byte[] HeaderImage
        {
            get
            {
                byte[] buffer = new byte[9];

                buffer[0] = Common.HeaderByte1;
                buffer[1] = Common.HeaderByte2;
                buffer[2] = FrameSize;

                return buffer;
            }
        }

        /// <summary>
        /// Gets the length of the <see cref="BodyImage"/>.
        /// </summary>
        protected override int BodyLength =>
            FrameSize - HeaderLength - 2; // Total frame size - header length - CRC value length

        /// <summary>
        /// Gets the binary body image of this <see cref="CommandFrame"/>.
        /// </summary>
        protected override byte[] BodyImage
        {
            get
            {
                byte[] buffer = new byte[BodyLength];

                buffer[0] = (byte)Command;
                buffer[1] = 0xC0;
                buffer[3] = 0x20;

                // Only add desired message rate for enable command
                if (Command == DeviceCommand.EnableUnsolicitedMessages)
                    BigEndian.CopyBytes((ushort)m_messagePeriod, buffer, 5);

                return buffer;
            }
        }

        /// <summary>
        /// <see cref="Dictionary{TKey,TValue}"/> of string based property names and values for the <see cref="DataFrame"/> object.
        /// </summary>
        public override Dictionary<string, string> Attributes
        {
            get
            {
                Dictionary<string, string> baseAttributes = base.Attributes;

                baseAttributes.Add("Defined Message Period", $"{(ushort)MessagePeriod}: {MessagePeriod}");

                return baseAttributes;
            }
        }

        #endregion

        #region [ Methods ]

        /// <summary>
        /// Calculates checksum of given <paramref name="buffer"/>.
        /// </summary>
        /// <param name="buffer">Buffer image over which to calculate checksum.</param>
        /// <param name="offset">Start index into <paramref name="buffer"/> to calculate checksum.</param>
        /// <param name="length">Length of data within <paramref name="buffer"/> to calculate checksum.</param>
        /// <returns>Checksum over specified portion of <paramref name="buffer"/>.</returns>
        protected override ushort CalculateChecksum(byte[] buffer, int offset, int length)
        {
            // SEL Fast Message uses CRC Modbus to calculate checksum for frames
            return buffer.ModBusCrcChecksum(offset, length);
        }

        /// <summary>
        /// Populates a <see cref="SerializationInfo"/> with the data needed to serialize the target object.
        /// </summary>
        /// <param name="info">The <see cref="SerializationInfo"/> to populate with data.</param>
        /// <param name="context">The destination <see cref="StreamingContext"/> for this serialization.</param>
        public override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            base.GetObjectData(info, context);

            // Serialize command frame
            info.AddValue("messagePeriod", m_messagePeriod, typeof(MessagePeriod));
        }

        #endregion
    }
}


text:
import greenfoot.*;  // (World, Actor, GreenfootImage, and Greenfoot)

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

/**
 * Wombat. A Wombat moves forward until it can't do so anymore, at
 * which point it turns left. If a wombat finds a leaf, it eats it.
 *
 * @author Michael Kolling
 * @version 1.0.1
 */
public class Wombat extends Actor
{
    private static final int EAST = 0;
    private static final int WEST = 1;
    private static final int NORTH = 2;
    private static final int SOUTH = 3;

    private int direction;
    private int leavesEaten;

    public Wombat()
    {
        setDirection(EAST);
        leavesEaten = 0;
        setImage("wombat.gif");
    }

    /**
     * Do whatever the wombat likes to to just now.
     */
    public void act()
    {
        optChangeDirection();
        if(foundFood()) {
            eatFood();
        }
        else if(canMove()) {
            move();
        }
        else {
            turnLeft();
        }
    }

    private void optChangeDirection() {
		if (Greenfoot.mousePressed(null)) {
			MouseInfo mouse = Greenfoot.getMouseInfo();
			int px = mouse.getX();
			int py = mouse.getY();
			int hx = this.getX();
			int hy = this.getY();
			switch (direction) {
			case WEST:
			case EAST:
				if (py <= hy) {
					setDirection(NORTH);
				} else {
					setDirection(SOUTH);
				}
				break;
			case NORTH:
			case SOUTH:
				if (px <= hx) {
					setDirection(WEST);
				} else {
					setDirection(EAST);
				}
				break;
			}
		}
	}

    /**
     * Check whether there is a leaf in the same cell as we are.
     */
    public boolean foundFood()
    {
        Actor food = getOneObjectAtOffset(0, 0, Food.class);
        if(food != null) {
            return true;
        }
        else {
            return false;
        }
    }

    /**
     * Eat a leaf.
     */
    public void eatFood()
    {
        Food food = (Food)getOneObjectAtOffset(0, 0, Food.class);
        if(food != null) {
            // eat the leaf...
            World world = getWorld();
            if(food.bPoisonous()){
                world.removeObject(food);
                world.removeObject(this);
                Greenfoot.stop();
            }else{
                world.removeObject(food);
                leavesEaten = leavesEaten + 1;
            }
        }
    }

    /**
     * Move one cell forward in the current direction.
     */
    public void move()
    {
        if (!canMove()) {
            return;
        }
        switch(direction) {
            case SOUTH :
                setLocation(getX(), getY() + 1);
                break;
            case EAST :
                setLocation(getX() + 1, getY());
                break;
            case NORTH :
                setLocation(getX(), getY() - 1);
                break;
            case WEST :
                setLocation(getX() - 1, getY());
                break;
        }
    }

    /**
     * Test if we can move forward. Return true if we can, false otherwise.
     */
    public boolean canMove()
    {
        World myWorld = getWorld();
        int x = getX();
        int y = getY();
        switch(direction) {
            case SOUTH :
                y++;
                break;
            case EAST :
                x++;
                break;
            case NORTH :
                y--;
                break;
            case WEST :
                x--;
                break;
        }
        // test for outside border
        if (x >= myWorld.getWidth() || y >= myWorld.getHeight()) {
            return false;
        }
        else if (x < 0 || y < 0) {
            return false;
        }
        return true;
    }

    /**
     * Turns towards the left.
     */
    public void turnLeft()
    {
        switch(direction) {
            case SOUTH :
                setDirection(EAST);
                break;
            case EAST :
                setDirection(NORTH);
                break;
            case NORTH :
                setDirection(WEST);
                break;
            case WEST :
                setDirection(SOUTH);
                break;
        }
    }

    /**
     * Sets the direction we're facing.
     */
    public void setDirection(int direction)
    {
        this.direction = direction;
        switch(direction) {
            case SOUTH :
                setRotation(90);
                break;
            case EAST :
                setRotation(0);
                break;
            case NORTH :
                setRotation(270);
                break;
            case WEST :
                setRotation(180);
                break;
            default :
                break;
        }
    }

    /**
     * Tell how many leaves we have eaten.
     */
    public int getLeavesEaten()
    {
        return leavesEaten;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView ="18.0sp" ="@color/dark_gray" ="left" ="fill_parent" ="wrap_content" ="true" style="@style/gotham_book"
  xmlns:android="http://schemas.android.com/apk/res/android" />


text:
This code of conduct outlines our expectations for participants within the open source community. Anyone who violates this code of conduct may be banned from contributing here.

# Requirements
* __Be friendly and patient.__
* __Be welcoming__ _We strive to be a community that welcomes and supports people of all backgrounds and identities._
* __Be respectful__ _Not all of us will agree all the time, but disagreement is no excuse for poor behavior and poor manners._

# Unacceptable Behaviour
* Offensive comments related to gender, sexual orientation, disability, mental illness, physical appearance, body size, race, age, regional discrimination, political or religious affiliation.
* Threats of violence, both physical and psycological.
* Incitement of violence towards any individual, including encouraging a person to commit suicide or to engage in self-harm.
* Continued communication after requests to cease.

# Interactions
* Don't just tell somebody they are wrong, or what they have done is wrong. You must always explain what is wrong, and why it is wrong.
* Don't reject contributions that are partially complete and then go and commit your own version. Try to work with the author to complete their work.
* We encourage everyone to participate and are committed to building a community for all, we seek to treat everyone both as fairly and equally as possible.


text:
HexavilleAuth is an Authentication(OAuth, simple password based) framework for [Hexaville](https://github.com/noppoMan/Hexaville).

HexavilleAuth recognizes that each application has unique authentication requirements. It allows individual authentication mechanisms to be packaged as plugins which it consumes.

Plugins can range from a simple password based authentication or, authentication using OAuth (via Facebook, Github OAuth provider, etc.).

HexavilleAuth automatically creates resources for authorize/callback for each sns platforms, So you can embed sns authentication features into your Hexaville application very quickly.

## Authentication Methods
* [ ] Email+password

## Authorization Methods
* [x] OAuth1
* [x] OAuth2

## Supported SNS Platforms

### OAuth2

* [x] Facebook
* [x] Github
* [x] Google
* [x] Instagram

### OAuth1
* [x] Twitter

## Installation

Just add `.Package(url: "https://github.com/Hexaville/HexavilleAuth.git", majorVersion: 0, minor: 1)` into your Package.swift

```swift
import PackageDescription

let package = Package(
    name: "MyHexavilleApplication",
    dependencies: [
        .Package(url: "https://github.com/Hexaville/HexavilleAuth.git", majorVersion: 0, minor: 1)
    ]
)
```

## Usage

Here is an example code for facebook oauth authorization with [HexavilleFramework](https://github.com/noppoMan/HexavilleFramework)

```swift
import Foundation
import HexavilleAuth
import HexavilleFramework

let app = HexavilleFramework()

var auth = HexavilleAuth()

let APP_URL = ProcessInfo.processInfo.environment["APP_URL"] ?? "http://localhost:3000"

let facebookProvider = FacebookAuthorizationProvider(
    path: "/auth/facebook",
    consumerKey: ProcessInfo.processInfo.environment["FACEBOOK_APP_ID"] ?? "",
    consumerSecret: ProcessInfo.processInfo.environment["FACEBOOK_APP_SECRET"] ?? "",
    callbackURL: CallbackURL(baseURL: APP_URL, path: "/auth/facebook/callback"),
    scope: "public_profile"
) { credential, user, request, context in

    // here is called when the access_token got successfully from sns.

    return Response(body: "\(user)")
}

auth.add(facebookProvider)

app.use(auth)

app.catch { error in
    switch error {
    case HexavilleAuthError.responseError(let response):
        return Response(body: response.body.asData())
    default:
        return Response(body: "\(error)")
    }
}

try app.run()
```

## Getting loginUser object on the every requests.

If you register `HexavilleAuth.AuthenticationMiddleware` and loginUser information is stored in the session, You can get it from `ApplicationContext` as `LoginUser` Object.

### LoginUser
```swift
public struct LoginUser {
    public let id: String
    public let name: String
    public let screenName: String?
    public let email: String?
    public let picture: String?
    public let raw: [String: Any]
}
```

### Example

```swift
import Foundation
import HexavilleAuth
import HexavilleFramework

let app = HexavilleFramework()

var auth = HexavilleAuth()

let APP_URL = ProcessInfo.processInfo.environment["APP_URL"] ?? "http://localhost:3000"

let twitterProvider = TwitterAuthorizationProvider(
    path: "/auth/twitter",
    consumerKey: ProcessInfo.processInfo.environment["TWITTER_APP_ID"] ?? "",
    consumerSecret: ProcessInfo.processInfo.environment["TWITTER_APP_SECRET"] ?? "",
    callbackURL: CallbackURL(baseURL: APP_URL, path: "/auth/twitter/callback"),
    scope: ""
) { credential, user, request, context in
    return Response(body: "\(user)")
}

app.use(HexavilleAuth.AuthenticationMiddleware()) // register to get loginUser Object

app.use { req, context in
  print(context.isAuthenticated()) // => true
  print(context.loginUser) // Get the loginUser object
  return .next(req)
}

auth.add(twitterProvider)

app.use(auth)

try app.run()
```

## Try Example!

[Here is an official full example code](https://github.com/Hexaville/HexavilleAuth/blob/master/Sources/HexavilleAuthExample/main.swift).

### Install and Build Example

```sh
git clone https://github.com/Hexaville/HexavilleAuth.git
cd HexavilleAuth
cd swift build
```

### Launch Server

```sh
./.build/debug/HexavilleAuthExample

# => Hexaville Builtin Server started at 0.0.0.0:3000
```

### Resources

Try to access following resources to authentication/authorization with Browser!

* Facebook: http://yourlocaldomain:3000/auth/facebook
* Github: http://yourlocaldomain:3000/auth/github
* Instagram: http://yourlocaldomain:3000/auth/instagram
* Google: http://yourlocaldomain:3000/auth/google

# Create Your Custom Authorization/Authentication Provider

You can create Custom Authorization/Authentication Provider with `OAuthXAuthorizationProvidable`/ `AuthenticationProvidable`

## Oauth2

#### OAuth2Authorization
```swift
public protocol OAuth2AuthorizationProvidable {
    var path: String { get } // path for authorize
    var oauth: OAuth2 { get }
    var callback: RespodWithCredential { get }  // callback for success handler
    init(path: String, consumerKey: String, consumerSecret: String, callbackURL: CallbackURL, scope: String, callback: @escaping RespodWithCredential)
    func getAccessToken(request: Request) throws -> Credential
}
```

here is an example for Salesforce Authorization.

```swift
public struct SalesforceAuthorizationProvider: OAuth2AuthorizationProvidable {

    public let path: String

    public let oauth: OAuth2

    public let callback: RespodWithCredential

    public init(path: String, consumerKey: String, consumerSecret: String, callbackURL: CallbackURL, scope: String, callback: @escaping RespodWithCredential) {
        self.path = path

        self.oauth = OAuth2(
            consumerKey: consumerKey,
            consumerSecret: consumerSecret,
            authorizeURL: "https://login.salesforce.com/services/oauth2/authorize",
            accessTokenURL: "https://login.salesforce.com/services/oauth2/token",
            callbackURL: callbackURL,
            scope: scope
        )

        self.callback = callback
    }
}
```

Use it!
```swift
var auth = HexavilleAuth()

let salesforceProvider = SalesforceAuthorizationProvider(
    path: "/auth/salesforce",
    consumerKey: "consumer",
    consumerSecret: "secret",
    callbackURL: CallbackURL(baseURL: APP_URL, path: "/auth/salesforce/callback"),
    scope: "public_profile"
) { credential, user, request, context in

    try DB.save(token: credential.accessToken)

    return Response(body: "\(user)")
}

auth.add(salesforceProvider)
```

## License

HexavilleAuth is released under the MIT license. See LICENSE for details.


text:
package org.abins.platform.utils;

import java.net.InetAddress;
import java.util.HashSet;
import java.util.Set;

/**
 * 功能描述:主键UUID生成
 *
 * @author : yaobin 2016-10-10
 * @modify : yaobin 2016-10-10 <描述修改内容>
 */
public class UUIDGenerator {

    /**
     * 产生一个32位的UUID
     *
     * @return
     */

    public static String generate() {
        return new StringBuilder(32).append(format(getIP())).append(format(getJVM())).append(format(getHiTime())).append(format(getLoTime())).append(format(getCount())).toString();

    }

    private static final int IP;
    static {
        int ipadd;
        try {
            ipadd = toInt(InetAddress.getLocalHost().getAddress());
        } catch (Exception e) {
            ipadd = 0;
        }
        IP = ipadd;
    }

    private static short counter = (short)0;

    private static final int JVM = (int)(System.currentTimeMillis() >>> 8);

    private final static String format(int intval) {
        String formatted = Integer.toHexString(intval);
        StringBuilder buf = new StringBuilder("00000000");
        buf.replace(8 - formatted.length(), 8, formatted);
        return buf.toString();
    }

    private final static String format(short shortval) {
        String formatted = Integer.toHexString(shortval);
        StringBuilder buf = new StringBuilder("0000");
        buf.replace(4 - formatted.length(), 4, formatted);
        return buf.toString();
    }

    private final static int getJVM() {
        return JVM;
    }

    private final static short getCount() {
        synchronized (UUIDGenerator.class) {
            if (counter < 0)
                counter = 0;
            return counter++;
        }
    }

    /**
     * Unique in a local network
     */
    private final static int getIP() {
        return IP;
    }

    /**
     * Unique down to millisecond
     */
    private final static short getHiTime() {
        return (short)(System.currentTimeMillis() >>> 32);
    }

    private final static int getLoTime() {
        return (int)System.currentTimeMillis();
    }

    private final static int toInt(byte[] bytes) {
        int result = 0;
        for (int i = 0; i < 4; i++) {
            result = (result << 8) - Byte.MIN_VALUE + (int)bytes[i];
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(UUIDGenerator.generate());
        for (int i = 0; i < 1000000; i++) {
            String a = UUIDGenerator.generate();
            Set<String> set = new HashSet<String>();
            if(set.contains(a)){
                System.out.println(a);
            }
            set.add(a);
        }
    }
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Wang, Jia & Bai, Int. J. Syst. Evol. Microbiol. 56(1): 291 (2006)

#### Original name
Pseudozyma hubeiensis F.Y. Bai & Q.M. Wang, 2006

### Remarks
null


text:
namespace Azure.ResourceManager.Monitor.Models
{
    /// <summary> The log files specific settings. </summary>
    internal partial class LogFilesDataSourceSettings : LogFileSettings
    {
        /// <summary> Initializes a new instance of LogFilesDataSourceSettings. </summary>
        public LogFilesDataSourceSettings()
        {
        }

        /// <summary> Initializes a new instance of LogFilesDataSourceSettings. </summary>
        /// <param name="text"> Text settings. </param>
        internal LogFilesDataSourceSettings(LogFileSettingsText text) : base(text)
        {
        }
    }
}