text:
#ifndef _TASKS_SOCKET_H_
#define _TASKS_SOCKET_H_

#include <string>
#include <exception>
#include <memory>
#include <cerrno>
#include <sys/types.h>
#include <sys/socket.h>

#include <tasks/io_base.h>
#include <tasks/tasks_exception.h>

#ifdef _OS_LINUX_
#define SEND_RECV_FLAGS MSG_NOSIGNAL
#else
#define SEND_RECV_FLAGS 0
#endif

struct sockaddr_in;

namespace tasks {
namespace net {

enum class socket_type { TCP, UDP };

/// The socket class.
class socket : public io_base {
  public:
    /// Constructor
    ///
    /// \param fd Use fd for the socket object.
    socket(int fd) : io_base(fd) {}

    /// Constructor
    ///
    /// \param socket_type The socket type. The default is socket_type::TCP for stream sockets (used for unix domain
    ///   sockets too). For UDP sockets use socket_type::UDP.
    socket(socket_type = socket_type::TCP);

    /// \return True if the socket type is socket_type::UDP.
    inline bool udp() const { return m_type == socket_type::UDP; }

    /// \return True if the socket type is socket_type::TCP.
    inline bool tcp() const { return m_type == socket_type::TCP; }

    /// \return The the socket type.
    inline socket_type type() const { return m_type; }

    /// \return A pointer to the sockaddr_in struct.
    inline std::shared_ptr<struct sockaddr_in> addr() { return m_addr; }

    /// Set the socket to blocking mode.
    inline void set_blocking() { m_blocking = true; }

    /// Bind for udp sockets. This method can be used to bind udp sockets. For tcp servers
    /// \link socket::listen(std::string path, int queue_size) \endlink or \link socket::listen(int port, std::string
    /// ip, int queue_size) \endlink has to be called.
    ///
    /// \param port The port.
    /// \param ip The ip address in dot notation (optional).
    void bind(int port, std::string ip = "");

    /// Listen for unix domain sockets.
    ///
    /// \param path The path to the socket file.
    /// \param queue_size The liste queue size. The default value is 128.
    void listen(const std::string& path, int queue_size = 128);

    // Listen for tcp sockets.
    ///
    /// \param port The port.
    /// \param ip The ip address in dot notation (optional).
    /// \param queue_size The liste queue size. The default value is 128.
    void listen(int port, std::string ip = "", int queue_size = 128);

    /// Accept new client connections.
    socket accept();

    /// Connect to a domain socket.
    ///
    /// \param path The path to the socket file.
    void connect(const std::string& path);

    /// Connect via tcp.
    ///
    /// \param host The hostname or ip address in dot notation.
    /// \param port The port.
    void connect(const std::string& host, int port);

    /// Call shutdown on the fd.
    void shutdown();

    /// Write data to the socket.
    ///
    /// \param data A pointer to the source data.
    /// \param len The number of bytes to write.
    /// \param port As UDP sockets are not connection based, the remote port has to be passed.
    /// \param ip Optional ip in dot notation for UDP writes.
    std::streamsize write(const char* data, std::size_t len, int port = -1, std::string ip = "");

    /// Read data from a socket.
    ///
    /// \param data A pointer to the destination data.
    /// \param len The number of bytes to write.
    std::streamsize read(char* data, std::size_t len);

  private:
    socket_type m_type = socket_type::TCP;
    bool m_blocking = false;
    std::shared_ptr<struct sockaddr_in> m_addr;

    void bind(int port, const std::string& ip, bool udp);
    void init_sockaddr(int port, std::string ip = "");
};

}  // net
}  // tasks

#endif  // _TASKS_SOCKET_H_


text:
package models;

import helpers.ApplicationHelpers;

import java.util.*;
import javax.persistence.*;

import play.db.jpa.*;
import play.data.validation.*;
import play.data.binding.*;

import org.joda.time.*;

import org.hibernate.annotations.Type;

import javax.persistence.*;
import javax.persistence.criteria.*;

/* One of the main business entities:
ALL RFIs are associated w/ an event, an "event" is the programmatic term that maps
to a business-level "Event or disaster the R3 team is supporting"
*/
@Entity
@Table(name="Events")
public class Event extends Model {
    @Required
    public String name;

    public Boolean archived;

    public String smtsCategory;

    @ManyToMany(fetch=FetchType.EAGER)
    public Set<Group> groups;

    @Lob
    @Required
    public String region;

    @Required
    @Lob
    public String description;

    @ManyToMany(cascade=CascadeType.ALL)
    public Set<EventActivity> eventActivities;

    @Required
    public String adminEmailAddresses;

    public String uuid;

    public String geoQId;

    @OneToMany(mappedBy="event", cascade=CascadeType.ALL)
    public List<RFI> rfis;

    public Event() {
        this.archived = false;
        this.rfis = new ArrayList<RFI>();
        this.groups = new HashSet<Group>();
        this.eventActivities = new HashSet<EventActivity>();
    }

    public String createdBy;

    @Column(name="created_at", nullable=false)
    @As("yyyy-MM-dd")
    public Date createdAt;

    @PrePersist
    public void onCreate() {
        if ( this.createdAt == null) {
            this.createdAt = new Date();
        }
        if ( this.uuid == null) {
            this.uuid = UUID.randomUUID().toString();
        }
    }

    @PostPersist
    public void onAfterCreate() {
        if ( this.networkID == null || this.networkID.equals("")) {
            this.networkID = ApplicationHelpers.getIDString(this.id);
        }
    }

    public static Long getCompletedRFICount(Event e) {
        return RFI.count("event = ? and (status = 'COMPLETED' or status = 'CANCELED')", e);
    }

    public String networkID;

    public static Long getActiveRFICount(Event e) {
        return RFI.count("event = ? and (archived is null or archived = 0)", e);
    }

    public static List<Event> getActive() {
        return Event.find("archived is null or archived = 0 order by createdAt desc").fetch();
    }

    // Only used in the RFI import
    public static Event fuzzyFind(Event e) {
        Event try1 = Event.find("byUUID", e.uuid).first();
        if ( try1 == null) {
            return Event.find("byName", e.name).first();
        }
        else {
            return try1;
        }
    }

    public static Map<String,Object> grid(String sort, String sortDirection, int page, int pageSize, Boolean active) {
        Map<String,Object> ret = new HashMap<String,Object>();

        if ( sort == null) {
            sort = "createdAt";
        }
        if ( sortDirection == null) {
            sortDirection = "desc";
        }

        if ( page < 0) {
            page = 0;
        }

        if ( pageSize <= 0) {
            pageSize = ApplicationHelpers.DEFAULT_PAGE_SIZE;
        }

        CriteriaBuilder builder = JPA.local.get().em().getCriteriaBuilder();
        CriteriaQuery qry = builder.createQuery(Event.class);
        CriteriaQuery cqry = builder.createQuery(Long.class);
        cqry.select(builder.count(cqry.from(Event.class)));
        Root<Event> eventLoad = qry.from(Event.class);
        Predicate notArchived = builder.equal(eventLoad.get("archived"), 0);
        Predicate archived = builder.equal(eventLoad.get("archived"), 1);
        Predicate archivedNotNull = builder.isNotNull(eventLoad.get("archived"));

        if ( active != null && active == false) {
            cqry.where(builder.and(archivedNotNull, archived));
            qry.where(builder.and(archivedNotNull, archived));
        }
        else if ( active != null && active == true) {
            cqry.where(builder.and(archivedNotNull, notArchived));
            qry.where(builder.and(archivedNotNull, notArchived));
        }

        if ( sortDirection.equals("asc")) {
            qry.orderBy(builder.asc(eventLoad.get(sort)));
        }
        else {
            qry.orderBy(builder.desc(eventLoad.get(sort)));
        }

        Query query = JPA.local.get().em().createQuery(qry);
        List<Event> events = query.setFirstResult(page*pageSize).setMaxResults(pageSize).getResultList();
        Long totalCount = (Long)JPA.local.get().em().createQuery(cqry).getSingleResult();

        int totalPages = (int)Math.ceil(totalCount / (float)pageSize);

        ret.put("totalPages", totalPages);
        ret.put("totalCount", totalCount);
        ret.put("events", events);
        ret.put("sort", sort);
        ret.put("sortDirection", sortDirection);
        ret.put("page", page);
        ret.put("pageSize", pageSize);
        ret.put("active", active);

        return ret;
    }

    public static List<Event> getAllNotArchived() {
        return Event.find("archived is null or archived = false").fetch();
    }

    public static List<Event> getAll() {
        return Event.all().fetch();
    }
}

redpajama_set_name: RedPajamaGithub


text:
package ch.alv.components.web.api.config;

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

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * Base implementation of a parameter.
 *
 * @since 1.0.0
 */
public abstract class BaseParameter implements Serializable {

    private String name;

    private String description;

    private ParameterType type;

    private boolean required;

    private boolean repeat;

    private List<String> enumeration = new ArrayList<>();

    private String pattern;

    private Integer minLength;

    private Integer maxLength;

    private java.math.BigDecimal minimum;

    private BigDecimal maximum;

    private String defaultValue;

    private String example;

    protected final Logger logger = LoggerFactory.getLogger(getClass());

    public BaseParameter() {
        this.type = ParameterType.STRING;
    }

    public BaseParameter(String name, ParameterType type, boolean required) {
        this.name = name;
        this.type = type;
        this.required = required;
    }

    public void setName(String displayName) {
        this.name = displayName;
    }

