text:
======================
django-shop-categories
======================

A extendable category app using django-mptt for django-shop.

.. image:: https://travis-ci.org/fivethreeo/django-shop-categories.png?branch=develop
   :target: https://travis-ci.org/fivethreeo/django-shop-categories

Installation
------------

For the current stable version:

::

    pip install django-shop-categories

For the development version:

::

    pip install -e git+git://github.com/fivethreeo/django-shop-categories.git#egg=django-shop-categories

Running tests:

::

    git clone git://github.com/fivethreeo/django-shop-categories.git
    cd django-shop-categories
    virtualenv test_env
    source ./test_env/bin/activate
    pip install -r requirements.txt
    python runtests.py

Configuration
-------------

Add ``shop_categories`` and ``treeadmin`` to ``settings.INSTALLED_APPS``.

Set ``SHOP_PRODUCT_MODEL`` to ``shop_categories.models.defaults.product.default.CategoryProduct``.

In your urls.py add this **before** your shop patterns:

::

    urlpatterns += patterns('',
        url(r'^catalog/', include('shop_categories.urls')),
    )

Then run:

::

    manage.py syncdb

Extending the Category model
----------------------------

In your own app make a models dir with __init__.py and a category.py dir, like so:

::

    app/models/__init__.py
    app/models/category.py

Note: Do not import the model from category.py in __init__.py, the model should NOT be in a "real" models module as this will cause the overridden Category model to be defined twice.

In category.py:

::

    from django.db import models
    from shop_categories.models.defaults.category.base import ProductCategoryBase

    class Category(ProductCategoryBase):

        image = models.ImageField(upload_to='categoryimages/', null=True, blank=True)

        class Meta:
            abstract = False
            app_label = 'app'

Set ``SHOP_CATEGORIES_CATEGORY_MODEL`` to ``('app.models.category.Category, 'app')``

Register your custom category model in admin.py:

::

    from shop_categories.models import Category
    from shop_categories.admin import ProductCategoryAdmin

    admin.site.register(Category, ProductCategoryAdmin)

Then, assuming your Product model is not already synced, run:

::

    manage.py syncdb

Extending the Product model
----------------------------

When extending Product models in your shop make sure they subclass from ``shop_categories.models.defaults.product.base.CategoryProductBase`` to add the Category Foreignkey and M2M fields.

Example implementation
----------------------
An example of a django-shop with django-shop-categories can be found here: https://github.com/fivethreeo/django-shop-example


text:
package main

import (
	"encoding/json"
	"fmt"
)

// Dump proints propperly formated JSON
func Dump(obj interface{}) {
	result, _ := json.MarshalIndent(obj, "", "\t")
	fmt.Println(string(result))
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * LoginForm is the model behind the login form.
 */
class LoginForm extends Model
{
    public $user_email;
    public $user_password;
    public $rememberMe = true;

    private $_user = false;

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            [['user_email', 'user_password'], 'required'],
            ['rememberMe', 'boolean'],
            ['user_password', 'validatePassword'],
        ];
    }

    public function attributeLabels() {
        return [
            'user_email' => 'Email',
            'user_password' => 'Password'
        ];
    }

    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();

            if (!$user || !$user->validatePassword($this->user_password)) {
                $this->addError($attribute, 'Incorrect username or password.');
            }
        }
    }

    public function login()
    {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
        }
        return false;
    }

    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::findByEmail($this->user_email);
        }

        return $this->_user;
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /home/gerard/sites/modules.w.doctrine/modules.zendframework.com/vendor/ZF2/library/Zend/Stdlib/Hydrator/ClassMethods.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

/home/gerard/sites/modules.w.doctrine/modules.zendframework.com /

vendor /

ZF2 /

library /

Zend /

Stdlib /

Hydrator /

ClassMethods.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

0.00%

0 / 1

25.00%

1 / 4

      CRAP

6.52%

3 / 46

      ClassMethods

0.00%

0 / 1

25.00%

1 / 4

      151.04

6.52%

3 / 46

       __construct($underscoreSeparatedKeys = true)

100.00%

1 / 1

      1

100.00%

3 / 3

       extract($object)

0.00%

0 / 1

      42

0.00%

0 / 24

       anonymous function($letters)

0.00%

0 / 1

      2

0.00%

0 / 4

       hydrate(array $data, $object)

0.00%

0 / 1

      30

0.00%

0 / 4

1
	<?php

2

10

11
	namespace Zend\Stdlib\Hydrator;

12

13
	use Zend\Stdlib\Exception;

14

15
	/**

16
	 * @category   Zend

17
	 * @package    Zend_Stdlib

18
	 * @subpackage Hydrator

19
	 */

20
	class ClassMethods extends AbstractHydrator

21
	{

22
	    /**

23
	     * Flag defining whether array keys are underscore-separated (true) or camel case (false)

24
	     * @var boolean

25
	     */

26
	    protected $underscoreSeparatedKeys;

27

28
	    /**

29
	     * Define if extract values will use camel case or name with underscore

30
	     * @param boolean $underscoreSeparatedKeys

31
	     */

32
	    public function __construct($underscoreSeparatedKeys = true)

33
	    {

34
	        parent::__construct();

35
	        $this->underscoreSeparatedKeys = $underscoreSeparatedKeys;

36
	    }

37

38
	    /**

39
	     * Extract values from an object with class methods

40
	     *

41
	     * Extracts the getter/setter of the given $object.

42
	     *

43
	     * @param  object $object

44
	     * @return array

45
	     * @throws Exception\BadMethodCallException for a non-object $object

46
	     */

47
	    public function extract($object)

48
	    {

49
	        if (!is_object($object)) {

50
	            throw new Exception\BadMethodCallException(sprintf(

51
	                '%s expects the provided $object to be a PHP object)', __METHOD__

52
	            ));

53
	        }

54

55
	        $transform = function($letters) {

56
	            $letter = array_shift($letters);

57
	            return '_' . strtolower($letter);

58
	        };

59
	        $attributes = array();

60
	        $methods = get_class_methods($object);

61

62
	        foreach ($methods as $method) {

63
	            if (!preg_match('/^(get|has|is)[A-Z]\w*/', $method)) {

64
	                continue;

65
	            }

66

67
	            $attribute = $method;

68
	            if (preg_match('/^get/', $method)) {

69
	                $attribute = substr($method, 3);

70
	                $attribute = lcfirst($attribute);

71
	            }

72

73
	            if ($this->underscoreSeparatedKeys) {

74
	                $attribute = preg_replace_callback('/([A-Z])/', $transform, $attribute);

75
	            }

76
	            $attributes[$attribute] = $this->extractValue($attribute, $object->$method());

77
	        }

78

79
	        return $attributes;

80
	    }

81

82
	    /**

83
	     * Hydrate an object by populating getter/setter methods

84
	     *

85
	     * Hydrates an object by getter/setter methods of the object.

86
	     *

87
	     * @param  array $data

88
	     * @param  object $object

89
	     * @return object

90
	     * @throws Exception\BadMethodCallException for a non-object $object

91
	     */

92
	    public function hydrate(array $data, $object)

93
	    {

94
	        if (!is_object($object)) {

95
	            throw new Exception\BadMethodCallException(sprintf(

96
	                '%s expects the provided $object to be a PHP object)', __METHOD__

97
	            ));

98
	        }

99

100
	        $transform = function($letters) {

101
	            $letter = substr(array_shift($letters), 1, 1);

102
	            return ucfirst($letter);

103
	        };

104

105
	        foreach ($data as $property => $value) {

106
	            if ($this->underscoreSeparatedKeys) {

107
	                $property = preg_replace_callback('/(_[a-z])/', $transform, $property);

108
	            }

109
	            $method = 'set' . ucfirst($property);

110
	            if (method_exists($object, $method)) {

111
	                $value = $this->hydrateValue($property, $value);

112

113
	                $object->$method($value);

114
	            }

115
	        }

116
	        return $object;

117
	    }

118
	}

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 1.2.13 using PHP 5.3.10-1ubuntu3.8 and PHPUnit 3.7.27 at Sat Oct 12 3:31:18 CEST 2013.


text:
<!DOCTYPE>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>MyTest</title>
        <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.min.css">
        <link rel="stylesheet" href="bower_components/normalize-css/normalize.css">
        <link rel="stylesheet" href="css/style.css">

                        <?php
                        if(isset($_GET['t'])):
                            require_once('../back/connect.php');
                            $getUser = $conn->prepare('SELECT * FROM users WHERE token=:token');
                            $getUser->execute(['token' => $_GET['t']]);
                            $user = $getUser->fetch();

                        if($user && $user['status'] != 1):
                            $active = $conn->prepare('UPDATE users SET status=:status WHERE id=:id');
                            $active->execute(['status' => 1, 'id' => $user['id']]);

                        ?>

Parabéns <?php echo $user['name']; ?>, sua conta foi ativada com sucesso!

                            Entrar
                        <?php else: ?>

Link inválido!

                        <?php
                            endif;
                        else:
                            header("Location: 404.html");
                        endif;

                        ?>


text:
<?php

error_reporting(E_ALL);
set_time_limit(0);

date_default_timezone_set('Europe/London');

?>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<title>PHPExcel Reader Example #13</title>

PHPExcel Reader Example #13

Simple File Reader for Multiple CSV Files

<?php

/** Include path **/
set_include_path(get_include_path() . PATH_SEPARATOR . '../../../Classes/');

/** PHPExcel_IOFactory */
include 'PHPExcel/IOFactory.php';

$inputFileType = 'CSV';
$inputFileNames = array('./sampleData/example1.csv','./sampleData/example2.csv');

$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$inputFileName = array_shift($inputFileNames);
echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' into WorkSheet #1 using IOFactory with a defined reader type of ',$inputFileType,'
';
$objPHPExcel = $objReader->load($inputFileName);
$objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
foreach($inputFileNames as $sheet => $inputFileName) {
	echo 'Loading file ',pathinfo($inputFileName,PATHINFO_BASENAME),' into WorkSheet #',($sheet+2),' using IOFactory with a defined reader type of ',$inputFileType,'
';
	$objReader->setSheetIndex($sheet+1);
	$objReader->loadIntoExisting($inputFileName,$objPHPExcel);
	$objPHPExcel->getActiveSheet()->setTitle(pathinfo($inputFileName,PATHINFO_BASENAME));
}

echo '
';

echo $objPHPExcel->getSheetCount(),' worksheet',(($objPHPExcel->getSheetCount() == 1) ? '' : 's'),' loaded

';
$loadedSheetNames = $objPHPExcel->getSheetNames();
foreach($loadedSheetNames as $sheetIndex => $loadedSheetName) {
	echo 'Worksheet #',$sheetIndex,' -> ',$loadedSheetName,'
';
	$objPHPExcel->setActiveSheetIndexByName($loadedSheetName);
	$sheetData = $objPHPExcel->getActiveSheet()->toArray(null,true,true,true);
	var_dump($sheetData);
	echo '

';
}

