text:
<?php

namespace Contentacle\Services;

class UserRepository
{
    private $repoDir, $userProvider;

    private $users = array();

    function __construct($repoDir, $userProvider)
    {
        $this->repoDir = $repoDir;
        $this->userProvider = $userProvider;
    }

    function getUsers($search = null, $from = 0, $to = 19)
    {
        $users = array();
        $count = 0;

        foreach (glob($this->repoDir.'/'.$search.'*', GLOB_ONLYDIR) as $userDir) {
            if ($count >= $from && $count <= $to) {
                try {
                    $user = $this->getUser(basename($userDir));
                    $users[$user->username] = $user;
                } catch (\Contentacle\Exceptions\ValidationException $e) {}
            }
            $count++;
        }
        return $users;
    }

    function getUser($username)
    {
        if (!isset($this->users[$username])) {
            $data = $this->readProfile($username);
            $this->users[$username] = $this->userProvider->__invoke($data);
        }

        return $this->users[$username];
    }

    /**
     * Given an email address, return the username of the Contentacle user who has that email address.
     * Used for tieing Git users to Contentacle users.
     *
     * Totally in-efficient way of doing this, needs a better solution.
     */
    function getUsernameFromEmail($emailAddress)
    {
        foreach ($this->getUsers() as $user) {
            if ($user->email == $emailAddress) {
                return $user->username;
            }
        }
        return null;
    }

    /**
     * Get the user that is currently signed into the site
     *
     * @param Contentacle\Services\OAuthServer oauth
     * @return Contentacle\Models\User
     */
    function getSignedInUser($oauth)
    {
        if ($oauth->verifyToken()) {
            $username = $oauth->getUsername();
            return $this->getUser($username);
        } elseif (
            isset($_SERVER['PHP_AUTH_USER']) && $_SERVER['PHP_AUTH_USER'] != '' &&
            isset($_SERVER['PHP_AUTH_PW']) && $_SERVER['PHP_AUTH_PW'] != ''
        ) {
            $user = $this->getUser($_SERVER['PHP_AUTH_USER']);
            if ($user->verifyPassword($_SERVER['PHP_AUTH_PW'])) {
                return $user;
            }
        }
        return null;
    }

    private function readProfile($username)
    {
        $profilePath = $this->repoDir.'/'.$username.'/profile.json';
        if (!file_exists($profilePath)) {
            throw new \Contentacle\Exceptions\UserException('User profile "'.$username.'" not found.');
        }
        return json_decode(file_get_contents($profilePath), true);
    }

    private function writeProfile($data)
    {
        if (!isset($data['username'])) {
            throw new \Contentacle\Exceptions\UserException('Username not provided in profile data');
        }
        if (!isset($data['password'])) {
            throw new \Contentacle\Exceptions\UserException('Password not provided in profile data');
        }

        $userPath = $this->repoDir.'/'.$data['username'];
        $profilePath = $userPath.'/profile.json';

        if (!file_exists($userPath)) {
            mkdir($userPath);
        }
        file_put_contents($profilePath, json_encode($data));
    }

    public function createUser($data)
    {
        $user = $this->userProvider->__invoke($data);
        $user->setPassword($data['password']);
        $this->writeProfile($user->props());
        return $user;
    }

    public function updateUser($user, $data, $patch = false)
    {
        if ($patch) {
            $user->patch($data);
        } else {
            $user->setProps($data);
        }
        $this->writeProfile($user->props());
        return $user;
    }

    private function removeDir($path)
    {
        foreach (scandir($path) as $item) {
            if ($item == '.' || $item == '..') continue;
            if (is_dir($path.DIRECTORY_SEPARATOR.$item)) {
                $this->removeDir($path.DIRECTORY_SEPARATOR.$item);
            } else {
                unlink($path.DIRECTORY_SEPARATOR.$item);
            }
        }
        rmdir($path);
    }

    public function deleteUser($user)
    {
        $this->removeDir($this->repoDir.'/'.$user->username);
    }
}


text:
/****************************************************************************
 *   Author: Juergen Pfeifer <juergen.pfeifer@gmx.net> 1995,1997            *
 ****************************************************************************/

#include "form.priv.h"

MODULE_ID("$Id: frm_opts.c,v 1.1.1.1 2012/03/29 17:21:09 uid42307 Exp $")

/*---------------------------------------------------------------------------
|   Facility      :  libnform
|   Function      :  int set_form_opts(FORM *form, Form_Options opts)
|
|   Description   :  Turns on the named options and turns off all the
|                    remaining options for that form.
|
|   Return Values :  E_OK              - success
|                    E_BAD_ARGUMENT    - invalid options
+--------------------------------------------------------------------------*/
int set_form_opts(FORM * form, Form_Options  opts)
{
  opts &= ALL_FORM_OPTS;
  if (opts & ~ALL_FORM_OPTS)
    RETURN(E_BAD_ARGUMENT);
  else
    {
      Normalize_Form( form )->opts = opts;
      RETURN(E_OK);
    }
}

/*---------------------------------------------------------------------------
|   Facility      :  libnform
|   Function      :  Form_Options form_opts(const FORM *)
|
|   Description   :  Retrieves the current form options.
|
|   Return Values :  The option flags.
+--------------------------------------------------------------------------*/
Form_Options form_opts(const FORM * form)
{
  return (Normalize_Form(form)->opts & ALL_FORM_OPTS);
}

/*---------------------------------------------------------------------------
|   Facility      :  libnform
|   Function      :  int form_opts_on(FORM *form, Form_Options opts)
|
|   Description   :  Turns on the named options; no other options are
|                    changed.
|
|   Return Values :  E_OK            - success
|                    E_BAD_ARGUMENT  - invalid options
+--------------------------------------------------------------------------*/
int form_opts_on(FORM * form, Form_Options opts)
{
  opts &= ALL_FORM_OPTS;
  if (opts & ~ALL_FORM_OPTS)
    RETURN(E_BAD_ARGUMENT);
  else
    {
      Normalize_Form( form )->opts |= opts;
      RETURN(E_OK);
    }
}

/*---------------------------------------------------------------------------
|   Facility      :  libnform
|   Function      :  int form_opts_off(FORM *form, Form_Options opts)
|
|   Description   :  Turns off the named options; no other options are
|                    changed.
|
|   Return Values :  E_OK            - success
|                    E_BAD_ARGUMENT  - invalid options
+--------------------------------------------------------------------------*/
int form_opts_off(FORM * form, Form_Options opts)
{
  opts &= ALL_FORM_OPTS;
  if (opts & ~ALL_FORM_OPTS)
    RETURN(E_BAD_ARGUMENT);
  else
    {
      Normalize_Form(form)->opts &= ~opts;
      RETURN(E_OK);
    }
}

/* frm_opts.c ends here */

redpajama_set_name: RedPajamaGithub


text:
{% extends 'SuperPortal/base.html' %}
{% load staticfiles %}
{% load i18n %}

{% block css %}

    {{ block.super }}
    <link rel="stylesheet" href="{% static 'SuperPortal/css/news_feed.css' %}">
    <link rel="stylesheet" href="{% static 'SuperPortal/css/slider.css' %}">
    <link rel="stylesheet" href="{% static 'PortalEnrollment/css/unit-enrollment-setting.css' %}">
    <link rel="stylesheet" href="{% static 'SuperPortal/css/external/owl.carousel.css' %}">
    <link rel="stylesheet" href="{% static 'SuperPortal/css/forum.css' %}">

{% endblock %}

{% block meta_description %}{{ short_description }}{% endblock %}
{% block body %}

{{ forum }}

                <input type="button" value="{% trans 'New thread' %}" />

            {% for thread in forum.threads.all %}

                        {{ thread.title }}

                        {{ thread.num_posts }}

                        {% with thread.last_post as last_post %}
                            {% if last_post %}

                                    {{ last_post.title|truncatechars:20  }}

                                {% trans 'by' %}
                                {{ last_post.creator.userprofile }}

{{ last_post.created|date:'D d N Y H:i' }}

                            {% endif %}
                        {% endwith %}

            {% endfor %}

{% endblock %}


text: This Project Auto Deploys. Be Careful!


text:
from __future__ import unicode_literals

import elasticsearch
import six
from django.db import models
from django.db.models.base import ModelBase
from django.db.models.signals import post_save, pre_delete
from elasticsearch.helpers import bulk

from gum.managers import ElasticsearchManager
from gum.settings import ELASTICSEARCH_INDICES, DEFAULT_ELASTICSEARCH_SETTINGS
from gum.signals import handle_save, handle_delete
from gum.utils import elasticsearch_connection

class AlreadyRegistered(Exception):
    pass

class NotRegistered(Exception):
    pass

class MappingType(object):

    # Custom URLs for connecting to an specific Elasticsearch server
    urls = None
    # Index to apply this mapping type
    index = None
    # Settings used for previous index
    settings = None

    def __init__(self, model):
        """Initialize a MappingType instance for a given
         `model`.

        :param model:
        :return:
        """
        self.model = model
        # If ``index`` is not defined, use settings
        if not self.index:
            self.index = ELASTICSEARCH_INDICES
        super(MappingType, self).__init__()

    def get_id(self, instance):
        """Gets the internal Elasticsearch id for instance.
        :param instance:
        """
        try:
            return instance.pk
        except AttributeError:
            return None

    def get_type(self):
        """Gets a strings that represents the type for the model."""
        return "%s_%s" % (
            self.model._meta.app_label, self.model._meta.model_name
        )

    def get_elasticsearch_connection(self):
        """Gets the Elasticsearch connection with the urls attribute"""
        return elasticsearch_connection(urls=self.urls)

    def get_actions(self, documents):
        """Gets a generator for obtaining the bulk action for each document
        in documents. We assume documents is iterable, and each document is
        a dictionary.
        """
        for document in documents:
            document["_index"] = self.index
            document["_type"] = self.get_type()
            yield document

    def mapping(self):
        """Gets the mapping of a given model. Only uses the model class, not
        the instance.

        TODO: By the moment, it must be implemented by subclasses.
        """
        raise NotImplementedError()

    def document(self, instance):
        """Logic to convert an instance of the model into a document for indexing.

        TODO: By the moment, it must be implemented by subclasses.

        :param instance:
        :return:
        """
        raise NotImplementedError()

    def create_mapping_type(self, update_all_types=False):
        """Creates the Elasticsearch type.

        :param update_all_types:
        """
        es = self.get_elasticsearch_connection()
        es.indices.put_mapping(
            index=self.index,
            doc_type=self.get_type(),
            body=self.mapping(),
            update_all_types=update_all_types,
            ignore=409
        )

    def index_single_document(self, es, document_id, document):
        """Creates a single new document in the index."""
        if not document_id:
            es.index(
                index=self.index,
                doc_type=self.get_type(),
                body=document
            )
        es.index(
            index=self.index,
            doc_type=self.get_type(),
            id=document_id,
            body=document
        )

    def index_bulk_documents(self, es, documents):
        """Creates a bulk of new documents in  the index."""
        actions = self.get_actions(documents)
        bulk(es, actions=actions)

    def index_document(self, instance):
        """Indexes an instance of the model.

        :param instance:
        :return:
        """
        es = self.get_elasticsearch_connection()
        document = self.document(instance)
        document_id = self.get_id(instance)
        if isinstance(document, dict):
            # If is a dict, single create
            self.index_single_document(es, document_id=document_id, document=document)
        else:
            try:
                # If iterable, then bulk create...
                _ = iter(document)
                self.index_bulk_documents(es, documents=document)
            except TypeError:
                # Not iterable, we don't index
                pass

    def delete_document(self, instance):
        """Deletes an instance of the model.

        :param instance:
        :return:
        """
        es = self.get_elasticsearch_connection()
        try:
            es.delete(
                index=self.index,
                doc_type=self.get_type(),
                id=self.get_id(instance),
            )
        except elasticsearch.exceptions.NotFoundError:
            pass