    public String getName() {
        return name;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDescription() {
        return description;
    }

    public void setType(ParameterType type) {
        this.type = type;
    }

    public ParameterType getType() {
        return type;
    }

    public void setRequired(boolean required) {
        this.required = required;
    }

    public boolean isRequired() {
        return required;
    }

    public boolean isRepeat() {
        return repeat;
    }

    public void setRepeat(boolean repeat) {
        this.repeat = repeat;
    }

    public String getDefaultValue() {
        return defaultValue;
    }

    public String getExample() {
        return example;
    }

    public List<String> getEnumeration() {
        return enumeration;
    }

    public void setEnumeration(List<String> enumeration) {
        this.enumeration = enumeration;
    }

    public String getPattern() {
        return pattern;
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    public Integer getMinLength() {
        return minLength;
    }

    public void setMinLength(Integer minLength) {
        this.minLength = minLength;
    }

    public Integer getMaxLength() {
        return maxLength;
    }

    public void setMaxLength(Integer maxLength) {
        this.maxLength = maxLength;
    }

    public BigDecimal getMinimum() {
        return minimum;
    }

    public void setMinimum(BigDecimal minimum) {
        this.minimum = minimum;
    }

    public BigDecimal getMaximum() {
        return maximum;
    }

    public void setMaximum(BigDecimal maximum) {
        this.maximum = maximum;
    }

    public void setDefaultValue(String defaultValue) {
        this.defaultValue = defaultValue;
    }

    public void setExample(String example) {
        this.example = example;
    }

}


text:
package com.hank.corelib.tools.task;

import rx.Observable;

/**
 * Created by hank on 2016/8/31.
 */
public abstract class TaskOnSubscribe<C> implements Observable.OnSubscribe<C> {
    private C c;

    public TaskOnSubscribe(C c) {
        setT(c);
    }

    public C getT() {
        return c;
    }

    public void setT(C c) {
        this.c = c;
    }

}


text:
<?php

require_once 'Sorter/Bubble/NumericArray.php';
require_once 'Storage/Array.php';

$bubbleSorter = new Sorter_Bubble_NumericArray();

$storage = new Storage_Array;
$storage->setElements(array(15, 204, 1, 4, 2, 6, 8, 3, 150));

$bubbleSorter->sort($storage);
var_dump($storage->getElements());


text:
class FontTrebuchetMs < Cask
  url 'http://downloads.sourceforge.net/sourceforge/corefonts/trebuc32.exe'
  homepage 'http://sourceforge.net/projects/corefonts/files/the%20fonts/final/'
  version '1.22'
  depends_on_formula 'cabextract'
  sha256 '5a690d9bb8510be1b8b4fe49f1f2319651fe51bbe54775ddddd8ef0bd07fdac9'
  font 'trebuc.ttf'
  font 'Trebucbd.ttf'
  font 'trebucbi.ttf'
  font 'trebucit.ttf'
end


text:
import * as React from "react";
import {connect} from "react-redux";
import {AppState} from "redux/reducers/AppReducers";
import * as layout from "components/css/layout.scss";
import * as sideBar from "components/css/sideBar.scss";
import * as controls from "components/css/controls.scss";
import {ComponentBase} from "components/ComponentBase";
import {loadImageList, imageListReset} from "redux/actions/ImageListActions";

interface SidebarOwnProps {
}

interface SidebarStateProps {
}

interface SidebarDispatchProps {
    dispatchLoadImageList: () => void;
    dispatchResetImageList: () => void;
}

class SidebarComponent extends ComponentBase<SidebarOwnProps, SidebarStateProps, SidebarDispatchProps, {}> {
    render() {
        return (
            <div className={this.styles(layout.sidebar2, sideBar.sideBar)}>
                <button className={this.styles(controls.stdButton)} onClick={() => this.props.dispatchLoadImageList()}>Load image list</button>
                <button className={this.styles(controls.stdButton)} onClick={() => this.props.dispatchResetImageList()}>Reset</button>
            </div>
        )
    }
}

const mapStateToProps = (state: AppState, ownProps: SidebarOwnProps): SidebarStateProps => {
    return {}
};

const mapDispatchToProps = (dispatch, ownProps: SidebarOwnProps): SidebarDispatchProps => {
    return {
        dispatchLoadImageList: () => dispatch(loadImageList()),
        dispatchResetImageList: () => dispatch(imageListReset()),
    };
};

export const Sidebar = connect<SidebarStateProps, SidebarDispatchProps, SidebarOwnProps>(
    mapStateToProps,
    mapDispatchToProps
)(SidebarComponent);


text:
    <button class="loadAnnotatorButton" title="Load annotations">
      Load
    </button>

      To load annotations, paste the code into the text box below and then click the Load button.

    <textarea class="loadAnnotatorWindow_JSON"></textarea>

      To save these annotations, copy the code contained in the text box below and paste it into a new file in your favorite text editor.

    <textarea class="saveAnnotatorWindow_JSON"></textarea>


text:
AIDE :: Sample Resource API Server
----

**This project is currently under development.**

curl -v -u sample-client-cli:AAAAAA123456 localhost:8088/oauth/token\?grant_type=client_credentials

curl localhost:8081/ping -H "Authorization: Bearer cc23ddd4-e47c-469f-9603-32fce81038f5"

pong

{"error":"invalid_token","error_description":"Access token expired: cc23ddd4-e47c-469f-9603-32fce81038f5"}

{"error":"invalid_token","error_description":"Invalid access token: cc23ddd4-e47c-469f-9603-32fce81038f5"}


text:
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models

class Migration(SchemaMigration):

    def forwards(self, orm):
        # Adding model 'Initiative'
        db.create_table(u'multilingual_initiatives_initiative', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('logo', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['filer.File'], null=True, blank=True)),
            ('start_date', self.gf('django.db.models.fields.DateField')(null=True, blank=True)),
            ('end_date', self.gf('django.db.models.fields.DateField')(null=True, blank=True)),
            ('description', self.gf('django.db.models.fields.CharField')(max_length=160, blank=True)),
            ('website', self.gf('django.db.models.fields.URLField')(max_length=200, blank=True)),
            ('phone', self.gf('django.db.models.fields.CharField')(max_length=128, blank=True)),
            ('organization', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['multilingual_orgs.Organization'], null=True, blank=True)),
        ))
        db.send_create_signal(u'multilingual_initiatives', ['Initiative'])

        # Adding model 'InitiativePluginModel'
        db.create_table(u'cmsplugin_initiativepluginmodel', (
            (u'cmsplugin_ptr', self.gf('django.db.models.fields.related.OneToOneField')(to=orm['cms.CMSPlugin'], unique=True, primary_key=True)),
            ('display_type', self.gf('django.db.models.fields.CharField')(max_length=256)),
            ('initiative', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['multilingual_initiatives.Initiative'])),
        ))
        db.send_create_signal(u'multilingual_initiatives', ['InitiativePluginModel'])

        # Adding model 'InitiativeTranslation'
        db.create_table(u'multilingual_initiatives_initiativetranslation', (
            (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
            ('title', self.gf('django.db.models.fields.CharField')(max_length=2000)),
            ('is_published', self.gf('django.db.models.fields.BooleanField')(default=False)),
            ('language', self.gf('django.db.models.fields.CharField')(max_length=16)),
            ('initiative', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['multilingual_initiatives.Initiative'])),
        ))
        db.send_create_signal(u'multilingual_initiatives', ['InitiativeTranslation'])

    def backwards(self, orm):
        # Deleting model 'Initiative'
        db.delete_table(u'multilingual_initiatives_initiative')

        # Deleting model 'InitiativePluginModel'
        db.delete_table(u'cmsplugin_initiativepluginmodel')

        # Deleting model 'InitiativeTranslation'
        db.delete_table(u'multilingual_initiatives_initiativetranslation')

    models = {
        u'auth.group': {
            'Meta': {'object_name': 'Group'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
            'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
        },
        u'auth.permission': {
            'Meta': {'ordering': "(u'content_type__app_label', u'content_type__model', u'codename')", 'unique_together': "((u'content_type', u'codename'),)", 'object_name': 'Permission'},
            'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['contenttypes.ContentType']"}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
        },
        u'auth.user': {
            'Meta': {'object_name': 'User'},
            'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
            'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
            'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
            'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u"orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
            'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
        },
        'cms.cmsplugin': {
            'Meta': {'object_name': 'CMSPlugin'},
            'changed_date': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'creation_date': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'language': ('django.db.models.fields.CharField', [], {'max_length': '15', 'db_index': 'True'}),
            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'parent': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.CMSPlugin']", 'null': 'True', 'blank': 'True'}),
            'placeholder': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['cms.Placeholder']", 'null': 'True'}),
            'plugin_type': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'}),
            'position': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True', 'blank': 'True'}),
            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'})
        },
        'cms.placeholder': {
            'Meta': {'object_name': 'Placeholder'},
            'default_width': ('django.db.models.fields.PositiveSmallIntegerField', [], {'null': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'slot': ('django.db.models.fields.CharField', [], {'max_length': '50', 'db_index': 'True'})
        },
        u'contenttypes.contenttype': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
            'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
        },
        'filer.file': {
            'Meta': {'object_name': 'File'},
            '_file_size': ('django.db.models.fields.IntegerField', [], {'null': 'True', 'blank': 'True'}),
            'description': ('django.db.models.fields.TextField', [], {'null': 'True', 'blank': 'True'}),
            'file': ('django.db.models.fields.files.FileField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
            'folder': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'all_files'", 'null': 'True', 'to': "orm['filer.Folder']"}),
            'has_all_mandatory_data': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'is_public': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
            'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}),
            'original_filename': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
            'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'owned_files'", 'null': 'True', 'to': u"orm['auth.User']"}),
            'polymorphic_ctype': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'polymorphic_filer.file_set'", 'null': 'True', 'to': u"orm['contenttypes.ContentType']"}),
            'sha1': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '40', 'blank': 'True'}),
            'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
        },
        'filer.folder': {
            'Meta': {'ordering': "('name',)", 'unique_together': "(('parent', 'name'),)", 'object_name': 'Folder'},
            'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'level': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'lft': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'modified_at': ('django.db.models.fields.DateTimeField', [], {'auto_now': 'True', 'blank': 'True'}),
            'name': ('django.db.models.fields.CharField', [], {'max_length': '255'}),
            'owner': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'filer_owned_folders'", 'null': 'True', 'to': u"orm['auth.User']"}),
            'parent': ('django.db.models.fields.related.ForeignKey', [], {'blank': 'True', 'related_name': "'children'", 'null': 'True', 'to': "orm['filer.Folder']"}),
            'rght': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'tree_id': ('django.db.models.fields.PositiveIntegerField', [], {'db_index': 'True'}),
            'uploaded_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'})
        },
        u'multilingual_initiatives.initiative': {
            'Meta': {'object_name': 'Initiative'},
            'description': ('django.db.models.fields.CharField', [], {'max_length': '160', 'blank': 'True'}),
            'end_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'logo': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['filer.File']", 'null': 'True', 'blank': 'True'}),
            'organization': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['multilingual_orgs.Organization']", 'null': 'True', 'blank': 'True'}),
            'phone': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
            'start_date': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
            'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'})
        },
        u'multilingual_initiatives.initiativepluginmodel': {
            'Meta': {'object_name': 'InitiativePluginModel', 'db_table': "u'cmsplugin_initiativepluginmodel'", '_ormbases': ['cms.CMSPlugin']},
            u'cmsplugin_ptr': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['cms.CMSPlugin']", 'unique': 'True', 'primary_key': 'True'}),
            'display_type': ('django.db.models.fields.CharField', [], {'max_length': '256'}),
            'initiative': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['multilingual_initiatives.Initiative']"})
        },
        u'multilingual_initiatives.initiativetranslation': {
            'Meta': {'object_name': 'InitiativeTranslation'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'initiative': ('django.db.models.fields.related.ForeignKey', [], {'to': u"orm['multilingual_initiatives.Initiative']"}),
            'is_published': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
            'language': ('django.db.models.fields.CharField', [], {'max_length': '16'}),
            'title': ('django.db.models.fields.CharField', [], {'max_length': '2000'})
        },
        u'multilingual_orgs.organization': {
            'Meta': {'object_name': 'Organization'},
            u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
            'logo': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['filer.File']", 'null': 'True', 'blank': 'True'}),
            'phone': ('django.db.models.fields.CharField', [], {'max_length': '128', 'blank': 'True'}),
            'website': ('django.db.models.fields.URLField', [], {'max_length': '200', 'blank': 'True'})
        }
    }

    complete_apps = ['multilingual_initiatives']


text:
package org.fastnate.generator.test.recursion;

import static org.assertj.core.api.Assertions.assertThat;

import java.io.IOException;

import org.fastnate.generator.test.AbstractEntitySqlGeneratorTest;
import org.junit.Test;

/**
 * Test that recursions are written correctly.
 *
 * @author Tobias Liefke
 */
public class RecursiveEntityTest extends AbstractEntitySqlGeneratorTest {