?>


text:
<component name="ProjectDictionaryState">
  <dictionary name="ben">
    <words>
      <w>parsable</w>
    </words>
  </dictionary>
</component>


text:
import time
import json
import hmac
import base64
from hashlib import sha1 as sha
import logging
from django.db import transaction
from django import http
from django.http import Http404
from django.http import JsonResponse
from django.urls import reverse
from django.conf import settings
from django.core.paginator import Paginator
from django.views.generic.base import TemplateResponseMixin as DjangoTemplateResponseMixin
from django.core.paginator import EmptyPage, InvalidPage
from django.utils import timezone
from picopico.utils.common import get_time_md5
from picopico.apps.file.models import ALLOWED_EXT

logger = logging.getLogger(__name__)

class RedirectResponseMixin:
    permanent = False
    redirect_url = None
    pattern_name = None
    kwargs = None
    args = None
    use_query_string = False
    redirect_to = 'redirect-to'

    def get_redirect_url(self, *args, **kwargs):
        if self.redirect_url:
            if kwargs:
                url = self.redirect_url % kwargs
            elif self.kwargs:
                url = self.redirect_url % self.kwargs
            else:
                url = self.redirect_url

        elif self.pattern_name:
            url = reverse(self.pattern_name, args=args, kwargs=kwargs)

        elif self.request.GET.get(self.redirect_to, None):
            url = self.request.GET.get(self.redirect_to)

        else:
            return None

        if self.use_query_string:
            args = self.request.META.get('QUERY_STRING', '')

            if args:
                url = "%s?%s" % (url, args)
            if self.args:
                url = "%s?%s" % (url, self.args)

        return url

    def redirect(self, request, *args, **kwargs):
        url = self.get_redirect_url(*args, **kwargs)
        if url:
            if self.permanent:
                return http.HttpResponsePermanentRedirect(url)
            else:
                return http.HttpResponseRedirect(url)
        else:
            return Http404

class JSONResponseMixin:
    @staticmethod
    def render_to_json_response(context, **kwargs):
        return JsonResponse(context, safe=False, **kwargs)

class ContextMixin:
    def get_context_data(self, request, *args, **kwargs):
        pass

    def post_context_data(self, request, *args, **kwargs):
        pass

    def get_json_context_data(self, request, *args, **kwargs):
        pass

    def post_json_context_data(self, request, *args, **kwargs):
        pass

    def put_json_context_data(self, request, *args, **kwargs):
        pass

    def delete_json_context_data(self, request, *args, **kwargs):
        pass

class MessageMixin:
    message_key_name = 'message'

    def add_message_dict(self, data):
        message = self.request.session.get(self.message_key_name, None)
        if message:
            message.update(data)
        else:
            message = data

        self.request.session[self.message_key_name] = message

    def add_message(self, name, value):
        message = self.request.session.get(self.message_key_name, None)
        if message:
            message.update({name: value})
        else:
            message = {name: value}
        self.request.session[self.message_key_name] = message

    def get_message(self):
        message = self.request.session.get(self.message_key_name, None)
        self.request.session[self.message_key_name] = None
        return message

    def render_to_response(self, context, **response_kwargs):
        message = self.get_message()
        if context is None:
            context = {}
        context.update({self.message_key_name: message})
        response_kwargs.setdefault('content_type', self.content_type)
        return self.response_class(
            request=self.request,
            template=self.get_template_names(),
            context=context,
            using=self.template_engine,
            **response_kwargs
        )

class LoginRedirectMixin:
    redirect_url = '/'
    login_redirect = True

    def check_login(self):
        if not self.request.user.is_authenticated():
            return False

        referrer = self.request.META.get('HTTP_REFERER')
        if referrer:
            self.redirect_url = referrer
        else:
            url = self.request.GET.get(self.redirect_to, None)
            if url:
                self.redirect_url = url
            else:
                self.redirect_url = '/'

        return True

class LoginRequiredMixin:
    login_required = True
    redirect_url = '/account/login'

    def check_login_required(self):
        if self.request.user.is_authenticated():
            return False
        else:
            url = self.request.get_full_path()
            self.redirect_url = reverse('account:login') + '?' + self.redirect_to + '=' + url
            return True

class OSSMixin:
    pass

class DOSSMixin:
    """
    this mixin is for direct send file to oss url via browser
    not like the other oss module act like send file to your
    server then your server send the file to oss
    """
    access_id = None
    access_secret = None
    end_point = None
    bucket = None
    use_callback = False
    success_action_redirect = 'https://www.picopico.com.cn'
    success_action_status = 201
    callback_url = 'https://www.picopico.com.cn'
    upload_dir = 'user/'
    expire = 30

    def get_token(self, bucket='picopico', expire=30):
        self.access_id = settings.ALIYUN_ACCESSKEYID
        self.access_secret = settings.ALIYUN_ACCESSKEYSECRET
        self.bucket = bucket
        self.end_point = 'http://' + self.bucket + '.' + settings.ALIYUN_OSS_END_POINT
        self.expire = expire
        return self._get_token()

    def _get_token(self):
        now = int(time.time())
        expire_syncpoint = now + self.expire
        expire = self._get_expire_time(expire_syncpoint)

        policy = {
            'expiration': expire
        }

        condition = []
        upload = ['starts-with', '$key', self.upload_dir]
        condition.append(upload)

        policy['conditions'] = condition
        policy = json.dumps(policy).strip()

        policy_encode = base64.b64encode(policy.encode())
        h = hmac.new(self.access_secret.encode(), policy_encode, sha)
        sign_result = base64.encodebytes(h.digest()).strip()
        user = self.request.user
        file_part_name = self.upload_dir + str(user.id) + '/' + get_time_md5(user.id) + '-'
        filename = file_part_name + '${filename}'
        callback = self._get_callback_body() if self.use_callback else None

        token = {
            'accessid': self.access_id,
            'action': self.end_point,
            'policy': policy_encode,
            'signature': sign_result,
            'expire': expire_syncpoint,
            'key': filename,
            'success_action_redirect': self.success_action_redirect,
            'success_action_status': self.success_action_status,
            'file_part_name': file_part_name
        }

        token.update({'callback': callback}) if self.use_callback else None

        if settings.DEBUG:
            logger.debug(token)
        return token

    @staticmethod
    def get_headers():
        return {'Access-Control-Allow-Methods': 'POST',
                'Access-Control-Allow-Origin': '*',
                }

    @staticmethod
    def _get_expire_time(time_str):
        import datetime
        gmt = datetime.datetime.fromtimestamp(time_str).isoformat()
        gmt += 'Z'
        return gmt

    def _get_callback_body(self):
        callback = {
            'callbackUrl': self.callback_url,
            'callbackHost': '',
            'callbackBody': 'filename=${object}&size=${size}&mimeType=${mimeType}'
                            '&height=${imageInfo.height}&width=${imageInfo.width}',
            'callbackBodyType': 'application/x-www-form-urlencoded'
        }
        callback_json = json.dumps(callback)
        return base64.b64encode(callback_json.encode())

class TemplateResponseMixin(DjangoTemplateResponseMixin):
    def __init__(self):
        pass

    def render_to_response(self, context, **response_kwargs):
        """
        Returns a response, using the `response_class` for this
        view, with a template rendered with the given context.

        If any keyword arguments are provided, they will be
        passed to the constructor of the response class.
        """
        response_kwargs.setdefault('content_type', self.content_type)

        headers = self.get_headers()

        response = self.response_class(
            request=self.request,
            template=self.get_template_names(),
            context=context,
            using=self.template_engine,
            **response_kwargs
        )
        if headers:
            for name, value in headers.items():
                setattr(response, name, value)
        return response

    @staticmethod
    def get_headers():
        return {}

class FilterMixin:
    model_class = None
    query_dict = None
    """
    query_dict = {'age': 'number', 'size': 'number', 'name': 'string'}
    """

    def get_queryset(self, query):
        return self.model_class.objects.filter(query)

    def get_query(self, params):
        from django.db.models import Q
        query = None

        for key in params:
            if key not in self.query_dict and not params.get(key, None):
                continue
            value = params.get(key)
            if query is None:
                query = Q(**{key: value})
            else:
                query = query & Q(**{key: value})

        return query

    def filter(self, params):
        """
        :param params: request.GET or request.POST or some dict like object contains your basic query string
        :return: a django queryset object so that you can do much more filter or pagination
        """
        query = self.get_query(params)
        queryset = self.get_queryset(query)
        return queryset

class PaginationMixin:
    allow_empty_first_page = False
    pagination_class = Paginator
    per_page = 10

    def get_page(self, query_set, page='1'):
        pager = self.pagination_class(query_set, self.per_page, allow_empty_first_page=self.allow_empty_first_page)

        try:
            page_obj = pager.page(page)
        except EmptyPage:
            if '1' == page:
                raise Http404
            else:
                page_obj = pager.page(1)
        except InvalidPage:
            page_obj = pager.page(1)

        return page_obj

class PermissionMixin:
    pass

class FileUploadMixin:
    KB = 1024
    MB = KB * 1024
    max_size = MB * 10  # in bytes, default is 10MB

    file_type = ALLOWED_EXT
    upload_to = 'local'
    path = None
    url = None

    @staticmethod
    def get_file_ext(file):
        ext = ''
        if file:
            ext = file.split('.')[-1]
        return ext

    @staticmethod
    @transaction.atomic
    def save_db(data, request):
        from picopico.apps.file.models import File
        for item in data:
            if request.user.is_authenticated():
                file = File(url=item.get('url', ''), user=request.user)
            else:
                file = File(url=item.get('url', ''))
            file.save()

    def upload(self, request, name='picopico'):
        ret = None

        if 'local' == self.upload_to:
            ret = self._save_to_local(request)

        elif 'oss' == self.upload_to:
            ret = self._save_to_oss(request, name)

        self.save_db(ret, request)
        return ret

    def _save_to_local(self, request):
        from picopico.utils.common import get_time_md5
        path = self.path if self.path else settings.MEDIA_ROOT
        url = self.url if self.url else settings.MEDIA_URL
        ret = []
        for item in request.FILES:
            file = request.FILES.get(item)
            ext = self.get_file_ext(file.name)

            if ext not in self.file_type or file.size > self.max_size:
                continue

            name = get_time_md5(file) + '.' + ext
            date_str = timezone.now().strftime('%Y%m%d')
            dir_name = '/' + date_str

            if request.user.is_authenticated():
                dir_name = '/user/' + str(request.user.id) + '/' + date_str
            path = path + dir_name

            info = {
                'name': name,
                'url': url + dir_name[1:] + '/' + name,
                'size': file.size
            }

            ret.append(info)

            try:
                import os
                os.makedirs(path)
            except OSError:
                pass

            with open(path + '/' + name, 'wb+') as d:
                for chunk in file.chunks():
                    d.write(chunk)
        return ret

    def _save_to_oss(self, request, name):
        from picopico.utils.aliyun.oss import Client
        client = Client(name=name)
        url = self.url if self.url else settings.ALIYUN_OSS_DOMAIN
        ret = []
        for item in request.FILES:
            file = request.FILES.get(item)
            ext = self.get_file_ext(file.name)

            if ext not in self.file_type or file.size > self.max_size:
                continue

            name = get_time_md5(file) + '.' + ext
            date_str = timezone.now().strftime('%Y%m%d')
            file_name = date_str

            if request.user.is_authenticated():
                file_name = 'user/' + request.user.get_id() + '/' + date_str
                oss_name = file_name + '/' + name

            else:
                oss_name = file_name + '/' + name

            info = {
                'name': name,
                'url': 'http://' + url + '/' + oss_name,
                'size': file.size
            }

            ret.append(info)
            client.bucket.put_object(oss_name, file)
        return ret