class Indexer(object):
    """Allows to register a model with its mapper class."""

    def __init__(self):
        self._registry = {}

    def register(self, model_or_iterable, mapping_type_class=None):
        """Register a given model(s) with the given mapping type class.

        The model(s) should be Model classes, not instances.

        If a model is already registered, this will raise AlreadyRegistered.
        :param mapping_type_class:
        :param model_or_iterable:
        """
        if not mapping_type_class:
            mapping_type_class = MappingType
        if isinstance(model_or_iterable, ModelBase):
            model_or_iterable = [model_or_iterable]
        for model in model_or_iterable:
            if model in self._registry:
                raise AlreadyRegistered('The model %s is already registered for indexing' % model.__name__)
            mapping_type = mapping_type_class(model)
            if not hasattr(model, "elasticsearch"):
                model.elasticsearch = ElasticsearchManager()
                model.elasticsearch.model = model
                model.elasticsearch.mapping_type = mapping_type
            post_save.connect(handle_save, sender=model)
            pre_delete.connect(handle_delete, sender=model)
            self._registry[model] = mapping_type

    def get_registered_models(self):
        """Returns a list of all registered models, or just concrete
        registered models.
        """
        return [model for (model, mapping_type_class) in self._registry.items()]

    def get_mapping_type(self, model):
        """Gets the mapping type instance for a given `model` class.
        :param model:
        """
        try:
            return self._registry[model]
        except KeyError:
            raise NotRegistered()

    def initialize_index(self):
        """Creates and initialize index.

        TODO: Add settings configuration of the index.
        """
        es = elasticsearch_connection()
        es.indices.create(index=ELASTICSEARCH_INDICES, body=DEFAULT_ELASTICSEARCH_SETTINGS, ignore=400)
        for _, mapping_type in six.iteritems(self._registry):
            mapping_type_es = mapping_type.get_elasticsearch_connection()
            if mapping_type.index != ELASTICSEARCH_INDICES or mapping_type.urls is not None:
                mapping_type_es.indices.create(
                    index=mapping_type.index,
                    body=mapping_type.settings or DEFAULT_ELASTICSEARCH_SETTINGS,
                    ignore=400
                )

    def update_settings(self):
        """Updates the settings of the indexes."""
        es = elasticsearch_connection()
        es.indices.close(index=ELASTICSEARCH_INDICES)
        es.indices.put_settings(index=ELASTICSEARCH_INDICES, body=DEFAULT_ELASTICSEARCH_SETTINGS)
        es.indices.open(index=ELASTICSEARCH_INDICES)
        for _, mapping_type in six.iteritems(self._registry):
            mapping_type_es = mapping_type.get_elasticsearch_connection()
            if mapping_type.index != ELASTICSEARCH_INDICES or mapping_type.urls is not None:
                mapping_type_es.indices.close(index=mapping_type.index)
                mapping_type_es.indices.put_settings(
                    index=mapping_type.index,
                    body=mapping_type.settings or DEFAULT_ELASTICSEARCH_SETTINGS,
                )
                mapping_type_es.indices.open(index=mapping_type.index)

    def remove_index(self):
        """Deletes used indices.

        TODO: Add settings configuration of the index.
        """
        es = elasticsearch_connection()
        es.indices.delete(index=ELASTICSEARCH_INDICES, ignore=400)
        for _, mapping_type in six.iteritems(self._registry):
            mapping_type_es = mapping_type.get_elasticsearch_connection()
            if mapping_type.index != ELASTICSEARCH_INDICES or mapping_type.urls is not None:
                mapping_type_es.indices.delete(index=mapping_type.index, ignore=400)

    def update_index(self, stdout=None, only_mapping=False, restrict_to=None, update_all_types=False):
        """Update index for all registered models.
        :param update_all_types:
        :param restrict_to:
        :param only_mapping:
        :param stdout:
        """
        for model, mapping_type in six.iteritems(self._registry):
            if restrict_to is not None and model not in restrict_to:
                continue
            if issubclass(model, models.Model):
                try:
                    instances = model.objects.all()
                    total_instances = instances.count()
                except AttributeError:
                    # Abstract model
                    instances = []
                    total_instances = 0
            else:
                # Object, not a Django model
                instances = []
                total_instances = 0
            if stdout:
                stdout.write("Indexing %s instances from %s " % (total_instances, str(model)))
            mapping_type.create_mapping_type(update_all_types=update_all_types)
            if not only_mapping:
                for step, instance in enumerate(instances):
                    mapping_type.index_document(instance)
                    if stdout:
                        import os
                        progress = (step + 1) / float(total_instances)
                        _, columns = os.popen('stty size', 'r').read().split()
                        limit = min(int(columns) - 10, 100)
                        graph_progress = int(progress * limit)
                        stdout.write('\r', ending='')
                        progress_format = "[%-{}s] %d%%".format(limit)
                        stdout.write(progress_format % ('='*graph_progress, int(progress*100)), ending='')
                        stdout.flush()
            if stdout:
                stdout.write('')

# This global object represents the singleton indexer object
indexer = Indexer()


