text:
/*global variables $Utils, $, ResizeSensor*/
loadOnce("/$Utils");
(function(){
    var BrowserWindow = require('electron').remote.BrowserWindow;
    var ipc = require('electron').ipcRenderer;

    //functions to read functions from string
    var getFunction = function(str){
        var funcContent = str.match(/function\s*\((.*)\)\s*{((\s|.)*)}/);
        if(funcContent){
            var args = funcContent[1].split(",");
            return Function(...args, funcContent[2]);
        }else
            return function(){
                throw Error("function content not found using regex: /function\\s*\\(\\)\\s*{((\\n|.)*)}/\nfunction string: "+str);
            }
    };
    var parseArrayFunctions = function(array){
        for(var i=0; i<array.length; i++){
            var val = array[i];
            if(val instanceof Object){
                if(Object.keys(val).length==1 && val["function"]){
                    array[i] = getFunction(val["function"]);
                }else{
                    parseObjectFunctions(val);
                }
            }else if(val instanceof Array){
                parseArrayFunctions(val);
            }
        }
    };
    var parseObjectFunctions = function(object){
        if(object!=null){
            var keys = Object.keys(object);
            for(var i=0; i<keys.length; i++){
                var key = keys[i];
                var val = object[key];
                if(val instanceof Object){
                    if(Object.keys(val).length==1 && val["function"]){
                        object[key] = getFunction(val["function"]);
                    }else{
                        parseObjectFunctions(val);
                    }
                }else if(val instanceof Array){
                    parseArrayFunctions(val);
                }
            }
        }
    };

    //parse the string to code
    var con = window.controller;
    parseObjectFunctions(con);

    //create the elements
    var n = $Utils.createTemplateElement(con.className, con.template);
    con.element = n.element;
    con.$ = n.querier;
    con.htmlClassName = n.htmlClassName;

    $("body").append(con.element);

    con.on = function(){
        ipc.on.apply(ipc, arguments);
    };

    var parent = BrowserWindow.fromId(con.parentWindowID);
    var thisID = con.windowID;
    window.on = con.on;
    con.send = function(event, data){
        parent.send("subWindowEvent", {id:thisID, event:event, data:data});
    };
    window.send = con.send;

    if(con.listeners){
        var keys = Object.keys(con.listeners);
        for(var i=0; i<keys.length; i++){
            var key = keys[i];
            var listener = con.listeners[key];
            console.log(listener, key)
            window.on(key, listener);
        }
    }

    var rsl = new ResizeSensor(con.element, function(){
        con.send("resize", {width: n.element.width(), height: n.element.height()});
    });
    $(function(){
        con.send("resize", {width: n.element.width(), height: n.element.height()});
    });

    if(con.onInit)
        con.onInit.call(con);

})();


text:
package Abstraction.Lab.P04SayHelloExtend;

public class Bulgarian extends BasePerson{
    public Bulgarian(String name) {
        super(name);
    }