text:
require "s3rbsync/version"
require "s3rbsync/command"
require "s3rbsync/configure"
require "s3rbsync/synchronizer"
require "s3rbsync/region"

module S3rbsync
  def self.cli_start
    S3rbsync::Command.start
  end
end


text:
include(hunter_add_version)
include(hunter_cacheable)
include(hunter_download)
include(hunter_pick_scheme)

hunter_add_version(
    PACKAGE_NAME
    hunter_box_1
    VERSION
    1.0.0
    URL
    "https://github.com/hunterbox/hunter_box_1/archive/v1.0.0.tar.gz"
    SHA1
    4fa7fe75629f148a61cedc6ba0bce74f177a6747
)

hunter_pick_scheme(DEFAULT url_sha1_cmake)
hunter_cacheable(hunter_box_1)
hunter_download(PACKAGE_NAME hunter_box_1)


text:
#ifndef __SHOW_FILTER_WINDOW_H__
#define __SHOW_FILTER_WINDOW_H__

#include "action/Action.h"
#include "singleton/GuiDescription.h"

class ShowFilterWindow: public Action {

  public:

    ShowFilterWindow() {

      Glib::RefPtr<Gtk::Builder> builder =
        GuiDescription::get_instance()->get_builder();

      // get the dialog ui element
      builder->get_widget("filterWindow", this->filterWindow);
    }

    /*-----------------------------------------------------------------------*/

    virtual void execute() {
      filterWindow->show();
    }

    /*-----------------------------------------------------------------------*/
  private:
    /** ui element for the dialog */
    Gtk::Window* filterWindow;
};

#endif


text:
package main

import (
	"bufio"
	"bytes"
	"encoding/json"
	"path"
	"strings"

	"github.com/mendersoftware/log"
	"github.com/pkg/errors"
)

var (
	identityDataHelper = path.Join(
		getDataDirPath(),
		"identity",
		"mender-device-identity",
	)
)

type IdentityDataGetter interface {
	// obtain identity data as a string or return an error
	Get() (string, error)
}

type IdentityDataRunner struct {
	Helper string
	cmdr   Commander
}

func NewIdentityDataGetter() IdentityDataGetter {
	return &IdentityDataRunner{
		identityDataHelper,
		&osCalls{},
	}
}

// Obtain identity data by calling a suitable helper tool
func (id IdentityDataRunner) Get() (string, error) {
	helper := identityDataHelper

	if id.Helper != "" {
		helper = id.Helper
	}

	cmd := id.cmdr.Command(helper)
	data, err := cmd.Output()

	if err != nil {
		return "", errors.Wrapf(err, "failed to call %s", helper)
	}

	idata, err := parseIdentityData(data)
	if err != nil {
		return "", errors.Wrapf(err, "failed to parse identity data")
	}

	encdata, err := json.Marshal(idata)
	if err != nil {
		return "", errors.Wrapf(err, "failed to encode identity data")
	}

	return string(encdata), nil
}

// device identity data content
type IdentityData map[string]string

func parseIdentityData(data []byte) (interface{}, error) {
	idata := make(IdentityData)

	in := bufio.NewScanner(bytes.NewBuffer(data))
	for in.Scan() {
		line := in.Text()

		if len(line) == 0 {
			continue
		}

		val := strings.SplitN(line, "=", 2)

		if len(val) < 2 {
			return nil, errors.Errorf("incorrect line '%s'", line)
		}

		if _, ok := idata[val[0]]; ok {
			log.Warningf("attribute %v already present in identity data", val[0])
		}
		idata[val[0]] = val[1]
	}

	if len(idata) == 0 {
		return nil, errors.Errorf("no data found")
	}

	return &idata, nil
}


text:
<!DOCTYPE html>

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

    <link rel="stylesheet" href="../bower_components/angular-ui-select/dist/select.min.css">
    <link rel="stylesheet" href="../bower_components/angular-growl-v2/build/angular-growl.css">
    <link rel="styleSheet" href="../bower_components/angular-ui-grid/ui-grid.min.css"/>


text:
package me.sniggle.android.utils.event.location;

import me.sniggle.android.utils.geo.Coords;

/**
 * Event to notify the application of a location change
 */
public final class LocationChangedEvent {

  private final Coords position;

  /**
   *
   * @param position
   *  the Geo Position
   */
  public LocationChangedEvent(Coords position) {
    this.position = position;
  }

  /**
   *
   * @return the Geo Position
   */
  public Coords getPosition() {
    return position;
  }

}


text:
package org.gradle.test.performance.mediummonolithicjavaproject.p30;

import org.gradle.test.performance.mediummonolithicjavaproject.p29.Production599;

import org.junit.Test;
import static org.junit.Assert.*;

public class Test602 {
    Production602 objectUnderTest = new Production602();

    @Test
    public void testProperty0() {
        Production599 value = new Production599();
        objectUnderTest.setProperty0(value);
        assertEquals(value, objectUnderTest.getProperty0());
    }

    @Test
    public void testProperty1() {
        Production600 value = new Production600();
        objectUnderTest.setProperty1(value);
        assertEquals(value, objectUnderTest.getProperty1());
    }

    @Test
    public void testProperty2() {
        Production601 value = new Production601();
        objectUnderTest.setProperty2(value);
        assertEquals(value, objectUnderTest.getProperty2());
    }

    @Test
    public void testProperty3() {
        String value = "value";
        objectUnderTest.setProperty3(value);
        assertEquals(value, objectUnderTest.getProperty3());
    }

    @Test
    public void testProperty4() {
        String value = "value";
        objectUnderTest.setProperty4(value);
        assertEquals(value, objectUnderTest.getProperty4());
    }

    @Test
    public void testProperty5() {
        String value = "value";
        objectUnderTest.setProperty5(value);
        assertEquals(value, objectUnderTest.getProperty5());
    }

    @Test
    public void testProperty6() {
        String value = "value";
        objectUnderTest.setProperty6(value);
        assertEquals(value, objectUnderTest.getProperty6());
    }

    @Test
    public void testProperty7() {
        String value = "value";
        objectUnderTest.setProperty7(value);
        assertEquals(value, objectUnderTest.getProperty7());
    }

    @Test
    public void testProperty8() {
        String value = "value";
        objectUnderTest.setProperty8(value);
        assertEquals(value, objectUnderTest.getProperty8());
    }

    @Test
    public void testProperty9() {
        String value = "value";
        objectUnderTest.setProperty9(value);
        assertEquals(value, objectUnderTest.getProperty9());
    }

}


text:
package org.eigenbase.sql.validate;

import java.util.List;

import org.eigenbase.sql.*;
import org.eigenbase.sql.SqlWithItem;

/** Scope providing the objects that are available after evaluating an item
 * in a WITH clause.
 *
 *
For example, in

 *
 *
{@code WITH t1 AS (q1) t2 AS (q2) q3}

 *
 *
{@code t1} provides a scope that is used to validate {@code q2}
 * (and therefore {@code q2} may reference {@code t1}),
 * and {@code t2} provides a scope that is used to validate {@code q3}
 * (and therefore q3 may reference {@code t1} and {@code t2}).

 */
class WithScope extends ListScope {
  private final SqlWithItem withItem;

  /** Creates a WithScope. */
  WithScope(SqlValidatorScope parent, SqlWithItem withItem) {
    super(parent);
    this.withItem = withItem;
  }

  public SqlNode getNode() {
    return withItem;
  }

  @Override
  public SqlValidatorNamespace getTableNamespace(List<String> names) {
    if (names.size() == 1 && names.get(0).equals(withItem.name.getSimple())) {
      return validator.getNamespace(withItem);
    }
    return super.getTableNamespace(names);
  }

  @Override
  public SqlValidatorNamespace resolve(String name,
      SqlValidatorScope[] ancestorOut,
      int[] offsetOut) {
    if (name.equals(withItem.name.getSimple())) {
      return validator.getNamespace(withItem);
    }
    return super.resolve(name, ancestorOut, offsetOut);
  }
}

// End WithScope.java


text:
#ifndef Magnum_Primitives_Square_h
#define Magnum_Primitives_Square_h

/** @file
 * @brief Class @ref Magnum::Primitives::Square
 */

#include "Magnum/Primitives/visibility.h"
#include "Magnum/Trade/Trade.h"

namespace Magnum { namespace Primitives {

/**
@brief 2D square primitive

2x2 square.
@see @ref Plane
*/
class MAGNUM_PRIMITIVES_EXPORT Square {
    public:
        /** @brief Whether to generate texture coordinates */
        enum class TextureCoords: UnsignedByte {
            DontGenerate,    /**< Don't generate texture coordinates */

            /** Generate texture coordinates with origin in bottom left corner. */
            Generate
        };

        /**
         * @brief Solid square
         *
         * Non-indexed @ref MeshPrimitive::TriangleStrip.
         */
        static Trade::MeshData2D solid(TextureCoords textureCoords = TextureCoords::DontGenerate);

        /**
         * @brief Wireframe square
         *
         * Non-indexed @ref MeshPrimitive::LineLoop.
         */
        static Trade::MeshData2D wireframe();

        Square() = delete;
};

}}

#endif


text:
class CreateWallets < ActiveRecord::Migration[5.1]
  def change
    create_table :wallets do |t|
      t.decimal :limit, :decimal, precision: 8, scale: 2, default: 0
      t.belongs_to :user, index: true

      t.timestamps
    end
  end
end


text:
<!DOCTYPE html>