text:
<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class users extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('users_model', 'obj_users', TRUE);
        $this->load->model('common_model', 'obj_common', TRUE);
        $this->load->model('usertype_model', 'obj_usertype', TRUE);
        $this->thumb_width = 64;
        $this->thumb_height = 70;
        $this->main_width = 800;
        $this->main_height = 600;
        $this->max_size = 2048; //2MB
        $this->crop_size = $this->thumb_width / $this->thumb_height;

        if ($this->session->userdata('ADMIN_NAME') == FALSE) {
            redirect('admin/login');
        }
    }

    function index($row = 0) {
        if ($this->session->userdata('user_type') == 2) {
            redirect('admin/login');
        }

        //$data['query'] = $this->obj_users->get_all_entries();
        //$this->load->view('academics/index', $entries);
        $limit = '10';
        $this->load->library('pagination');
        $config['base_url'] = base_url() . 'admin/users/index/';
        $config['full_tag_open'] = '
';
        $config['full_tag_close'] = '
';
        $config['uri_segment'] = 4;
        $condition = array();
        $total = $this->obj_users->countrows();
        $config['total_rows'] = $total;
        $data['total_rows'] = $total;
        $config['per_page'] = $limit;
        $this->pagination->initialize($config);
        $data['links'] = $this->pagination->create_links();
        $data['users'] = $this->obj_users->get_all_entries($row, $limit, $condition, 'users_display_order', 'asc');
        $data['row'] = $row;
        $data['page_active'] = 8;
        $this->load->view('admin/users/users_list', $data);
    }

    function search($row = 0) {
        if ($this->session->userdata('user_type') == 2) {
            redirect('admin/login');
        }
        $users_branch = $this->input->post('users_branch');
        $users_usertype = $this->input->post('users_usertype');
        if ($users_branch && $users_usertype) {

            $sess_data = array('users_branch' => $users_branch,
                'users_usertype' => $users_usertype);
            $this->session->set_userdata($sess_data);
        } else {
            $users_branch = $this->session->userdata('users_branch');
            $users_usertype = $this->session->userdata('users_usertype');
        }
        $condition = array('users_branch' => $users_branch,
            'users_usertype' => $users_usertype);

        $limit = 10;
        $config['base_url'] = site_url() . '/admin/users/search/';
        $config['full_tag_open'] = '
';
        $config['full_tag_close'] = '
';
        $config['uri_segment'] = 4;
        $config['total_rows'] = $this->obj_users->countrows($condition);
        $config['per_page'] = $limit;
        $this->pagination->initialize($config);
        $data['links'] = $this->pagination->create_links();
        $data['users'] = $this->obj_users->get_all_entries($row, $limit, $condition, 'users_id', 'desc');
        $data['row'] = $row;
        $data['page_active'] = 3;
        $data['per_page'] = $limit;
        $data['users_branch'] = $users_branch;
        $data['users_usertype'] = $users_usertype;
        $this->load->view('admin/users/users_list', $data);
    }

    function add() {
        if ($this->session->userdata('user_type') == 2) {
            redirect('admin/login');
        }
        $data = array();
        $data['page_active'] = 8;
        $this->load->helper(array('form'));
        $this->load->library(array('form_validation', 'image_lib'));

        $this->form_validation->set_rules('full_name', 'Full Name', 'required');
        $this->form_validation->set_rules('username', 'Username', 'required|min_length[4]|max_length[18]|is_unique[users.users_username]');
        $this->form_validation->set_rules('password', 'Password', 'required|min_length[4]|max_length[18]');

        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[users.users_email]');
        $this->form_validation->set_rules('phone', 'Phone');
        $this->form_validation->set_rules('address', 'Address');

        if ($this->form_validation->run() == FALSE) {

            $this->load->view('admin/users/add_users', $data);
        } else {
            //image start
            $file_name_image = '';
            $extension = '';
            $error = '';
            $users_url = url_title(strtolower($this->input->post('users_title')));
            if ($_FILES['image']['name'] != '') {
                $config['upload_path'] = 'uploads/users/main/';
                $config['allowed_types'] = 'gif|jpg|png|jpeg|pdf';
                $config['max_size'] = $this->max_size;
                $config['file_name'] = $users_url;
                $this->load->library('upload', $config);
                if (!$this->upload->do_upload('image')) {
                    $error = $this->upload->display_errors();
                } else {
                    $data = array('upload_data' => $this->upload->data());
                    $file_name_image = $data['upload_data']['file_name'];
                    //$extension=$data['upload_data']['file_ext'];
                    $config['source_image'] = 'uploads/users/main/' . $file_name_image;
                    $config['new_image'] = 'uploads/users/thumb/' . $file_name_image;
                    $config['width'] = $this->thumb_width;
                    $config['height'] = $this->thumb_height;
                    $config['maintain_ratio'] = FALSE;
                    $config['quality'] = '100';
                    $this->image_lib->initialize($config);
                    $this->image_lib->resize();
                    $this->image_lib->clear();
                    if ($data['upload_data']['image_height'] > $this->main_height || $data['upload_data']['image_width'] > $this->main_width) {
                        $config['image_library'] = 'gd2';
                        $config['source_image'] = 'uploads/users/main/' . $file_name_image;
                        $config['new_image'] = 'uploads/users/main/' . $file_name_image;
                        $config['width'] = $this->main_width;
                        $config['height'] = $this->main_height;
                        $config['maintain_ratio'] = TRUE;
                        $this->image_lib->initialize($config);
                        $this->image_lib->resize();
                    }
                }
            }
            //image end
            $password = $this->input->post('password');
            $salt = sha1($password);
            $password = md5($salt . $password);
            $datas = array(
                'users_usertype' => $this->input->post('user_type'),
                'users_full_name' => $this->input->post('full_name'),
                'users_username' => $this->input->post('username'),
                'users_email' => $this->input->post('email'),
                'users_phone' => $this->input->post('phone'),
                'users_designation' => $this->input->post('designation'),
                'users_image' => $file_name_image,
                'users_password' => $password);

            $this->obj_users->add($datas);

            redirect('admin/users/index');
        }
    }

    public function crop($id, $row = 0) {
        $condition = array('users_id' => $id);
        $data['users'] = $this->obj_users->get_all($condition);
        $data["row"] = $row;
        $this->load->view('admin/users/crop', $data);
    }

    public function save($row = 0) {

        $config['image_library'] = 'gd2';
        $config['source_image'] = 'uploads/users/main/' . $this->input->post('image_name');
        $config['new_image'] = 'uploads/users/thumb/' . $this->input->post('image_name');
        $config['maintain_ratio'] = FALSE;
        $config['quality'] = '100';
        $config['x_axis'] = $this->input->post('x');
        $config['y_axis'] = $this->input->post('y');
        $config['width'] = $this->input->post('w');
        $config['height'] = $this->input->post('h');
        //	$config['dynamic_output'] = TRUE;
        $this->image_lib->initialize($config);
        if ($this->image_lib->crop()) {
            $this->session->set_userdata('users_crop_msg', 'Sucessfully updated');
            $config2['image_library'] = 'gd2';
            $config2['source_image'] = 'uploads/users/thumb/' . $this->input->post('image_name');
            $config2['new_image'] = 'uploads/users/thumb/' . $this->input->post('image_name');
            $config2['maintain_ratio'] = TRUE;
            $config2['quality'] = '100';
            $config2['width'] = $this->thumb_width;
            $config2['height'] = $this->thumb_height;
            $this->image_lib->initialize($config2);
            $this->image_lib->resize();
        }

        $users_id = $this->input->post('users_id');
        redirect('admin/users/crop/' . $users_id . '/' . $row);
    }

    function edit($id = '', $row = 0) {
        if ($this->session->userdata('user_type') == 2) {
            redirect('admin/login');
        }
        $data['page_active'] = 8;
        $original_username = $this->input->post('original_username');
        $original_email = $this->input->post('original_email');

        if ($this->input->post('user_name') != $original_username) {
            $is_unique_username = '|is_unique[users.users_username]';
        } else {
            $is_unique_username = '';
        }

        if ($this->input->post('email') != $original_email) {
            $is_unique_email = '|is_unique[users.users_email]';
        } else {
            $is_unique_email = '';
        }

        $this->form_validation->set_rules('user_name', 'User Name', 'required|trim' . $is_unique_username);
        $this->form_validation->set_rules('email', 'Email', 'required|trim' . $is_unique_email);

        $this->form_validation->set_rules('full_name', 'Full Name', 'required');

        $this->form_validation->set_rules('phone', 'Phone');
        $this->form_validation->set_rules('address', 'Address');

        if ($this->form_validation->run() == FALSE) {

            $condition = array('users_id' => $id);
            $data['product_category'] = $this->obj_users->get_all($condition);
            $data["users_id"] = $id;
            $data["row"] = $row;
            $this->load->view('admin/users/edit_users', $data);
        } else {

            //image start
            $file_name_image = '';
            $extension = '';
            $error = '';
            $users_url = url_title(strtolower($this->input->post('users_title')));
            if ($_FILES['image']['name'] != '') {
                $config['upload_path'] = 'uploads/users/main/';
                $config['allowed_types'] = 'gif|jpg|png|jpeg';
                $config['max_size'] = $this->max_size;
                $config['file_name'] = $users_url;
                $this->load->library('upload', $config);
                if (!$this->upload->do_upload('image')) {
                    $error = $this->upload->display_errors();
                } else {
                    $data = array('upload_data' => $this->upload->data());
                    $file_name_image = $data['upload_data']['file_name'];
                    $extension = $data['upload_data']['file_ext'];
                    $config['source_image'] = 'uploads/users/main/' . $file_name_image;
                    $config['new_image'] = 'uploads/users/thumb/' . $file_name_image;
                    $config['width'] = $this->thumb_width;
                    $config['height'] = $this->thumb_height;
                    $config['maintain_ratio'] = FALSE;
                    $config['quality'] = '100';
                    $this->image_lib->initialize($config);
                    $this->image_lib->resize();
                    $this->image_lib->clear();
                    if ($data['upload_data']['image_height'] > $this->main_height || $data['upload_data']['image_width'] > $this->main_width) {
                        $config['image_library'] = 'gd2';
                        $config['source_image'] = 'uploads/users/main/' . $file_name_image;
                        $config['new_image'] = 'uploads/users/main/' . $file_name_image;
                        $config['width'] = $this->main_width;
                        $config['height'] = $this->main_height;
                        $config['maintain_ratio'] = TRUE;
                        $this->image_lib->initialize($config);
                        $this->image_lib->resize();
                    }
                    @unlink('./uploads/users/main/' . $this->input->post('old_users_image'));
                    @unlink('./uploads/users/thumb/' . $this->input->post('old_users_image'));
                }
            } else {
                $file_name_image = $this->input->post('old_users_image');
            }
            //image end
            //thumb image

            if ($_FILES['image_thumb']['name'] != '') {
                @unlink('./uploads/users/thumb/' . $file_name_image);
                $config['upload_path'] = 'uploads/users/thumb/';
                $config['allowed_types'] = 'gif|jpg|png|jpeg';
                $config['file_name'] = $file_name_image;
                $this->load->library('upload', $config);
                $this->upload->initialize($config);
                if (!$this->upload->do_upload('image_thumb')) {
                    $error = $this->upload->display_errors();
                } else {
                    $data = array('upload_data' => $this->upload->data());
                }
            }

            //thumb image end

            if ($this->input->post('password')) {

                $password = $this->input->post('password');
                $salt = sha1($password);
                $password = md5($salt . $password);
                $datas = array(
                    'users_usertype' => $this->input->post('user_type'),
                    'users_branch' => $this->input->post('branch'),
                    'users_full_name' => $this->input->post('full_name'),
                    'users_username' => $this->input->post('user_name'),
                    'users_email' => $this->input->post('email'),
                    'users_phone' => $this->input->post('phone'),
                    'users_designation' => $this->input->post('designation'),
                    'users_image' => $file_name_image,
                    'users_password' => $password);
            } else {
                $datas = array(
                    'users_usertype' => $this->input->post('user_type'),
                    'users_branch' => $this->input->post('branch'),
                    'users_full_name' => $this->input->post('full_name'),
                    'users_username' => $this->input->post('user_name'),
                    'users_email' => $this->input->post('email'),
                    'users_image' => $file_name_image,
                    'users_phone' => $this->input->post('phone'),
                    'users_designation' => $this->input->post('designation')
                );
            }
            $condition = array('users_id' => $id);
            $this->obj_users->edit($condition, $datas);
            $this->session->set_userdata('users_msg', 'Sucessfully updated');

            redirect('admin/users/edit/' . $id . '/' . $row);
        }
    }

    function delete($id, $row) {

        if ($this->session->userdata('user_type') == 2) {
            redirect('admin/login');
        }

        // Delete Product image
        $condition = array('users_id' => $id);
        $img = $this->obj_users->get_all($condition);

        @unlink('uploads/users/main/' . $img[0]['users_image']);
        @unlink('uploads/users/thumb/' . $img[0]['users_image']);

        $condition = array('users_id' => $id);
        $this->obj_users->delete($condition);
        redirect('admin/users/index/' . $row);
    }

    function update_order() {

        $users_id = $this->input->post('users_id');
        $users_order = $this->input->post('users_order');
        $condition = array('users_id' => $users_id);
        $data_array = array('users_display_order' => $users_order);
        $this->obj_users->edit($condition, $data_array);
    }

    function update_status() {
        $users_id = $this->input->post('users_id');
        $users_active = $this->input->post('users_active');
        $condition = array('users_id' => $users_id);
        $data_array = array('users_active' => $users_active,
            'users_active_date' => time(),
            'users_active_by' => $this->session->userdata('users_id')
        );
        $this->obj_users->edit($condition, $data_array);
    }

    function change_password() {

        $this->form_validation->set_rules('old_password', 'Old Password', 'trim|required');
        $this->form_validation->set_rules('password', 'New Password', 'trim|required|matches[password_re]');
        $this->form_validation->set_rules('password_re', 'Re enter Password', 'trim|required');

        if ($this->form_validation->run() == FALSE) {

            $data['page_active'] = 8;
            $this->load->view('admin/users/change_password', $data);
        } else {

            $status = $this->obj_users->change_password();

            $data['status'] = $status;
            $data['page_active'] = 8;
            $this->load->view('admin/users/change_password', $data);
        }
    }

    function delete_image($id, $row = '') {
        // Delete Product image
        $condition = array('users_id' => $id);
        $img = $this->obj_users->get_all($condition);
        @unlink('uploads/users/main/' . $img[0]['users_image']);
        @unlink('uploads/users/thumb/' . $img[0]['users_image']);
        $datas = array('users_image' => '');
        $this->obj_users->edit($condition, $datas);
        redirect('admin/users/edit/' . $id . '/' . $row);
    }

}


text:
package com.khorn.terraincontrol.forge.generator;

import com.khorn.terraincontrol.BiomeIds;
import com.khorn.terraincontrol.configuration.BiomeConfig;
import com.khorn.terraincontrol.configuration.WeightedMobSpawnGroup;
import com.khorn.terraincontrol.forge.util.MobSpawnGroupHelper;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.world.ColorizerFoliage;
import net.minecraft.world.biome.BiomeGenBase;

import java.util.List;

public class BiomeGenCustom extends BiomeGenBase
{

    private int skyColor;
    private int grassColor;
    private boolean grassColorIsMultiplier;
    private int foliageColor;
    private boolean foliageColorIsMultiplier;

    private boolean grassColorSet = false;
    private boolean foliageColorSet = false;

    public final int generationId;

    public BiomeGenCustom(String name, BiomeIds id)
    {
        super(id.getSavedId(), // Use the saved id for Minecraft compatibility
                !id.isVirtual() // Only register non-virtual biomes
        );
        this.setBiomeName(name);
        this.generationId = id.getGenerationId();
    }

    /**
     * Needs a BiomeConfig that has all the visual settings present.
     *
     * @param config
     */
    @SuppressWarnings("unchecked")
    public void setEffects(BiomeConfig config)
    {
        this.temperature = config.biomeTemperature;
        this.rainfall = config.biomeWetness;
        if (this.rainfall == 0)
        {
            this.setDisableRain();
        }
        this.waterColorMultiplier = config.waterColor;
        this.skyColor = config.skyColor;
        this.grassColor = config.grassColor;
        this.grassColorIsMultiplier = config.grassColorIsMultiplier;
        this.foliageColor = config.foliageColor;
        this.foliageColorIsMultiplier = config.foliageColorIsMultiplier;

        if (this.grassColor != 0xffffff)
            this.grassColorSet = true;

        if (this.foliageColor != 0xffffff)
            this.foliageColorSet = true;

        // Mob spawning
        addMobs(this.spawnableMonsterList, config.spawnMonsters);
        addMobs(this.spawnableCreatureList, config.spawnCreatures);
        addMobs(this.spawnableWaterCreatureList, config.spawnWaterCreatures);
        addMobs(this.spawnableCaveCreatureList, config.spawnAmbientCreatures);

        // color ?
        // this.x = 522674;

        // duno.
        // this.A = 9154376;

    }