	/**
	 * Tests to write recursion.
	 *
	 * @throws IOException
	 *             if the generator throws one
	 */
	@Test
	public void testRecursion() throws IOException {
		// Check that both nodes are written, no matter which order we use
		final TestRecursiveEntity root = new TestRecursiveEntity(null, "Test Recursion Root");
		final TestRecursiveEntity child = new TestRecursiveEntity(root, "Test Recursion Child");
		write(root);

		final String query = "SELECT e FROM TestRecursiveEntity e WHERE e.name = :name";
		final TestRecursiveEntity writtenChild = findSingleResult(query, TestRecursiveEntity.class, "name",
				child.getName());
		assertThat(writtenChild.getChildren()).isEmpty();
		final TestRecursiveEntity writtenRoot = writtenChild.getParent();
		assertThat(writtenRoot.getName()).isEqualTo(root.getName());
		assertThat(writtenRoot.getParent()).isNull();
		assertThat(writtenRoot.getChildren()).contains(writtenChild);

		final TestRecursiveEntity root2 = new TestRecursiveEntity(null, "Test Recursion Root2");
		final TestRecursiveEntity child2 = new TestRecursiveEntity(root2, "Test Recursion Child2");
		write(child2);

		final TestRecursiveEntity writtenRoot2 = findSingleResult(query, TestRecursiveEntity.class, "name",
				root2.getName());
		assertThat(writtenRoot2.getParent()).isNull();
		assertThat(writtenRoot2.getChildren()).hasSize(1);
		final TestRecursiveEntity writtenChild2 = writtenRoot2.getChildren().iterator().next();
		assertThat(writtenChild2.getName()).isEqualTo(child2.getName());
	}

}


text:
package com.github.ompc.greys.core.command;

import com.github.ompc.greys.core.advisor.Enhancer;
import com.github.ompc.greys.core.command.annotation.Cmd;
import com.github.ompc.greys.core.server.Session;
import com.github.ompc.greys.core.util.affect.EnhancerAffect;
import com.github.ompc.greys.core.util.affect.RowAffect;

import java.lang.instrument.Instrumentation;

import static org.apache.commons.lang3.StringUtils.EMPTY;

/**
 * 恢复所有增强类<br/>
 * Created by oldmanpushcart@gmail.com on 15/5/29.
 */
@Cmd(name = "reset", sort = 11, summary = "Reset all the enhanced classes",
        eg = {
                "reset",
                "reset *List",
                "reset -E .*List"
        })
public class ResetCommand implements Command {

    @Override
    public Action getAction() {

        return new RowAction() {

            @Override
            public RowAffect action(
                    Session session,
                    Instrumentation inst,
                    Printer printer) throws Throwable {

                final EnhancerAffect enhancerAffect = Enhancer.reset(inst);
                printer.print(EMPTY).finish();
                return new RowAffect(enhancerAffect.cCnt());
            }

        };
    }

}


text:
<?xml version='1.0' encoding='UTF-8'?>
<!--
  ~ Copyright 2013, Rogue.IO
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<faces-config version="2.2"
              xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">
    <application>
        <locale-config>
            <default-locale>en</default-locale>
        </locale-config>
        <resource-handler>rogue.app.framework.view.faces.application.AppResourceHandler</resource-handler>
    </application>
    <lifecycle>
        <phase-listener>
            rogue.app.framework.support.appengine.faces.listener.SessionSerializationListener
        </phase-listener>
    </lifecycle>
</faces-config>


text:
package org.apache.maven.plugins.toolchains.its.custom;

import java.io.File;

import org.apache.maven.toolchain.DefaultToolchain;
import org.apache.maven.toolchain.model.ToolchainModel;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.logging.Logger;
import org.codehaus.plexus.util.FileUtils;
import org.codehaus.plexus.util.Os;

/**
 * @author Hervé Boutemy
 */
public class CustomToolchainImpl
    extends DefaultToolchain
    implements CustomToolchain
{
    private String toolHome;

    public static final String KEY_TOOLHOME = "toolHome";

    public CustomToolchainImpl( ToolchainModel model, Logger logger )
    {
        super( model, "custom", logger );
    }

    public String getToolHome()
    {
        return toolHome;
    }

    public void setToolHome( String toolHome )
    {
        this.toolHome = toolHome;
    }

    public String toString()
    {
        return "Custom[" + getToolHome() + "]";
    }

    public String findTool( String toolName )
    {
        File tool = findTool( toolName, new File( getToolHome() ) );

        if ( tool != null )
        {
            return tool.getAbsolutePath();
        }

        return null;
    }

    private static File findTool( String toolName, File installFolder )
    {
        File bin = new File( installFolder, "bin" ); //NOI18N

        if ( bin.exists() )
        {
            File tool = new File( bin, toolName + ( Os.isFamily( "windows" ) ? ".exe" : "" ) ); // NOI18N

            if ( tool.exists() )
            {
                return tool;
            }
        }

        return null;
   }
}


text:
 * Wrong history stack bug fix

## Mortar Architect 0.20 *11/19/15*

 * Chaining navigation bug fix x3

## Mortar Architect 0.19.1 *11/18/15*

 * Chaining navigation bug fix x2

## Mortar Architect 0.19 *11/18/15*

 * Chaining navigation bug fix

## Mortar Architect 0.18 *11/16/15*

 * Dispatching bug fix

## Mortar Architect 0.17 *10/01/15*

 * History bug fix