契約主文

				<input type="text" class="form-control userInput" placeholder="工程名稱" aria-describedby="basic-addon2" id="eng_name">

				 <input type="text" class="form-control userInput" placeholder="業主(甲方)" aria-describedby="basic-addon2" id="owner">

				<input type="text" class="form-control userInput" placeholder="廠商(乙方)" aria-describedby="basic-addon2" id="company">

				<input type="text" class="form-control userInput" placeholder="業主代表人" aria-describedby="basic-addon2" id="owner_pic">

				<input type="text" class="form-control userInput" placeholder="廠商代表人" aria-describedby="basic-addon2" id="company_pic">

				<input type="text" class="form-control userInput" placeholder="設計單位" aria-describedby="basic-addon2" id="du">

				<input type="text" class="form-control userInput" placeholder="監造單位" aria-describedby="basic-addon2" id="su">

				<input type="text" class="form-control userInput" placeholder="專案管理單位" aria-describedby="basic-addon2" id="pmu">

				<input type="text" class="form-control userInput" placeholder="契約編號" aria-describedby="basic-addon2" id="prj_no">

				<input type="text" class="form-control userInput" placeholder="工程地點" aria-describedby="basic-addon2" id="eng_place">

				<input type="text" class="form-control userInput inputNumberOnly" placeholder="契約總價" aria-describedby="basic-addon2" id="prj_tp">

					<input type="text" class="form-control userInput date" placeholder="開工日期" aria-describedby="basic-addon2" id="sdate">

						<input id="work-month" type="radio" checked="checked">
						日曆天

						<input id="work-workday" type="radio">
						工作天

				<input type="number" class="form-control userInput inputNumberOnly" placeholder="工期" aria-describedby="basic-addon2" id="duration">

				<input type="number" class="form-control userInput inputNumberOnly" placeholder="估驗計價(以日為單位)" aria-describedby="basic-addon2" id="tv">

				<input type="text" class="form-control userInput" placeholder="進度落後(%)" aria-describedby="basic-addon2" id="bs">

				<input type="number" class="form-control userInput inputNumberOnly" placeholder="懲罰性違約金" aria-describedby="basic-addon2" id="pd">

				<input type="text" class="form-control userInput" placeholder="逾期罰款每日金額(‰,千分比)" aria-describedby="basic-addon2" id="penalty">

				<input type="number" class="form-control userInput inputNumberOnly" placeholder="預付款" aria-describedby="basic-addon2" id="ap">

				<input type="text" class="form-control userInput" placeholder="保留款比例(%)" aria-describedby="basic-addon2" id="rmp">

				<input type="text" class="form-control userInput" placeholder="保固金比例(%)" aria-describedby="basic-addon2" id="dp">

					<button type="button" class="btn btn-success col-xs-6 col-md-6" onclick="getInput();">儲存</button>
					<button type="button" class="btn btn-default col-xs-6 col-md-6 btn-color-bk">取消</button>


text:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import json
from builder.helper import get_tensor_size
from tensorflow.examples.tutorials.mnist import input_data
import os
import datetime
import math

VALIDATION_SIZE = 5000
mnist = input_data.read_data_sets('MNIST_data', one_hot=False, reshape=False, validation_size=VALIDATION_SIZE)

class Network:
    """A nerual network build from a JSON specification."""

    def __init__(self, json_network_spec, test=False):

        self.network_spec = json.loads(json_network_spec)
        if self.network_spec['max_number_of_iterations'] % self.network_spec['validate_each_n_steps'] != 0:
            raise(ValueError('max_number_of_iterations is no multiple of validate_each_n_steps.'))
        self.x = None
        self.y_ = None
        self.loss = None
        self.accuracy = None
        self.train_op = None
        self._build_network()
        self._test = test

    def evaluate(self, get_weights=False):
        """Evaluate performance of network.

        Returns:
            The accuracy on the validation data.
        """

        merged_summary = tf.summary.merge_all()
        # Time when starting the training.
        start_time = datetime.datetime.now()
        # Arrays for storing intermediate results.
        losses = np.zeros(self.network_spec['max_number_of_iterations'] // self.network_spec['validate_each_n_steps'])
        accuracies = np.zeros(self.network_spec['max_number_of_iterations'] // self.network_spec['validate_each_n_steps'])
        with tf.Session() as sess:
            if(get_weights):
                saver = tf.train.Saver()
            writer = tf.summary.FileWriter(self.network_spec['logdir'], graph=sess.graph)
            sess.run(tf.global_variables_initializer())
            for i in range(self.network_spec['max_number_of_iterations']):
                batch = mnist.train.next_batch(self.network_spec['hyperparameters']['batchsize'])
                self.train_op.run(feed_dict={self.x: batch[0], self.y_: batch[1]})
                if i % self.network_spec['validate_each_n_steps'] == 0:
                    # Write summary and save data for plots.
                    summary, accuracy_val, loss_val = sess.run([merged_summary, self.accuracy, self.loss],
                                                               feed_dict={self.x: batch[0], self.y_: batch[1]})
                    writer.add_summary(summary, global_step=i)
                    losses[int(i / self.network_spec['validate_each_n_steps'])] = loss_val
                    accuracies[int(i / self.network_spec['validate_each_n_steps'])] = accuracy_val

                    # Check whether training has taken too long.
                    if (datetime.datetime.now() - start_time).seconds // 60 > self.network_spec['max_runtime']:
                        break
            writer.close()
            # Since data is to big to fit in GPU, split data into chunks of 1000 and calculate the mean.
            chunk_size = 1000
            steps = int(VALIDATION_SIZE / chunk_size)
            validation_accuracies = np.zeros(steps)
            if not self._test:
                for i in range(steps):
                    validation_accuracies[i] = sess.run(
                        self.accuracy,
                        feed_dict={self.x: mnist.validation.images[i * chunk_size:(i+1) * chunk_size],
                                   self.y_: mnist.validation.labels[i * chunk_size:(i+1) * chunk_size]}
                    )
            else:
                for i in range(steps):
                    validation_accuracies = sess.run(
                        self.accuracy,
                        feed_dict={self.x: mnist.test.images,
                                   self.y_: mnist.test.labels}
                    )
            # Save plots for losses and accuracies.
            self._plot(loss=losses, accuracy=accuracies)

            # Get total number of weights.
            n_weights = 0

            for var in tf.trainable_variables():
                n_weights += get_tensor_size(var)

            extended_spec = self._extend_network_spec(accuracy=float(validation_accuracies.mean()),
                                                      n_weights=n_weights)

            # Write extended to logdir.
            self._write_to_logdir(extended_spec, 'network.json')

            if(get_weights):
                save_path = saver.save(sess, self.network_spec['logdir'] + "model.ckpt")

            return extended_spec

    def feedforward_layer(self, input_tensor, layer_number):
        """Build a feedforward layer ended with an activation function.

        Args:
            input_tensor: The output from the layer before.
            layer_number (int): The number of the layer in the network.

        Returns:
            tensor: The activated output.
        """
        layer_spec = self.network_spec['layers'][layer_number]
        with tf.name_scope('feedforward' + str(layer_number)):
            weighted = self._feedforward_step(input_tensor, layer_spec['size'])
            activation = getattr(tf.nn, layer_spec['activation_function'])(weighted)
        return activation

    def conv_layer(self, input_tensor, layer_number):
        """Build a convolution layer ended with an activation function.

        Args:
            input_tensor: The output from the layer before.
            layer_number (int): The number of the layer in the network.

        Returns:
            tensor: The activated output.
        """
        inchannels, input_tensor = self._ensure_2d(input_tensor)

        layer_spec = self.network_spec['layers'][layer_number]
        filter_shape = (layer_spec['filter']['height'],
                        layer_spec['filter']['width'],
                        inchannels,
                        layer_spec['filter']['outchannels'])
        filter_strides = (layer_spec['strides']['inchannels'],
                          layer_spec['strides']['x'],
                          layer_spec['strides']['y'],
                          layer_spec['strides']['batch'])
        with tf.name_scope('conv' + str(layer_number)):
            w = self._weight_variable(filter_shape, name='W')
            b = self._bias_variable([layer_spec['filter']['outchannels']], name='b')
            conv = tf.nn.conv2d(input_tensor, w, strides=filter_strides, padding='SAME')
            activation = getattr(tf.nn, layer_spec['activation_function'])(conv + b, name='activation')
        return activation

    def maxpool_layer(self, input_tensor, layer_number):
        """Build a maxpooling layer.

               Args:
                   input_tensor: The output from the layer before.
                   layer_number (int): The number of the layer in the network.

               Returns:
                   tensor: The max pooled output.
               """

        _, input_tensor = self._ensure_2d(input_tensor)
        layer_spec = self.network_spec['layers'][layer_number]
        kernel_shape = (1,  # First number has to be one for ksize of maxpool layer.
                        layer_spec['kernel']['height'],
                        layer_spec['kernel']['width'],
                        layer_spec['kernel']['outchannels'])
        kernel_strides = (layer_spec['strides']['inchannels'],
                          layer_spec['strides']['x'],
                          layer_spec['strides']['y'],
                          layer_spec['strides']['batch'])

        with tf.name_scope('maxpool' + str(layer_number)):
            pool = tf.nn.max_pool(input_tensor, ksize=kernel_shape,
                                  strides=kernel_strides, padding='SAME', name='maxpool')
        return pool

    def _build_network(self):
        """Build network based on JSON specification.

        Construct all layers according to the JSON specification. Then project
        everything on a readout layer. Then build loss and the training op.
        """
        # Write extended to logdir.
        os.makedirs(self.network_spec['logdir'], exist_ok=True)
        self._write_to_logdir(json.dumps(self.network_spec), 'network.json')
        # Reset the old graphs from previous candidates.
        tf.reset_default_graph()
        self.x = tf.placeholder(tf.float32, shape=[None, 28, 28, 1], name='input')
        self.y_ = tf.placeholder(tf.int32, shape=[None], name='labels')
        current_tensor = self._build_layers(self.x)
        readout = self._build_readout_layer(current_tensor, n_classes=10)
        loss = self._build_loss(readout, self.y_)
        self.train_op = self._build_train_op(loss)

    def _build_layers(self, current_tensor):
        """Build layers based on the JSON specification.

        Returns:
            tensor: The output from the last layer.
        """
        for i, layer_spec in enumerate(self.network_spec['layers']):
            current_tensor = getattr(self, layer_spec['type'])(current_tensor, layer_number=i)
        return current_tensor

    def _build_readout_layer(self, input_tensor, n_classes):
        """Project into tensor onto readout layer with n classes."""
        with tf.name_scope('readout'):
            readout = self._feedforward_step(input_tensor, n_classes)
        return readout

    def _build_loss(self, readout, labels):
        """Build the layer including the loss and the accuracy.

        Args:
            readout (tensor): The readout layer. A probability distribution over the classes.
            labels (tensor): Labels as integers.

        Returns:
            tensor: The loss tensor (cross entropy).
        """

        with tf.name_scope('loss'):
            self.loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=readout, labels=labels))
            tf.summary.scalar('cross_entropy', self.loss)
            correct_prediction = tf.nn.in_top_k(readout, labels, 1)
            self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
            tf.summary.scalar('accuracy', self.accuracy)
        return self.loss

    def _build_train_op(self, loss):
        """Build the training op.

        Args:
            loss (tensor): The loss function to be optimized.

        Returns:
            The training op.
        """
        with tf.name_scope('train'):
            learning_rate = self.network_spec['hyperparameters']['learningrate']
            optimizer = getattr(tf.train, self.network_spec['hyperparameters']['optimizer'])(learning_rate)
            train_op = optimizer.minimize(loss)
        return train_op

    def _feedforward_step(self, input_tensor, size):
        """Project tensor on column of `size` many neurons.

        Args:
            input_tensor: The tensor to be projected.
            size: The size of the feedforward layer.

        Returns:
            tensor: The forwarded tensor.
        """
        # Flatten the input tensor.
        flat_dim = get_tensor_size(input_tensor)
        input_tensor_flat = tf.reshape(input_tensor, [-1, flat_dim], name='reshape')
        w = self._weight_variable([flat_dim, size], name='W')
        b = self._bias_variable([size], name='b')
        weighted = tf.matmul(input_tensor_flat, w) + b
        return weighted

    def _ensure_2d(self, input_tensor):
        """Make sure that `input_tensor` can be used for convolution and maxpooling ops.

        Args:
            input_tensor (tensor): The tensor that potentially has to be converted to 2D.

        Returns:
            Number of inchannels for the next layer.
            The `input_tensor` for the next layer.

        """
        if len(input_tensor.get_shape()) > 2:
            inchannels = int(input_tensor.get_shape()[-1])  # inchannels
        else:
            inchannels = 1
            input_tensor = self._reshape_to_2d(input_tensor)

        return inchannels, input_tensor

    @staticmethod
    def _reshape_to_2d(input_tensor):

        # The length of the flat tensor.
        flat_size = int(input_tensor.get_shape()[1])
        side_length = math.ceil(math.sqrt(flat_size))
        padding_size = (side_length ** 2) - flat_size
        if padding_size != 0:
            padding = tf.zeros(shape=[tf.shape(input_tensor)[0], (side_length ** 2) - flat_size], name='padding')
            input_tensor = tf.concat([input_tensor, padding], axis=1)
        input_tensor_2d = tf.reshape(input_tensor, [-1, side_length, side_length, 1], name='reshape')
        return input_tensor_2d

    @staticmethod
    def _weight_variable(shape, name):
        """Initialize weights randomly with normal distribution."""
        initial = tf.truncated_normal(shape, stddev=0.1)
        return tf.Variable(initial, name=name)

    @staticmethod
    def _bias_variable(shape, name):
        """Set all biases to 0.1"""
        initial = tf.constant(0.1, shape=shape)
        return tf.Variable(initial, name=name)

    def _write_to_logdir(self, file_str, fname):
        """Write a string to a file in the logdir.

        Args:
            file_str: The string to be written to the file.
            fname: The name of the file.
        """
        file_loc = os.path.join(self.network_spec['logdir'], fname)
        with open(file_loc, 'w') as fp:
            fp.write(file_str)

    def _extend_network_spec(self, **kwargs):
        """Write results into JSON."""
        extended_spec = self.network_spec
        extended_spec['results'] = kwargs
        extended_json_spec = json.dumps(extended_spec)
        return extended_json_spec

    def _plot(self, **kwargs):
        """Save plots in logdir.

        Keyword Args:
            A mapping between a label and a numpy array to be plotted.
        """
        steps = np.arange(
            self.network_spec['max_number_of_iterations'] // self.network_spec['validate_each_n_steps']
        ) * self.network_spec['validate_each_n_steps']
        for y_label, y_vals in kwargs.items():
            fig = plt.figure()
            ax = fig.add_subplot(111)
            ax.plot(steps, y_vals)
            ax.set_xlabel('batch')
            ax.set_ylabel(y_label)
            fig.savefig(self.network_spec['logdir'] + y_label + '.png', format='png')
            plt.clf()
            plt.close(fig)