    @Override
    public String sayHello() {
        return "Здравей";
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.github.weisj.darklaf.components.tabframe;

import javax.swing.*;

public interface TabFramePopupUI {

    /**
     * Add a button to the popup matching the frames' appearance.
     *
     * @param icon the icon of the button
     * @param tooltipText the tooltip text
     * @return the added button. Use this to configure any actions.
     */
    AbstractButton addButton(final Icon icon, final String tooltipText);

    /**
     * Remove a button added through {@link #addButton(Icon, String)}.
     *
     * @param button the button to remove
     */
    void removeButton(final AbstractButton button);
}


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

namespace ArDrone3Pcap
{
    public class RingBuffer
    {
        private const int BufferSize = 64 * 1024;

        public int BytesRemaining
        {
            get { return blen - bstart; }
        }

        private byte[] buffer = new byte[BufferSize];
        private int bstart = 0;
        private int blen = 0;

        private Frame.FrameDirection direction;

        public RingBuffer(Frame.FrameDirection direction)
        {
            this.direction = direction;
        }

        public void AddData(byte[] data)
        {
            // Ring buffer
            var len = data.Length;
            Buffer.BlockCopy(data, 0, buffer, bstart, len);
            blen += len;
        }

        public Frame ReadFrame()
        {
            if (blen > 7)
            {
                int frameLen = 0;
                frameLen = buffer[bstart + 3];
                frameLen |= (buffer[bstart + 4] << 8);
                frameLen |= (buffer[bstart + 5] << 16);
                frameLen |= (buffer[bstart + 6] << 24);

                if (blen >= frameLen)
                {
                    // Process packet
                    var payload = new byte[frameLen - 7];
                    Buffer.BlockCopy(buffer, bstart + 7, payload, 0, frameLen - 7);
                    var type = buffer[bstart];
                    var id = buffer[bstart + 1];
                    var seq = buffer[bstart + 2];

                    var frame = new Frame(direction, (FrameType) type, id, seq, payload);
                    bstart += frameLen;
                    blen -= frameLen;

                    if (blen == 0)
                    {
                        bstart = 0;
                    }
                    else if (bstart > 0 && (bstart + blen) >= buffer.Length)
                    {
                        Buffer.BlockCopy(buffer, bstart, buffer, 0, blen);
                        bstart = 0;
                    }

                    return frame;
                }
            }
            return null;
        }
    }
}


text:
<?php

namespace Preconditions\Exception;

class IndexOutOfBoundsException extends \OutOfBoundsException
{

}


text:
'use strict';

const models = require('./index');

/**
 * @class
 * Initializes a new instance of the ExpressRouteCircuitsArpTableListResult class.
 * @constructor
 * Response for ListArpTable associated with the Express Route Circuits API.
 *
 * @member {array} [value] Gets list of the ARP table.
 *
 * @member {string} [nextLink] The URL to get the next set of results.
 *
 */
class ExpressRouteCircuitsArpTableListResult {
  constructor() {
  }

  /**
   * Defines the metadata of ExpressRouteCircuitsArpTableListResult
   *
   * @returns {object} metadata of ExpressRouteCircuitsArpTableListResult
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'ExpressRouteCircuitsArpTableListResult',
      type: {
        name: 'Composite',
        className: 'ExpressRouteCircuitsArpTableListResult',
        modelProperties: {
          value: {
            required: false,
            serializedName: 'value',
            type: {
              name: 'Sequence',
              element: {
                  required: false,
                  serializedName: 'ExpressRouteCircuitArpTableElementType',
                  type: {
                    name: 'Composite',
                    className: 'ExpressRouteCircuitArpTable'
                  }
              }
            }
          },
          nextLink: {
            required: false,
            serializedName: 'nextLink',
            type: {
              name: 'String'
            }
          }
        }
      }
    };
  }
}

module.exports = ExpressRouteCircuitsArpTableListResult;


text:
using System;
using Azure.Core;

namespace Azure.ResourceManager.ServiceFabricManagedClusters.Models
{
    /// <summary> IPTag associated with the object. </summary>
    public partial class ManagedClusterIPTag
    {
        /// <summary> Initializes a new instance of ManagedClusterIPTag. </summary>
        /// <param name="ipTagType"> The IP tag type. </param>
        /// <param name="tag"> The value of the IP tag. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="ipTagType"/> or <paramref name="tag"/> is null. </exception>
        public ManagedClusterIPTag(string ipTagType, string tag)
        {
            Argument.AssertNotNull(ipTagType, nameof(ipTagType));
            Argument.AssertNotNull(tag, nameof(tag));

            IPTagType = ipTagType;
            Tag = tag;
        }

        /// <summary> The IP tag type. </summary>
        public string IPTagType { get; set; }
        /// <summary> The value of the IP tag. </summary>
        public string Tag { get; set; }
    }
}


text:
import logging
from datetime import datetime

import mongoengine as mongo

from nefertari.json_httpexceptions import (
    JHTTPBadRequest, JHTTPNotFound, JHTTPConflict)
from nefertari.utils import (
    process_fields, process_limit, _split, dictset, DataProxy,
    to_dicts)
from .metaclasses import ESMetaclass, DocumentMetaclass
from .fields import DateTimeField, IntegerField, ForeignKeyField

log = logging.getLogger(__name__)

def get_document_cls(name):
    try:
        return mongo.document.get_document(name)
    except:
        raise ValueError('`%s` does not exist in mongo db' % name)

def process_lists(_dict):
    for k in _dict:
        new_k, _, _t = k.partition('__')
        if _t == 'in' or _t == 'all':
            _dict[k] = _dict.aslist(k)
    return _dict

def process_bools(_dict):
    for k in _dict:
        new_k, _, _t = k.partition('__')
        if _t == 'bool':
            _dict[new_k] = _dict.pop_bool_param(k)

    return _dict

class BaseMixin(object):
    """ Represents mixin class for models.

    Attributes:
        _auth_fields: String names of fields meant to be displayed to
            authenticated users.
        _public_fields: String names of fields meant to be displayed to
            NOT authenticated users.
        _nested_fields: ?
        _nested_relationships: String names of reference/relationship fields
            that should be included in JSON data of an object as full
            included documents. If reference/relationship field is not
            present in this list, this field's value in JSON will be an
            object's ID or list of IDs.
    """
    _auth_fields = None
    _public_fields = None
    _nested_fields = None
    _nested_relationships = ()
    _backref_hooks = ()

    _type = property(lambda self: self.__class__.__name__)
    Q = mongo.Q

    @classmethod
    def id_field(cls):
        return cls._meta['id_field']

    @classmethod
    def check_fields_allowed(cls, fields):
        if issubclass(cls, mongo.DynamicDocument):
            # Dont check if its dynamic doc
            return
        fields = [f.split('__')[0] for f in fields]
        fields_to_query = set(cls.fields_to_query())
        if not set(fields).issubset(fields_to_query):
            not_allowed = set(fields) - fields_to_query
            raise JHTTPBadRequest(
                "'%s' object does not have fields: %s" % (
                    cls.__name__, ', '.join(not_allowed)))

    @classmethod
    def filter_fields(cls, params):
        """ Filter out fields with invalid names. """
        fields = cls.fields_to_query()
        return dictset({
            name: val for name, val in params.items()
            if name.split('__')[0] in fields
        })

    @classmethod
    def apply_fields(cls, query_set, _fields):
        fields_only, fields_exclude = process_fields(_fields)

        try:
            if fields_only:
                query_set = query_set.only(*fields_only)

            if fields_exclude:
                query_set = query_set.exclude(*fields_exclude)

        except mongo.InvalidQueryError as e:
            raise JHTTPBadRequest('Bad _fields param: %s ' % e)

        return query_set

    @classmethod
    def apply_sort(cls, query_set, _sort):
        if not _sort:
            return query_set
        return query_set.order_by(*_sort)

    @classmethod
    def count(cls, query_set):
        return query_set.count(with_limit_and_skip=True)

    @classmethod
    def get_collection(cls, **params):
        """
        params may include '_limit', '_page', '_sort', '_fields'
        returns paginated and sorted query set
        raises JHTTPBadRequest for bad values in params
        """
        params.pop('__confirmation', False)
        __strict = params.pop('__strict', True)

        _sort = _split(params.pop('_sort', []))
        _fields = _split(params.pop('_fields', []))
        _limit = params.pop('_limit', None)
        _page = params.pop('_page', None)
        _start = params.pop('_start', None)

        _count = '_count' in params; params.pop('_count', None)
        _explain = '_explain' in params; params.pop('_explain', None)
        __raise_on_empty = params.pop('__raise_on_empty', False)

        query_set = cls.objects

        # Remove any __ legacy instructions from this point on
        params = dictset(filter(lambda item: not item[0].startswith('__'), params.items()))

        if __strict:
            _check_fields = [f.strip('-+') for f in params.keys() + _fields + _sort]
            cls.check_fields_allowed(_check_fields)
        else:
            params = cls.filter_fields(params)

        process_lists(params)
        process_bools(params)

        #if param is _all then remove it
        params.pop_by_values('_all')

        try:
            query_set = query_set(**params)
            _total = query_set.count()
            if _count:
                return _total

            if _limit is None:
                raise JHTTPBadRequest('Missing _limit')

            _start, _limit = process_limit(_start, _page, _limit)

            # Filtering by fields has to be the first thing to do on the query_set!
            query_set = cls.apply_fields(query_set, _fields)
            query_set = cls.apply_sort(query_set, _sort)
            query_set = query_set[_start:_start+_limit]

            if not query_set.count():
                msg = "'%s(%s)' resource not found" % (cls.__name__, params)
                if __raise_on_empty:
                    raise JHTTPNotFound(msg)
                else:
                    log.debug(msg)

        except (mongo.ValidationError, mongo.InvalidQueryError) as e:
            raise JHTTPBadRequest(str(e), extra={'data': e})

        if _explain:
            return query_set.explain()

        log.debug('get_collection.query_set: %s(%s)',
                  cls.__name__, query_set._query)

        query_set._nefertari_meta = dict(
            total=_total,
            start=_start,
            fields=_fields)

        return query_set

    @classmethod
    def has_field(cls, field):
        return field in cls._fields

    @classmethod
    def fields_to_query(cls):
        query_fields = ['id', '_limit', '_page', '_sort', '_fields', '_count', '_start']
        return query_fields + cls._fields.keys() #+ cls._meta.get('indexes', [])

    @classmethod
    def get_resource(cls, **params):
        params.setdefault('__raise_on_empty', True)
        params['_limit'] = 1
        query_set = cls.get_collection(**params)
        return query_set.first()

    @classmethod
    def get(cls, **kw):
        return cls.get_resource(__raise_on_empty=kw.pop('__raise', False), **kw)

    def unique_fields(self):
        id_field = [self._meta['id_field']]
        uniques = [e['fields'][0][0] for e in self._unique_with_indexes()]
        return uniques + id_field

    @classmethod
    def get_or_create(cls, **params):
        defaults = params.pop('defaults', {})
        try:
            return cls.objects.get(**params), False
        except mongo.queryset.DoesNotExist:
            defaults.update(params)
            return cls(**defaults).save(), True
        except mongo.queryset.MultipleObjectsReturned:
            raise JHTTPBadRequest('Bad or Insufficient Params')

    def _update(self, params, **kw):
        process_bools(params)
        id_field = self.id_field()
        for key, value in params.items():
            if key == id_field:  # can't change the primary key
                continue
            setattr(self, key, value)
        return self.save(**kw)

    @classmethod
    def _delete(cls, **params):
        cls.objects(**params).delete()

    @classmethod
    def _delete_many(cls, items):
        for item in items:
            item.delete()

    @classmethod
    def _update_many(cls, items, **params):
        for item in items:
            item._update(params)

    def __repr__(self):
        parts = ['%s:' % self.__class__.__name__]

        if hasattr(self, 'id'):
            parts.append('id=%s' % self.id)

        if hasattr(self, '_version'):
            parts.append('v=%s' % self._version)

        return '<%s>' % ', '.join(parts)

    @classmethod
    def get_by_ids(cls, ids, **params):
        id_field = '{}__in'.format(cls.id_field())
        params.update({
            id_field: ids,
            '_limit': len(ids),
        })
        return cls.get_collection(**params)

    def to_dict(self, **kwargs):
        def _process(key, val):
            is_doc = isinstance(val, mongo.Document)
            include = key in self._nested_relationships
            if is_doc and not include:
                val = getattr(val, val.id_field(), None)
            return val

        _data = {}
        for attr in self._data:
            # Ignore ForeignKeyField fields
            if isinstance(self._fields.get(attr), ForeignKeyField):
                continue
            value = getattr(self, attr, None)
            if isinstance(value, list):
                value = [_process(attr, v) for v in value]
            else:
                value = _process(attr, value)
            _data[attr] = value
        _dict = DataProxy(_data).to_dict(**kwargs)
        _dict['_type'] = self._type
        return _dict

    def get_reference_documents(self):
        # TODO: Make lazy load of documents
        models = self.__class__._meta['delete_rules'] or {}
        for model_cls, key in models:
            documents = to_dicts(model_cls.objects(**{key: self}))
            yield model_cls, documents

    def update_iterables(self, params, attr, unique=False, value_type=None):
        is_dict = isinstance(type(self)._fields[attr], mongo.DictField)
        is_list = isinstance(type(self)._fields[attr], mongo.ListField)

        def split_keys(keys):
            neg_keys = []
            pos_keys = []

            for key in keys:
                if key.startswith('__'):
                    continue
                if key.startswith('-'):
                    neg_keys.append(key[1:])
                else:
                    pos_keys.append(key.strip())
            return pos_keys, neg_keys

        def update_dict():
            name = params.pop('name')

            if name.startswith("-"):
                self[attr].pop(name[1:], None)
            else:
                pos, neg = split_keys(params.keys())
                vals = pos + ["-%s" % n for n in neg]
                if not vals:
                    raise JHTTPBadRequest('missing params')

                if value_type == list:
                    self[attr][name] = vals
                else:
                    self[attr][name] = vals[0]
            self.save()

        def update_list():
            pos_keys, neg_keys = split_keys(params.keys())

            if not (pos_keys + neg_keys):
                raise JHTTPBadRequest('missing params')

            if pos_keys:
                if unique:
                    self.update(**{'add_to_set__%s' % attr: pos_keys})
                else:
                    self.update(**{'push_all__%s' % attr: pos_keys})

            if neg_keys:
                self.update(**{'pull_all__%s' % attr: neg_keys})

        if is_dict:
            update_dict()

        elif is_list:
            update_list()

    @classmethod
    def expand_with(cls, with_cls, join_on=None, attr_name=None, params={},
                    with_params={}):
        """ Acts like "join" and inserts the with_cls objects in
        the result as "attr_name".
        """
        if join_on is None:
            join_on = with_cls.__name__.lower()
        if attr_name is None:
            attr_name = with_cls.__name__.lower()

        with_fields = with_params.pop('_fields', [])
        with_objs = with_cls.get_by_ids(
            cls.objects.scalar(join_on),
            **with_params)
        with_objs = dict([[str(wth.id), wth] for wth in with_objs])

        params['%s__in' % join_on] = with_objs.keys()
        objs = cls.get_collection(**params)

        for ob in objs:
            ob._data[attr_name] = with_objs[getattr(ob, join_on)]
            setattr(ob, attr_name, ob._data[attr_name])

        return objs

class BaseDocument(BaseMixin, mongo.Document):
    __metaclass__ = DocumentMetaclass

    updated_at = DateTimeField()
    _version = IntegerField(default=0)

    meta = {
        'abstract': True,
    }

    def save(self, *arg, **kw):
        sync_backref = kw.pop('sync_backref', True)
        if self._get_changed_fields():
            self.updated_at = datetime.utcnow()
            self._version += 1
        try:
            super(BaseDocument, self).save(*arg, **kw)
        except (mongo.NotUniqueError, mongo.OperationError) as e:
            if e.__class__ is mongo.OperationError and 'E11000' not in e.message:
                raise  # Other error, not duplicate

            raise JHTTPConflict(
                detail='Resource `%s` already exists.' % self.__class__.__name__,
                extra={'data': e})
        else:
            if sync_backref:
                self.run_backref_hooks()
            self._backref_hooks = ()
            return self

    def run_backref_hooks(self):
        """ Runs post-save backref hooks.

        Hooks only include backref hooks which are one-time hooks
        used to sync backrefs.
        """
        for hook in self._backref_hooks:
            hook(document=self)

    def update(self, params, **kw):
        try:
            return self._update(params, **kw)
        except (mongo.NotUniqueError, mongo.OperationError) as e:
            if e.__class__ is mongo.OperationError and 'E11000' not in e.message:
                raise #other error, not duplicate

            raise JHTTPConflict(
                detail='Resource `%s` already exists.' % self.__class__.__name__,
                extra={'data': e})

    def validate(self, *arg, **kw):
        try:
            return super(BaseDocument, self).validate(*arg, **kw)
        except mongo.ValidationError as e:
            raise JHTTPBadRequest(
                'Resource `%s`: %s' % (self.__class__.__name__, e),
                extra={'data':e})

    def clean(self):
        """ Override `clean` method to apply each field's processors
        before running validation.
        """
        for name, field in self._fields.items():
            if hasattr(field, 'apply_processors'):
                value = self._data.get(name)
                value = field.apply_processors(value)
                setattr(self, name, value)

class ESBaseDocument(BaseDocument):
    __metaclass__ = ESMetaclass
    meta = {
        'abstract': True,
    }


text:
'Guess It' is developed to demonstarte 'Information Theory' under 'CS Unplugged' activities.

  - Tools and Technologies - Java , Greenfoot, MongoDb.
  - Deployed on Heroku container.

## Compiler Instruction

### Requirements

* Java JDK Version 1.8
* Greenfoot Version 3.0.4
* MongoDb (mLab)
* Eclipse Mars Release (4.5.0)
* Tomcat 1.7.0

And of course Dillinger itself is open source with a [public repository][dill]
 on GitHub.

### Installation

* GuessIt requires Java 1.8. Download it and add bin folders path to system path.Install [Java 1.8](http://www.oracle.com/technetwork/java/javase/downloads/java-archive-javase8-2177648.html#jdk-8u102-oth-JPR)
* Download and install [Greenfoot](http://www.greenfoot.org/download).
* Clone this repository to your local machine and click on 'project' icon.This will open the game in greenfoot ide.

### Database SetUp

We are using mongodb, hosted on mLab for storing game's information. Otherwise you can also use [mLab database connection URL]("mongodb://guessitadmin:techadmin@ds151137.mlab.com:51137/guessit")

#### Steps to create your own databse
Create an account in [mLab](https://mlab.com/) and add a new deployement database using 'Create' button.Cloud provider will be Amazon AWS Single Node Cluster.Provide deployment's name as 'guessit'.
Now copy the MongoDB URI.You can use this uri in web service to store and get data.

Install the dependencies and devDependencies and start the server.

### Deployment in Heroku
Guessit's webservice is very easy to modify and deploy in a Heroku Container.
By default, pom.xml is added to take care of the deployement process. So in your eclipse project you have to do this following steps to deploy webservice in cloud.
* Login to Heroku and create an app.
* Set this app name in pom.xml under
<plugin>
      	<groupId>com.heroku.sdk</groupId>
      	   <artifactId>heroku-maven-plugin</artifactId>
      	   <version>0.3.4</version>
      	   <configuration>
      	      <appName>app_name</appName>
      	   </configuration>
</plugin>
* Click on Project-> Run As -> Maven build
* Give a name to this deployment logic.i.e. guessit_deployment
* Include 'heroku:deploy-war' in goals field
* Go to tab environment add a new venvironment variable with name 'HEROKU_API_KEY'
* Now Click on 'Run'.

Everytime you change code, you first need to use 'maven claen', 'maven install' and lastly deploy using 'maven-build'(using guessit_deployment configuration)

More details steps can be found [here](https://devcenter.heroku.com/articles/deploying-java-applications-to-heroku-from-eclipse-or-intellij-idea#deploying-from-eclipse)

License
----

MIT

**Free Software, Hell Yeah!**


text:
package i2c

// GroveLcdDriver is a driver for the Jhd1313m1 LCD display which has two i2c addreses,
// one belongs to a controller and the other controls solely the backlight.
// This module was tested with the Seed Grove LCD RGB Backlight v2.0 display which requires 5V to operate.
// http://www.seeedstudio.com/wiki/Grove_-_LCD_RGB_Backlight
type GroveLcdDriver struct {
	*JHD1313M1Driver
}

// GroveAccelerometerDriver is a driver for the MMA7660 accelerometer
type GroveAccelerometerDriver struct {
	*MMA7660Driver
}

// NewGroveLcdDriver creates a new driver with specified i2c interface.
// Params:
//		conn Connector - the Adaptor to use with this Driver
//
// Optional params:
//		i2c.WithBus(int):	bus to use with this driver
//		i2c.WithAddress(int):	address to use with this driver
//
func NewGroveLcdDriver(a Connector, options ...func(Config)) *GroveLcdDriver {
	lcd := &GroveLcdDriver{
		JHD1313M1Driver: NewJHD1313M1Driver(a),
	}

	for _, option := range options {
		option(lcd)
	}

	return lcd
}

// NewGroveAccelerometerDriver creates a new driver with specified i2c interface
// Params:
//		conn Connector - the Adaptor to use with this Driver
//
// Optional params:
//		i2c.WithBus(int):	bus to use with this driver
//		i2c.WithAddress(int):	address to use with this driver
//
func NewGroveAccelerometerDriver(a Connector, options ...func(Config)) *GroveAccelerometerDriver {
	mma := &GroveAccelerometerDriver{
		MMA7660Driver: NewMMA7660Driver(a),
	}

	for _, option := range options {
		option(mma)
	}

	return mma
}


text:
#include "SampleApplication/AudioManager/SDS/SDSReader.h"
#include "SampleApplication/Utils/RadiantLogger.h"

namespace multiAgentExperience {
namespace sampleApplication {
namespace audioManager {
namespace sds {

/// Metadata parameters that will be passed into our logging system.
static const std::string MODULE_TAG("JSONUtils");
#define LX(logCommand, message) \
    SAMPLE_APP_LOG_##logCommand(utils::RadiantLogger::MAX_APP_COMPONENT_NAME, __func__, MODULE_TAG, message)

SDSReader::SDSReader(
    const std::string& readerName,
    const multiAgentExperience::audio::AudioFormat& audioFormat,
    std::shared_ptr<alexaClientSDK::avsCommon::avs::AudioInputStream::Reader> reader,
    bool enabled) :
        m_readerName{readerName},
        m_audioFormat{audioFormat},
        m_sdsReader{reader},
        m_wordSize{reader->getWordSize()},
        m_isReaderEnabled{enabled} {
}

SDSReader::~SDSReader() {
    close();
}

multiAgentExperience::audio::AudioFormat SDSReader::getAudioFormat() const {
    return m_audioFormat;
}

ssize_t SDSReader::read(void* buf, size_t nBytes) {
    std::lock_guard<std::mutex> guard(m_mutex);
    if (!m_isReaderEnabled) {
        LX(WARN, "Reader is not enabled, returning.");
        return 0;
    }

    if (!m_sdsReader) {
        LX(ERROR, "SDS Reader is nullptr, returning.");
        return 0;
    }

    // Convert bytes to words
    size_t nWords = nBytes / m_wordSize;
    ssize_t wordsRead = m_sdsReader->read(buf, nWords);
    if (wordsRead <= 0) {
        return wordsRead;
    }

    // Convert words to bytes
    return wordsRead * m_wordSize;
}

void SDSReader::seekToNow() {
    LX(DEBUG3, "");

    std::lock_guard<std::mutex> guard(m_mutex);

    if (m_sdsReader) {
        LX(DEBUG3, "Seeking.");
        m_sdsReader->seek(0, alexaClientSDK::avsCommon::avs::AudioInputStream::Reader::Reference::BEFORE_WRITER);
    }
}

void SDSReader::close() {
    LX(DEBUG3, "");

    std::lock_guard<std::mutex> guard(m_mutex);

    if (m_sdsReader) {
        LX(DEBUG3, "Closing SDS.");
        m_sdsReader->close();
        m_sdsReader = nullptr;
    }
}

}  // namespace sds
}  // namespace audioManager
}  // namespace sampleApplication
}  // namespace multiAgentExperience


text:
layout: post
date: 2018-03-21
title: "Sarah Houston Scarlet 2012"
category: Sarah Houston
tags: [Sarah Houston,2012]
---
### Sarah Houston Scarlet
Just **$469.99**
### 2012

BRANDS	Sarah Houston

Years	2012

Buy it: [https://www.readybrides.com/en/sarah-houston/47344-sarah-houston-scarlet.html](https://www.readybrides.com/en/sarah-houston/47344-sarah-houston-scarlet.html)


text:
package subnet

import (
	"encoding/json"
	"errors"
	"fmt"
	"time"

	"github.com/coreos/flannel/Godeps/_workspace/src/golang.org/x/net/context"
	"github.com/coreos/flannel/pkg/ip"
)

type LeaseAttrs struct {
	PublicIP    ip.IP4
	BackendType string          `json:",omitempty"`
	BackendData json.RawMessage `json:",omitempty"`
}

type Lease struct {
	Subnet     ip.IP4Net
	Attrs      *LeaseAttrs
	Expiration time.Time
}

func (l *Lease) Key() string {
	return l.Subnet.StringSep(".", "-")
}

type (
	EventType int

	Event struct {
		Type    EventType `json:"type"`
		Lease   Lease     `json:"lease,omitempty"`
		Network string    `json:"network,omitempty"`
	}
)

const (
	EventAdded EventType = iota
	EventRemoved
)

type LeaseWatchResult struct {
	// Either Events or Snapshot will be set.  If Events is empty, it means
	// the cursor was out of range and Snapshot contains the current list
	// of items, even if empty.
	Events   []Event     `json:"events"`
	Snapshot []Lease     `json:"snapshot"`
	Cursor   interface{} `json:"cursor"`
}

type NetworkWatchResult struct {
	// Either Events or Snapshot will be set.  If Events is empty, it means
	// the cursor was out of range and Snapshot contains the current list
	// of items, even if empty.
	Events   []Event     `json:"events"`
	Snapshot []string    `json:"snapshot"`
	Cursor   interface{} `json:"cursor,omitempty"`
}

func (et EventType) MarshalJSON() ([]byte, error) {
	s := ""

	switch et {
	case EventAdded:
		s = "added"
	case EventRemoved:
		s = "removed"
	default:
		return nil, errors.New("bad event type")
	}
	return json.Marshal(s)
}

func (et *EventType) UnmarshalJSON(data []byte) error {
	switch string(data) {
	case "\"added\"":
		*et = EventAdded
	case "\"removed\"":
		*et = EventRemoved
	default:
		fmt.Println(string(data))
		return errors.New("bad event type")
	}

	return nil
}

type Manager interface {
	GetNetworkConfig(ctx context.Context, network string) (*Config, error)
	AcquireLease(ctx context.Context, network string, attrs *LeaseAttrs) (*Lease, error)
	RenewLease(ctx context.Context, network string, lease *Lease) error
	WatchLeases(ctx context.Context, network string, cursor interface{}) (LeaseWatchResult, error)
	WatchNetworks(ctx context.Context, cursor interface{}) (NetworkWatchResult, error)
}


text:
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
es6id: 23.3.2
description: >
  The value of the [[Prototype]] internal slot of the WeakMap constructor is the
  intrinsic object %FunctionPrototype% (19.2.3).
---*/

assert.sameValue(
  Object.getPrototypeOf(WeakMap),
  Function.prototype,
  '`Object.getPrototypeOf(WeakMap)` returns `Function.prototype`'
);


text:
Android Developers Days 2015 site.
=============

### Live demo www.androiddeveloperdays.com

Original project you can find [here](https://github.com/gdg-x/zeppelin).

1.  Install [Node.js](www.nodejs.org) and [Ruby](https://www.ruby-lang.org/)
2.  Run `gem install bundler`
3.  Install 'grunt-cli' and 'bower' globally with `npm install -g grunt-cli bower`
4.  `$cd` to the directory and run `bundle install`
5.  Run `npm install` to install the necessary "npm" dependencies
6.  Then run `bower install` to install the front-end dependencies
7.  Install [ImageMagick](http://www.imagemagick.org/script/binary-releases.php) to resize images during building
8.  **That's all. Your template is ready**

Following commands are available:

1.  `grunt` (by default it runs `grunt serve`) - build and start your site for **development** (with livereload, js uglifing and sass compilation)
2.  `grunt serve:dist` - build and start your site with **production** configs (this is how it will look online)
3.  `grunt deploy` - build and deploy your site into a repository you defined in previous steps

### Contributors
Created by [Oleh Zasadnyy](https://github.com/ozasadnyy), [GDG Lviv](https://plus.google.com/102444623953913144164).

### License

Project is published under the [MIT license](https://github.com/ozasadnyy/zeppelin-grunt/blob/master/LICENSE). Feel free to clone and modify repo as you want, but don't forget to add reference to authors :)


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.14"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Vigilante Game Framework: Class Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

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

Vigilante Game Framework
    1.0.0.8

A 2D/3D C++ Game Framework using SFML.

Here is a list of all documented class members with links to the class documentation for each member:

- n -

normal
: V3DVertex

normalizeAngles()
: V3DCamera

NUM_PATH_CURVES
: VTextPath

<address class="footer">
Generated by

 1.8.14
</address>


text:
define([
	'math/Vector'
], function(
	Vector
) {
	var nextPlatformGeometryId = 0;
	function PlatformGeometry(params) {
		params = params || {};
		this._platformGeometryId = nextPlatformGeometryId++;
		this.platformGeometryType = params.geometryType;
		this._vel = new Vector(0, 0);
		this._movement = new Vector(0, 0);
	}
	PlatformGeometry.prototype.sameAs = function(other) {
		return other && this._platformGeometryId === other._platformGeometryId;
	};
	PlatformGeometry.prototype.sameAsAny = function(others) {
		if(others) {
			for(var i = 0; i < others.length; i++) {
				if(this.sameAs(others[i])) {
					return true;
				}
			}
		}
		return false;
	};
	PlatformGeometry.prototype.move = function(movement, vel) {
		this._movement.copy(movement);
		this._vel.copy(vel);
	};
	PlatformGeometry.prototype.checkForCollisionWithEntity = function(enttiy) {
		throw new Error("Need to implement in subclasses");
	};
	PlatformGeometry.prototype.render = function() {};
	return PlatformGeometry;
});


text:
package me.devsaki.hentoid.util.download;

import android.util.Pair;

import androidx.annotation.NonNull;

import com.annimon.stream.function.Consumer;

import org.apache.commons.lang3.tuple.ImmutablePair;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;

import me.devsaki.hentoid.enums.Site;
import me.devsaki.hentoid.util.FileHelper;
import me.devsaki.hentoid.util.ImageHelper;
import me.devsaki.hentoid.util.StringHelper;
import me.devsaki.hentoid.util.exception.DownloadInterruptedException;
import me.devsaki.hentoid.util.exception.UnsupportedContentException;
import me.devsaki.hentoid.util.network.HttpHelper;
import okhttp3.Response;
import okhttp3.ResponseBody;
import timber.log.Timber;

/**
 * Helper for general newtworking
 */
public class DownloadHelper {

    private DownloadHelper() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * Download the given resource to the given disk location
     *
     * @param site              Site to use params for
     * @param url               URL to download from
     * @param resourceId        ID of the corresponding resource (for logging purposes only)
     * @param requestHeaders    HTTP request headers to use
     * @param targetFolder      Folder where to save the downloaded resource
     * @param targetFileName    Name of the file to save the downloaded resource
     * @param forceMimeType     Forced mime-type of the downloaded resource (null for auto-set)
     * @param interruptDownload Used to interrupt the download whenever the value switches to true. If that happens, the file will be deleted.
     * @param notifyProgress    Consumer called with the download progress %
     * @return Pair containing
     * - Left : Downloaded file
     * - Right : Detected mime-type of the downloades resource
     * @throws IOException,UnsupportedContentException,DownloadInterruptedException if anything goes wrong
     */
    public static ImmutablePair<File, String> downloadToFile(
            @NonNull Site site,
            @NonNull String url,
            int resourceId,
            List<Pair<String, String>> requestHeaders,
            @NonNull File targetFolder,
            @NonNull String targetFileName,
            String forceMimeType,
            @NonNull final AtomicBoolean interruptDownload,
            Consumer<Float> notifyProgress) throws
            IOException, UnsupportedContentException, DownloadInterruptedException {

        if (interruptDownload.get())
            throw new DownloadInterruptedException("Download interrupted");

        Timber.d("CACHE DOWNLOADING %d %s", resourceId, url);
        Response response = HttpHelper.getOnlineResourceFast(url, requestHeaders, site.useMobileAgent(), site.useHentoidAgent(), site.useWebviewAgent());
        Timber.d("CACHE DOWNLOADING %d - RESPONSE %s", resourceId, response.code());
        if (response.code() >= 300) throw new IOException("Network error " + response.code());

        ResponseBody body = response.body();
        if (null == body)
            throw new IOException("Could not read response : empty body for " + url);

        long size = body.contentLength();
        if (size < 1) size = 1;

        String mimeType = StringHelper.protect(forceMimeType);

        File targetFile = new File(targetFolder, targetFileName);
        if (!targetFile.exists() && !targetFile.createNewFile())
            throw new IOException("Could not create file " + targetFile.getPath());

        Timber.d("WRITING CACHED DOWNLOAD %d TO %s (size %.2f KB)", resourceId, targetFile.getAbsolutePath(), size / 1024.0);
        byte[] buffer = new byte[FileHelper.FILE_IO_BUFFER_SIZE];
        int len;
        long processed = 0;
        int iteration = 0;
        try (InputStream in = body.byteStream(); OutputStream out = FileHelper.getOutputStream(targetFile)) {
            while ((len = in.read(buffer)) > -1) {
                if (interruptDownload.get()) break;
                processed += len;
                // Read mime-type on the fly if not forced
                if (0 == iteration && mimeType.isEmpty()) {
                    mimeType = ImageHelper.getMimeTypeFromPictureBinary(buffer);
                    if (mimeType.isEmpty() || mimeType.equals(ImageHelper.MIME_IMAGE_GENERIC)) {
                        String message = String.format(Locale.ENGLISH, "Invalid mime-type received from %s (size=%.2f)", url, size / 1024.0);
                        throw new UnsupportedContentException(message);
                    }
                }
                if (notifyProgress != null && 0 == ++iteration % 50) // Notify every 200KB
                    notifyProgress.accept((processed * 100f) / size);
                out.write(buffer, 0, len);
            }
            if (!interruptDownload.get()) {
                if (notifyProgress != null) notifyProgress.accept(100f);
                out.flush();
                Timber.d("CACHED DOWNLOAD %d [%s] WRITTEN TO %s (%.2f KB)", resourceId, mimeType, targetFile.getAbsolutePath(), targetFile.length() / 1024.0);
                return new ImmutablePair<>(targetFile, mimeType);
            }
        }
        // Remove the remaining file chunk if download has been interrupted
        FileHelper.removeFile(targetFile);
        throw new DownloadInterruptedException("Download interrupted");
    }

    /**
     * Extract the given HTML document's canonical URL using link and OpenGraph metadata when available
     * NB : Uses the URL with the highest number when both exist and are not the same
     *
     * @param doc HTML document to parse
     * @return Canonical URL of the given document; empty string if nothing found
     */
    public static String getCanonicalUrl(@NonNull final Document doc) {
        // Get the canonical URL
        String canonicalUrl = "";
        Element canonicalElt = doc.select("head link[rel=canonical]").first();
        if (canonicalElt != null) canonicalUrl = canonicalElt.attr("href").trim();

        // Get the OpenGraph URL
        String ogUrl = "";
        Element ogUrlElt = doc.select("head meta[property=og:url]").first();
        if (ogUrlElt != null) ogUrl = ogUrlElt.attr("content").trim();

        final String finalUrl;
        if (!canonicalUrl.isEmpty() && !ogUrl.isEmpty() && !ogUrl.equals(canonicalUrl)) {
            int canonicalDigits = Integer.parseInt(StringHelper.keepDigits(canonicalUrl));
            int ogDigits = Integer.parseInt(StringHelper.keepDigits(ogUrl));
            finalUrl = (canonicalDigits > ogDigits) ? canonicalUrl : ogUrl;
        } else {
            if (!canonicalUrl.isEmpty()) finalUrl = canonicalUrl;
            else finalUrl = ogUrl;
        }
        return finalUrl;
    }
}


text:
from flexbe_core import Behavior, Autonomy, OperatableStateMachine, ConcurrencyContainer, PriorityContainer, Logger
from flexbe_states.calculation_state import CalculationState
from sara_flexbe_behaviors.action_move_sm import Action_MoveSM
from sara_flexbe_states.SetRosParam import SetRosParam
# Additional imports can be added inside the following tags
# [MANUAL_IMPORT]

# [/MANUAL_IMPORT]

'''
Created on 22/05/2018
@author: Lucas Maurice
'''
class ActionWrapper_MoveSM(Behavior):
	'''
	action wrapper pour move
	'''

	def __init__(self):
		super(ActionWrapper_MoveSM, self).__init__()
		self.name = 'ActionWrapper_Move'

		# parameters of this behavior

		# references to used behaviors
		self.add_behavior(Action_MoveSM, 'Try to reach/Action_Move')

		# Additional initialization code can be added inside the following tags
		# [MANUAL_INIT]

		# [/MANUAL_INIT]

		# Behavior comments:

		# O 290 19
		# Move|n1- Location|n2- Location Container|n3- Location Container

	def create(self):
		# x:267 y:194, x:706 y:131, x:92 y:292
		_state_machine = OperatableStateMachine(outcomes=['finished', 'failed', 'critical_fail'], input_keys=['Action'])
		_state_machine.userdata.Action = ["Move","zone"]
		_state_machine.userdata.relative = False

		# Additional creation code can be added inside the following tags
		# [MANUAL_CREATE]

		# [/MANUAL_CREATE]

		# x:131 y:459, x:447 y:470
		_sm_try_to_reach_0 = OperatableStateMachine(outcomes=['finished', 'failed'], input_keys=['Action'])

		with _sm_try_to_reach_0:
			# x:84 y:67
			OperatableStateMachine.add('get destination',
										CalculationState(calculation=lambda x: x[1:]),
										transitions={'done': 'Action_Move'},
										autonomy={'done': Autonomy.Off},
										remapping={'input_value': 'Action', 'output_value': 'destination'})

			# x:258 y:149
			OperatableStateMachine.add('Action_Move',
										self.use_behavior(Action_MoveSM, 'Try to reach/Action_Move'),
										transitions={'finished': 'finished', 'failed': 'failed'},
										autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit},
										remapping={'pose': 'destination'})

		with _state_machine:
			# x:65 y:108
			OperatableStateMachine.add('Try to reach',
										_sm_try_to_reach_0,
										transitions={'finished': 'finished', 'failed': 'gen fail cause'},
										autonomy={'finished': Autonomy.Inherit, 'failed': Autonomy.Inherit},
										remapping={'Action': 'Action'})

			# x:532 y:113
			OperatableStateMachine.add('paramoffailure',
										SetRosParam(ParamName="behavior/GPSR/CauseOfFailure"),
										transitions={'done': 'failed'},
										autonomy={'done': Autonomy.Off},
										remapping={'Value': 'FailureCause'})

			# x:290 y:110
			OperatableStateMachine.add('gen fail cause',
										CalculationState(calculation=lambda x: "I couldn't reach the "+x[1]+"."),
										transitions={'done': 'paramoffailure'},
										autonomy={'done': Autonomy.Off},
										remapping={'input_value': 'Action', 'output_value': 'FailureCause'})

		return _state_machine

	# Private functions can be added inside the following tags
	# [MANUAL_FUNC]

	# [/MANUAL_FUNC]


text:
layout: post
title: High-Quality JavaScript Code ツールまとめ
date: '2013-07-27T01:34:32+09:00'
tags:
- JavaScript
- "スライド"
- "まとめ"
permalink: /post/56525802407/high-quality-javascript-code
---

 High-Quality JavaScript Code  from Den Odell

というスライドの流れが結構良かったので紹介。

AKQA Anoraks というイベントで発表されたもので、 タイトル通りコードのクオリティがテーマの内容です。

内容的には、モジュールパターン、JSDoc、コードレビュー、Lint、テスト、自動化、コードカバレッジ、ステータスの可視化 のツール、サービスなどを それぞれ軽く触れられていて、最近見る感じのツールが良い感じの流れでまとまってる気がします。

ただ、スライドにURLやツール名が載ってなかったので、自分で書きだしたものをまとめておきます。

Module/JSDoc

YUIDoc - Javascript Documentation Tool

Peer Code Review

ピアコードレビューツール | Atlassian

Static Code Analysis

JSHint, a JavaScript Code Quality Tool

Lintツール

Jasmine

テスティングフレームワーク

Automated & Manual Testing

Grunt: The JavaScript Task Runner

ビルド、タスク自動化CLI

Cross Browser Testing Tool. 200+ Browsers, Mobile, Real IE.

仮想環境のブラウザを利用できるサービス(表示確認やAPIを使ってテストするのに使うとかで見かける)

Selenium - Web Browser Automation

Seleniumについてわかりやすいまとめ => Selenium何とかっていうツールがやたら色々あるのはどういうわけなのか

Code Measured For Quality

istanbul-js: A Javascript code coverage tool written in JS

esprimaを使ったコードカバレッジツール

karma-coverageもこれ使用

Visibility & Accountability

名前がわからなかった…

名前がわからなかった…

名前がわからなかった…

可視化するツール周りの名前がよくわかりませんでした。(分かる人教えて欲しいです)

その他

このスライドに類似するようなツールのまとめだと以下も似た感じの内容だと思います。

最近のJavaScript開発まとめ : アシアルブログ


text:
<?php
	session_start();
	include("connection.php");
	include("function.php");
	if($_SESSION['login'] != 'admingroup'){
		header("location:index.php");
	}
	$id = $_SESSION['member_id'];
	$grouppost_id = $_GET['id'];
		if(isset($_POST['status'])){
			$status = $_POST['accept'];
			$postid = $_POST['cantseeme'];
			mysqli_query($con,"UPDATE groupposts SET status='$status' WHERE grouppost_id='$postid'")or die(mysqli_error());
		}
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>BPS Social Media</title>

    <link href="../vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

    <link href="../vendor/metisMenu/metisMenu.min.css" rel="stylesheet">

    <link href="../dist/css/sb-admin-2.css" rel="stylesheet">

    <link href="../vendor/morrisjs/morris.css" rel="stylesheet">

    <link href="../vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

	<link href="../facebox1.2/src/facebox.css" media="screen" rel="stylesheet" type="text/css" />

            <?php
			include "groupbar.php";
			?>

                            Home

                             Members

                                <?php
								$group_id=$_SESSION['member_id'];
								$group = mysqli_query($con,"SELECT * FROM groupmembers WHERE group_id = '$group_id' AND status='1' ")or die(mysqli_error());
								while ($row = mysqli_fetch_array($group)){
									$member_id = $row['member_id'];
									$sql = mysqli_query($con,"SELECT * FROM members WHERE member_id = '$member_id' ")or die(mysqli_error());
									$rows = mysqli_fetch_array($sql);
									echo '
 '.$rows['firstname'].' '.$rows['lastname'].'
';
								}
							?>

                             Recent Active Members

                                <?php
								$post_a = mysqli_query($con,"SELECT DISTINCT member_id FROM groupposts WHERE group_id = '$id' ORDER by date DESC LIMIT 0,5")or die(mysqli_error());
								$num_rows  =mysqli_num_rows($post_a);

								if ($num_rows != 0 ){
									while($row = mysqli_fetch_array($post_a)){
									$member = $row['member_id'];
									$member_id=$_SESSION['member_id'];
									if ($member!=$member_id){
										$friends = mysqli_query($con,"SELECT * FROM members WHERE member_id = '$member'")or die(mysqli_error());
										$friendsa = mysqli_fetch_array($friends);

										echo '
 '.$friendsa['firstname'].' '.$friendsa['lastname'].'
';
										$cekid2 = $member;
									}else {}
									}
								}
							?>

                             Check Post Status

							<?php
								$admingroup_id = $_SESSION['member_id'];
								$post = mysqli_query($con,"SELECT * FROM groupposts WHERE group_id = '$admingroup_id' AND grouppost_id='$grouppost_id'")or die(mysqli_error());
								$row = mysqli_fetch_array($post);
								$id = $row['member_id'];
								if ($id==$admingroup_id){
									$hu_u = mysqli_query($con,"SELECT * FROM groups WHERE group_id = '$admingroup_id'")or die(mysqli_error());
									$rows = mysqli_fetch_array($hu_u);
									$name = $rows['group_name'];
									$photo = "../image/groups/".$rows['photo'];
								}else{
									$hu_u = mysqli_query($con,"SELECT * FROM members WHERE member_id = '$id'")or die(mysqli_error());
									$rows = mysqli_fetch_array($hu_u);
									$name = $rows['firstname']." ".$rows['lastname'];
									$photo = "../image/members/".$rows['photo'];
								}
								$cekfile = $row['file'];
								if ($cekfile!=""){
									$msg = '
';
								}
								else{
									$msg = "";
								}
								$iyaid = $row['grouppost_id'];
								$allcomm = mysqli_query($con,"SELECT * FROM grouppostcomments WHERE grouppost_id = '$iyaid'")or die(mysqli_error());
									$counters = 0;
									WHILE($stat = mysqli_fetch_array($allcomm)){
									$counters++;
								}
								$allcount = $counters;

								$all_like = mysqli_query($con,"SELECT * FROM grouppostlike WHERE grouppost_id = '$iyaid'")or die(mysqli_error());
									$counterss = 0;
									WHILE($stat = mysqli_fetch_array($all_like)){
									$counterss++;
								}
								$allcounts = $counterss;
							?>

									<input type='hidden' value='<?php echo $row['grouppost_id'];?>' name='cantseeme'/>

                                        <img src="<?php echo $photo;?>" alt="User Avatar" class="img-circle" width="40" height="40"/>

                                            <?php echo $name;?>

                                                 <?php echo $row['date'];?>

											<?php echo $row['posts'];?>

											<?php echo $msg;?>

										<form method="post" action="">
											<input type='hidden' value='<?php echo $row['grouppost_id'];?>' name='cantseeme'/>
											<select name='accept'>
												<option selected value=''>----Status----</option>
												<option value='0'>Not Accepted</option>
												<option value='1'>Still Considered</option>
												<option value='2'>Accepted</option>
											</select>
											<input type="submit" id="searchbutton2" value="Change" name="status"/>
										<?php
										if ($row['status']==2){
											echo"

";}
										elseif ($row['status']==1){
											echo"

";}
										else{
											echo"

";}
											echo"</form>
";
											echo"

  (".$allcounts.")
";
											echo"
Comments(".$allcount.")
";
											echo "
Delete
";
										?>

                             Similar Posts

						<?php
							$data = $grouppost_id;
							$data2 = '11';

							// Execute the python script with the JSON data
							$command = print_r(shell_exec("C:\Python27\word2vec\maclearn.py $data"),true);
							$rows = json_decode($command,true);

							$data = $rows['row'];
							if ($data !=NULL){
								foreach ($data as $key => $row){
									$similarity[$key]=$row['similarity'];
								}
								array_multisort($similarity,SORT_DESC,$data);
							}
							for($i=0;$i<count($data);$i++){
						?>

										<?php echo $data[$i]['data'];?>

										<?php echo "Similarity: ".$data[$i]['similarity']." %  "."<progress value=".$data[$i]['similarity']." max='100'></progress>";?>

						<?php
							}
						?>

                             Search Groups or Friends

                            <form name="search" method="post" action="search.php">

                                <input type="text" class="form-control" placeholder="Search...">

                                <button name="search" class="btn btn-default">

                                </button>

							</form>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;

namespace BenzGorokuSearch
{
	enum ExpressionType
	{
		Literal,And,Or,Not,Dummy
	}

	interface ConditionExpression
	{
		ExpressionType Type{get;}
		bool IsMatch(string text);
	}

	class LiteralExpression:ConditionExpression
	{

		public ExpressionType Type
		{
			get
			{
				return ExpressionType.Literal;
			}
		}

		public string Keyword{get;set;}

		public int IndexOf(string text,string searchText)
		{
			int findIndex=-1,searchTextIndex=0;
			for(int i=0;i<text.Length&&searchTextIndex<searchText.Length;++i){
				char currentChar=text[i],searchChar=searchText[searchTextIndex];
				if(((searchChar=='\u25CB'||searchChar=='\u25EF'||searchChar=='*')&&
					!char.IsWhiteSpace(currentChar)&&
					!char.IsControl(currentChar)&&
					!char.IsSeparator(currentChar))||
					char.ToUpper(searchChar)==char.ToUpper(currentChar)){
					if(findIndex==-1) findIndex=i;
					++searchTextIndex;
				}else{
					findIndex=-1;
					searchTextIndex=0;
				}
			}
			if(searchTextIndex<searchText.Length) findIndex=-1;
			return findIndex;
		}

		public bool IsMatch(string text)
		{
			return IndexOf(text,Keyword)!=-1;
		}

		public LiteralExpression(string keyword)
		{
			Keyword=keyword;
		}
	}

	class AndOperatorExpression:ConditionExpression
	{
		public ExpressionType Type
		{
			get
			{
				return ExpressionType.And;
			}
		}

		public ConditionExpression Operand1{get;set;}
		public ConditionExpression Operand2{get;set;}

		public bool IsMatch(string text)
		{
			return Operand1.IsMatch(text)&&Operand2.IsMatch(text);
		}

		public AndOperatorExpression(ConditionExpression op1,ConditionExpression op2)
		{
			Operand1=op1;
			Operand2=op2;
		}
	}

	class OrOperatorExpression:ConditionExpression
	{
		public ExpressionType Type
		{
			get
			{
				return ExpressionType.Or;
			}
		}

		public ConditionExpression Operand1{get;set;}
		public ConditionExpression Operand2{get;set;}

		public bool IsMatch(string text)
		{
			return Operand1.IsMatch(text)||Operand2.IsMatch(text);
		}

		public OrOperatorExpression(ConditionExpression op1,ConditionExpression op2)
		{
			Operand1=op1;
			Operand2=op2;
		}
	}

	class NotOperatorExpression:ConditionExpression
	{
		public ExpressionType Type
		{
			get
			{
				return ExpressionType.Not;
			}
		}

		public ConditionExpression Operand{get;set;}

		public bool IsMatch(string text)
		{
			return !Operand.IsMatch(text);
		}

		public NotOperatorExpression(ConditionExpression op)
		{
			Operand=op;
		}
	}

	class DummyExpression:ConditionExpression
	{
		public ExpressionType Type
		{
			get
			{
				return ExpressionType.Dummy;
			}
		}

		public bool Result{get;set;}

		public bool IsMatch(string text)
		{
			return Result;
		}

		public DummyExpression(bool result)
		{
			Result=result;
		}
	}

	static class ExpressionBuilder
	{

		//public static ConditionExpression Parse(string str)
		//{
		//	var quoting=0;
		//	var literal=false;
		//	var words=new List<string>();
		//	str=str.Trim();
		//	var startIndex=0;
		//	for(int i=0;i<str.Length;++i){
		//		if(quoting==0&&!literal){
		//			if(!char.IsWhiteSpace(str[i])){
		//				startIndex=i;
		//				literal=true;
		//				if(str[i]=='"'){
		//					++quoting;
		//					++startIndex;
		//				}
		//			}
		//		}else if(literal){
		//			if(quoting>0&&str[i]=='"'&&char.IsWhiteSpace(str[i+1])){

		//				quoting=false;
		//				literal=false;
		//				words.Add(str.Substring(startIndex,i-startIndex-1);
		//			}else if(char.IsWhiteSpace(str[i])){
		//				literal=false;
		//			}
		//		}

		//		if(str[i]=='"'&&((quoting&&char.IsWhiteSpace(str[i+1]))||!quoting)){
		//			quoting=!quoting;
		//		}
		//	}
		//}

		public static ConditionExpression Create(string str)
		{
			var literal=false;
			var words=new List<string>();
			str=str.Trim();
			if(str=="") return new DummyExpression(true);
			var startIndex=0;
			for(int i=0;i<str.Length;++i){
				if(!literal&&!char.IsWhiteSpace(str[i])){
					literal=true;
					startIndex=i;
				}else if(literal&&char.IsWhiteSpace(str[i])){
					words.Add(str.Substring(startIndex,i-startIndex));
					literal=false;
				}
			}
			if(literal) words.Add(str.Substring(startIndex,str.Length-startIndex));
			words=words.Select(w=>CharWidthNormalizer.Normalize(w)).ToList();
			ConditionExpression root=null;
			if(words.Count==1) root=new LiteralExpression(words.First());
			else{
				var last=new AndOperatorExpression(null,null);
				root=last;
				for(int i=0;i<words.Count;++i){
					last.Operand1=new LiteralExpression(words[i]);
					if(words.Count==i+2){
						last.Operand2=new LiteralExpression(words[i+1]);
						++i;
					}else{
						var newExpr=new AndOperatorExpression(null,null);
						last.Operand2=newExpr;
						last=newExpr;
					}
				}
			}
			return root;
		}

	}

	class SearchQuery
	{
		public ConditionExpression Condition{get;set;}
		public bool SearchFromSelectedDate{get;set;}
		public DateTime? StartDate{get;set;}
		public DateTime? EndDate{get;set;}
		public bool SearchFromSelectedParts{get;set;}
		public int[] Parts{get;set;}
		public bool SearchFromSelectedPeople{get;set;}
		public string[] People{get;set;}

		public event Action<ResponseViewModel[]> SearchCompleted;

		public SearchQuery()
		{
			Condition=new DummyExpression(true);
			SearchFromSelectedParts=false;
			Parts=new int[0];
			SearchFromSelectedPeople=false;
			People=new string[0];
			SearchFromSelectedDate=false;
			StartDate=null;
			EndDate=null;
		}

		public ResponseViewModel[] Search(ResponseViewModel[] source)
		{
			var searchTask1=new Task<ResponseViewModel[]>(SearchInternal,source.Take(source.Length/2).ToArray());
			var searchTask2=new Task<ResponseViewModel[]>(SearchInternal,source.Skip(source.Length/2).ToArray());
			searchTask1.Start();
			searchTask2.Start();
			Task.WaitAll(searchTask1,searchTask2);
			return searchTask1.Result.Concat(searchTask2.Result).ToArray();
		}

		public void SearchAsync(ResponseViewModel[] source)
		{
			if(SearchCompleted!=null) ThreadPool.QueueUserWorkItem(_=>SearchCompleted(Search(source)));
		}

		private ResponseViewModel[] SearchInternal(object source)
		{
			var result=(IEnumerable<ResponseViewModel>)source;
			if(SearchFromSelectedParts) result=result.Where(r=>Parts.Any(p=>p==r.PartNumber));
			if(SearchFromSelectedPeople) result=result.Where(r=>People.Any(p=>p==r.Tag));
			if(SearchFromSelectedDate&&(StartDate!=null||EndDate!=null)){
				var start=StartDate??DateTime.MinValue;
				var end=EndDate==null?DateTime.MaxValue:EndDate.Value.Date.Add(new TimeSpan(23,59,59));
				result=result.Where(r=>r.Date>=start&&r.Date<=end);
			}
			var buffer=new StringBuilder(1000);
			return result.Where(r=>
			{
				CharWidthNormalizer.NormalizeFast(r.Text,buffer);
				return Condition.IsMatch(CharWidthNormalizer.Normalize(buffer.ToString()));
			}).ToArray();
		}
	}
}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

Búsqueda

      <?php echo form_open() ?>

          <select class="form-control wz-multiple" name="ingredients[]" multiple="multiple" placeholder="Ingredientes...">
            <?php foreach($all_ingredients as $ingredient): ?>
              <option value="<?php echo $ingredient->id ?>"
              <?php echo
                is_array(set_value("ingredients")) && array_search($ingredient->id, set_value("ingredients")) !== FALSE
                ? "selected": ""?>>
                <?php echo $ingredient->name?>
              </option>
            <?php endforeach; ?>
          </select>

          <button type="submit" class="btn btn-success"> Buscar</button>

      <?php echo form_close() ?>

    <?php if(!$has_search): ?>

¿Qué necesitas?

    <?php else: ?>

      <?php if(count($recipes)): ?>

                <?php for($i = 0; $i < sizeof($recipes); $i++): ?>

<a href="/recipes/show/<?php echo $recipes[$i] ?>"><?php echo $recipes[$i] ?>

                <?php endfor; ?>

      <?php else: ?>

No hay coincidencias

      <?php endif; ?>

    <?php endif; ?>