## Mortar Architect 0.15 *07/17/15*

 * Add `HandlesViewTransition` to hook up on the view transition
 * Add examples of working with `Toolbar
 * Rename `TransitionDirection` to `ViewTransitionDirection`
 * Move all View transitions to project commons

## Mortar Architect 0.14 *07/17/15*

 * Do not make view transition for intermediate paths during navigation events
 * Do not require a `StackableParceler` when don't restore navigation stack option is enabled
 * Add `Navigator.backToRoot()`
 * Modify `Navigator.push()` to be able to take a varargs of `StackablePath`
 * Modify `Navigator.delegate().onCreate()` to be able to take a varargs of `StackablePath`
 * Modifiy `StackablePath` to take the parent ViewGroup as paramter. It allows to inflate a view from xml.
 * Update `@AutoStackable` by adding new member `pathWithLayout` to reflect the change above
 * Add `Navigator.set()`
 * Add transition direction to `NavigatorChain`
 * Modify `Navigator.show()` to be able to show several modals at the same time
 * Add `TransitionDirection` to specify the direction of the transition. It has only impact is on the transition animation.

## Mortar Architect 0.13 *07/10/15*

 * Refactoring of core with many breaking changes, but it's mostly simplification
 * Remove `StackScope` and `StackPath`
 * Introduce `Stackable` and `StackablePath` interfaces
 * Unique class for Navigator and view stacking
 * Unique annotation processor: Robot
 * Remove `ArchitectApp` and `ArchitectActivity`
 * Introduce `ArcitivtyArchitector`

## Mortar Architect 0.12 *07/08/15*

 * Improvements in `StackPagerAdapter`

## Mortar Architect 0.11 *07/08/15*

 * Improve `NavigationChain` with `Navigator.chain()`
 * Add `ReceivesResult` and `HasPresenter` interfaces, that let you pass back result to previous ViewPresenter in the history stack
 * All the commons views implements now `HasPresenter`

## Mortar Architect 0.1

- Initial release


text:
package ca.uwaterloo.ece.qhanam.jrsrepair.mutation;

import ca.uwaterloo.ece.qhanam.jrsrepair.DocumentASTRewrite;
import ca.uwaterloo.ece.qhanam.jrsrepair.SourceStatement;

import org.eclipse.jdt.core.dom.rewrite.ASTRewrite;
import org.eclipse.jface.text.IDocument;

import java.util.HashMap;

public abstract class Mutation {

	protected HashMap<String, DocumentASTRewrite> sourceMap;
    protected DocumentASTRewrite docrwt;
	protected SourceStatement faulty;
	protected SourceStatement seed;
	protected IDocument document;
	protected ASTRewrite rewrite;
	private boolean mutated;

	/**
	 * Creates a new Mutation object.
	 * @param sourceMap The map of source file paths to source file contents.
	 * @param faulty A potentially faulty statement.
	 * @param seed A seed statement (from somewhere in the program source).
	 */
	public Mutation(HashMap<String, DocumentASTRewrite> sourceMap, SourceStatement faulty, SourceStatement seed){
		this.docrwt = sourceMap.get(faulty.sourceFile);
		this.rewrite = docrwt.rewriter;
		this.document = docrwt.document;
		this.sourceMap = sourceMap;
		this.faulty = faulty;
		this.seed = seed;
		this.mutated = false;
	}

	/**
	 * Uses the seed statement to apply a mutation to the faulty statement.
	 * @throws Exception
	 */
	public void mutate() throws Exception {
		if(mutated) throw new Exception("A mutate operation has allready been applied. Must call undo() before mutating again.");

		/* The subclass will perform its mutation. */
		this.concreteMutate();

		this.mutated = true;
	}

	/**
	 * Each concrete mutator will perform its own mutation to the AST and
	 * write the new AST to a document in DocumentASTRewrite.
	 * @throws Exception
	 */
	protected abstract void concreteMutate() throws Exception;

	/**
	 * Undoes the mutation that was applied in mutate().
	 *
	 * This will undo both the change to the text file (Document) as
	 * well as the change to the AST.
	 *
	 * Best used with memento pattern.
	 */
	public void undo() throws Exception {
		if(!mutated) throw new Exception("The mutate operation has not been applied. Must call mutate() before undo().");

		/* Undo the operation applied to the AST. */
		this.concreteUndo();

		/* Set the status to not mutated. */
		this.mutated = false;

		/* Relinquish use of the statements. */
		this.faulty.inUse = false;
		if(this.seed != null) this.seed.inUse = false;
	}

	/**
	 * Each concrete mutator must also be able to undo its mutation. Because
	 * mutation operations are recursive, the concrete mutator must undo its
	 * own AST mutation, then re-write the document.
	 * @throws Exception
	 */
	protected abstract void concreteUndo() throws Exception;

	/**
	 * Returns the document modified by the mutation.
	 * @return
	 */
	public DocumentASTRewrite getRewriter() throws Exception{
		if(!mutated) throw new Exception("No mutation operation has been applied. Must call mutate() before getMutatedDocument().");
        return this.docrwt;
	}

	/**
	 * Returns true if a mutation operation has been applied.
	 */
	public boolean mutated(){
		return this.mutated;
	}

	@Override
	public String toString(){
		String s = "\nFaulty = " + this.faulty.sourceFile + "@" + this.faulty.statement.getStartPosition() + ": " + this.faulty.statement + "\n\n";
		s += "Seed = ";
		if(this.seed == null) s += "null" + ": " + "\n============================\n";
		else s += this.seed.sourceFile + "@" + this.seed.statement.getStartPosition() + ": " + this.seed.statement + "\n============================\n";

		return s;
	}
}


text:
package org.acme.foo.archiver;

import org.acme.foo.archiver.api.ArchiverService;
import org.osgi.service.event.EventConstants;
import org.osgi.service.component.annotations.*;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;

@Component(
		service = {ArchiverService.class, EventHandler.class},
		property = EventConstants.EVENT_TOPIC + ":String=acme/welcome",
		immediate = true
		)
public class ArchiverComponent implements ArchiverService, EventHandler {

	private String lastName;

	@Override
	public void handleEvent(Event event) {
		lastName = String.valueOf(event.getProperty("name"));
	}

	@Override
	public String getLastName() {
		return lastName;
	}

}


text:
package org.pentaho.det.di;

import org.pentaho.det.api.services.IDataSourceProvider;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.debug.StepDebugMeta;
import org.pentaho.di.trans.debug.TransDebugMeta;
import org.pentaho.di.trans.debug.TransDebugMetaWrapper;
import org.pentaho.di.trans.step.StepInterface;
import org.pentaho.di.trans.step.StepMeta;
import org.pentaho.di.ui.spoon.SpoonUiExtenderPlugin;
import org.pentaho.di.ui.spoon.SpoonUiExtenderPluginInterface;
import org.pentaho.di.ui.spoon.trans.TransGraph;

import java.util.Collections;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

// TODO: check plugin id
@SpoonUiExtenderPlugin( id = "pentaho-det-preview-data-source-provider", image = "" )
public class PreviewDataSourceProvider implements IDataSourceProvider, SpoonUiExtenderPluginInterface {

  // region Inner Definitions
  private static final class RegisterDataSources extends EventHandler<TransDebugMetaWrapper> {

    private final Map<UUID, StepPreviewDataSource> dataSources;

    // region Constructors
    public RegisterDataSources( Map<UUID, StepPreviewDataSource> dataSources ) {
      super( TransDebugMetaWrapper.class );

      this.dataSources = dataSources;
    }
    // endregion

    @Override public void handle( TransDebugMetaWrapper transDebugMetaWrapper ) {
      // clear datasources as new steps are created for each
      this.dataSources.clear();

      final Trans trans = transDebugMetaWrapper.getTrans();
      TransDebugMeta transDebugMeta = transDebugMetaWrapper.getTransDebugMeta();
      Map<StepMeta, StepDebugMeta> stepDebugMetaMap = transDebugMeta.getStepDebugMetaMap();
      // for each step being debugged / previewed
      for ( final StepMeta stepMeta : stepDebugMetaMap.keySet() ) {
        String stepName = stepMeta.getName();
        for ( StepInterface baseStep : trans.findBaseSteps( stepName ) ) {
          StepPreviewDataSource dataSource = new StepPreviewDataSource( baseStep );
          this.dataSources.put( dataSource.getUUID(), dataSource );
        }
      }
    }

  }

  // endregion

  // region Properties
  public Map<UUID, StepPreviewDataSource> getDataSources() {
    return Collections.unmodifiableMap( this.dataSources );
  }
  public PreviewDataSourceProvider setDataSources( Map<UUID, StepPreviewDataSource> dataSources ) {
    this.dataSources = dataSources;
    return this;
  }
  private Map<UUID, StepPreviewDataSource> dataSources;

  private EventHandlerMap getEventHandlers() {
    return this.eventHandlers;
  }
  private EventHandlerMap eventHandlers;

  // endregion

  // region Constructors
  public PreviewDataSourceProvider() {
    // TODO: verify threading
    Map<UUID, StepPreviewDataSource> dataSources = new Hashtable<>(  ); //new ConcurrentHashMap<>();
    this.setDataSources( dataSources );

    this.eventHandlers = new EventHandlerMap();
    this.eventHandlers.addEventHandler( TransGraph.PREVIEW_TRANS, new RegisterDataSources( dataSources ) );
  }
  // endregion

  // region SpoonUiExtenderPluginInterface

  /**
   * @inheritDoc
   */
  @Override public Map<Class<?>, Set<String>> respondsTo() {
    return this.getEventHandlers().respondsTo();
  }

  /**
   * @inheritDoc
   */
  @Override public void uiEvent( Object o, String s ) {
    this.getEventHandlers().callHandlers( o, s );
  }
  // endregion

}


text:
/* Exports a function which returns an object that overrides the default &
 *   plugin grunt configuration object.
 *
 * You can familiarize yourself with Lineman's defaults by looking at:
 *
 *   - https://github.com/linemanjs/lineman/blob/master/config/application.coffee
 *   - https://github.com/linemanjs/lineman/blob/master/config/plugins
 *
 * You can also ask about Lineman's  config from the command line:
 *
 *   $ lineman config #=> to print the entire config
 *   $ lineman config concat_sourcemap.js #=> to see the JS config for the concat task.
 */
module.exports = function(lineman) {
  //Override application configuration here. Common examples follow in the comments.
  return {

    // API Proxying
    //
    // During development, you'll likely want to make XHR (AJAX) requests to an API on the same
    // port as your lineman development server. By enabling the API proxy and setting the port, all
    // requests for paths that don't match a static asset in ./generated will be forwarded to
    // whatever service might be running on the specified port.
    //
    // server: {
    //   apiProxy: {
    //     enabled: true,
    //     host: 'localhost',
    //     port: 3000
    //   }
    // }

    // Sass
    //
    // Lineman supports Sass via grunt-contrib-sass, which requires you first
    // have Ruby installed as well as the `sass` gem. To enable it, uncomment the
    // following line:
    //
    // enableSass: true

    // Asset Fingerprints
    //
    // Lineman can fingerprint your static assets by appending a hash to the filename
    // and logging a manifest of logical-to-hashed filenames in dist/assets.json
    // via grunt-asset-fingerprint
    //
    // enableAssetFingerprint: true

    // LiveReload
    //
    // Lineman can LiveReload browsers whenever a file is changed that results in
    // assets to be processed, preventing the need to hit F5/Cmd-R every time you
    // make a change in each browser you're working against. To enable LiveReload,
    // comment out the following line:
    //
    // livereload: true

  };
};


text:
package akka.persistence.jdbc.query

abstract class CurrentPersistenceIdsTest(config: String) extends QueryTestSpec(config) {

  it should "not find any persistenceIds for empty journal" in withActorSystem { implicit system =>
    val journalOps = new ScalaJdbcReadJournalOperations(system)
    journalOps.withCurrentPersistenceIds() { tp =>
      tp.request(1)
      tp.expectComplete()
    }
  }

  it should "find persistenceIds for actors" in withActorSystem { implicit system =>
    val journalOps = new JavaDslJdbcReadJournalOperations(system)
    withTestActors() { (actor1, actor2, actor3) =>
      actor1 ! 1
      actor2 ! 1
      actor3 ! 1

      eventually {
        journalOps.withCurrentPersistenceIds() { tp =>
          tp.request(3)
          tp.expectNextUnordered("my-1", "my-2", "my-3")
          tp.expectComplete()
        }
      }
    }
  }
}

// Note: these tests use the shared-db configs, the test for all persistence ids use the regular db config

class PostgresScalaCurrentPersistenceIdsTest extends CurrentPersistenceIdsTest("postgres-shared-db-application.conf") with PostgresCleaner

class MySQLScalaCurrentPersistenceIdsTest extends CurrentPersistenceIdsTest("mysql-shared-db-application.conf") with MysqlCleaner

class OracleScalaCurrentPersistenceIdsTest extends CurrentPersistenceIdsTest("oracle-shared-db-application.conf") with OracleCleaner

class SqlServerScalaCurrentPersistenceIdsTest extends CurrentPersistenceIdsTest("sqlserver-application.conf") with SqlServerCleaner

class H2ScalaCurrentPersistenceIdsTest extends CurrentPersistenceIdsTest("h2-shared-db-application.conf") with H2Cleaner


text:
{{$state.current.title}}

<button type="button" class="btn btn-success text-uppercase toggle-sidebar">Upload</button>

Do you really want to delete this media?

<button type="button" class="btn btn-success text-uppercase">Yes</button>
<button type="button" class="btn btn-danger text-uppercase" data-dismiss="modal">No</button>

Image-1

January 11, 2017

Edit

Video-1

January 11, 2017

Edit

Video-2

January 11, 2017

Edit

Image-2

January 11, 2017

Edit

<button type="button" class="close" aria-label="Close">×</button>

Upload file

Add image

<button type="button" class="btn btn-sm btn-link">From URL</button>
<button type="button" class="btn btn-sm btn-link" data-toggle="modal" data-target="#delete-media-modal">Delete</button>


text:
describe("A Body", function () {

  it("throws TypeError if columns is not given", function () {
    expect(function () {
      new Backgrid.Body({
        collection: new Backbone.Collection()
      });
    }).toThrow(new TypeError("'columns' is required"));
  });

  it("throws TypeError if collection is not given", function () {
    expect(function () {
      new Backgrid.Body({
        columns: [{
          name: "name",
          cell: "string"
        }]
      });
    }).toThrow(new TypeError("'collection' is required"));
  });

  var Book = Backbone.Model.extend({});
  var Books = Backbone.Collection.extend({
    model: Book
  });

  var books;
  var body;
  beforeEach(function () {

    books = new Books([{
      title: "Alice's Adventures in Wonderland"
    }, {
      title: "A Tale of Two Cities"
    }, {
      title: "The Catcher in the Rye"
    }]);

    body = new Backgrid.Body({
      columns: [{
        name: "title",
        cell: "string"
      }],
      collection: books
    });

    body.render();
  });

  it("renders table rows using the given column definitions and collection", function () {
    expect(body.el.tagName).toBe("TBODY");
    var $trs = body.$el.children();
    expect($trs.length).toBe(3);
    expect(body.el.innerHTML).toBe('
Alice\'s Adventures in Wonderland
' +
                                   '
A Tale of Two Cities
' +
                                   '
The Catcher in the Rye
');
  });

  it("will render a new row if a new model is added to its collection", function () {
    body.collection.add({
      title: "The Great Gatsby"
    });
    var $trs = body.$el.children();
    expect($trs.length).toBe(4);
    expect($trs[3].outerHTML).toBe('
The Great Gatsby
');

    body.collection.add({
      title: "Les Misérables"
    }, {at: 1});
    $trs = body.$el.children();
    expect($trs.length).toBe(5);
    expect($trs[1].outerHTML).toBe('
Les Misérables
');
  });

  it("will render a new row by calling insertRow directly with a new model", function () {
    books = new Books();

    body = new Backgrid.Body({
      columns: [{
        name: "title",
        cell: "string"
      }],
      collection: books
    });

    body.render();

    body.insertRow({
      title: "The Great Gatsby"
    });

    var $trs = body.$el.children();
    expect($trs.length).toBe(1);
    expect($trs[0].outerHTML).toBe('
The Great Gatsby
');

    body.insertRow({
      title: "Les Misérables"
    }, {at: 0});
    $trs = body.$el.children();
    expect($trs.length).toBe(2);
    expect($trs[0].outerHTML).toBe('
Les Misérables
');
  });

  it("will remove a row from the DOM if a model is removed from its collection", function () {
    var twocities = body.collection.at(1);
    body.collection.remove(twocities);
    var $trs = body.$el.children();
    expect($trs.length).toBe(2);
    expect(body.el.innerHTML).toBe('
Alice\'s Adventures in Wonderland
' +
                                   '
The Catcher in the Rye
');
  });

  it("will remove a row from the DOM is removeRow is called directly with a model", function () {
    var twocities = body.collection.at(1);
    body.removeRow(twocities);
    var $trs = body.$el.children();
    expect($trs.length).toBe(2);
    expect(body.el.innerHTML).toBe('
Alice\'s Adventures in Wonderland
' +
                                   '
The Catcher in the Rye
');
  });

  it("will refresh if its collection is reset", function () {
    var eventFired = false;
    var handler = function () {
      eventFired = true;
    };
    body.collection.on("backgrid:refresh", handler);
    body.collection.reset([{
      title: "Oliver Twist"
    }]);
    body.collection.off("backgrid:refresh", handler);
    expect(eventFired).toBe(true);
    var $trs = body.$el.children();
    expect($trs.length).toBe(1);
    expect(body.el.innerHTML).toBe('
Oliver Twist
');
  });

  it("will render rows using the Row class supplied in the constructor options", function () {

    var CustomRow = Backgrid.Row.extend({});

    spyOn(CustomRow.prototype, "render").andCallThrough();

    body = new Backgrid.Body({
      columns: [{
        name: "title",
        cell: "string"
      }],
      collection: books,
      row: CustomRow
    });

    body.render();

    expect(CustomRow.prototype.render).toHaveBeenCalled();
  });

  describe("maintain page size at page boundary", function () {

    var col;

    beforeEach(function () {
      col = new Backbone.PageableCollection([
        {id: 1},
        {id: 2},
        {id: 3}
      ], {
        state: {
          pageSize: 2
        },
        mode: "client"
      });

      body = new Backgrid.Body({
        columns: [{
          name: "id",
          cell: "integer"
        }],
        collection: col
      });

      body.render();
    });

    it("when adding to a full page", function () {
      col.add(new Backbone.Model({id: 4}));
      expect(body.$el.find("tr").length).toBe(2);
    });

    it("when removing from a full page", function () {
      col.remove(col.get(1));
      expect(body.$el.find("tr").length).toBe(2);
    });

  });

  it("will not display the empty row if collection is not empty", function () {
    body = new Backgrid.Body({
      emptyText: " ",
      columns: [{
        name: "title",
        cell: "string"
      }],
      collection: books
    });
    body.render();

    expect(body.$el.find("tr.empty").length).toBe(0);
  });

  it("will not display the empty row if `options.emptyText` is not supplied", function () {
    expect(body.$el.find("tr.empty").length).toBe(0);

    books.reset();
    body = new Backgrid.Body({
      columns: [{
        name: "title",
        cell: "string"
      }],
      collection: books
    });
    body.render();

    expect(body.$el.find("tr.empty").length).toBe(0);
  });

  it("will display the empty row if the collection is empty and `options.emptyText` is supplied", function () {
    books.reset();
    body = new Backgrid.Body({
      emptyText: " ",
      columns: [{
        name: "title",
        cell: "string"
      }],
      collection: books
    });
    body.render();

    expect(body.$el.find("tr.empty").length).toBe(1);
    expect(body.$el.find("tr.empty > td").attr("colspan")).toBe("1");
  });

  it("will clear the empty row if a new model is added to an empty collection", function () {
    books.reset();
    body = new Backgrid.Body({
      emptyText: " ",
      columns: [{
        name: "title",
        cell: "string"
      }],
      collection: books
    });
    body.render();
    expect(body.$el.find("tr.empty").length).toBe(1);

    books.add({name: "Oliver Twist"});
    expect(body.$el.find("tr.empty").length).toBe(0);

    books.reset();
    expect(body.$el.find("tr.empty").length).toBe(1);

    body.insertRow({title: "The Catcher in the Rye"});
    expect(body.$el.find("tr.empty").length).toBe(0);
  });

  it("will put the next editable and renderable cell in edit mode when a save or one of the navigation commands is triggered via backgrid:edited from the collection", function () {
    var people = new Backbone.Collection([
      {name: "alice", age: 28, married: false},
      {name: "bob", age: 30, married: true}
    ]);
    var columns = new Backgrid.Columns([{
      name: "name",
      cell: "string"
    }, {
      name: "age",
      cell: "integer",
      editable: false
    }, {
      name: "sex",
      cell: "boolean",
      renderable: false
    }]);
    var body = new Backgrid.Body({
      collection: people,
      columns: columns
    });
    body.render();

    body.rows[0].cells[0].enterEditMode();

    // right
    people.trigger("backgrid:edited", people.at(0), columns.at(0), new Backgrid.Command({keyCode: 9}));
    expect(body.rows[0].cells[0].$el.hasClass("editor")).toBe(false);
    expect(body.rows[1].cells[0].$el.hasClass("editor")).toBe(true);

    // left
    people.trigger("backgrid:edited", people.at(1), columns.at(0), new Backgrid.Command({keyCode: 9, shiftKey: true}));
    expect(body.rows[0].cells[0].$el.hasClass("editor")).toBe(true);
    expect(body.rows[1].cells[0].$el.hasClass("editor")).toBe(false);

    // down
    people.trigger("backgrid:edited", people.at(0), columns.at(0), new Backgrid.Command({keyCode: 40}));
    expect(body.rows[0].cells[0].$el.hasClass("editor")).toBe(false);
    expect(body.rows[1].cells[0].$el.hasClass("editor")).toBe(true);

    // up
    people.trigger("backgrid:edited", people.at(1), columns.at(0), new Backgrid.Command({keyCode: 38}));
    expect(body.rows[0].cells[0].$el.hasClass("editor")).toBe(true);
    expect(body.rows[1].cells[0].$el.hasClass("editor")).toBe(false);

    // enter
    people.trigger("backgrid:edited", people.at(0), columns.at(0), new Backgrid.Command({keyCode: 13}));
    expect(body.rows[0].cells[0].$el.hasClass("editor")).toBe(false);
    expect(body.rows[1].cells[0].$el.hasClass("editor")).toBe(false);

    // esc
    body.rows[1].cells[0].enterEditMode();
    people.trigger("backgrid:edited", people.at(1), columns.at(0), new Backgrid.Command({keyCode: 27}));
    expect(body.rows[0].cells[0].$el.hasClass("editor")).toBe(false);
    expect(body.rows[1].cells[0].$el.hasClass("editor")).toBe(false);
  });

});


text:
local http = require('socket.http')
--local json = require('cjson')
local base64 = require('base64')
local exports = {}
local CLIENT_ID="QIC2k0tpZB_.yjgfC9-ks0WGDauRnmaM7F.gbzK9"
local CLIENT_SECRET="ZnFc8jL?uqnUxI6!;ZjCfhwKS@H0RtZV2=Iu;iHbMqtK5a@XcfQ3@3oD2FZh?tvahz?Qohz-Vnb2ECaNlJ4r_vwb@hXig;QNjydwAE4f5qx7L2D7BbXhZMVsdT?sNJQM"
local head_data = base64.encode(CLIENT_ID..":"..CLIENT_SECRET)
print(head_data)
exports.auth = function(user_name, passwd)
    local request_body = {}
    local response_body = {}
    request_body.grant_type = "password"
    request_body.scope = "read"
    request_body.username = user_name
    request_body.password = passwd
    --request_body = json.encode(request_body)
    --print(request_body)
    local send_data = "grant_type='password'&username="..user_name.."&password="..passwd

    local _, code = http.request({
        --url = "http://192.168.200.218:9000/api/0/user_key",
        --url = "http://192.168.200.218:9000/api/0/user_key?username=admin@loginsight.cn&password=123",
        url = "http://192.168.200.218:8000/o/token/",
        method = "POST",
        headers = {
            --["Content-Type"] = "application/x-www-form-urlencoded";
						--["Content-Length"] = #send_data;
            ["Authorization"] = "Basic "..head_data;
        },
        source = ltn12.source.string(send_data),
        sink = ltn12.sink.table(response_body),
    })
    if code >= 200 and code < 300 then
        local response = table.concat(response_body)
        local result = json.decode(response)
        return result.access_token
    else
        print("error code = "..code)
    end
end
exports.host = function(user_key, host_name, host_type, system, distver)
    local request_body = {}
    local response_body = {}
    request_body.user_key = user_key
    request_body.host_name = host_name
    request_body.host_type = host_type
    request_body.system = system
    request_body.distver = distver
    request_body = json.encode(request_body)
    local _, code = http.request{
        --url = "/API/v1/Storage/host",
        url = "http://192.168.200.218:9000/api/0/agent/hosts",
        method = "POST",
        headers = {
            ["Content-Type"] = "application/json";
            ["Content-Length"] = #request_body;
        },
        source = ltn12.source.string(request_body);
        sink = ltn12.sink.table(response_body);
    }
    if code >= 200 and code < 300 then
        local response = table.concat(response_body)
        local resualt = json.decode(response)
        return resualt.host_key
    else
        print("error code = "..code)
    end
end
print(exports.auth("wanghe", "123"))
--print(exports.host("123", "ma", "test", "ubuntu", "V2.6.3"))
return exports


text:
import run from "ember-metal/run_loop";
import EventDispatcher from "ember-views/system/event_dispatcher";
import jQuery from "ember-views/system/jquery";
import {View} from "ember-views/views/view";

var view, dispatcher;

// Adapted from https://github.com/jquery/jquery/blob/f30f7732e7775b6e417c4c22ced7adb2bf76bf89/test/data/testinit.js
var canDataTransfer,
    fireNativeWithDataTransfer;
if (document.createEvent) {
  canDataTransfer = !!document.createEvent('HTMLEvents').dataTransfer;
  fireNativeWithDataTransfer = function(node, type, dataTransfer) {
    var event = document.createEvent('HTMLEvents');
    event.initEvent(type, true, true);
    event.dataTransfer = dataTransfer;
    node.dispatchEvent(event);
  };
} else {
  canDataTransfer = !!document.createEventObject().dataTransfer;
  fireNativeWithDataTransfer = function(node, type, dataTransfer) {
    var event = document.createEventObject();
    event.dataTransfer = dataTransfer;
    node.fireEvent('on' + type, event);
  };
}

module("EventDispatcher", {
  setup: function() {
    run(function() {
      dispatcher = EventDispatcher.create();
      dispatcher.setup();
    });
  },

  teardown: function() {
    run(function() {
      if (view) { view.destroy(); }
      dispatcher.destroy();
    });
  }
});

if (canDataTransfer) {
  test("jQuery.event.fix copies over the dataTransfer property", function() {
    var originalEvent;
    var receivedEvent;

    originalEvent = {
      type: 'drop',
      dataTransfer: 'success',
      target: document.body
    };

    receivedEvent = jQuery.event.fix(originalEvent);

    ok(receivedEvent !== originalEvent, "attributes are copied to a new event object");
    equal(receivedEvent.dataTransfer, originalEvent.dataTransfer, "copies dataTransfer property to jQuery event");
  });

  test("drop handler should receive event with dataTransfer property", function() {
    var receivedEvent;
    var dropCalled = 0;

    view = View.createWithMixins({
      render: function(buffer) {
        buffer.push('please drop stuff on me');
        this._super(buffer);
      },

      drop: function(evt) {
        receivedEvent = evt;
        dropCalled++;
      }
    });

    run(function() {
      view.append();
    });

    fireNativeWithDataTransfer(view.$().get(0), 'drop', 'success');

    equal(dropCalled, 1, "called drop handler once");
    equal(receivedEvent.dataTransfer, 'success', "copies dataTransfer property to jQuery event");
  });
}


text:
@import HomeKit;

NSString * const RoomDataSourceDidChangeNotification = @"RoomDataSourceDidChangeNotification";

@implementation RoomDataSource

#pragma mark - Customer Getters / Setters

- (void)setHome:(HMHome *)home {
    _home = home;
    [[NSNotificationCenter defaultCenter] postNotificationName:RoomDataSourceDidChangeNotification object:nil];
}

#pragma mark - Table View Data Source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.home.rooms count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RoomCell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"RoomCell"];
    }

    HMRoom *room = self.home.rooms[indexPath.row];
    cell.textLabel.text = room.name;

    return cell;
}

- (HMRoom *)roomForRow:(NSInteger)row {
    return self.home.rooms[row];
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        HMRoom *room = self.home.rooms[indexPath.row];
        [self.home removeRoom:room completionHandler:^(NSError *error) {
            if (error) {
                NSLog(@"%@", error);
            } else {
                [tableView deleteRowsAtIndexPaths:@[ indexPath ] withRowAnimation:UITableViewRowAnimationAutomatic];
            }
        }];
    }
}

#pragma mark - Room Management

- (void)addRoomWithname:(NSString *)name {
    [self.home addRoomWithName:name completionHandler:^(HMRoom *room, NSError *error) {
        if (error) {
            NSLog(@"%@", error);
        } else {
            [[NSNotificationCenter defaultCenter] postNotificationName:RoomDataSourceDidChangeNotification object:nil];
        }
    }];
}

@end


text:
try:
    import roboschool
except:
    pass
import sys

import gym
import pybullet_envs.gym_locomotion_envs as e

env_name = sys.argv[1]

env = e.AntBulletEnv(render=True)

for i in range(100):
    done = False
    obs = env.reset()
    r = 0
    while not done:
        env.render()
        action = env.action_space.sample()
        ob, reward, done, _ = env.step(action)
        r += reward
    print('Episode {}, Reward {}'.format(i + 1, r))


text:
[English](#simple-and-secure-voting-system-with-bitcoin) ∙ [Türkçe](#bitcoin-ile-g%C3%BCvenli-ve-basit-bir-oy-sistemi) ∙
[Bahasa Malaysia](#sistem-pengundian-selamat-dan-mudah-dengan-bitcoin)

## Simple and secure voting system with Bitcoin

A schema designed to utilize Bitcoin cryptocurrency for secure and simple electronic voting. In the heart of the schema lies the [Blockchain](https://en.wikipedia.org/wiki/Bitcoin#Block_chain), so all the processes of the system are open to public audition.

#### Requirements:

* All actors of the election should be able to have a Bitcoin account.
* All actors of the election should be able to secure their voting computer.

#### Actors:

* Election Authority
* Candidate
* Voter

#### Terminology:

* Block Chain: Bitcoin public transaction list
* 0.00000001 Bitcoin: the smallest unit of Bitcoin
* BTC: Abbreviation for Bitcoin currency

#### Schema:

0. **Election Authority declaration:**
 - Election Authority publicly announces its Bitcoin address.

1. **Voter registration:**
 - Voters show a valid ID and provide their Bitcoin address to Election Authority, who sends them 0.00000001 BTC in return.
 - All voter Bitcoin addresses are publicly listed in the Blockchain.
 - To carry out citizens' right to vote anonymously, the Election Authority keeps the IDs to prevent double registration but does not keep a record of association between the IDs and the provided Bitcoin addresses.

2. **Candidate registration:**
 - Candidates provide a valid ID and their Bitcoin address to Election Authority, who sends them 0.00000002 BTC in return.
 - All Candidate Bitcoin addresses are publicly listed in the Blockchain.
 - As opposed to Voter registration, Election Authority stores and publicly announces a record of association between each candidate ID and their provided Bitcoin address.
 - Candidates are obliged to announce their Bitcoin addresses.

3. **Starting the election:**
 - Election starts when Election Authority sends 0.00000001 BTC to all the Voters' Bitcoin addresses publicly listed in the Blockchain.

4. **Voting:**
 - Voters send 0.00000001 BTC to their preferred candidate's Bitcoin addresses publicly listed in the Blockchain.

5. **Ending the election:**
 - Election ends when all voting transactions are processed for each candidate in the Blockchain.
 - If time limit is put in place, Election Authority must declare the election start and end date and time.
 - If this is a time limited election, any vote before the start datetime and after end datetime is considered invalid.

6. **Election result:**
 - Election result is obtained by counting all valid voting transactions from the registered voting addresses to the registered candidate addresses in the Blockchain.
 - Any other transaction after the first 0.00000001 BTC transaction from the Voter to the Candidate is considered disqualified.
 - The whole process from the registrations to the voting and counting the results is open to audition by anyone.

#### Contribution

This basic schema can be implemented today with the existing Bitcoin infrastructure. One can develop applications and interfaces for better user experience of this system. Please send your comments and questions on issues and feel free to fork the repository and send pull requests.

#### License

[The MIT License (MIT)](https://github.com/arikan/bitcoin-voting/blob/master/LICENSE)

## Bitcoin ile güvenli ve basit bir oy sistemi

Şifreli elektronik para birimi Bitcoin 2009'da ilk kullanıma girdiğinden beri internet üzerinde çalışan bir değer aktarım katmanı olarak hızla yayılmakta. Alışveriş ve borsalar dışında elektronik noterlik, elektronik sözleşme vb pek çok farklı alanda kullanılmakta.

Aşağıda göreceğiniz Bitcoin ile çalışan bir sistem şemasıdır. Herkese açık ve anonim kayıt tutan Bitcoin işlem defteri Blockchain bu sistemin çekirdeğini oluşturmakta ve aşağıda belirtilen tüm aşamalar isteyen herkesin denetimine açıktır ve Bitcoin doğası gereği tüm işlemler şifrelidir.

#### Gereksinimler:

* Seçime katılacak tüm taraflar birer Bitcoin hesabı açabilmelidir.
* Seçime katılacak tüm taraflar oy verecekleri bilgisayarın güvenliğini sağlayabilmelidir.

#### Aktörler:

* Seçim Düzenleyicisi (Örn yüksek seçim kurulu)
* Aday (Örn Belediye Başkanı Adayı ya da Siyasi Parti)
* Seçmen (Örn oy verebilen vatandaş)

#### Terimler:

* Blockchain: Herkese açık Bitcoin işlem defteri
* 0.00000001 bitcoin: Mümkün olan en küçük Bitcoin birimi
* BTC: Bitcoin para birimi kısaltması

#### Şema:

0. **Seçim Düzenleyicisi'nin ilanı:**
 - Seçim Düzenleyicisi Bitcoin hesap numarasını ilan eder.

1. **Seçmen kaydı:**
 - Seçim Düzenleyicisi kimliğini gösterip Bitcoin hesabını ibraz eden her seçmene 0.00000001 BTC gönderir.
 - Böylece, tüm seçmenlerin Bitcoin adresleri Blockchain'de listelenmiş olur.
 - Seçmenlerin anonim oy verme hakkını kullanabilmesi için Seçim Düzenleyicisi kayıt aşamasında kaydın bir defa yapıldığını kontrol etmek üzere sadece kimlik bilgisini tutar, Bitcoin hesap numarası kayıt edilmemelidir.

2. **Aday kaydı:**
 - Seçim Düzenleyicisi kimliğini ve Bitcoin hesabını ibraz eden her adayın hesabına 0.00000002 BTC gönderir.
 - Böylece adaylar Blockchain'de listelenmiş olur.
 - Seçmen kaydının tersine Seçim Düzenleyicisi Adayları kaydederken kimlik bilgisiyle Bitcoin hesabını eşleştirerek tutmak ve eşleştirmeyi herkese açıklamak zorundadır.
 - Seçim Düzenleyicisi'nin Bitcoin hesabından gönderilen 0.00000002 bitcoin alanlar aday olarak listelenmiş olur.
 - Adaylar Bitcoin hesaplarını ilan etmekle yükümlüdür.

3. **Seçimi başlatma:**
 - Seçim Düzenleyicisi listelenmiş tüm seçmenlere tekrar 0.00000001 BTC gönderdiğinde seçim başlar.

4. **Oy verme:**
 - Seçmenler listelenen adaylardan birine 0.00000001 BTC gönderdiklerinde oy vermiş olurlar.
 - Bir seçmenin hesabından listelenen Adaylardan birinin hesabına sadece bir defa gönderim yapabilir, ilk gönderim sonrasında yapılacak herhangi bir gönderim geçersiz sayılır.

5. **Seçimi bitirme:**
 - Tüm kayıtlı seçmenler oy verdiğinde seçim biter.
 - Seçimi bitirmek için zaman sınırı koyulursa, Seçim Düzenleyicisi başlangıç ve bitiş zamanını seçim başında ilan etmek zorundadır.
 - Zaman sınırılı seçimde, başlangıç zamanında önce ve bitiş zamanından sonra verilen oylar geçersizdir.

6. **Oy dökümü ve sayım:**
 - Herkese açık Bitcoin işlem defteri Blockchain'den tüm seçmenlerin listelenmiş adaylara gönderdiği tüm geçerli gönderimler sayılırak seçim sonucu belirlenir.
 - Seçim süreci başlangıcındaki kayıt aşamasından listelenmeye, oy vermeye, ve sonuçların sayılmasına kadar tümüyle Bitcoin Blockhain'de herkesin denetimine açık olarak kayıt altındadır.

#### Katılım

Bu temel sistem mevcut Bitcoin altyapısı ile bugün uygulamaya koyulabilir. Daha kolay kullanımlar için seçime özel uygulamalar ve arayüzler geliştirilebilir. Sistemle ilgili gördüğünüz açıklar ve iyileştirmeler için lütfen önerilerinizi ve eleştirilerinizi gönderiniz. Ayrıca doğrudan repo'dan fork/pull ile değiştirebilir ve katkıda bulunabilirsiniz.

#### Lisans

[The MIT License (MIT)](https://github.com/arikan/bitcoin-voting/blob/master/LICENSE)

## Sistem pengundian selamat dan mudah dengan Bitcoin

Kaedah kerja menggunakan matawang kripto Bitcoin sebagai sistem pengundian yang selamat dan mudah. Di dalam kaedah ini juga menggunakan algoritma [Blockchain](http://en.wikipedia.org/wiki/Blockchain) agar semua proses adalah terbuka kepada semua Rakyat.

#### Keperluan:

* Kesemua aktor pengundian harus mempunyai satu akaun Bitcoin (wallet).
* Kesemua aktor pengundian harus menggunakan komputer untuk mengundi.

#### Aktor:

* Pihak Berkuasa Pengundian (SPR)
* Calon
* Pengundi (Rakyat)

#### Terminologi:

* Block Chain: Senarai awam transaksi Bitcoin
* 1 Satoshi (0.00000001 Bitcoin): Unit terkecil matawang Bitcoin
* BTC: Singkatan matawang Bitcoin

#### Skema:

0. **Deklarasi Pihak Berkuasa Pengundian:**
 - Pihak Berkuasa Pengundian mengumumkan alamat Bitcoin secara terbuka.

1. **Pendaftaran pengundi:**
 - Pengundi menyediakan ID dan alamat Bitcoin yang sah kepada Pihak Berkuasa Pengundian, seterusnya menyalurkan 1 Satoshi kepada pengundi tersebut.
 - Semua alamat Bitcoin calon akan dipaparkan secara terbuka di dalam Blockchain.
 - Untuk mengekalkan privasi pengundi, Pihak Berkuasa Pengundian menyimpan ID untuk mengelakkan pendaftaran berganda, tetapi tidak menyimpan rekod yang berkaitan dengan ID dan alamat Bitcoin yang diberikan.

2. **Pendaftaran calon:**
 - Calon menyediakan ID dan alamat Bitcoin yang sah kepada Pihak Berkuasa Pengundian, seterusnya menyalurkan 2 Satoshi kepada calon tersebut.
 - Semua alamat Bitcoin calon akan dipaparkan secara terbuka di dalam Blockchain.
 - Dalam hal calon, Pihak Berkuasa Pengundian akan menyimpan rekod berkaitan ID dan alamat Bitcoin calon, dan berkuasa untuk memaparkan kedua-duanya secara terbuka.
 - Calon calon wajib mengumumkan alamat Bitcoin mereka.

3. **Pilihan raya:**
 - Pilihan raya bermula apabila Pihak Berkuasa Pengundian menyalurkan 1 Satoshi kepada semua alamat Bitcoin pengundi.
 - Alamat Bitcoin pengundi boleh disemak di Blockchain.

4. **Pengundian:**
 - Pengundi akan melakukan pemindahan/transaksi 1 Satoshi kepada alamat Bitcoin calon yang dipilih.
 - Proses transaksi Satoshi boleh disemak di Blockchain.

5. **Pengakhiran proses pengundian:**
 - Proses pengundian akan berakhir apabila semua transaksi telah diproses dan disahkan oleh Pihak Berkuasa Pengundian.
 - Had masa juga boleh di gunakan dalam proses ini.
 - Jika had masa ditetapkan, Pihak Berkuasa Pengundian harus mengumumkan waktu mula dan akhir pengundian tersebut.
 - Jika pengundian ditetapkan had masa, apa-apa undi sebelum dan selepas had masa di kira tidak sah.

6. **Election result:**
 - Keputusan pengundian diputuskan dengan mengira semua transaksi yang sah daripada alamat pengundian menggunakan Blockchain API.
 - Apa-apa transaksi selepas 1 Satoshi yang disalurkan adalah dikira tidak sah.
 - Semua proses-proses di atas daripada proses pendaftaran adalah terbuka kepada semua Rakyat.

#### Todo

 - Ikut proses sebenar PRU Malaysia
 - Cari isu berbangkit dalam kaedah ini

#### Sumbangan:

 - Kaedah asas ini boleh dilaksanakan menggunakan infrastruktur Bitcoin yang sedia ada.
 - Sumbangan kepada teknologi boleh dilakukan dengan membina sebuah aplikasi sistem antara muka untuk pengalaman pengguna yang baik.
 - Anda boleh menyumbang dengan memberi pendapat dan soalan berkaitan isu-isu berbangkit.
 - Adalah digalakkan untuk fork repositori dan hantar pull request.

#### Lesen

[The MIT License (MIT)](https://github.com/arikan/bitcoin-voting/blob/master/LICENSE)


text:
HEES
====

0 Download and Compile
------------------------

To run the simulator, you will need the simulator itself,
the sundials library and the boost library.

### 0.1 Download the simulator

### 0.2 Download and install the sundials library

1. Download the library from: [sundials website](http://computation.llnl.gov/casc/sundials/download/download.php).
   You only need the KINSOL package though.

2. untar the package, and go into the directory:

   ```
   tar -xzvf kinsol-2.7.0.tar.gz
   cd kinsol-2.7.0
   ```

   I would recommand you to read section B.1, B.2 and B.4 of the INSTALL\_NOTES,
   but if you don't want to, then you can just do:

   ```bash
   # Assume I want to install them to ~/usr/sundials directory
   ./configure --prefix=$HOME/usr/sundials --enable-examples
   make
   make install
   ```

### 0.3 Download and install the boost library
What we really need from boost library is just the program\_options.

#### 0.3.1 Install on Ubuntu

1. To find the this library in your Ubuntu release:

  ```
  sudo apt-cache search libboost-program-options\*
  ```
2. To install them, my Ubuntu comes with 1.55 version, so I just do

  ```
  sudo apt-get install libboost1.55-dev libboost-program-options1.55-dev libboost-program-options1.55.0
  ```

  Note that you will need the libboost1.55-dev for the header file "boost/program\_options.hpp"
3. Finally, you can verify your installation by using the command:

  ```
  dpkg-query --listfiles libboost1.55-dev

  dpkg-query --listfiles libboost-program-options1.55.0
  ```

  To check if the files have been installed correctly or just try to compile them.

#### 0.3.2 Install on Redhat

#### 0.3.3 Install from scratch

### 0.4 Compile the simulator

Set the following variable to correct path in Makefile:

```Makefile
SUNDIALS_INC_DIR = "$(HOME)/usr/sundials/include"
SUNDIALS_LIB_DIR = "$(HOME)/usr/sundials/lib"
BOOST_INC_DIR    = "$(HOME)/usr/include"
BOOST_LIB_DIR    = "$(HOME)/usr/lib/boost"
```

Then just do make in your command line:

```sh
$ make
```


text:
// TypeScript Version: 2.0

/**
* Interface describing `snanstdevyc`.
*/
interface Routine {
	/**
	* Computes the standard deviation of a single-precision floating-point strided array ignoring `NaN` values and using a one-pass algorithm proposed by Youngs and Cramer.
	*
	* @param N - number of indexed elements
	* @param correction - degrees of freedom adjustment
	* @param x - input array
	* @param stride - stride length
	* @returns standard deviation
	*
	* @example
	* var Float32Array = require( `@stdlib/array/float32` );
	*
	* var x = new Float32Array( [ 1.0, -2.0, NaN, 2.0 ] );
	*
	* var v = snanstdevyc( x.length, 1, x, 1 );
	* // returns ~2.0817
	*/
	( N: number, correction: number, x: Float32Array, stride: number ): number;

	/**
	* Computes the standard deviation of a single-precision floating-point strided array ignoring `NaN` values and using a one-pass algorithm proposed by Youngs and Cramer and alternative indexing semantics.
	*
	* @param N - number of indexed elements
	* @param correction - degrees of freedom adjustment
	* @param x - input array
	* @param stride - stride length
	* @param offset - starting index
	* @returns standard deviation
	*
	* @example
	* var Float32Array = require( `@stdlib/array/float32` );
	*
	* var x = new Float32Array( [ 1.0, -2.0, NaN, 2.0 ] );
	*
	* var v = snanstdevyc.ndarray( x.length, 1, x, 1, 0 );
	* // returns ~2.0817
	*/
	ndarray( N: number, correction: number, x: Float32Array, stride: number, offset: number ): number; // tslint:disable-line:max-line-length
}

/**
* Computes the standard deviation of a single-precision floating-point strided array ignoring `NaN` values and using a one-pass algorithm proposed by Youngs and Cramer.
*
* @param N - number of indexed elements
* @param correction - degrees of freedom adjustment
* @param x - input array
* @param stride - stride length
* @returns standard deviation
*
* @example
* var Float32Array = require( `@stdlib/array/float32` );
*
* var x = new Float32Array( [ 1.0, -2.0, NaN, 2.0 ] );
*
* var v = snanstdevyc( x.length, 1, x, 1 );
* // returns ~2.0817
*
* @example
* var Float32Array = require( `@stdlib/array/float32` );
*
* var x = new Float32Array( [ 1.0, -2.0, NaN, 2.0 ] );
*
* var v = snanstdevyc.ndarray( x.length, 1, x, 1, 0 );
* // returns ~2.0817
*/
declare var snanstdevyc: Routine;

// EXPORTS //

export = snanstdevyc;


text:
const UP = 0;
const DOWN = 1;
const LEFT = 2;
const RIGHT = 3;

class Food extends Phaser.GameObjects.Image {
    constructor(scene, x, y) {
        super(scene);
        this.scene = scene;

        this.setTexture('food');
        this.setPosition(x * 16, y * 16);
        this.setOrigin(0);

        this.total = 0;

        this.scene.children.add(this);
    }

    eat() {
        this.total++;
    }
}

class Snake {
    constructor(scene, x, y) {
        // super(scene);
        console.log("NEW");
        this.scene = scene;

        this.headPosition = new Phaser.Geom.Point(x, y);

        this.body = this.scene.add.group();

        this.head = this.body.create(x * 16, y * 16, 'body');
        this.head.setOrigin(0);

        this.alive = true;

        this.speed = 100;

        this.moveTime = 0;

        this.tail = new Phaser.Geom.Point(x, y);

        this.heading = RIGHT;
        this.direction = RIGHT;
    }

    update(time) {
        if (time >= this.moveTime) {
            return this.move(time);
        }
    }

    faceLeft() {
        if (this.direction === UP || this.direction === DOWN) {
            this.heading = LEFT;
        }
    }

    faceRight() {
        if (this.direction === UP || this.direction === DOWN) {
            this.heading = RIGHT;
        }
    }

    faceUp() {
        if (this.direction === LEFT || this.direction === RIGHT) {
            this.heading = UP;
        }
    }

    faceDown() {
        if (this.direction === LEFT || this.direction === RIGHT) {
            this.heading = DOWN;
        }
    }

    move(time) {
        switch (this.heading) {
            case LEFT:
                this.headPosition.x = Phaser.Math.Wrap(this.headPosition.x - 1, 0, 40);
                break;

            case RIGHT:
                this.headPosition.x = Phaser.Math.Wrap(this.headPosition.x + 1, 0, 40);
                break;

            case UP:
                this.headPosition.y = Phaser.Math.Wrap(this.headPosition.y - 1, 0, 30);
                break;

            case DOWN:
                this.headPosition.y = Phaser.Math.Wrap(this.headPosition.y + 1, 0, 30);
                break;
        }

        this.direction = this.heading;

        Phaser.Actions.ShiftPosition(this.body.getChildren(), this.headPosition.x * 16, this.headPosition.y * 16, 1, this.tail);

        var hitBody = Phaser.Actions.GetFirst(this.body.getChildren(), { x: this.head.x, y: this.head.y }, 1);

        if (hitBody) {
            console.log('dead');

            this.alive = false;

            return false;
        }
        else {
            this.moveTime = time + this.speed;
            return true;
        }
    }

    grow() {
        var newPart = this.body.create(this.tail.x, this.tail.y, 'body');
        newPart.setOrigin(0);
    }

    collideWithFood(food) {
        if (this.head.x === food.x && this.head.y === food.y) {
            this.grow();

            food.eat();

            //  For every 5 items of food eaten we'll increase the snake speed a little
            if (this.speed > 20 && food.total % 5 === 0) {
                this.speed -= 5;
            }

            return true;
        }
        else {
            return false;
        }
    }

    updateGrid(grid) {
        //  Remove all body pieces from valid positions list
        this.body.children.each(function (segment) {

            var bx = segment.x / 16;
            var by = segment.y / 16;

            grid[by][bx] = false;

        });

        return grid;
    }
}

class SceneGame extends Phaser.Scene {
    constructor() {
        super({ key: "SceneGame" });
    }
    preload() {
        this.load.image('food', 'assets/food.png');
        this.load.image('body', 'assets/body.png');
    }
    create() {
        console.log("game");

        this.snake = new Snake(this, 8, 8);
        this.food = new Food(this, 3, 4);
        this.cursors = this.input.keyboard.createCursorKeys();
        console.log(this.snake);
    }

    update(time, delta) {
        if (!this.snake.alive) {
            return;
        }

        if (this.cursors.left.isDown) {
            this.snake.faceLeft();
        }
        else if (this.cursors.right.isDown) {
            this.snake.faceRight();
        }
        else if (this.cursors.up.isDown) {
            this.snake.faceUp();
        }
        else if (this.cursors.down.isDown) {
            this.snake.faceDown();
        }

        if (this.snake.update(time)) {
            //  If the snake updated, we need to check for collision against food

            if (this.snake.collideWithFood(this.food)) {
                this.repositionFood();
            }
        }
    }

    repositionFood() {
        var testGrid = [];

        for (var y = 0; y < 30; y++) {
            testGrid[y] = [];

            for (var x = 0; x < 40; x++) {
                testGrid[y][x] = true;
            }
        }

        this.snake.updateGrid(testGrid);

        //  Purge out false positions
        var validLocations = [];

        for (var y = 0; y < 30; y++) {
            for (var x = 0; x < 40; x++) {
                if (testGrid[y][x] === true) {
                    //  Is this position valid for food? If so, add it here ...
                    validLocations.push({ x: x, y: y });
                }
            }
        }

        if (validLocations.length > 0) {
            //  Use the RNG to pick a random food position
            var pos = Phaser.Math.RND.pick(validLocations);

            //  And place it
            this.food.setPosition(pos.x * 16, pos.y * 16);

            return true;
        }
        else {
            return false;
        }
    }
}

export default SceneGame;


text:
package org.kie.dmn.validation.dtanalysis.model;

import java.util.Collections;
import java.util.List;

public class DDTAInputClause {

    private final Interval domainMinMax;
    private final List discreteValues;

    public DDTAInputClause(Interval domainMinMax) {
        this.domainMinMax = domainMinMax;
        this.discreteValues = Collections.emptyList();
    }

    public DDTAInputClause(Interval domainMinMax, List discreteValues) {
        this.domainMinMax = domainMinMax;
        this.discreteValues = discreteValues;
    }

    public Bound<?> getMin() {
        return domainMinMax.getLowerBound();
    }

    public Bound<?> getMax() {
        return domainMinMax.getUpperBound();
    }

    public Interval getDomainMinMax() {
        return domainMinMax;
    }

    public List getDiscreteValues() {
        return Collections.unmodifiableList(discreteValues);
    }

    public boolean isDiscreteDomain() {
        return discreteValues != null && !discreteValues.isEmpty();
    }

}


text:
package com.nextreme.demo;
import com.nextreme.lib.*;

import java.util.*;

public class Main {
    static void testMoreClass() {
        More more = new More();

        if( more instanceof More ) {
            System.out.println("object type is More");
        }

        more.printName();
    }

    public static void testMethodBenchmark(String[] args) {
        int count = Integer.parseInt(args[0]);

        long time = new MethodBenchmark().repeat(count);
        System.out.println(count + " methods in " + time + " nanoseconds");
    }

    public static void testCollections() {
        ArrayList<String> al = new ArrayList<String>();
        al.add("dafasfasf");
        al.add("other");

        System.out.println(al);

        HashSet<String> hs = new HashSet<String>();
        hs.add("fdaa");

        System.out.println(hs);

        LinkedList<String> ll = new LinkedList<String>();
        ll.add("LinkedList has ssdfsaf");
        System.out.println(ll);

        PriorityQueue<String> pq = new PriorityQueue<String>();

        LinkedHashMap<String, String> hm = new LinkedHashMap<String, String>();
        hm.put("age","34");
        System.out.println(hm);
    }

    public static void main(String[] args) {
        Body mercury;
        Body.nextID = 34;

        Body b = new Body("zhang", null);

        System.out.println("Hello world");

        testMoreClass();
        testMethodBenchmark(args);
        testCollections();;

        int aas = 45;
        Number n = aas;
        Object obj = n;

        Cell<String> strCell = new Cell<String>("Hello");
        Cell<ConsoleVerbose> conCell = new Cell<ConsoleVerbose>(new ConsoleVerbose());
        assert strCell.getNext()==null; // assert

        List<String> l = new ArrayList<String>();
    }
}


text:
import React, {Component} from "react";
import PropTypes from "prop-types";
import {connect} from "react-redux";
import {fetchConfigs, logoutUser, isLoginUser} from "../actions/index";
import {Link} from "react-router";

class App extends Component {
  componentDidMount() {
    const {fetchConfigs, isLoginUser} = this.props;

    if (!isLoginUser().payload) {
      this.props.router.push("/login");
    }

    fetchConfigs();
  }

  componentDidMount() {
    // Toggle menu
    const burger = document.querySelector(".nav-toggle");
    const menu = document.querySelector(".nav-menu");

    burger.addEventListener("click", () => {
      burger.classList.toggle("is-active");
      menu.classList.toggle("is-active");
    });
  }

  render() {
    const {config, location, children, logoutUser} = this.props;

    return (

                {config.title}

            <Link to="/dashboard" className={(
                location.pathname == "/dashboard" || location.pathname == "/dashboard/")
                ? "nav-item is-tab active"
                : "nav-item is-tab"}>
              Dashboard
            </Link>
            <Link to="/dashboard/posts" className={(
                location.pathname == "/dashboard/posts")
                ? "nav-item is-tab active"
                : "nav-item is-tab"}>
              Posts
            </Link>
            <Link to="/dashboard/new-post" className={(
                location.pathname == "/dashboard/new-post/")
                ? "nav-item is-tab active"
                : "nav-item is-tab"}>
              NewPost
            </Link>
            <Link to="/dashboard/categories" className={(
                location.pathname == "/dashboard/categories/")
                ? "nav-item is-tab active"
                : "nav-item is-tab"}>
              Categories
            </Link>
            <Link to="/dashboard/tags" className={(
                location.pathname == "/dashboard/tags/")
                ? "nav-item is-tab active"
                : "nav-item is-tab"}>
              Tags
            </Link>
            <Link to="/dashboard/config" className={(
                location.pathname == "/dashboard/config/")
                ? "nav-item is-tab active"
                : "nav-item is-tab"}>
              Config
            </Link>
            <Link to="/login" onClick={logoutUser} className={(
                location.pathname == "/login")
                ? "nav-item is-tab active"
                : "nav-item is-tab"}>
              Logout
            </Link>

Main

              <Link to="/dashboard" className={(
                  location.pathname == "/dashboard" || location.pathname == "/dashboard/")
                  ? "item active"
                  : "item"}>

                Dashboard
              </Link>
              <Link to="/dashboard/posts" className={(
                  location.pathname == "/dashboard/posts")
                  ? "item active"
                  : "item"}>

                Posts
              </Link>
              <Link to="/dashboard/new-post" className={(
                  location.pathname == "/dashboard/new-post")
                  ? "item active"
                  : "item"}>

                NewPost
              </Link>
              <Link to="/dashboard/categories" className={(
                  location.pathname == "/dashboard/categories")
                  ? "item active"
                  : "item"}>

                Categories
              </Link>
              <Link to="/dashboard/tags" className={(
                  location.pathname == "/dashboard/tags")
                  ? "item active"
                  : "item"}>

                Tags
              </Link>
              <Link to="/dashboard/config" className={(
                  location.pathname == "/dashboard/config")
                  ? "item active"
                  : "item"}>

                Config
              </Link>
              <Link to="/login" onClick={logoutUser} className={(
                  location.pathname == "/login")
                  ? "item active"
                  : "item"}>

                Logout
              </Link>

          {children}

              Rubel
              by bmf. The source code is licensed
              MIT.

);
  }
}

App.propTypes = {
  fetchConfigs: PropTypes.func,
  location: PropTypes.object,
  config: PropTypes.object,
  children: PropTypes.object,
  logoutUser: PropTypes.func,
  isLoginUser: PropTypes.func,
  router: PropTypes.object
};

App.contextTypes = {
  router: PropTypes.object
};

function mapStateToProps(state) {
  const obj = {};

  state.configs.all.map((config) => {
    obj[config.name] = config.value;
  });

  return {configs: state.configs, config: obj};
}

export default connect(mapStateToProps, {fetchConfigs, logoutUser, isLoginUser})(App);


text:
package com.thinkgem.jeesite.modules.pdd.bean;

import com.fasterxml.jackson.annotation.JsonProperty;

import java.util.List;

public class SeriesBean {
    @JsonProperty("name")
    private String name;
    @JsonProperty("color")
    private String color;
    @JsonProperty("data")
    private double[] data;

    public SeriesBean(String name, String color, double[] data) {
      this.name = name;
      this.color = color;
      this.data = data;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public double[] getData() {
        return data;
    }

    public void setData(double[] data) {
        this.data = data;
    }
}


text:
Simple Laravel Web Application with CRUD (Create, Read, Update, Delete) functions.

### Updates
- 26/08/2018
  - Upgraded Laravel version from 5.4 to 5.6
  - Fix forms styles to display errors correctly
  - Change some codes to be more 'Laravel ways'
- 07/02/2017
  - Upgraded Laravel version from 5.3 to 5.4
- 29/01/2017
  - Now have table migration script
  - Updates table columns in pages, to lowercase
  - Form now will display errors and success message
  - Update edit, delete, search pages.
- 09/11/2016
  - Added pagination to the data results (view stock and search page)
- 31/10/2016
  - Added stock image upload
  - Create user authentication, user can now register and login

# Purpose
- First web application that I developed using Laravel Framework. Developed during my learning process.
- This project will be keep on updated during my learning process, where I will improve my Laravel knowledge.

# Developed By
- Afif - https://fb.me/afzafri

# Installation
- Download or Clone this repository
```
git clone https://github.com/afzafri/Simple-Laravel-CRUD.git
```
- Create a new database
- Copy or rename file ```.env.example``` to ```.env```, and edit the file to change the attributes for database to your database configurations (host,username,password etc)
-  Open up Command Prompt(CMD) or Terminal in the project directory and run these commands:
```
composer install
php artisan key:generate
php artisan migrate
php artisan storage:link
```
- Launch web server
```
php artisan serve
```

# Credits
- Laravel PHP Framework - https://laravel.com/docs/5.3/installation
- Bootstrap Framework - http://getbootstrap.com/
- jQuery Library - https://jquery.com/
- Font Awesome - http://fontawesome.io/

# License
This library is under MIT license, please look at the `LICENSE` file


text:
cd ./UI
call yarn install
call npm run build -- --prod --base-href /ui/
cd ../


text:
Rails.application.routes.draw do

  devise_for :teachers, path: 'auth'

  get '/students/import' => 'students#import', as: :students_import
  post '/students/import' => 'students#create_multiple'
  resources :students

  patch '/students/:student_id/teachers/:id' => 'students_teachers#update', as: :student_teacher
  patch '/students/:student_id/teachers/:id/remove' => 'students_teachers#remove', as: :remove_student_teacher

  get '/teachers/:id' => 'teachers#show', as: :teacher
  get '/teachers' => 'teachers#index', as: :teachers

  delete '/teachers/:id' => 'teachers#destroy'

  root to: 'welcome#index'
end