text:
//
//  AKABindingControllerDelegate.h
//  AKABeacon
//
//  Created by Michael Utech on 24.05.16.
//  Copyright © 2016 Michael Utech & AKA Sarl. All rights reserved.
//

@import Foundation;
#import "AKABeaconNullability.h"

@class AKABindingController;
@protocol AKABindingControllerDelegate <NSObject>

@optional
/**
 Determines whether a binding with the specified parameters should be created and added to the binding controller.

 @param controller        the binding controller
 @param bindingType       a subclass of AKABinding (f.e. AKABinding_UILabel_textBinding)
 @param target            the binding target (f.e. an instance of UILabel)
 @param bindingProperty   the property (getter selector) holding the binding expression (f.e. textBinding_aka)
 @param bindingExpression the binding expression that will be used to create the new binding

 @return YES if the binding should be created and added to the binding controller, NO if it should be ignored.
 */
- (BOOL)                                  shouldController:(req_AKABindingController)controller
                                          addBindingOfType:(req_Class)bindingType
                                                 forTarget:(req_id)target
                                                  property:(req_SEL)bindingProperty
                                         bindingExpression:(req_AKABindingExpression)bindingExpression;

@optional
/**
 Called after a binding was created and before it is added to the binding controller.

 @param controller        the binding controller
 @param binding           an instance of AKABinding
 @param target            the binding target (f.e. an instance of UILabel)
 @param bindingProperty   the property (getter selector) holding the binding expression (f.e. textBinding_aka)
 @param bindingExpression the binding expression that was used to create the binding.
 */
- (void)                                        controller:(req_AKABindingController)controller
                                            willAddBinding:(req_AKABinding)binding
                                                 forTarget:(req_id)view
                                                  property:(req_SEL)bindingProperty
                                         bindingExpression:(req_AKABindingExpression)bindingExpression;

@optional
- (void)                                        controller:(req_AKABindingController)controller
                               failedToCreateBindingOfType:(req_Class)bindingType
                                                 forTarget:(req_id)target
                                                  property:(req_SEL)bindingProperty
                                         bindingExpression:(req_AKABindingExpression)bindingExpression
                                                 withError:(req_NSError)error;

@optional
- (void)                                        controller:(req_AKABindingController)controller
                                             didAddBinding:(req_AKABinding)binding
                                                 forTarget:(req_id)view
                                                  property:(req_SEL)bindingProperty
                                         bindingExpression:(req_AKABindingExpression)bindingExpression;

#pragma mark - AKABindingDelegate Propagation

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKABinding)binding
                     sourceValueDidChangeFromOldValue:(id _Nullable)oldSourceValue
                                                   to:(id _Nullable)newSourceValue;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKABinding)binding
                     sourceValueDidChangeFromOldValue:(opt_id)oldSourceValue
                                       toInvalidValue:(opt_id)newSourceValue
                                            withError:(opt_NSError)error;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKABinding)binding
                               sourceArrayItemAtIndex:(NSUInteger)index
                                                value:(opt_id)oldValue
                                          didChangeTo:(opt_id)newValue;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKABinding)binding
                               targetArrayItemAtIndex:(NSUInteger)index
                                                value:(opt_id)oldValue
                                          didChangeTo:(opt_id)newValue;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKABinding)binding
               targetUpdateFailedToConvertSourceValue:(opt_id)sourceValue
                               toTargetValueWithError:(opt_NSError)error;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKABinding)binding
              targetUpdateFailedToValidateTargetValue:(opt_id)targetValue
                             convertedFromSourceValue:(opt_id)sourceValue
                                            withError:(opt_NSError)error;

@optional
- (BOOL)                                   controller:(req_AKABindingController)controller
                                        shouldBinding:(req_AKABinding)binding
                                    updateTargetValue:(opt_id)oldTargetValue
                                                   to:(opt_id)newTargetValue
                                       forSourceValue:(opt_id)oldSourceValue
                                             changeTo:(opt_id)newSourceValue;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKABinding)binding
                                willUpdateTargetValue:(opt_id)oldTargetValue
                                                   to:(opt_id)newTargetValue;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKABinding)binding
                                 didUpdateTargetValue:(opt_id)oldTargetValue
                                                   to:(opt_id)newTargetValue
                                       forSourceValue:(opt_id)oldSourceValue
                                             changeTo:(opt_id)newSourceValue;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKAControlViewBinding)binding
               sourceUpdateFailedToConvertTargetValue:(opt_id)targetValue
                               toSourceValueWithError:(opt_NSError)error;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKAControlViewBinding)binding
              sourceUpdateFailedToValidateSourceValue:(opt_id)sourceValue
                             convertedFromTargetValue:(opt_id)targetValue
                                            withError:(opt_NSError)error;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKAControlViewBinding)binding
                           targetValueDidChangeFromOldValue:(opt_id)oldTargetValue
                                             toInvalidValue:(opt_id)newTargetValue
                                                  withError:(opt_NSError)error;

@optional
- (BOOL)                                   controller:(req_AKABindingController)controller
                                        shouldBinding:(req_AKAControlViewBinding)binding
                                    updateSourceValue:(opt_id)oldSourceValue
                                                   to:(opt_id)newSourceValue
                                       forTargetValue:(opt_id)oldTargetValue
                                             changeTo:(opt_id)newTargetValue;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKAControlViewBinding)binding
                                willUpdateSourceValue:(opt_id)oldSourceValue
                                                   to:(opt_id)newSourceValue;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKAControlViewBinding)binding
                                 didUpdateSourceValue:(opt_id)oldSourceValue
                                                   to:(opt_id)newSourceValue;

#pragma mark - AKAKeyBoardControlViewBindingDelegate

#pragma mark Keyboard Activation Requests

@optional
- (BOOL)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKAKeyboardControlViewBinding)binding
                       responderRequestedActivateNext:(req_UIResponder)responder;

@optional
- (BOOL)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKAKeyboardControlViewBinding)binding
                           responderRequestedGoOrDone:(req_UIResponder)responder;

#pragma mark UIResponder Events

@optional
- (BOOL)                                   controller:(req_AKABindingController)controller
                                        shouldBinding:(req_AKAKeyboardControlViewBinding)binding
                                    responderActivate:(req_UIResponder)responder;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKAKeyboardControlViewBinding)binding
                                responderWillActivate:(req_UIResponder)responder;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKAKeyboardControlViewBinding)binding
                                 responderDidActivate:(req_UIResponder)responder;

@optional
- (BOOL)                                   controller:(req_AKABindingController)controller
                                        shouldBinding:(req_AKAKeyboardControlViewBinding)binding
                                  responderDeactivate:(req_UIResponder)responder;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKAKeyboardControlViewBinding)binding
                              responderWillDeactivate:(req_UIResponder)responder;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKAKeyboardControlViewBinding)binding
                               responderDidDeactivate:(req_UIResponder)responder;

#pragma mark - AKACollectionViewBindingDelegate

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKACollectionControlViewBinding)binding
                    sourceControllerWillChangeContent:(req_id)sourceDataController;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKACollectionControlViewBinding)binding
                                     sourceController:(req_id)sourceDataController
                                         insertedItem:(opt_id)sourceCollectionItem
                                          atIndexPath:(req_NSIndexPath)indexPath;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKACollectionControlViewBinding)binding
                                     sourceController:(req_id)sourceDataController
                                          updatedItem:(opt_id)sourceCollectionItem
                                          atIndexPath:(req_NSIndexPath)indexPath;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKACollectionControlViewBinding)binding
                                     sourceController:(req_id)sourceDataController
                                          deletedItem:(opt_id)sourceCollectionItem
                                          atIndexPath:(req_NSIndexPath)indexPath;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKACollectionControlViewBinding)binding
                                     sourceController:(req_id)sourceDataController
                                            movedItem:(opt_id)sourceCollectionItem
                                        fromIndexPath:(req_NSIndexPath)fromIndexPath
                                          toIndexPath:(req_NSIndexPath)toIndexPath;