    // Adds the mobs to the internal list
    protected void addMobs(List<SpawnListEntry> internalList, List<WeightedMobSpawnGroup> configList)
    {
        internalList.clear();
        internalList.addAll(MobSpawnGroupHelper.toMinecraftlist(configList));
    }

    /**
     * Copies all properties from another biome. Later on, some properties may
     * get overwritten or modified by {@link #setEffects(BiomeConfig)}. Other
     * properties are not used by Terrain Control, but may be used by other
     * mods.
     * @param baseBiome The biome to copy the settings from.
     */
    public void copyBiome(BiomeGenBase baseBiome)
    {
        this.fillerBlock = baseBiome.fillerBlock;
        this.topBlock = baseBiome.topBlock;
        this.color = baseBiome.color;
        this.minHeight = baseBiome.minHeight;
        this.maxHeight = baseBiome.maxHeight;
        this.temperature = baseBiome.temperature;

        this.theBiomeDecorator = baseBiome.theBiomeDecorator;
        this.waterColorMultiplier = baseBiome.waterColorMultiplier;

        this.spawnableMonsterList = baseBiome.getSpawnableList(EnumCreatureType.MONSTER);
        this.spawnableCreatureList = baseBiome.getSpawnableList(EnumCreatureType.CREATURE);
        this.spawnableWaterCreatureList = baseBiome.getSpawnableList(EnumCreatureType.WATER_CREATURE);
        this.spawnableCaveCreatureList = baseBiome.getSpawnableList(EnumCreatureType.AMBIENT);
    }

    // Sky color from Temp
    @Override
    public int getSkyColorByTemp(float v)
    {
        return this.skyColor;
    }

    // getGrassColorAtCoords
    @Override
    public int getModdedBiomeGrassColor(int original)
    {
        if (!this.grassColorSet)
            return original;
        if (grassColorIsMultiplier)
        {
            return ((ColorizerFoliage.getFoliageColor(Math.min(temperature, 1.0f), rainfall) & 0xFEFEFE) + grassColor) / 2;
        } else
        {
            return grassColor;
        }

    }

    // getFoliageColorAtCoords
    @Override
    public int getModdedBiomeFoliageColor(int original)
    {
        if (!this.foliageColorSet)
            return original;
        if (foliageColorIsMultiplier)
        {
            return ((ColorizerFoliage.getFoliageColor(Math.min(temperature, 1.0f), rainfall) & 0xFEFEFE) + foliageColor) / 2;
        } else
        {
            return foliageColor;
        }
    }

    @Override
    public String toString()
    {
        return "BiomeGenCustom of " + biomeName;
    }

}


text:
/**
 * script requeridos para el sub modulo producto/unidad del proveedor
 * @author Max Llaupi <max.llaupi@espol.cl>
 * @version 2017-05-15
 */
$(function() {

	var ci = {
        controller  : $('#main').data('controller-producto'),
        unidad 		: $('#main').data('controller-unidad')
    };

	/**
     * filtro de busqueda en la tabla ficha de producto
     * @author Max Llaupi <max.llaupi@espol.cl>
     * @version 2017-05-15
     */
    $('#tb_ficha_producto').DataTable({
        "language": {
            url : 'http://cdn.datatables.net/plug-ins/1.10.13/i18n/Spanish.json'
        },
		"columnDefs": [
            {
                "targets": 4, //first column / numbering column
                "orderable": false//set not orderable
            }
        ],
    });

	/**
     * filtro de busqueda en la tablas de Unidades base, intermedia, embalaje y pallet
     * @author Max Llaupi <max.llaupi@espol.cl>
     * @version 2017-05-19
     */
	$('.unidad-datatable').DataTable({
        "language": {
            url : 'http://cdn.datatables.net/plug-ins/1.10.13/i18n/Spanish.json'
        },
		"columnDefs": [
            {
                "targets": 6, //first column / numbering column
                "orderable": false//set not orderable
            }
        ],
    });

	/**
	 * formato numerico con decimales cuando corresponde para los formulario de
	 * unidad
	 * @author Max Llaupi <max.llaupi@espol.cl>
	 * @version 2017-05-15
	 */
	$('#fp_contenido').number(true, 0, ',', '.');
	$('#fp_duracion').number(true, 0, ',', '.');
	$('#fp_alto').number(true, 2, ',', '.');
	$('#fp_ancho').number(true, 2, ',', '.');
	$('#fp_fondo').number(true, 2, ',', '.');
	$('#fp_peso_bruto').number(true, 2, ',', '.');
	$('#fp_peso_drenado').number(true, 2, ',', '.');
	$('#fp_max_api').number(true, 0, ',', '.');
	$('#fp_precio_venta').number(true, 0, ',', '.');

	$("#fp_precio_base").number(true, 0, ',', '.');
	$("#fp_desc_base").number(true, 2, ',', '.');
	$("#fp_desc_financiero").number(true, 2, ',', '.');
	$("#fp_desc_promocional").number(true, 2, ',', '.');

	$("#fp_desc_base_porc").number(true, 2, ',', '.');
	$("#fp_desc_financiero_porc").number(true, 2, ',', '.');
	$("#fp_desc_promocional_porc").number(true, 2, ',', '.');

	$("#fp_peso_carga").number(true, 2, ',', '.');

	$('.container').on('click', '.calcular-descuento', function(event) {
		event.preventDefault();
		/* Act on the event */
	});

	/**
	 * ejecuta la funciom que realiza los descuentos cada vez que el valor del
	 * input que tenga la clase .calcular-descuento
	 * @author Max Llaupi <max.llaupi@espol.cl>
	 * @version 2017-05-15
	 */
	$('.calcular-descuento').keyup(function(e) {

		var precio_base = $('#fp_precio_base').val();

		// descuento base
		var desc_base 			= calcular_desc(precio_base, $('#fp_desc_base_porc').val());
		$('#fp_desc_base').val(desc_base);

		// descuento financiero
		var desc_financiero 	= calcular_desc(desc_base, $('#fp_desc_financiero_porc').val());
		$('#fp_desc_financiero').val(desc_financiero);

		// descuento promocional
		var desc_promocional 	= calcular_desc(desc_financiero, $('#fp_desc_promocional_porc').val());
		$('#fp_desc_promocional').val(desc_promocional);

	});

	/**
	 * calcula los descuentos en base al precio_base
	 * @author Max Llaupi <max.llaupi@espol.cl>
	 * @version 2017-05-15
	 */
	var calcular_desc = function(precio, descuento) {

		var result = precio - ((precio * descuento) / 100);
		return result;

	}

	/**
	 * modifica la propiedad length del campo gtin del formulario en base al
	 * tipo de gtin seleccionado
	 * @author Max Llaupi <max.llaupi@espol.cl>
	 * @version 2017-05-15
	 */
	$('#gtin_tipo').change(function(e) {

		// valor seleccionado
		var tipo = $(this).val();
		var tipoSelect = $(this).context;
		var largo = 8;
		var tipo_nombre = '';

		switch (tipo) {
			case '1':
				largo = 8;
				tipo_nombre = tipoSelect[tipo]['innerHTML'];
				break;

			case '2':
				largo = 12;
				tipo_nombre = tipoSelect[tipo]['innerHTML'];
				break;

			case '3':
				largo = 13;
				tipo_nombre = tipoSelect[tipo]['innerHTML'];
				break;

			case '4':
				largo = 14;
				tipo_nombre = tipoSelect[tipo]['innerHTML'];
				break;
		}

		$('#gtin').attr({
			minlength: largo,
			maxlength: largo
		});

		$('#gtin_tipo_nombre').val(tipo_nombre);

	});

	/**
	 * envia los datos del formulario agregar nueva unidad al server
	 * para ser validado y enviados al formulario de la unidad seleccionada
	 * @author Max Llaupi <max.llaupi@espol.cl>
	 * @version 2017-05-15
	 */
	$('#form_unidad').submit(function(e) {

		e.preventDefault();

		$.ajax({
			url: ci.controller + 'form',
			type: 'POST',
			dataType: 'json',
			data: $('#form_unidad').serialize()
		})
		.done(function(data) {
			console.log("success");
			if (data.correcto) {

				console.log('Si paso la validacion');
				console.log(data.url);
				window.location.href = data.url;

			} else {

				console.log('No paso la validacion');

				addError(data.errores.tipo_unidad, $('#msg_tipo_unidad'));
				addError(data.errores.procedencia, $('#msg_procedencia'));
				addError(data.errores.gtin_tipo, $('#msg_gtin_tipo'));
				addError(data.errores.gtin, $('#msg_gtin'));

			}

		})
		.fail(function() {
			console.log("error");
		})
		.always(function() {
			console.log("complete");
		});

	});

	$('.container').on('click', '.contenedor-delete', function (e) {

		var elemento 	= $(this).closest('.img-producto');
		var id_imagen 	= $(this).data('id');

		$.ajax({
			url: ci.controller + 'deleteIMG',
			type: 'POST',
			dataType: 'json',
			data: {id_imagen: id_imagen},
		})
		.done(function(data) {
			console.log("success");
			console.log(data);

			if (data) {

				// remueve el elemento del dom
				elemento.remove();
			}

		})
		.fail(function() {
			console.log("error");
		})
		.always(function() {
			console.log("complete");
		});

	});

	/**
	 * muestra la modal eliminar ficha de producto
	 * @author Max Llaupi <max.llaupi@espol.cl>
	 * @version 2017-05-24
	 */
	$('.btn-delete-gtin').click(function (e) {

		var gtin_enc 	= $(this).data('gtin');
		var url 		= $(this).data('url');
		var tr 			= $(this).closest('tr');
		var gtin		= tr.children('td.gtin').text();
		var descripcion	= tr.children('td.descripcion').text();
		var tipo_unidad	= $(this).data('tipo-unidad');

		var mensaje = 'Esta seguro de que desea eliminar el producto  ' + descripcion + ', cuyo GTIN  ' + gtin + '.';

		$('#title-md-delete-gtin').html('Eliminar ' + tipo_unidad);
		$('#mensaje-eliminar').html(mensaje);
		$('#gtin-enc').val(gtin_enc);

		$('#respuesta-eliminar').addClass('hide');
		$('#respuesta-eliminar-text').html('');
		$('#btn-delete-confirmar').removeClass('hide');
		$('#btn-delete-confirmar').data('url', url);
		$('#btn-cerrar-cancelar').html('Cancelar');

		$('.md-delete-gtin').modal('show');

	});

	/**
	 * envia los datos al servidor para ser eliminados dependiendo de la respuesta
	 * muestra una alert con el mensaje o recarga la pagina
	 * @author Max Llaupi <max.llaupi@espol.cl>
	 * @version 2017-05-24
	 */
	$('#btn-delete-confirmar').click(function (e) {

		var gtin = $('#gtin-enc').val();
		var url  = $(this).data('url');

		$.ajax({
			url: ci.controller + 'delete/'+gtin,
			dataType: 'json',
		})
		.done(function(data) {
			if (data.estado == 0) {

				$('#respuesta-eliminar').removeClass('hide');
				$('#respuesta-eliminar-text').html(data.mensaje);
				$('#btn-delete-confirmar').addClass('hide');
				$('#btn-cerrar-cancelar').html('Cerrar');

			}else {
				window.location.href = url;
			}
		})
		.fail(function() {
			console.log("error");
		})
		.always(function() {
			console.log("complete");
		});

	});

});


text:
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