@optional
- (void)                                   controller:(req_AKABindingController)controller
                                              binding:(req_AKACollectionControlViewBinding)binding
                     sourceControllerDidChangeContent:(req_id)sourceDataController;

@end


text:
using PKISharp.WACS.Services;
using System;
using System.Net;
using System.Net.Mail;
using System.Reflection;

namespace PKISharp.WACS.Clients
{
    class EmailClient
    {
        private readonly ILogService _log;
        private readonly ISettingsService _settings;
        private readonly string _server;
        private readonly int _port;
        private readonly string _user;
        private readonly string _password;
        private readonly bool _secure;
        private readonly string _senderName;
        private readonly string _senderAddress;
        private readonly string _receiverAddress;

        public EmailClient(ILogService log, ISettingsService settings)
        {
            _log = log;
            _settings = settings; // Must be initialized to create settings.config on clean install
            _server = Properties.Settings.Default.SmtpServer;
            _port = Properties.Settings.Default.SmtpPort;
            _user = Properties.Settings.Default.SmtpUser;
            _password = Properties.Settings.Default.SmtpPassword;
            _secure = Properties.Settings.Default.SmtpSecure;
            _senderName = Properties.Settings.Default.SmtpSenderName;
            if (string.IsNullOrWhiteSpace(_senderName))
            {
                _senderName = Properties.Settings.Default.ClientName;
            }
            _senderAddress = Properties.Settings.Default.SmtpSenderAddress;
            _receiverAddress = Properties.Settings.Default.SmtpReceiverAddress;

            // Criteria for emailing to be enabled at all
            Enabled =
                !string.IsNullOrEmpty(_senderAddress) &&
                !string.IsNullOrEmpty(_server) &&
                !string.IsNullOrEmpty(_receiverAddress);
            _log.Verbose("Sending e-mails {_enabled}", Enabled);
        }

        public bool Enabled { get; internal set; }

        public void Send(string subject, string content, MailPriority priority)
        {
            if (Enabled)
            {
                try
                {
                    _log.Information("Sending e-mail with subject {subject} to {_receiverAddress}", subject, _receiverAddress);
                    var sender = new MailAddress(_senderAddress, _senderName);
                    var receiver = new MailAddress(_receiverAddress);
                    var message = new MailMessage(sender, receiver)
                    {
                        Priority = priority,
                        Subject = subject,
                        IsBodyHtml = true,
                        Body = content + $"
Sent by win-acme version {Assembly.GetExecutingAssembly().GetName().Version} from {Environment.MachineName}
"
                    };
                    var server = new SmtpClient(_server, _port)
                    {
                        EnableSsl = _secure
                    };
                    if (!string.IsNullOrEmpty(_user))
                    {
                        server.Credentials = new NetworkCredential(_user, _password);
                    }
                    server.Send(message);
                }
                catch (Exception ex)
                {
                    _log.Error(ex, "Problem sending e-mail");
                }
            }
        }
    }
}


text:
  Save New Workspace:

  <input type="text" data-submit-handler="TT.Workspace.saveWorkspace" id="new-workspace-name" class="textfield" value="{{current_workspace}}" />Save


text:
package client

import (
	"encoding/json"
	"net/http"
	"net/http/httptest"
	"net/url"
	"testing"

	httpHelpers "github.com/dcos/dcos-metrics/util/http/helpers"
	. "github.com/smartystreets/goconvey/convey"
)

func TestClient(t *testing.T) {
	Convey("User-Agent should match Git version", t, func() {
		var gotUserAgent string

		ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			td, err := json.Marshal(map[string]string{
				"foo": "bar",
			})
			if err != nil {
				panic(err)
			}

			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusOK)
			w.Write(td)

			gotUserAgent = r.UserAgent()
		}))
		defer ts.Close()

		u, err := url.Parse(ts.URL)
		if err != nil {
			panic(err)
		}

		if err := Fetch(http.DefaultClient, *u, nil); err != nil {
			panic(err)
		}

		// Default is "unset"; this is set by 'scripts/build.sh' via ldflags.
		// The actual test for the version in the built binary is in TestMain,
		// located in dcos-metrics_test.go.
		So(gotUserAgent, ShouldEqual, "unset")
	})
}

func TestFetch(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		td, err := json.Marshal(map[string]string{
			"foo": "bar",
		})
		if err != nil {
			panic(err)
		}

		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(200)
		w.Write(td)
	}))
	defer ts.Close()

	testClient, err := httpHelpers.NewMetricsClient("", "")
	if err != nil {
		t.Error("Error retreiving HTTP Client:", err)
	}

	Convey("Should fetch data and return", t, func() {
		var data map[string]string
		host, err := extractHostFromURL(ts.URL)
		if err != nil {
			panic(err)
		}

		testURL := url.URL{
			Scheme: "http",
			Host:   host,
			Path:   "/",
		}
		err = Fetch(testClient, testURL, &data)

		So(data["foo"], ShouldEqual, "bar")
		So(err, ShouldBeNil)
	})
}

func extractHostFromURL(u string) (string, error) {
	parsed, err := url.Parse(u)
	if err != nil {
		return "", err
	}
	return parsed.Host, nil
}


text:
package org.onosproject.cli.net;

import java.util.Optional;

import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.apache.karaf.shell.commands.Option;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.net.ChannelSpacing;
import org.onosproject.net.DeviceId;
import org.onosproject.net.GridType;
import org.onosproject.net.OchSignal;
import org.onosproject.net.PortNumber;
import org.onosproject.net.intent.IntentId;
import org.onosproject.net.resource.ResourceAllocation;
import org.onosproject.net.resource.ResourceConsumer;
import org.onosproject.net.resource.Resource;
import org.onosproject.net.resource.ResourceService;
import org.onosproject.net.resource.Resources;

/**
 * Test tool to allocate resources.
 */
@Command(scope = "onos", name = "test-allocate-resources",
         description = "Test tool to allocate resources")
public class TestAllocateResource extends AbstractShellCommand {

    // TODO add support for other resource types

    // FIXME provide a proper way to specify a lambda and lambda ranges
    @Option(name = "-l", aliases = "--lambda",
            description = "Lambda Resource to allocate",
            required = false, multiValued = false)
    private String lambda = "1";

    @Option(name = "-i", aliases = "--intentId",
            description = "IntentId to use for allocation",
            required = false, multiValued = false)
    private int nIntendId = 42;

    @Argument(index = 0, name = "deviceId", description = "Device ID",
            required = true, multiValued = false)
    String deviceIdStr = null;

    @Argument(index = 1, name = "portNumber", description = "PortNumber",
            required = true, multiValued = false)
    String portNumberStr = null;

    private ResourceService resourceService;

    @Override
    protected void execute() {
        resourceService = get(ResourceService.class);
        DeviceId did = DeviceId.deviceId(deviceIdStr);
        PortNumber portNum = PortNumber.fromString(portNumberStr);

        ResourceConsumer consumer = IntentId.valueOf(nIntendId);

        Resource resource = Resources.discrete(did, portNum,
                createLambda(Integer.parseInt(lambda))).resource();

        Optional<ResourceAllocation> allocate = resourceService.allocate(consumer, resource);
        if (allocate.isPresent()) {
            print("Allocated: %s", allocate.get());
        } else {
            print("Failed to allocate %s for %s", resource, consumer);
        }
    }

    private OchSignal createLambda(int i) {
        return new OchSignal(GridType.FLEX,
                             ChannelSpacing.CHL_6P25GHZ,
                             i,
                             1);
    }

}


text:
:man_page: mongoc_client_session_t
:tags: session

mongoc_client_session_t
=======================

Use a session for a sequence of operations, optionally with causal consistency. See `the MongoDB Manual Entry for Causal Consistency <http://dochub.mongodb.org/core/causal-consistency>`_.

Synopsis
--------

.. include:: includes/session-lifecycle.txt

Example
-------

.. literalinclude:: ../examples/example-session.c
   :language: c
   :caption: example-session.c

.. only:: html

  Functions
  ---------

  .. toctree::
    :titlesonly:
    :maxdepth: 1

    mongoc_client_session_start_transaction
    mongoc_client_session_in_transaction
    mongoc_client_session_commit_transaction
    mongoc_client_session_abort_transaction
    mongoc_client_session_advance_cluster_time
    mongoc_client_session_advance_operation_time
    mongoc_client_session_append
    mongoc_client_session_get_client
    mongoc_client_session_get_cluster_time
    mongoc_client_session_get_operation_time
    mongoc_client_session_get_opts
    mongoc_client_session_get_lsid
    mongoc_client_session_destroy


text:
<?php defined('SYSPATH') or die('No direct script access.');

class Modulargaming_Character_Event {

	/**
	 * Hook into before function.
	 */
	public static function before()
	{
		$t = Event::$data;

		// If load_character is set and is TRUE, load the character
		if (isset($t->load_character) AND $t->load_character) {
			Character_Event::load_character($t);
		}

		// If character is loaded, and character is required, make sure we got a character.
		if (isset($t->load_character) AND $t->load_character AND isset($t->require_character) AND $t->require_character )
		{
			if ( ! $t->character->loaded())
			{
				Request::instance()->redirect('character/create');
			}
		}
	}

	/**
	 * Loads a character, and assigns it to a variable.
	 * @param $t
	 */
	public static function load_character($t)
	{
		if ($t->user && ! isset($t->character))
		{
			$t->character = Jelly::select('character')
				->where('user', '=', $t->user->id)
				->load();
		}
	}

	/**
	 * Hook into the dasboard display system, and assign the character stats view.
	 */
	public static function dashboard_left()
	{
		$t = Event::$data;

		Character_Event::load_character($t);

		$t->left[] = View::factory('character/dashboard/status')
			->set('character', $t->character)
			->set('char', new Character($t->character));

	}

	public static function sidebar_left()
	{
		$t = Event::$data;

		Character_Event::load_character($t);

		$t->sidebar_left[] = View::factory('character/dashboard/sidebar');
	}

	public static function sidebar_right()
	{
		$s = Event::$data;

		if ( ! $s->user)
		{
			return false;
		}

		Character_Event::load_character($s);

		$s->sidebar_right[] = View::factory('character/sidebar')
				->set('character', $s->character)
				->set('char', new Character($s->character));

	}
}


text:
"use strict";

const apisObject = {
	"type": "object",
	"required": false,
	"patternProperties": {
		"^[_a-z\/][_a-zA-Z0-9\/:]*$": { //pattern to match an api route
			"type": "object",
			"required": true,
			"properties": {
				"access": {"type": "boolean", "required": false},
				"group:": {"type": "string", "required": false}
			}
		}
	}
};

const granularAcl = {
	"type": "object",
	"required": false,
	"properties": {
		"apis": apisObject
	}
};

const granular = {
	"type": "object",
	"required": false,
	"patternProperties": {
		".+": {
			"type": "object",
			"required": false,
			"properties": {
				"access": {"type": "boolean", "required": false},
				"apisPermission": {
					"type": "string", "enum": ["restricted"], "required": false
				},
				"apis": apisObject,
				"get": granularAcl,
				"post": granularAcl,
				"put": granularAcl,
				"delete": granularAcl,
				"head": granularAcl,
				"patch": granularAcl,
				"options": granularAcl,
				"other": granularAcl,
				"apisRegExp": {
					"type": "array",
					"required": false,
					"minItems": 1,
					"items": {
						"type": "object",
						"properties": {
							"regExp": {
								"type": "pattern",
								"required": true,
								"pattern": /\.+/
							},
							"access": {"type": "boolean", "required": false}
						},
						"additionalProperties": false
					}
				},
				"additionalProperties": false
			},
			"additionalProperties": false
		}
	},
	"additionalProperties": false
};

module.exports = granular;


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <link rel="stylesheet" href="style.css" type="text/css">
    <title>Submit a Pic!</title>

 YEAR BOOK

Home

          Students

            View Students
            Add Student

          Projects

            View Projects
            Add Project

About Us

      <form id="submit">
        <input class="size" name="firstName" type="text" placeholder="First Name"/>
        <input class="size" name="lastName" type="text" placeholder="Last Name"/>
        <input class="size" name="studentImg" type="text" placeholder="Picture URL">
        <input class="size" name="linkdIn" type="text" placeholder="linkdIn Profile URL">
        <input class="size" name="gitHub" type="text" placeholder="GitHub Profile URL">

        <button id="but" onclick="location.href = 'studentAlbum.html'" type="submit">Add Student</button>
      </form>

Contact Us


text:
# :nodoc:
Dir["#{File.expand_path(File.dirname(__FILE__))}/**/*.rb"].each{|f| require f}

STDOUT.sync = true
STDERR.sync = true

# :nodoc:
include Stash::DSL


text:
import os
import sys
from ..tween import SubprocessTween

subprocess_env = os.environ.copy()
subprocess_env['PYTHONPATH'] = os.pathsep.join(sys.path[1:])

def should_transform(request, response):
    return 'X-No-Transform' not in request.headers

def after_transform(request, response):
    response.headers['X-After-Transform'] = 'true'

def _reload_process(process):
    return False

# Wrapper so _reload_subprocess can be mocked
def reload_process(process):
    return _reload_process(process)

testing_tween = SubprocessTween(
    should_transform=should_transform,
    after_transform=after_transform,
    reload_process=reload_process,
    args=[sys.executable, '-m', 'subprocess_middleware.tests.testing_transform'],
    env=subprocess_env,
)

startup_error_tween = SubprocessTween(
    should_transform=should_transform,
    after_transform=after_transform,
    args=[sys.executable, '-m', 'subprocess_middleware.tests.testing_transform', '--error'],
    env=subprocess_env,
)


text:
// File: vogl_mem.cpp
#include "vogl_core.h"
#include "vogl_console.h"
#include "vogl.h"
#include "vogl_threading.h"
#include "vogl_strutils.h"
#include <malloc.h>

// Set to 1 to enable stb_malloc, otherwise voglcore uses plain malloc/free/realloc
#ifndef VOGL_USE_STB_MALLOC
#define VOGL_USE_STB_MALLOC 1
#endif

#ifndef VOGL_RAND_FILL_ALLLOCATED_MEMORY
#define VOGL_RAND_FILL_ALLLOCATED_MEMORY 0
#endif

#ifndef VOGL_SCRUB_FREED_MEMORY
#define VOGL_SCRUB_FREED_MEMORY 0
#endif

#if VOGL_RAND_FILL_ALLLOCATED_MEMORY || VOGL_SCRUB_FREED_MEMORY
#warning VOGL_RAND_FILL_ALLLOCATED_MEMORY and/or VOGL_SCRUB_FREED_MEMORY is enabled
#endif

#ifdef VOGL_USE_WIN32_API
#include "vogl_winhdr.h"
#endif

#if defined(__GNUC__)
#include "mcheck.h"
#endif

#if VOGL_USE_STB_MALLOC
#include "vogl_stb_heap.h"
#endif

#if VOGL_MALLOC_DEBUGGING
#define MALLOC_DEBUG
#include "rmalloc.h"
#endif

#undef vogl_malloc
#undef vogl_realloc
#undef vogl_calloc
#undef vogl_free
#undef vogl_check_heap
#undef vogl_print_heap_stats
#undef vogl_new
#undef vogl_new_array
#undef vogl_delete
#undef vogl_delete_array

#if VOGL_MALLOC_DEBUGGING
#warning vogl_mem.cpp: Malloc debugging enabled
#endif

#if VOGL_USE_STB_MALLOC

#define STB_ALLOC_INITIAL_HEAP_SIZE 32U * 1024U * 1024U
// Purposely written C-style so we can safely do heap allocs BEFORE C++ global construction time.

static uint64_t g_initial_heap_storage[(STBM_HEAP_SIZEOF + STB_ALLOC_INITIAL_HEAP_SIZE + sizeof(uint64_t) - 1) / sizeof(uint64_t)];
static stbm_heap *g_pHeap;
static pthread_mutex_t g_mutex;
static size_t g_page_size;

// This flag helps us detect calls to malloc, etc. from within asynchronous signal handlers.
static bool g_allocating_flag;

static void *sys_alloc(void *user_context, size_t size_requested, size_t *size_provided)
{
    VOGL_NOTE_UNUSED(user_context);

    if (!g_page_size)
    {
        g_page_size = sysconf(_SC_PAGE_SIZE);
        if (!g_page_size)
            g_page_size = 65536;
    }

    size_requested = (size_requested + g_page_size - 1) & (~(g_page_size - 1));

    void *p = mmap(NULL, size_requested, PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0);

    if ((!p) || (p == MAP_FAILED))
    {
        uint e = errno;

        // Not using strerror_r because it fails when we're completely out of memory.
        char *pError_desc = strerror(e);

        char buf[256];
        sprintf(buf, "%s: mmap() of %zu bytes failed! Reason: %s (errno 0x%x)\n", VOGL_FUNCTION_NAME, size_requested, pError_desc, e);

        write(STDERR_FILENO, buf, strlen(buf));
        abort();
    }

    *size_provided = size_requested;

    return p;
}

static void sys_free(void *user_context, void *ptr, size_t size)
{
    VOGL_NOTE_UNUSED(user_context);

    int res = munmap(ptr, size);
    if (res != 0)
    {
        uint e = errno;

        // Not using strerror_r because it fails when we're completely out of memory.
        char *pError_desc = strerror(e);

        char buf[256];
        sprintf(buf, "%s: munmap() ptr 0x%" PRIxPTR " size 0x%" PRIxPTR " failed! Reason: %s (errno 0x%x)\n", VOGL_FUNCTION_NAME, (uintptr_t)ptr, size, pError_desc, e);

        write(STDERR_FILENO, buf, strlen(buf));
        abort();
    }
}

#if VOGL_MALLOC_DEBUGGING
static void *rmalloc_malloc_callback(size_t size, void *pUser)
{
    VOGL_NOTE_UNUSED(pUser);
    return stbm_alloc(NULL, g_pHeap, size, 0);
}

static void rmalloc_free_callback(void *ptr, void *pUser)
{
    VOGL_NOTE_UNUSED(pUser);
    stbm_free(NULL, g_pHeap, ptr);
}

static void *rmalloc_realloc_callback(void *ptr, size_t size, void *pUser)
{
    VOGL_NOTE_UNUSED(pUser);
    return stbm_realloc(NULL, g_pHeap, ptr, size, 0);
}
#endif

static void init_heap()
{
    if (g_pHeap)
        return;

    pthread_mutex_init(&g_mutex, NULL);

    stbm_heap_config config;
    memset(&config, 0, sizeof(config));
    config.system_alloc = sys_alloc;
    config.system_free = sys_free;

    g_pHeap = stbm_heap_init(g_initial_heap_storage, sizeof(g_initial_heap_storage), &config);

#if VOGL_MALLOC_DEBUGGING
    Rmalloc_set_callbacks(rmalloc_malloc_callback, rmalloc_free_callback, rmalloc_realloc_callback, NULL);
#endif
}

static void lock_heap()
{
    VOGL_ASSERT(g_pHeap);

    pthread_mutex_lock(&g_mutex);

    VOGL_ASSERT(!g_allocating_flag);
    g_allocating_flag = true;
}

static void unlock_heap()
{
    g_allocating_flag = false;

    VOGL_ASSERT(g_pHeap);
    pthread_mutex_unlock(&g_mutex);
}

static void *malloc_block(size_t size, const char *pFile_line)
{
    VOGL_ASSERT(g_pHeap);

    lock_heap();

#if VOGL_MALLOC_DEBUGGING
    void *p = Rmalloc(size, pFile_line);
#else
    VOGL_NOTE_UNUSED(pFile_line);
    void *p = stbm_alloc(NULL, g_pHeap, size, 0);
#endif

    unlock_heap();

    return p;
}

static void *realloc_block(void *p, size_t size, const char *pFile_line)
{
    VOGL_ASSERT(g_pHeap);

    lock_heap();

#if VOGL_MALLOC_DEBUGGING
    void *q = Rrealloc(p, size, pFile_line);
#else
    VOGL_NOTE_UNUSED(pFile_line);
    void *q = stbm_realloc(NULL, g_pHeap, p, size, 0);
#endif

    unlock_heap();

    return q;
}

static void free_block(void *p, const char *pFile_line)
{
    VOGL_ASSERT(g_pHeap);

    lock_heap();

#if VOGL_MALLOC_DEBUGGING
    Rfree(p, pFile_line);
#else
    VOGL_NOTE_UNUSED(pFile_line);
    stbm_free(NULL, g_pHeap, p);
#endif

    unlock_heap();
}

static size_t msize_block(void *p, const char *pFile_line)
{
    VOGL_ASSERT(g_pHeap);

    lock_heap();

#if VOGL_MALLOC_DEBUGGING
    size_t n = Rmalloc_usable_size(p, pFile_line);
#else
    VOGL_NOTE_UNUSED(pFile_line);
    size_t n = stbm_get_allocation_size(p);
#endif

    unlock_heap();

    return n;
}

static void print_stats(const char *pFile_line)
{
    VOGL_ASSERT(g_pHeap);

#if VOGL_MALLOC_DEBUGGING
    lock_heap();

    Rmalloc_stat(pFile_line);

    unlock_heap();
#else
    VOGL_NOTE_UNUSED(pFile_line);
#endif
}