/* Specification.  */
#include "x-po.h"
#include "x-properties.h"
#include "x-stringtable.h"

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>

#include "message.h"
#include "xgettext.h"
#include "xalloc.h"
#include "read-catalog.h"
#include "read-po.h"
#include "read-properties.h"
#include "read-stringtable.h"
#include "po-lex.h"
#include "gettext.h"

/* A convenience macro.  I don't like writing gettext() every time.  */
#define _(str) gettext (str)

/* The charset found in the header entry.  */
static char *header_charset;

/* Define a subclass extract_catalog_reader_ty of default_catalog_reader_ty.  */

static void
extract_add_message (default_catalog_reader_ty *this,
                     char *msgctxt,
                     char *msgid,
                     lex_pos_ty *msgid_pos,
                     char *msgid_plural,
                     char *msgstr, size_t msgstr_len,
                     lex_pos_ty *msgstr_pos,
                     char *prev_msgctxt,
                     char *prev_msgid,
                     char *prev_msgid_plural,
                     bool force_fuzzy, bool obsolete)
{
  /* See whether we shall exclude this message.  */
  if (exclude != NULL && message_list_search (exclude, msgctxt, msgid) != NULL)
    goto discard;

  /* If the msgid is the empty string, it is the old header.  Throw it
     away, we have constructed a new one.  Only remember its charset.
     But if no new one was constructed, keep the old header.  This is useful
     because the old header may contain a charset= directive.  */
  if (msgctxt == NULL && *msgid == '\0' && !xgettext_omit_header)
    {
      {
        const char *charsetstr = strstr (msgstr, "charset=");

        if (charsetstr != NULL)
          {
            size_t len;
            char *charset;

            charsetstr += strlen ("charset=");
            len = strcspn (charsetstr, " \t\n");
            charset = XNMALLOC (len + 1, char);
            memcpy (charset, charsetstr, len);
            charset[len] = '\0';

            if (header_charset != NULL)
              free (header_charset);
            header_charset = charset;
          }
      }

     discard:
      if (msgctxt != NULL)
        free (msgctxt);
      free (msgid);
      if (msgid_plural != NULL)
        free (msgid_plural);
      free (msgstr);
      if (prev_msgctxt != NULL)
        free (prev_msgctxt);
      if (prev_msgid != NULL)
        free (prev_msgid);
      if (prev_msgid_plural != NULL)
        free (prev_msgid_plural);
      return;
    }

  /* Invoke superclass method.  */
  default_add_message (this, msgctxt, msgid, msgid_pos, msgid_plural,
                       msgstr, msgstr_len, msgstr_pos,
                       prev_msgctxt, prev_msgid, prev_msgid_plural,
                       force_fuzzy, obsolete);
}

/* So that the one parser can be used for multiple programs, and also
   use good data hiding and encapsulation practices, an object
   oriented approach has been taken.  An object instance is allocated,
   and all actions resulting from the parse will be through
   invocations of method functions of that object.  */

static default_catalog_reader_class_ty extract_methods =
{
  {
    sizeof (default_catalog_reader_ty),
    default_constructor,
    default_destructor,
    default_parse_brief,
    default_parse_debrief,
    default_directive_domain,
    default_directive_message,
    default_comment,
    default_comment_dot,
    default_comment_filepos,
    default_comment_special
  },
  default_set_domain, /* set_domain */
  extract_add_message, /* add_message */
  NULL /* frob_new_message */
};

static void
extract (FILE *fp,
         const char *real_filename, const char *logical_filename,
         catalog_input_format_ty input_syntax,
         msgdomain_list_ty *mdlp)
{
  default_catalog_reader_ty *pop;

  header_charset = NULL;

  pop = default_catalog_reader_alloc (&extract_methods);
  pop->handle_comments = true;
  pop->allow_domain_directives = false;
  pop->allow_duplicates = false;
  pop->allow_duplicates_if_same_msgstr = true;
  pop->file_name = real_filename;
  pop->mdlp = NULL;
  pop->mlp = mdlp->item[0]->messages;
  catalog_reader_parse ((abstract_catalog_reader_ty *) pop, fp, real_filename,
                        logical_filename, input_syntax);
  catalog_reader_free ((abstract_catalog_reader_ty *) pop);

  if (header_charset != NULL)
    {
      if (!xgettext_omit_header)
        {
          /* Put the old charset into the freshly constructed header entry.  */
          message_ty *mp =
            message_list_search (mdlp->item[0]->messages, NULL, "");

          if (mp != NULL && !mp->obsolete)
            {
              const char *header = mp->msgstr;

              if (header != NULL)
                {
                  const char *charsetstr = strstr (header, "charset=");

                  if (charsetstr != NULL)
                    {
                      size_t len, len1, len2, len3;
                      char *new_header;

                      charsetstr += strlen ("charset=");
                      len = strcspn (charsetstr, " \t\n");

                      len1 = charsetstr - header;
                      len2 = strlen (header_charset);
                      len3 = (header + strlen (header)) - (charsetstr + len);
                      new_header = XNMALLOC (len1 + len2 + len3 + 1, char);
                      memcpy (new_header, header, len1);
                      memcpy (new_header + len1, header_charset, len2);
                      memcpy (new_header + len1 + len2, charsetstr + len, len3 + 1);
                      mp->msgstr = new_header;
                      mp->msgstr_len = len1 + len2 + len3 + 1;
                    }
                }
            }
        }

      free (header_charset);
    }
}

void
extract_po (FILE *fp,
            const char *real_filename, const char *logical_filename,
            flag_context_list_table_ty *flag_table,
            msgdomain_list_ty *mdlp)
{
  extract (fp, real_filename,  logical_filename, &input_format_po, mdlp);
}

void
extract_properties (FILE *fp,
                    const char *real_filename, const char *logical_filename,
                    flag_context_list_table_ty *flag_table,
                    msgdomain_list_ty *mdlp)
{
  extract (fp, real_filename,  logical_filename, &input_format_properties,
           mdlp);
}

void
extract_stringtable (FILE *fp,
                     const char *real_filename, const char *logical_filename,
                     flag_context_list_table_ty *flag_table,
                     msgdomain_list_ty *mdlp)
{
  extract (fp, real_filename,  logical_filename, &input_format_stringtable,
           mdlp);
}