static void check(const char *pFile_line)
{
    VOGL_ASSERT(g_pHeap);

#if VOGL_MALLOC_DEBUGGING
    lock_heap();

    Rmalloc_test(pFile_line);

    unlock_heap();
#else
    VOGL_NOTE_UNUSED(pFile_line);
#endif
}

#else // !VOGL_USE_STB_MALLOC

static bool g_heap_initialized;
static pthread_mutex_t g_mutex;

static void init_heap()
{
    if (g_heap_initialized)
        return;

    pthread_mutex_init(&g_mutex, NULL);
    g_heap_initialized = true;
}

#if VOGL_USE_STB_MALLOC
static void lock_heap()
{
    VOGL_ASSERT(g_heap_initialized);
    pthread_mutex_lock(&g_mutex);
}

static void unlock_heap()
{
    VOGL_ASSERT(g_heap_initialized);
    pthread_mutex_unlock(&g_mutex);
}
#endif

static void *malloc_block(size_t size, const char *pFile_line)
{
    VOGL_ASSERT(g_heap_initialized);
    VOGL_NOTE_UNUSED(pFile_line);

#if VOGL_MALLOC_DEBUGGING
    lock_heap();
    void *p = Rmalloc(size, pFile_line);
    unlock_heap();
#else
    void *p = malloc(size);
#endif

    return p;
}

static void *realloc_block(void *p, size_t size, const char *pFile_line)
{
    VOGL_ASSERT(g_heap_initialized);
    VOGL_NOTE_UNUSED(pFile_line);

#if VOGL_MALLOC_DEBUGGING
    lock_heap();
    void *q = Rrealloc(p, size, pFile_line);
    unlock_heap();
#else
    void *q = realloc(p, size);
#endif

    return q;
}

static void free_block(void *p, const char *pFile_line)
{
    VOGL_ASSERT(g_heap_initialized);
    VOGL_NOTE_UNUSED(pFile_line);

#if VOGL_MALLOC_DEBUGGING
    lock_heap();
    Rfree(p, pFile_line);
    unlock_heap();
#else
    free(p);
#endif
}

static size_t msize_block(void *p, const char *pFile_line)
{
    VOGL_ASSERT(g_heap_initialized);
    VOGL_NOTE_UNUSED(pFile_line);

#if VOGL_MALLOC_DEBUGGING
    lock_heap();
    size_t n = Rmalloc_usable_size(p, pFile_line);
    unlock_heap();
#else
    size_t n = malloc_usable_size(p);
#endif

    return n;
}

static void print_stats(const char *pFile_line)
{
    VOGL_ASSERT(g_heap_initialized);
    VOGL_NOTE_UNUSED(pFile_line);

#if VOGL_MALLOC_DEBUGGING
    lock_heap();
    Rmalloc_stat(pFile_line);
    unlock_heap();
#endif
}

static void check(const char *pFile_line)
{
    VOGL_ASSERT(g_heap_initialized);
    VOGL_NOTE_UNUSED(pFile_line);

#if VOGL_MALLOC_DEBUGGING
    lock_heap();
    Rmalloc_test(pFile_line);
    unlock_heap();
#endif
}

#endif // #ifdef VOGL_USE_STB_MALLOC

class global_heap_constructor
{
public:
    global_heap_constructor()
    {
        //printf("global_heap_constructor\n");

        init_heap();
    }
};

global_heap_constructor g_global_heap_constructor __attribute__((init_priority(102)));

VOGL_NAMESPACE_BEGIN(vogl)

void vogl_init_heap()
{
    init_heap();
}

// TODO: vararg this
void vogl_mem_error(const char *pMsg, const char *pFile_line)
{
    char buf[512];
    vogl::vogl_sprintf_s(buf, sizeof(buf), "%s: Fatal error: %s. Originally called from %s.\n", VOGL_FUNCTION_NAME, pMsg, pFile_line ? pFile_line : "?");
    vogl_fail(buf, __FILE__, __LINE__);
    abort();
}

#if VOGL_RAND_FILL_ALLLOCATED_MEMORY || VOGL_SCRUB_FREED_MEMORY
static uint32 g_cur_rand = 0xDEADBEEF;

static void random_fill(void *p, size_t size)
{
#define JSR (jsr ^= (jsr << 17), jsr ^= (jsr >> 13), jsr ^= (jsr << 5));
    uint32 jsr = g_cur_rand;

    while (size >= sizeof(uint32) * 4)
    {
        static_cast<uint32 *>(p)[0] = jsr;
        JSR;
        static_cast<uint32 *>(p)[1] = jsr;
        JSR;
        static_cast<uint32 *>(p)[2] = jsr;
        JSR;
        static_cast<uint32 *>(p)[3] = jsr;
        JSR;

        size -= sizeof(uint32) * 4;
        p = static_cast<uint32 *>(p) + 4;
    }

    while (size >= sizeof(uint32))
    {
        static_cast<uint32 *>(p)[0] = jsr;
        JSR;

        size -= sizeof(uint32);
        p = static_cast<uint32 *>(p);
    }

    while (size)
    {
        static_cast<uint8 *>(p)[0] = static_cast<uint8>(jsr);
        JSR;

        size--;
        p = static_cast<uint8 *>(p) + 1;
    }

    g_cur_rand = jsr;
#undef JSR
}
#endif // VOGL_RAND_FILL_ALLLOCATED_MEMORY || VOGL_SCRUB_FREED_MEMORY

void *vogl_tracked_malloc(const char *pFile_line, size_t size, size_t *pActual_size)
{
    size = (size + sizeof(uint32) - 1U) & ~(sizeof(uint32) - 1U);
    if (!size)
        size = sizeof(uint32);

    if (size > VOGL_MAX_POSSIBLE_HEAP_BLOCK_SIZE)
    {
        vogl_mem_error("vogl_malloc: size too big", pFile_line);
        return NULL;
    }

    uint8 *p_new = (uint8 *)malloc_block(size, pFile_line);

    VOGL_ASSERT((reinterpret_cast<ptr_bits_t>(p_new) & (VOGL_MIN_ALLOC_ALIGNMENT - 1)) == 0);

    if (!p_new)
    {
        vogl_mem_error("vogl_malloc: out of memory", pFile_line);
        return NULL;
    }

    if (pActual_size)
    {
        *pActual_size = msize_block(p_new, pFile_line);

        if ((size) && (*pActual_size >= static_cast<uint64_t>(size) * 16U))
        {
            // I've seen this happen with glibc's absolutely terrible debug heap crap, best to let the caller know that shit is going to die
            fprintf(stderr, "%s: malloc_usable_size may be misbehaving! Requested %zu bytes, but the usable size is reported as %zu bytes.\n", __FUNCTION__, size, *pActual_size);
        }
    }

#if VOGL_RAND_FILL_ALLLOCATED_MEMORY
    random_fill(p_new, size);
#endif

    return p_new;
}

void *vogl_tracked_realloc(const char *pFile_line, void *p, size_t size, size_t *pActual_size)
{
    if ((ptr_bits_t)p & (VOGL_MIN_ALLOC_ALIGNMENT - 1))
    {
        vogl_mem_error("vogl_realloc: bad ptr", pFile_line);
        return NULL;
    }

    if (size > VOGL_MAX_POSSIBLE_HEAP_BLOCK_SIZE)
    {
        vogl_mem_error("vogl_realloc: size too big!", pFile_line);
        return NULL;
    }

    if ((size) && (size < sizeof(uint32)))
        size = sizeof(uint32);

#if VOGL_RAND_FILL_ALLLOCATED_MEMORY || VOGL_SCRUB_FREED_MEMORY
    size_t orig_size = p ? msize_block(p, pFile_line) : 0;

#if VOGL_SCRUB_FREED_MEMORY
    if ((orig_size) && (!size))
        random_fill(p, orig_size);
#endif
#endif

    void *p_new = realloc_block(p, size, pFile_line);

    VOGL_ASSERT((reinterpret_cast<ptr_bits_t>(p_new) & (VOGL_MIN_ALLOC_ALIGNMENT - 1)) == 0);

    if (pActual_size)
    {
        *pActual_size = 0;

        if (size)
        {
            if (p_new)
                *pActual_size = msize_block(p_new, pFile_line);
            else if (p)
                *pActual_size = msize_block(p, pFile_line);

            if (*pActual_size >= static_cast<uint64_t>(size) * 16U)
            {
                // I've seen this happen with glibc's absolutely terrible debug heap crap, best to let the caller know that shit is going to die
                fprintf(stderr, "%s: malloc_usable_size may be misbehaving! Requested %zu bytes, but the usable size is reported as %zu bytes.\n", __FUNCTION__, size, *pActual_size);
            }
        }
    }

#if VOGL_RAND_FILL_ALLLOCATED_MEMORY
    if ((size) && (p_new))
    {
        size_t new_size = msize_block(p_new, pFile_line);

        if (new_size > orig_size)
            random_fill(static_cast<uint8 *>(p_new) + orig_size, new_size - orig_size);
    }
#endif

    return p_new;
}

void *vogl_tracked_calloc(const char *pFile_line, size_t count, size_t size, size_t *pActual_size)
{
    size_t total = count * size;
    void *p = vogl_tracked_malloc(pFile_line, total, pActual_size);
    if (p)
        memset(p, 0, total);
    return p;
}

void vogl_tracked_free(const char *pFile_line, void *p)
{
    if (!p)
        return;

    if (reinterpret_cast<ptr_bits_t>(p) & (VOGL_MIN_ALLOC_ALIGNMENT - 1))
    {
        vogl_mem_error("vogl_free: bad ptr", pFile_line);
        return;
    }

#if VOGL_SCRUB_FREED_MEMORY
    random_fill(p, msize_block(p, pFile_line));
#endif

    free_block(p, pFile_line);
}

size_t vogl_msize(void *p)
{
    if (!p)
        return 0;

    if (reinterpret_cast<ptr_bits_t>(p) & (VOGL_MIN_ALLOC_ALIGNMENT - 1))
    {
        vogl_mem_error("vogl_msize: bad ptr", VOGL_FILE_POS_STRING);
        return 0;
    }

    return msize_block(p, VOGL_FILE_POS_STRING);
}

void vogl_tracked_print_stats(const char *pFile_line)
{
    print_stats(pFile_line);
}

void vogl_tracked_check_heap(const char *pFile_line)
{
    check(pFile_line);

#ifdef WIN32
    // Also see_CrtSetDbgFlag ()
    int status = _CrtCheckMemory();
    VOGL_VERIFY(status == TRUE);
#elif defined(__GNUC__)
    // App MUST have been linked with -mlcheck! Unfortunately -mlcheck() causes the CRT's heap API's to be unusable on some dev boxes, no idea why.
    mcheck_check_all();
#else
    fprintf(stderr, "%s: Need implementation\n", __FUNCTION__);
#endif
}

VOGL_NAMESPACE_END(vogl)

extern "C" void *vogl_realloc(const char *pFile_line, void *p, size_t new_size)
{
    return vogl::vogl_tracked_realloc(pFile_line, p, new_size, NULL);
}