text:
{-# LANGUAGE OverloadedStrings #-}

module Main where

import           Data.Aeson
import qualified Data.ByteString.Lazy as BSL
import           Data.Time.Clock (UTCTime)
import           Data.Time.Clock.POSIX (posixSecondsToUTCTime)
import           Test.Hspec
import           Test.QuickCheck
import           Test.QuickCheck.Monadic
import           Universum

import           Cardano.Faucet.Types
import           Cardano.Faucet.Types.Recaptcha
import           Cardano.WalletClient

main :: IO ()
main = hspec $ do
    describe "randomAmount" $ do
        it "should be within PaymentDistribution" $ do
            property $ prop_randomAmount

    describe "Aeson encode and decode" $ do
        it "CreatedWallet" $ property (prop_aeson_id :: CreatedWallet -> Bool)
        it "WithdrawalRequest" $ property (prop_aeson_id :: WithdrawalRequest -> Bool)
        it "CaptchaResponse decode" $ captchaDecode

    describe "Reading the recaptcha secret from a file" $ do
        it "Should read from a file that exists" $ do
            readCaptchaSecret "test/valid-secret.txt" `shouldReturn` CaptchaSecret "test"
        it "Should throw ReadRecaptchaSecretError if the file doesn't have one line" $ do
            readCaptchaSecret "test/multi-line-secret.txt"
            `shouldThrow`
            (== MoreThanOneLine "test/multi-line-secret.txt")

prop_randomAmount :: PaymentDistribution -> Property
prop_randomAmount pd = monadicIO $ do
    c <- run (liftIO $ randomAmount pd)
    assert (between pd c)
  where
    between (PaymentDistribution m s) c = c <= m + s
                                      && c >= m - s

prop_aeson_id :: (Arbitrary a, ToJSON a, FromJSON a, Eq a) => a -> Bool
prop_aeson_id a = Just a == (decode $ encode a)

t :: UTCTime
t = posixSecondsToUTCTime 1527811200

getJSON :: FromJSON a => FilePath -> IO (Either String a)
getJSON f = eitherDecode <$> BSL.readFile f

captchaDecode :: Expectation
captchaDecode = do
    getJSON "test/captcha-resp-ok.json" `shouldReturn` Right (CaptchaResponse True (Just t) (Just "test") [])


text:
#include <ProjectConfig.h>
#include <esp8266.h>
#include <Platform.h>

#include <SCDE_s.h>

#include "Include_Command.h"

// set default build verbose - if no external override
#ifndef Include_Command_DBG
#define Include_Command_DBG  5	// 5 is default
#endif

// -------------------------------------------------------------------------------------------------

// make data root locally available
static SCDERoot_t* SCDERoot;

// make locally available from data-root: the SCDEFn (Functions / callbacks) for operation
static SCDEFn_t* SCDEFn;

// -------------------------------------------------------------------------------------------------

/*
 * -------------------------------------------------------------------------------------------------
 *  DName: Include_Command
 *  Desc: Data 'Provided By Command' for the Include Command (functions + infos this command provides
 *        to SCDE)
 *  Data:
 * -------------------------------------------------------------------------------------------------
 */

// Command Help
const uint8_t Include_helpText[] =
  "Usage: Include <filename>, to read the commands from <filenname>";
// CommandHelp (detailed)
const uint8_t Include_helpDetailText[] =
  "Usagebwrebwerb: Include <filename>, to read the commands from <filenname>";

ProvidedByCommand_t Include_ProvidedByCommand = {
  "Include",			// command-name text -> libfilename.so !
  7,				// command-name text length
  Include_InitializeCommandFn,	// Initialize Fn
  Include_CommandFn,		// the Fn code
  { &Include_helpText, sizeof(Include_helpText) },
  { &Include_helpDetailText, sizeof(Include_helpDetailText) }
};

/* --------------------------------------------------------------------------------------------------
 *  FName: Include_Initialize
 *  Desc: Initializion of SCDE Function Callback of an new loaded command
 *  Info: Stores Command-Information (Function Callbacks) to SCDE-Root
 *  Para: SCDERoot_t* SCDERootptr -> ptr to SCDE Data Root
 *  Rets: ? unused
 *--------------------------------------------------------------------------------------------------
 */
int
Include_InitializeCommandFn(SCDERoot_t* SCDERootptr)
{
  // make data root locally available
  SCDERoot = SCDERootptr;

  // make locally available from data-root: SCDEFn (Functions / callbacks) for faster operation
  SCDEFn = SCDERootptr->SCDEFn;

// --------------------------------------------------------------------------------------------------

  #if Include_Command_DBG >= 3
  SCDEFn->Log3Fn(Include_ProvidedByCommand.commandNameText
	,Include_ProvidedByCommand.commandNameTextLen
	,3
	,"InitializeFn called. Now useable.");
  #endif

// --------------------------------------------------------------------------------------------------

  return 0;
}

/* -------------------------------------------------------------------------------------------------
 *  FName: Include_CommandFn
 *  Desc: Opens the fileName, loads and splits the content it in multiple lines by '\r\n',
 *        recreates multi-line text by '//' and executes each line.
 *  Info: 'fileName' is the file-name that should be loaded
 *  Para: const uint8_t *argsText  -> prt to include command args text "fileName"
 *        const size_t argsTextLen -> attr command args text length
 *  Rets: struct headRetMsgMultiple_s -> STAILQ head of multiple retMsg, if NULL -> NO entry
 * -------------------------------------------------------------------------------------------------
 */
struct headRetMsgMultiple_s ICACHE_FLASH_ATTR
Include_CommandFn (const uint8_t *argsText
		,const size_t argsTextLen)
{
  #if Include_Command_DBG >= 7
  SCDEFn->Log3Fn(Include_ProvidedByCommand.commandNameText
	,Include_ProvidedByCommand.commandNameTextLen
	,7
	,"CommandFn called with args '%.*s'"
	,argsTextLen
	,argsText);
  #endif

// --------------------------------------------------------------------------------------------------

  // prepare STAILQ head for multiple RetMsg storage
  struct headRetMsgMultiple_s headRetMsgMultiple;

  // Initialize the queue
  STAILQ_INIT(&headRetMsgMultiple);

  // set start of possible def-Name-Text
  const uint8_t *fileNameText = argsText;

  // length of def-Name-Text
  size_t fileNameTextLen = argsTextLen;

// -------------------------------------------------------------------------------------------------

  // veryfy lengths > 0, definition 0 allowed
  if (fileNameTextLen == 0) {

	// alloc mem for retMsg
	strTextMultiple_t *retMsg =
		 malloc(sizeof(strTextMultiple_t));

	// response with error text
	retMsg->strTextLen = asprintf(&retMsg->strText
		,"Could not interpret command '%.*s'! Usage: Include <fileName>"
		,argsTextLen
		,argsText);

	// insert retMsg in stail-queue
	STAILQ_INSERT_TAIL(&headRetMsgMultiple, retMsg, entries);

	// return STAILQ head, stores multiple retMsg, if NULL -> no retMsg-entries
	return headRetMsgMultiple;
  }

// -------------------------------------------------------------------------------------------------

 /*
  FILE *fp = fopen("/data/x", "w");

  // return msg in case of an error
  if (fp == NULL) {

	// alloc mem for retMsg
	strTextMultiple_t *retMsg =
		 malloc(sizeof(strTextMultiple_t));

	// response with error text
	retMsg->strTextLen = asprintf(&retMsg->strText
	,"should load: %.*s here!\r\n"
	,fileNameTextLen
	,fileNameText);

  // insert retMsg in stail-queue
  STAILQ_INSERT_TAIL(&headRetMsgMultiple, retMsg, entries);

  // return STAILQ head, stores multiple retMsg, if NULL -> no retMsg-entries
  return headRetMsgMultiple;

  }

*/

/*
  // !! correct to default LOG Fn!
  printf("Including %.*s\n"
	,fileNameTextLen
	,fileNameText);
*/

  SCDEFn->Log3Fn(Include_ProvidedByCommand.commandNameText //Common_Definition->name
		,Include_ProvidedByCommand.commandNameTextLen  					 //Common_Definition->nameLen
		,1
		,"Including %.*s.cfg\n"
		,fileNameTextLen
		,fileNameText);

/*

1222	  my @t = localtime();
1223	  my $gcfg = ResolveDateWildcards(AttrVal("global", "configfile", ""), @t);
1224	  my $stf  = ResolveDateWildcards(AttrVal("global", "statefile",  ""), @t);

1225	  if(!$init_done && $arg ne $stf && $arg ne $gcfg) {
1226	    my $nr =  $devcount++;
1227	    $comments{$nr}{TEXT} = "include $arg";
1228	    $comments{$nr}{CFGFN} = $currcfgfile		if($currcfgfile ne $gcfg);
1229	  }
*/

  // Open the configfile or statefile for reading
  char *fileName;
  asprintf(&fileName
		,"/spiffs/%.*s.cfg"
		,fileNameTextLen
		,fileNameText);

  FILE *f;

	f = fopen(fileName, "r");

	if ( f == NULL ) {
		SCDEFn->Log3Fn(Include_ProvidedByCommand.commandNameText //Common_Definition->name
			,Include_ProvidedByCommand.commandNameTextLen  					 //Common_Definition->nameLen
			,1
			,"Failed to open file %.*s.cfg for reading!"
			,fileNameTextLen
			,fileNameText);
	//	return; HOW TO EXIT ???????
	}

  free(fileName);

  // our delimiters
  char delimiter[] = "\r\n";

  // backup old configuration file, for reconstruction
  strText_t oldCfgFile = SCDERoot->current_config_file;

  // set temporary to filename from include arg
  SCDERoot->current_config_file.strText = fileNameText;
  SCDERoot->current_config_file.strTextLen = fileNameTextLen;

  // clear, reset the global quit-flag
  SCDERoot->global_control_register_a &= ~(F_RECEIVED_QUIT);

  // to build one complete command row, start empty
  strTextMultiple_t rebuiltCmdRow;
  rebuiltCmdRow.strText = NULL;

  // our one line cache
	char line [256+1];

	// get one file content line, till /n newline
	while (fgets(line, sizeof(line), f)) {

	  // partialCmdRow building (line may contain multiple commands)
	  strTextMultiple_t partialCmdRow;

		// initialize strtok
  	partialCmdRow.strText = strtok(line, delimiter);

		// do till we have chars from line
    while ( partialCmdRow.strText != NULL ) {

			// get length in this loop
			partialCmdRow.strTextLen = (size_t) strlen(partialCmdRow.strText);

			// further processing only if we have chars
		 	if (partialCmdRow.strTextLen > 0) {

			 	// if starting with new command row (not continuing one) ...
			 	if (rebuiltCmdRow.strText == NULL) {

				 	// memory allocation for new command row
				 	rebuiltCmdRow.strText = (char *) malloc(partialCmdRow.strTextLen);

				 	// copy corrent row to allocated memory
				 	memcpy(rebuiltCmdRow.strText
				  	,partialCmdRow.strText
					  ,partialCmdRow.strTextLen);

					 // init length
				 	rebuiltCmdRow.strTextLen = partialCmdRow.strTextLen;
			  }

			 	// continuing a command row with an part ...
			 	else {

				  // Reallocate memory to new size
				  rebuiltCmdRow.strText = (char *) realloc(rebuiltCmdRow.strText
				  	,rebuiltCmdRow.strTextLen + partialCmdRow.strTextLen);

				 	// add command-part to allocated memory
				  memcpy(rebuiltCmdRow.strText + rebuiltCmdRow.strTextLen
					 	,partialCmdRow.strText
				 	 	,partialCmdRow.strTextLen);

					 // save new length
			 	 	rebuiltCmdRow.strTextLen += partialCmdRow.strTextLen;
		 		}

		 	 	// not ending with //? -> execute its complete
		 	 	if ( (rebuiltCmdRow.strTextLen < 2) ||
				 	(memcmp(rebuiltCmdRow.strText + rebuiltCmdRow.strTextLen - 2, "//", 2)) ) {

			 	 	printf("Rebuilt an CMD row from file '%.*s'\n"
				  	,rebuiltCmdRow.strTextLen
				   	,rebuiltCmdRow.strText);

					// call the AnalyzeCommandChainFn, if retMsg != NULL -> got ret Msgs entries
					struct headRetMsgMultiple_s headRetMsgMultipleFromFn =
						SCDEFn->AnalyzeCommandChainFn((const uint8_t *) rebuiltCmdRow.strText,
							rebuiltCmdRow.strTextLen);

					// retMsgMultiple stailq filled from Fn ? -> get the entries till empty
					while (!STAILQ_EMPTY(&headRetMsgMultipleFromFn)) {

						// for the retMsg elements
						strTextMultiple_t *retMsg =
							STAILQ_FIRST(&headRetMsgMultipleFromFn);

						printf("AddingRetMsg: %.*s\n"
							,retMsg->strTextLen
							,retMsg->strText);

						// first remove this entry
						STAILQ_REMOVE(&headRetMsgMultipleFromFn, retMsg, strTextMultiple_s, entries);

						// then insert retMsg in stail-queue
						STAILQ_INSERT_TAIL(&headRetMsgMultiple, retMsg, entries);
					}

					// release memory for next cycle
					free(rebuiltCmdRow.strText);
					rebuiltCmdRow.strText = NULL;

					// break, if the global quit-flag is set
					if (SCDERoot->global_control_register_a & F_RECEIVED_QUIT) break;
				}

				// ending with //? -> more to come
				else {

					// sub 2 chars (//)
					rebuiltCmdRow.strTextLen -= 2;
				}
			}

			partialCmdRow.strText = strtok(NULL, delimiter);
		}
  }

  // there may be an incomplete processed multiline row in memory -> release it
  if (rebuiltCmdRow.strText) free(rebuiltCmdRow.strText);

  // rebuilt current cfg file
  SCDERoot->current_config_file = oldCfgFile;

  // close file
  fclose(f);

  // return STAILQ head, queue stores multiple retMsg entries, if NULL -> no retMsg-entry
  return headRetMsgMultiple;
}

/*

	printf("Abschnitt gefunden: %s\n", ptr);

	// call the AnalyzeCommandChainFn, if retMsg != NULL -> head of the ret Msgs
	struct headRetMsgMultiple_s headRetMsgMultipleFromFn =
		SCDEFn->AnalyzeCommandChainFn((uint8_t *) ptr, (size_t) strlen(ptr));

	// retMsgMultiple stailq filled from Fn ? -> get the entries till empty
	while (!STAILQ_EMPTY(&headRetMsgMultipleFromFn)) {

		// for the retMsg elements
		strTextMultiple_t *retMsg =
			STAILQ_FIRST(&headRetMsgMultipleFromFn);

		printf("AddingRetMsg: %.*s\n"
			,retMsg->strTextLen
			,retMsg->strText);

		// first remove this entry
		STAILQ_REMOVE(&headRetMsgMultipleFromFn, retMsg, strTextMultiple_s, entries);

		// then insert retMsg in stail-queue
		STAILQ_INSERT_TAIL(&headRetMsgMultiple, retMsg, entries);

	}

	// break, if the global quit-flag is set
	if (SCDERoot->globalCtrlRegA & F_RECEIVED_QUIT) break;

	// loop through the next lines
 	ptr = strtok(NULL, delimiter);

  }

  // return STAILQ head, stores multiple retMsg, if NULL -> no retMsg-entries
  return headRetMsgMultiple;

}

*/

 /*
 // for the retMsg elements
  strTextMultiple_t *retMsg;

  STAILQ_FOREACH(retMsg, &headRetMsgMultiple, entries) {

		printf("added: %.*s\n"
			,retMsg->strTextLen
			,retMsg->strText);
  }

*/

/*

  // max row length
  char buffer[256];
  char *pbuff;
  int value;

  // parse file
  while (1) {

	// end of file reached?
	if (!fgets(buffer, sizeof buffer, stdin)) break;

	printf("Line contains");

	pbuff = buffer;

	// search for end of line
	while (1) {

	// found ?
	if (*pbuff == '\n') break;

	value = strtol(pbuff, &pbuff, 10);

	printf(" %d", value);

	}
  }

fprintf(fp, "Hello!");
*/

/*
  uint8_t testcmd[] = "attr esp32ctrl hallo maik";
  size_t testcmdlen = 25;

  struct headRetMsgMultiple_s headRetMsgMultiplex;

   // get the module ptr by name
   headRetMsgMultiplex = SCDEFn->AnalyzeCommandChainFn(testcmd
		   , testcmdlen);

  if (!STAILQ_EMPTY(&headRetMsgMultiplex)) {

	// get the multiple retMsg
	strTextMultiple_t *retMsgx;

	// Read2 (remove).
	while (!STAILQ_EMPTY(&headRetMsgMultiplex)) {

		retMsgx = STAILQ_FIRST(&headRetMsgMultiplex);

		printf("Type-Name:%.*s, module* NOT loaded!\n"
			,retMsgx->strTextLen
			,retMsgx->strText);

		STAILQ_REMOVE(&headRetMsgMultiplex, retMsgx, strTextMultiple_s, entries);

		free(retMsgx->strText);

		free(retMsgx);
	}
  }

//----

	// alloc mem for retMsg
	strTextMultiple_t *retMsg =
		 malloc(sizeof(strTextMultiple_t));

	// response with error text
	retMsg->strTextLen = asprintf(&retMsg->strText
	,"should load: %.*s here!\r\n"
	,fileNameTextLen
	,fileNameText);

  // insert retMsg in stail-queue
  STAILQ_INSERT_TAIL(&headRetMsgMultiple, retMsg, entries);

//----

  // return STAILQ head, stores multiple retMsg, if NULL -> no retMsg-entries
  return headRetMsgMultiple;
*/

//https://www.freebsd.org/cgi/man.cgi?query=queue&sektion=3

//https://github.com/stockrt/queue.h/blob/master/sample.c

/*

  // prepare STAILQ head for multiple RetMsg storage
  struct headRetMsgMultiple_s headRetMsgMultiple;

  // Initialize the queue
  STAILQ_INIT(&headRetMsgMultiple);

   FILE *fp;
   char str[60];

   // opening file for reading
   fp = fopen("file.txt" , "r");

   if(fp == NULL) {
      perror("Error opening file");
      return(-1);

   }

   if( fgets (str, 60, fp) != NULL ) {
      // writing content to stdout
      puts(str);
   }

   fclose(fp);

char line[256];
char com[3];

char separators[] = " ";
fgets(line, sizeof(line), fp);

//add or copy
strncpy(&com, p, sizeof(com));    // copy the command string in com

  char input[1024];  /buffer
  char *string[256]; /onerow           // 1) 3 is dangerously small,256 can hold a while;-)

                                // You may want to dynamically allocate the pointers
                                // in a general, robust case.
  char delimit[]=" \t\r\n\v\f"; // 2) POSIX whitespace characters
  int i = 0, j = 0;

  if (fgets(input, sizeof input, stdin)) // 3) fgets() returns NULL on error.
                                        // 4) Better practice to use sizeof
                                        //    input rather hard-coding size
  {
    string[i]=strtok(input,delimit);    // 5) Make use of i to be explicit
    while(string[i]!=NULL)
    {
      printf("string [%d]=%s\n",i,string[i]);
      i++;
      string[i]=strtok(NULL,delimit);
    }

    for (j=0;j<i;j++)
    printf("%s", string[i]);
  }

  return 0;
  }

  char string[] = "Kurt,Kanns;555678;DE";
  char delimiter[] = "\r\n";
  char *ptr;

  // clear, reset global rcvdquit-flag
  clear rcvdquit-flag here

  // initialize strtok, start with first line
  ptr = strtok(string, delimiter);

  while(ptr != NULL) {

	printf("Abschnitt gefunden: %s\n", ptr);

	// call the AnalyzeCommandChainFn, if retMsg != NULL -> head of the ret Msgs
	struct headRetMsgMultiple_s headRetMsgMultipleFromFn
		AnalyzeCommandChain(ptr, strlen(ptr));

	// retMsgMultiple stailq from Fn filled ?
	if (!STAILQ_EMPTY(&headRetMsgMultipleFromFn)) {

		// for the retMsg elements
		strTextMultiple_t *retMsg;

		// get the entries till empty
		while (!STAILQ_EMPTY(&headRetMsgMultipleFromFn)) {

			retMsg = STAILQ_FIRST(&headRetMsgMultipleFromFn);

			// insert retMsg in stail-queue
			STAILQ_INSERT_TAIL(&headRetMsgMultiple, retMsg, entries);

			// done, remove this entry
			STAILQ_REMOVE(&headRetMsgMultipleFromFn, retMsg, strTextMultiple_s, entries);
		}
	}

	// break if global rcvdquit-flag is set
	if (rcvdquit-flag) break;

	// loop through the next lines
 	ptr = strtok(NULL, delimiter);

  }

  // return STAILQ head, it stores multiple RetMsg, if NULL -> no RetMsg-entries
  return headRetMsgMultiple;

seek through file, split lines by '\r\n'
identify multiline commands and add them
call AnalyzeCommandChain with the identified line
push answer(if any) to multiple msg
loop through lines, break if rcvdquit-flag is set

1209	#####################################
1210	sub
1211	CommandInclude($$)
1212	{
1213	  my ($cl, $arg) = @_;			// arg = filename
1214	  my $fh;
1215	  my @ret;
1216	  my $oldcfgfile;
1217
1218	  if(!open($fh, $arg)) {		// arg = filename ��en + fehlermeldung + abrechen
1219	    return "Can't open $arg: $!";
1220	  }

1221	  Log 1, "Including $arg";

1222	  my @t = localtime();
1223	  my $gcfg = ResolveDateWildcards(AttrVal("global", "configfile", ""), @t);
1224	  my $stf  = ResolveDateWildcards(AttrVal("global", "statefile",  ""), @t);

1225	  if(!$init_done && $arg ne $stf && $arg ne $gcfg) {
1226	    my $nr =  $devcount++;
1227	    $comments{$nr}{TEXT} = "include $arg";
1228	    $comments{$nr}{CFGFN} = $currcfgfile		if($currcfgfile ne $gcfg);
1229	  }

1230	  $oldcfgfile  = $currcfgfile;
1231	  $currcfgfile = $arg;
1232

1233	  my $bigcmd = "";
1234	  $rcvdquit = 0;
1235	  while(my $l = <$fh>) {

		// search for linereturn
1236	  	$l =~ s/[\r\n]//g;
1237
		// add multiline commands
1238	        if ($l =~ m/^(.*)\\ *$/) {       # Multiline commands
1239	      		$bigcmd .= "$1\n";
1240	        }

		else {
1241	      		my $tret = AnalyzeCommandChain($cl, $bigcmd . $l);
1242	     		push @ret, $tret if(defined($tret));
1243	      		$bigcmd = "";
1244	        }

1245	    last if($rcvdquit);
1246
1247	  }

1248	  $currcfgfile = $oldcfgfile;
1249	  close($fh);
1250	  return join("\n", @ret) if(@ret);
1251	  return undef;
1252	}

*/


text:
<?php

namespace Tests\Feature;

use Tests\TestCase;
use Tests\Traits\UserInfoDataProvider;
use App\Models\User;

class UserModelTest extends TestCase
{
    use UserInfoDataProvider;

    /**
     * @dataProvider userInfoProvider
     */
    public function test_user_attributes($name, $email, $password)
    {
        $user = User::factory()->make([
            'name'     => $name,
            'email'    => $email,
            'password' => $password
        ]);

        $this->assertEquals($name, $user->name);
        $this->assertEquals($email, $user->email);
        $this->assertEquals($password, $user->password);
    }
}


text:
Voice recognition and visualization demo.

## Running locally

* Run `python server.py` from the root directory
* Navigate to [https://localhost:8000](https://localhost:8000) in your browser
* Start talking!

Note: if you get an SSL error, try running `generate_cert.sh` and following the
prompts. This will generate a new certificate for the https server to use. This
is not secure, but it's necessary to avoid having to re-enable the microphone
every few seconds (allowing the voice recognition to run continuously)

## Team Members

Greg Blaszczuk : Word cloud rendering, frequency calculation
Martin Wozniewicz : Speech recognition, https server


text:
package co.cask.hydrator.transforms;

import co.cask.cdap.api.annotation.Description;
import co.cask.cdap.api.annotation.Name;
import co.cask.cdap.api.annotation.Plugin;
import co.cask.cdap.api.data.format.StructuredRecord;
import co.cask.cdap.api.data.schema.Schema;
import co.cask.cdap.api.plugin.PluginConfig;
import co.cask.cdap.etl.api.Emitter;
import co.cask.cdap.etl.api.PipelineConfigurer;
import co.cask.cdap.etl.api.Transform;

import java.util.List;

@Plugin(type = "transform")
@Name("CloneRows")
@Description("Creates copies (clones) of a row and outputs them directly after the original row to the next steps.")
public final class CloneRows extends Transform<StructuredRecord, StructuredRecord> {
  private final Config config;

  // Required only for testing.
  public CloneRows(Config config) {
    this.config = config;
  }

  @Override
  public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException {
    super.configurePipeline(pipelineConfigurer);
    if(config.copies == 0 || config.copies > Integer.MAX_VALUE) {
      throw new IllegalArgumentException("Number of copies specified '" + config.copies + "' is incorrect. Specify " +
                                       "proper integer range");
    }
  }

  @Override
  public void transform(StructuredRecord in, Emitter<StructuredRecord> emitter) throws Exception {
    List<Schema.Field> fields = in.getSchema().getFields();
    for(int i = 0; i < config.copies; ++i) {
      StructuredRecord.Builder builder = StructuredRecord.builder(in.getSchema());
      for(Schema.Field field : fields) {
        String name = field.getName();
        builder.set(name, in.get(name));
      }
      emitter.emit(builder.build());
    }
  }

  /**
   * Clone rows plugin configuration.
   */
  public static class Config extends PluginConfig {
    @Name("copies")
    @Description("Specifies number of copies to be made of every row.")
    private final int copies;

    public Config(int copies) {
      this.copies = copies;
    }

  }
}


text:
// @file sock.h

#pragma once

#include "mongo/pch.h"

#include <stdio.h>

#ifndef _WIN32

#include <sys/socket.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <errno.h>

#ifdef __openbsd__
# include <sys/uio.h>
#endif

#endif // not _WIN32

#ifdef MONGO_SSL
#include <openssl/ssl.h>
#endif

#include "mongo/platform/compiler.h"

namespace mongo {

    class SSLManagerInterface;

    const int SOCK_FAMILY_UNKNOWN_ERROR=13078;

    void disableNagle(int sock);

#if defined(_WIN32)

    typedef short sa_family_t;
    typedef int socklen_t;

    // This won't actually be used on windows
    struct sockaddr_un {
        short sun_family;
        char sun_path[108]; // length from unix header
    };

#else // _WIN32

    inline void closesocket(int s) { close(s); }
    const int INVALID_SOCKET = -1;
    typedef int SOCKET;

#endif // _WIN32

    string makeUnixSockPath(int port);

    // If an ip address is passed in, just return that.  If a hostname is passed
    // in, look up its ip and return that.  Returns "" on failure.
    string hostbyname(const char *hostname);

    void enableIPv6(bool state=true);
    bool IPv6Enabled();
    void setSockTimeouts(int sock, double secs);

    /**
     * wrapped around os representation of network address
     */
    struct SockAddr {
        SockAddr() {
            addressSize = sizeof(sa);
            memset(&sa, 0, sizeof(sa));
            sa.ss_family = AF_UNSPEC;
        }
        SockAddr(int sourcePort); /* listener side */
        SockAddr(const char *ip, int port); /* EndPoint (remote) side, or if you want to specify which interface locally */

        template <typename T> T& as() { return *(T*)(&sa); }
        template <typename T> const T& as() const { return *(const T*)(&sa); }

        string toString(bool includePort=true) const;

        /**
         * @return one of AF_INET, AF_INET6, or AF_UNIX
         */
        sa_family_t getType() const;

        unsigned getPort() const;

        string getAddr() const;

        bool isLocalHost() const;

        bool operator==(const SockAddr& r) const;

        bool operator!=(const SockAddr& r) const;

        bool operator<(const SockAddr& r) const;

        const sockaddr* raw() const {return (sockaddr*)&sa;}
        sockaddr* raw() {return (sockaddr*)&sa;}

        socklen_t addressSize;
    private:
        struct sockaddr_storage sa;
    };

    extern SockAddr unknownAddress; // ( "0.0.0.0", 0 )

    /** this is not cache and does a syscall */
    string getHostName();

    /** this is cached, so if changes during the process lifetime
     * will be stale */
    string getHostNameCached();

    string prettyHostName();

    /**
     * thrown by Socket and SockAddr
     */
    class SocketException : public DBException {
    public:
        const enum Type { CLOSED , RECV_ERROR , SEND_ERROR, RECV_TIMEOUT, SEND_TIMEOUT, FAILED_STATE, CONNECT_ERROR } _type;

        SocketException( Type t , const std::string& server , int code = 9001 , const std::string& extra="" )
            : DBException( (string)"socket exception ["  + _getStringType( t ) + "] for " + server, code ),
              _type(t),
              _server(server),
              _extra(extra)
        {}

        virtual ~SocketException() throw() {}

        bool shouldPrint() const { return _type != CLOSED; }
        virtual string toString() const;
        virtual const std::string* server() const { return &_server; }
    private:

        // TODO: Allow exceptions better control over their messages
        static string _getStringType( Type t ){
            switch (t) {
                case CLOSED:        return "CLOSED";
                case RECV_ERROR:    return "RECV_ERROR";
                case SEND_ERROR:    return "SEND_ERROR";
                case RECV_TIMEOUT:  return "RECV_TIMEOUT";
                case SEND_TIMEOUT:  return "SEND_TIMEOUT";
                case FAILED_STATE:  return "FAILED_STATE";
                case CONNECT_ERROR: return "CONNECT_ERROR";
                default:            return "UNKNOWN"; // should never happen
            }
        }

        string _server;
        string _extra;
    };

    /**
     * thin wrapped around file descriptor and system calls
     * todo: ssl
     */
    class Socket : boost::noncopyable {
    public:

        static const int errorPollIntervalSecs;

        Socket(int sock, const SockAddr& farEnd);

        /** In some cases the timeout will actually be 2x this value - eg we do a partial send,
            then the timeout fires, then we try to send again, then the timeout fires again with
            no data sent, then we detect that the other side is down.

            Generally you don't want a timeout, you should be very prepared for errors if you set one.
        */
        Socket(double so_timeout = 0, int logLevel = 0 );

        ~Socket();

        bool connect(SockAddr& farEnd);
        void close();

        void send( const char * data , int len, const char *context );
        void send( const vector< pair< char *, int > > &data, const char *context );

        // recv len or throw SocketException
        void recv( char * data , int len );
        int unsafe_recv( char *buf, int max );

        int getLogLevel() const { return _logLevel; }
        void setLogLevel( int ll ) { _logLevel = ll; }

        SockAddr remoteAddr() const { return _remote; }
        string remoteString() const { return _remote.toString(); }
        unsigned remotePort() const { return _remote.getPort(); }

        void clearCounters() { _bytesIn = 0; _bytesOut = 0; }
        long long getBytesIn() const { return _bytesIn; }
        long long getBytesOut() const { return _bytesOut; }

        void setTimeout( double secs );
        bool isStillConnected();

#ifdef MONGO_SSL
        /** secures inline */
        void secure( SSLManagerInterface* ssl );

        void secureAccepted( SSLManagerInterface* ssl );
#endif

        /**
         * This function calls SSL_accept() if SSL-encrypted sockets
         * are desired. SSL_accept() waits until the remote host calls
         * SSL_connect().
         * This function may throw SocketException.
         */
        void doSSLHandshake();

        /**
         * @return the time when the socket was opened.
         */
        uint64_t getSockCreationMicroSec() const {
            return _fdCreationMicroSec;
        }

    private:
        void _init();

        /** sends dumbly, just each buffer at a time */
        void _send( const vector< pair< char *, int > > &data, const char *context );

        /** raw send, same semantics as ::send */
        int _send( const char * data , int len );

        /** raw recv, same semantics as ::recv */
        int _recv( char * buf , int max );

        void _handleRecvError(int ret, int len, int* retries);
        MONGO_COMPILER_NORETURN void _handleSendError(int ret, const char* context);

        int _fd;
        uint64_t _fdCreationMicroSec;
        SockAddr _remote;
        double _timeout;

        long long _bytesIn;
        long long _bytesOut;
        time_t _lastValidityCheckAtSecs;

#ifdef MONGO_SSL
        SSL* _ssl;
        SSLManagerInterface* _sslManager;
#endif
        int _logLevel; // passed to log() when logging errors

    };

} // namespace mongo


text:
package org.drools.workbench.screens.scenariosimulation.client.rightpanel;

import elemental2.dom.DomGlobal;
import elemental2.dom.HTMLElement;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.Templated;

/**
 * This class is used to represent a single row in the coverage decision/rule section
 */
@Templated
public class CoverageElementViewImpl implements CoverageElementView {

    @DataField
    protected HTMLElement description = (HTMLElement) DomGlobal.document.createElement("dt");

    @DataField
    protected HTMLElement numberOfTime = (HTMLElement) DomGlobal.document.createElement("dd");

    @Override
    public void setDescriptionValue(String description) {
        this.description.textContent = description;
    }

    @Override
    public void setElementValue(String numberOfTime) {
        this.numberOfTime.textContent = numberOfTime;
    }

    @Override
    public HTMLElement getDescription() {
        return description;
    }

    @Override
    public HTMLElement getNumberOfTime() {
        return numberOfTime;
    }
}


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

namespace Microsoft.Azure.Commands.Relay.Test.ScenarioTests
{
    using Microsoft.WindowsAzure.Commands.ScenarioTest;
    using Microsoft.WindowsAzure.Commands.Test.Utilities.Common;
    using ServiceManagemenet.Common.Models;
    using Xunit;
    using Xunit.Abstractions;
    public class TestAzureRmRelayNameTests : RMTestBase
    {
        public XunitTracingInterceptor _logger;

        public TestAzureRmRelayNameTests(ITestOutputHelper output)
        {
            _logger = new XunitTracingInterceptor(output);
            XunitTracingInterceptor.AddToContext(_logger);
        }

        [Fact(Skip = "Need service team to re-record test after changes to the ClientRuntime.")]
        [Trait(Category.AcceptanceType, Category.CheckIn)]
        [Trait("Re-record", "ClientRuntime changes")]
        public void CheckNameAvailability()
        {
            RelayController.NewInstance.RunPsTest(_logger, "TestAzureRmRelayNameTests");
        }
    }
}


text:
package com.cloud.migration;

import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import javax.persistence.Transient;

import com.cloud.offering.ServiceOffering;

@Entity
@Table(name="service_offering_21")
@DiscriminatorValue(value="Service")
@PrimaryKeyJoinColumn(name="id")
public class ServiceOffering21VO extends DiskOffering21VO implements ServiceOffering {
    @Column(name="cpu")
	private int cpu;

    @Column(name="speed")
    private int speed;

    @Column(name="ram_size")
	private int ramSize;

    @Column(name="nw_rate")
    private Integer rateMbps;

    @Column(name="mc_rate")
    private Integer multicastRateMbps;

    @Column(name="ha_enabled")
    private boolean offerHA;

    @Column(name="host_tag")
    private String hostTag;

    protected ServiceOffering21VO() {
        super();
    }

    public ServiceOffering21VO(String name, int cpu, int ramSize, int speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, boolean useLocalStorage, boolean recreatable, String tags) {
        super(name, displayText, false, tags, recreatable, useLocalStorage);
        this.cpu = cpu;
        this.ramSize = ramSize;
        this.speed = speed;
        this.rateMbps = rateMbps;
        this.multicastRateMbps = multicastRateMbps;
        this.offerHA = offerHA;
    }

    public ServiceOffering21VO(String name, int cpu, int ramSize, int speed, Integer rateMbps, Integer multicastRateMbps, boolean offerHA, String displayText, boolean useLocalStorage, boolean recreatable, String tags, String hostTag) {
    	this(name, cpu, ramSize, speed, rateMbps, multicastRateMbps, offerHA, displayText, useLocalStorage, recreatable, tags);
       	this.hostTag = hostTag;
    }

	@Override
	public boolean getOfferHA() {
	    return offerHA;
	}

	@Override
	public boolean getLimitCpuUse() {
	    return false;
	}

	public void setOfferHA(boolean offerHA) {
		this.offerHA = offerHA;
	}

	@Override
    @Transient
	public String[] getTagsArray() {
	    String tags = getTags();
	    if (tags == null || tags.length() == 0) {
	        return new String[0];
	    }

	    return tags.split(",");
	}

	@Override
	public int getCpu() {
	    return cpu;
	}

	public void setCpu(int cpu) {
		this.cpu = cpu;
	}

	public void setSpeed(int speed) {
		this.speed = speed;
	}

	public void setRamSize(int ramSize) {
		this.ramSize = ramSize;
	}

	@Override
	public int getSpeed() {
	    return speed;
	}

	@Override
	public int getRamSize() {
	    return ramSize;
	}

	public void setRateMbps(Integer rateMbps) {
		this.rateMbps = rateMbps;
	}

	@Override
    public Integer getRateMbps() {
		return rateMbps;
	}

	public void setMulticastRateMbps(Integer multicastRateMbps) {
		this.multicastRateMbps = multicastRateMbps;
	}

	@Override
    public Integer getMulticastRateMbps() {
		return multicastRateMbps;
	}

	public String gethypervisorType() {
		return null;
	}

	public void setHostTag(String hostTag) {
		this.hostTag = hostTag;
	}

	public String getHostTag() {
		return hostTag;
	}

    @Override
    public boolean getDefaultUse() {
        return false;
    }

    @Override
    public String getSystemVmType() {
        return null;
    }

    @Override
    public String getUuid() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean getVolatileVm() {
        return false;
    }

    @Override
    public String getDeploymentPlanner() {
        // TODO Auto-generated method stub
        return null;
    }

}


text:
package uk.org.cowgill.james.jircd.commands;

import uk.org.cowgill.james.jircd.Client;
import uk.org.cowgill.james.jircd.Command;
import uk.org.cowgill.james.jircd.Message;

/**
 * The QUIT command - quits the IRC server
 *
 * @author James
 */
public class Quit implements Command
{
	@Override
	public void run(Client client, Message msg)
	{
		//Construct quit message
		String quitMsg;
		if(msg.paramCount() == 0)
		{
			quitMsg = client.id.nick;
		}
		else
		{
			quitMsg = msg.getParam(0);
		}

		client.close(quitMsg);
	}

	@Override
	public int getMinParameters()
	{
		return 0;
	}

	@Override
	public String getName()
	{
		return "QUIT";
	}

	@Override
	public int getFlags()
	{
		return FLAG_NORMAL | FLAG_REGISTRATION;
	}
}