text:
In C# exceptions can be handled using a simple try-catch statement:

```cs
try{
	//do something...
}catch(Exception ex){
	//do something with ex...
}
```

This will work for any exception since we are using the ```Exception``` type. However, we can also define specific exception types to be catched. For example, if we wanted to catch a divide-by-zero exception, we can do it in the following way:

```cs
try{
	//try something...
}catch(DivideByZeroException ex){
	//do something with this ex...
}
```
We can also rethrow exceptions. For example, we can throw the exception that we previously catched like so

```cs
try{
	//do stuff...
}catch(DivideByZeroException ex){
	//do stuff with ex...
	throw ex;
}
```
Or, we can throw a different exception in the same catch-block and add a message like this

```cs
try{
	//try something...
}catch(DivideByZeroException ex){
	throw new InvalidOperationException("Different exception message..",ex);
}
```

Another nice thing about C# is that we can get more detailed information about these exceptions. So for example, using the same exception types above, we can get the type and message of an exception and output them to the console.

```cs
try{
	//ooh let's try something...
}catch(DivideByZeroException ex){
    //do some cool stuff with this exception..
	Console.WriteLine(ex.GetType().Name);
	Console.WriteLine(ex.Message);
	throw new InvalidOperationException("This is also a different ex..",ex);
}
```

### C++

In C++ exceptions are defined in per-library or per-subsystem class hierarchies, etc...

In general, Stroustrup [1] defines exceptions like this :

---
```cpp
void f(){
	try{
	    throw(E);
    }catch(H){
        //when do we get here?
    }
}
```

The handler is invoked:
1. If H is the same type as E.
2. If H is an unambiguous public base of E.
3. If H and E are pointer types and 1 or 2 holds for the types to which they refer.
4. If H is a reference and 1 or 2 holds for the types to which H refers.

---

In this case, the E parameter will be passed to throw and the code under ```catch(H)``` will be executed if the type passed to throw matches H. For example,

```cpp
try{
    throw 20;
}catch (int e){
    cout << "An exception occurred. Exception Nr. " << e << '\n';
}
```
will match the type of e with the number 20 and print the exception message given.[2]

C++ defines exception types in libraries, and the standard C++ library throws exceptions derived from its exception class, which are: *bad_alloc, bad_cast, bad_exception, bad_typeid, bad_function_call,and bad_weak_ptr*.

But we can also define a general form for handling any type of exception we might need using ellipses (...) like this

```cpp
try{
    //do something..
}catch(...){
	//handle this exception.
}
```

Another important thing to know is that the order of catch statements in C++ matters, which can help us define a sequence to follow to handle exceptions if we need one.[2]

```cpp
try {
  // code here
}catch (int param){
    cout << "int exception";
}catch (char param){
    cout << "char exception";
}catch (...){
    cout << "default exception";
}
```

The code above would first try to match the type of exception to ```int```, then to ```char```, and finally it would default to the ellipsis case.

If we want to rethrow exceptions we could do it like this

```cpp
void f(){
	try{
	    E1 myException;
        throw myException;
    }catch(E1& e){
         throw;
    }
}

main(){
    try{
	    f();
    }catch(...){
	    throw;
    }
}
```
Here ```E1``` can be defined earlier. Once the the catch statement catches the pointer to ```myException```, it is rethrown and caught by the catch block in the ```main()``` function.[3]

Lastly, try-catch blocks can be nested in C++ and we can do it like this

```cpp
try{
    try{
	    //try something...
    }catch(int n){
	    throw;
    }
}catch(...){
	cout << "Exception occurred";
}
```
So, the code above tries something, catches an int exception, rethrows it, and the outter catch block can still catch it using the general case of (...).[2]

### Sources:
1. C++ Programming Language, Third Edition - Bjarne Stroustrup.
2. [www.cplusplus.com](http://www.cplusplus.com/doc/tutorial/exceptions/)
3. [IBM](https://www.ibm.com/support/knowledgecenter/SSB27U_6.3.0/com.ibm.zos.r12.cbclx01/cplr153.htm)


text:
author: admin
comments: true
date: 2010-06-22 19:41:12+00:00
layout: post
slug: install-pyqt4-in-snow-leopard
title: Install PyQt4 in Snow Leopard
wordpress_id: 307
categories:
- Guides
tags:
- mac os x
- pyqt
- python
- qt
- snow leopard
---

New country, new life style, new spoken language and new GUI toolkit ! After 5 years of wxPython toolkit now it's the time to move to PyQt4. Let's see how install this GUI toolkit under Mac OS X Snow Leopard.

<!-- more -->

First, donwload th QT4 SDK from QT official site, from [here](http://qt.nokia.com/products/) you can choose between LGPL and Commercial version. If you want just the LGPL version you can go directly [here](http://qt.nokia.com/downloads/downloads#lgpl). The .dmg it's about 500Mb so if you have a slow connection it will take some minutes.

In the meanwhile donwload the SIP and PyQt4 sources from the Riverbank website, [here](http://www.riverbankcomputing.co.uk/software/sip/download) for SIP package and [here](http://www.riverbankcomputing.co.uk/software/pyqt/download) for PyQt4 package. These files are small (about 10Mb) so they will take one minute or two.

When the download of the Qt4 package is done, open the .dmg file and install the package as usual. Extract the SIP and PyQt4 .tar.gz files as well.

Starting from the installation of SIP package, open the Terminal, move into the folder where the SIP's sources reside and type:

    $ export MACOSX_DEPLOYMENT_TARGET=10.6
    $ python configure.py -n  --arch=i386 -s MacOSX10.6.sdk
    $ make
    $ sudo make install

Now move into the PyQt4 folder and type:

    $ export QTDIR=/Developer/Applications/Qt
    $ python configure.py --use-arch=i386
    $ make
    $ sudo make install

After the long compilation and installation phase, just for testing if the PyQt4 package is installed correctly, from the Terminal type:

    $ python
    Python 2.6.5 (r265:79359, Mar 24 2010, 01:32:55)
    [GCC 4.0.1 (Apple Inc. build 5493)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import PyQt4
    >>>

No errors after `import` command means the PyQt4 package is installed.

And now good work with PyQt !

redpajama_set_name: RedPajamaGithub


text:
import _extends from "@babel/runtime/helpers/builtin/extends";
import _jsx from "@babel/runtime/helpers/builtin/jsx";
import _objectWithoutProperties from "@babel/runtime/helpers/builtin/objectWithoutProperties";
import cx from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import IconButton from "@material-ui/core/es/IconButton";
import ImportIcon from "@material-ui/icons/es/PlaylistAdd";

var _ref2 =
/*#__PURE__*/
_jsx(ImportIcon, {});

var PlaylistRow = function PlaylistRow(_ref) {
  var className = _ref.className,
      playlist = _ref.playlist,
      onImport = _ref.onImport,
      attrs = _objectWithoutProperties(_ref, ["className", "playlist", "onImport"]);

  var thumbnail = _jsx("div", {
    className: "MediaListRow-thumb"
  }, void 0, _jsx("img", {
    className: "MediaListRow-image",
    src: playlist.thumbnail,
    alt: ""
  }, playlist.id));

  return React.createElement("div", _extends({
    className: cx('MediaListRow', 'src-youtube-PlaylistRow', className)
  }, attrs), thumbnail, _jsx("div", {
    className: "src-youtube-PlaylistRow-info",
    title: playlist.description
  }, void 0, _jsx("div", {
    className: "src-youtube-PlaylistRow-name"
  }, void 0, playlist.name), _jsx("div", {
    className: "src-youtube-PlaylistRow-size"
  }, void 0, "Items: ", playlist.size)), _jsx(IconButton, {
    className: "src-youtube-PlaylistRow-import",
    onClick: onImport
  }, void 0, _ref2));
};

PlaylistRow.propTypes = process.env.NODE_ENV !== "production" ? {
  className: PropTypes.string,
  playlist: PropTypes.object.isRequired,
  onImport: PropTypes.func.isRequired
} : {};
export default PlaylistRow;
//# sourceMappingURL=PlaylistRow.js.map


text:
package apple.multipeerconnectivity;

import java.io.*;
import java.nio.*;
import java.util.*;
import com.google.j2objc.annotations.*;
import com.google.j2objc.runtime.*;
import com.google.j2objc.runtime.block.*;
import apple.audiotoolbox.*;
import apple.corefoundation.*;
import apple.coregraphics.*;
import apple.coreservices.*;
import apple.foundation.*;
import apple.uikit.*;
import apple.security.*;

@Library("MultipeerConnectivity/MultipeerConnectivity.h") @Mapping("MCNearbyServiceAdvertiserDelegate")
public interface MCNearbyServiceAdvertiserDelegate
    extends NSObjectProtocol {

    @Mapping("advertiser:didReceiveInvitationFromPeer:withContext:invitationHandler:")
    void didReceiveInvitation(MCNearbyServiceAdvertiser advertiser, MCPeerID peerID, NSData context, @Block VoidBlock2<Boolean, MCSession> invitationHandler);
    @Mapping("advertiser:didNotStartAdvertisingPeer:")
    void didNotStart(MCNearbyServiceAdvertiser advertiser, NSError error);

    /*<adapter>*/
    /*</adapter>*/
}


text:
layout: minimal
title: "About me"
permalink: /about/index.html
description: "Some description about Victor Igor..."
---

Our Goals

Customers will find best deals with best shops.

Unlimited shirt design ideas from a lively community.

Fun quests that have rewards. :)


text:
AsyncHttpClient client = new DefaultAsyncHttpClient();
client.prepare("GET", "http://mockbin.com/har")
  .setHeader("accept", "application/json")
  .setHeader("x-foo", "Bar")
  .execute()
  .toCompletableFuture()
  .thenAccept(System.out::println)
  .join();

client.close();


text:
package com.snell.michael.kawaii.person;

import com.snell.michael.kawaii.string.StringMicroType;

import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.commons.lang.StringUtils.isBlank;

public abstract class Name extends StringMicroType {
    protected Name(String value) {
        super(value);
    }

    @Override
    protected void validate() {
        super.validate();
        checkArgument(!isBlank(value), "Name cannot be blank");
        checkArgument(!value.contains(" "), "Name cannot contain spaces");
    }
}


text:
package com.runnerdtalks.mockitos;

import static org.junit.Assert.assertEquals;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;

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

import org.junit.Test;
import org.mockito.Mockito;

public class MyMessageReaderTest {

	private MyMessageReader myMessageReader;

	private Connection connection;

	@Test
	public void readMessageTest() {
		connection = mock(Connection.class);

		given(connection.readMessage()).willReturn("minhaMensagem");
//		when(connection.readMessage()).thenReturn("minhaMensagem");
		myMessageReader = new MyMessageReader(connection);

		String readedMessage = myMessageReader.readMessage();

		assertEquals(readedMessage, "minhaMensagem");
	}
}


text:
'''
@author: lalluanthoor

Views in the VirtualBet application
'''

'''
Public section
'''

from datetime import date

from django.contrib import messages
from django.contrib.auth import authenticate, forms, login, logout
from django.db.models import Sum
from django.http import HttpResponse
from django.http.response import HttpResponseRedirect
from django.shortcuts import render

from vb.core import manageBets, manageCentral, manageFunds
from vb.forms import AddMoneyForm, BetForm, ConfigForm, LoginForm, MultiplierForm, RegistrationForm, ResultForm, TransferForm
from vb.models import Bet, BettingUser, Configuration, Fixture

def index(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('/bet/')
    else:
        theme = Configuration.objects.get(pk=1).theme.theme_name
        return HttpResponse(render(request, 'user/index.html', context={'title': 'Home', 'theme': theme, 'active': {'home': 'active'}}))

def loginForm(request):
    if request.user.is_authenticated():
        if not BettingUser.objects.get(username=request.user.username).bet_admin:
            return HttpResponseRedirect('/bet/')
        else:
            return HttpResponseRedirect('/bet/super/')
    else:
        if request.method == 'POST':
            form = LoginForm(request.POST)
            if form.is_valid():
                user = authenticate(
                    username=request.POST['username'], password=request.POST['password'])
                if user is not None:
                    if user.is_active:
                        usr = BettingUser.objects.get(username=user.username)
                        login(request, user)
                        if usr.bet_admin:
                            return HttpResponseRedirect('/bet/super/')
                        else:
                            return HttpResponseRedirect('/bet/')
                    else:
                        messages.error(request, 'Invalid username/password')
                else:
                    messages.error(request, 'Invalid username/password')
            else:
                messages.error(request, 'Validation Error')
        else:
            form = LoginForm()
        theme = Configuration.objects.get(pk=1).theme.theme_name
        return HttpResponse(render(request, 'user/login.html', context={'form': form, 'title': 'Login', 'theme': theme, 'active': {'login': 'active'}}))

def register(request):
    if request.method == 'POST':
        return manageCentral.registerUser(request)
    else:
        form = RegistrationForm()
        theme = Configuration.objects.get(pk=1).theme.theme_name
        return HttpResponse(render(request, 'user/registration.html', context={'form': form, 'theme': theme, 'title': 'Register', 'active': {'login': 'active'}}))

def standings(request):
    if request.user.is_authenticated():
        return HttpResponseRedirect('bet/standings.html')
    else:
        theme = Configuration.objects.get(pk=1).theme.theme_name
        context = {'users': BettingUser.objects.order_by(
            '-account_balance', 'first_name', 'last_name').filter(bet_admin=False), 'title': 'Standings', 'theme': theme, 'active': {'standings': 'active'}}
        return HttpResponse(render(request, 'user/standings.html', context))

'''
View functions for betting user (non-admin)
'''

def bet(request):
    if request.user.is_authenticated() and not BettingUser.objects.get(username=request.user.username).bet_admin:
        theme = Configuration.objects.get(pk=1).theme.theme_name
        context = {'bets': Bet.objects.order_by(
            '-match').filter(user=request.user), 'active': {'home': "active"}, 'title': 'Bet Home', 'theme': theme}
        return HttpResponse(render(request, 'bet/index.html', context=context))
    else:
        return HttpResponseRedirect('/login/')

def betStandings(request):
    if request.user.is_authenticated() and not BettingUser.objects.get(username=request.user.username).bet_admin:
        theme = Configuration.objects.get(pk=1).theme.theme_name
        context = {'users': BettingUser.objects.order_by(
            '-account_balance', 'first_name', 'last_name').filter(bet_admin=False), 'active': {'standings': "active"}, 'title': 'Standings', 'theme': theme}
        return HttpResponse(render(request, 'bet/standings.html', context))
    else:
        return HttpResponseRedirect('/login/')

def placeBet(request):
    if request.user.is_authenticated() and not BettingUser.objects.get(username=request.user.username).bet_admin:
        if request.method == 'POST':
            return manageBets.placeBets(request)
        else:
            form = BetForm()
            theme = Configuration.objects.get(pk=1).theme.theme_name
            return HttpResponse(render(request, 'bet/placebet.html', context={'form': form, 'active': {"placebet": "active"}, 'title': 'Bet', 'theme': theme}))
    else:
        return HttpResponseRedirect('/login/')

def transfer(request):
    if request.user.is_authenticated() and not BettingUser.objects.get(username=request.user.username).bet_admin:
        if request.method == 'POST':
            return manageFunds.transferFunds(request)
        else:
            form = TransferForm()
            theme = Configuration.objects.get(pk=1).theme.theme_name
            return HttpResponse(render(request, 'bet/transfer.html', context={'form': form, 'active': {'transfer': 'active'}, 'title': 'Transfers', 'theme': theme}))
    else:
        return HttpResponseRedirect('/login/')

'''
View functions for bet administrator
'''

def admin(request):
    if request.user.is_authenticated() and BettingUser.objects.get(username=request.user.username).bet_admin:
        futureMatches = Fixture.objects.filter(match_date__gte=date.today())
        betAggregate = []
        for match in futureMatches:
            if Bet.objects.filter(match=match, team=match.away_team).aggregate(Sum('amount'))['amount__sum'] > 0 or Bet.objects.filter(match=match, team=match.home_team).aggregate(Sum('amount'))['amount__sum'] > 0:
                betAggregate.append({'match': match, 'home': Bet.objects.filter(match=match, team=match.home_team).aggregate(
                    Sum('amount')), 'away': Bet.objects.filter(match=match, team=match.away_team).aggregate(Sum('amount'))})
        futureBets = []
        for match in futureMatches:
            if len(Bet.objects.filter(match=match)) != 0:
                futureBets.append(
                    Bet.objects.filter(match=match).order_by('team', '-amount'))
        theme = Configuration.objects.get(pk=1).theme.theme_name
        return HttpResponse(render(request, 'super/index.html', context={'active': {'home': 'active'}, 'data': betAggregate, 'bets': futureBets, 'title': 'Admin Home | Virtual Bet', 'theme': theme}))
    else:
        return HttpResponseRedirect('/login/')

def addResult(request):
    if request.user.is_authenticated() and BettingUser.objects.get(username=request.user.username).bet_admin:
        if request.method == 'POST':
            return manageBets.addResult(request)
        else:
            form = ResultForm()
            theme = Configuration.objects.get(pk=1).theme.theme_name
            return HttpResponse(render(request, 'super/addresult.html', context={'active': {'addresult': 'active'}, 'form': form, 'title': 'Add Result', 'theme': theme}))
    else:
        return HttpResponseRedirect('/login/')

def adminStandings(request):
    if request.user.is_authenticated() and BettingUser.objects.get(username=request.user.username).bet_admin:
        theme = Configuration.objects.get(pk=1).theme.theme_name
        context = {'users': BettingUser.objects.order_by(
            '-account_balance', 'first_name', 'last_name').filter(bet_admin=False), 'active': {'standings': "active"}, 'title': 'Standings', 'theme': theme}
        return HttpResponse(render(request, 'super/standings.html', context))
    else:
        return HttpResponseRedirect('/login/')

def multiplier(request):
    if request.user.is_authenticated() and BettingUser.objects.get(username=request.user.username).bet_admin:
        if request.method == 'POST':
            return manageFunds.addMultiplier(request)
        else:
            form = MultiplierForm()
            theme = Configuration.objects.get(pk=1).theme.theme_name
            return HttpResponse(render(request, 'super/multiplier.html', context={'form': form, 'active': {'multiplier': 'active'}, 'title': 'Win Multiplier', 'theme': theme}))
    else:
        return HttpResponseRedirect('/login/')

def config(request):
    if request.user.is_authenticated() and BettingUser.objects.get(username=request.user.username).bet_admin:
        if request.method == 'POST':
            return manageCentral.configUpdate(request)
        else:
            form = ConfigForm(instance=Configuration.objects.get(pk=1))
            theme = Configuration.objects.get(pk=1).theme.theme_name
            return HttpResponse(render(request, 'super/config.html', context={'form': form, 'active': {'config': 'active'}, 'title': 'Configuration', 'theme': theme}))
    else:
        return HttpResponseRedirect('/login/')

def addmoney(request):
    if request.user.is_authenticated() and BettingUser.objects.get(username=request.user.username).bet_admin:
        if request.method == 'POST':
            return manageFunds.addMoney(request)
        else:
            form = AddMoneyForm()
            theme = Configuration.objects.get(pk=1).theme.theme_name
            return HttpResponse(render(request, 'super/addmoney.html', context={'form': form, 'active': {'addmoney': 'active'}, 'title': 'Add Money', 'theme': theme}))
    else:
        return HttpResponseRedirect('/login/')

def luckydraw(request):
    if request.user.is_authenticated() and BettingUser.objects.get(username=request.user.username).bet_admin:
        if request.method == 'POST':
            return manageFunds.addLuckyDraw(request)
        else:
            form = TransferForm()
            theme = Configuration.objects.get(pk=1).theme.theme_name
            return HttpResponse(render(request, 'super/luckydraw.html', context={'form': form, 'theme': theme, 'title': 'Lucky Draw', 'active': {'luckydraw': 'active'}}))
    else:
        return HttpResponseRedirect('/login/')

'''
Common view functions
'''

def changepassword(request):
    if request.user.is_authenticated():
        if request.method == 'POST':
            return manageCentral.changePassword(request)
        else:
            form = forms.PasswordChangeForm(user=request.user)
            theme = Configuration.objects.get(pk=1).theme.theme_name
            return HttpResponse(render(request, 'bet/changepassword.html', context={'form': form, 'theme': theme, 'title': 'Change Password'}))
    else:
        return HttpResponseRedirect('/login/')

def logoutForm(request):
    logout(request)
    return HttpResponseRedirect('/login/')


text:
Arduino Pinball Controller
==========================

MPF can control System3 to System11c machines directly using the Arduino
Pinball Controller (APC).
It contains CPU and drivers so it can also be used to build full custom
machines.
Uses the :doc:`LISY protocol </hardware/lisy/protocol>`.

This is how APC generally works:

.. youtube:: w4Po8OE5Zkw

See `Arduino Pinball Controller Documentation <https://github.com/AmokSolderer/APC>`_
on github for details.

This is an example config:

.. code-block:: mpf-config

   #config_version=5
   hardware:
     platform: lisy
   lisy:
     connection: serial
     port: com1      # change this for your setup
     baud: 115200
   digital_outputs:
     game_over_relay:
       number: 1
       type: light
       enable_events: ball_started
       disable_events: ball_will_end
   segment_displays:
     info_display:
       number: 0
     player1_display:
       number: 1
     player2_display:
       number: 2
     player3_display:
       number: 3
     player4_display:
       number: 4
   hardware_sound_systems:
     default:
       label: APC

See the :doc:`LISY platform </hardware/lisy/index>` for more details on
configuring hardware.

.. toctree::
   :titlesonly:

   connection


text:
<?php
namespace App\LoginModule\Profile\Verification;

use App\LoginModule\Platform\PlatformContext;
use App\VerificationMethod;
use Carbon\Carbon;

class Verification {

    const STATE_NOT_VERIFIED = 'NOT_VERIFIED';
    const STATE_VERIFICATION_REQUIRED = 'VERIFICATION_REQUIRED';
    const STATE_IN_PROCESS = 'IN_PROCESS';
    const STATE_ACTION_REQUIRED = 'ACTION_REQUIRED';
    const STATE_REFRESH_REQUIRED = 'REFRESH_REQUIRED';
    const STATE_OBSOLETE = 'OBSOLETE';
    const STATE_VERIFIED = 'VERIFIED';
    const STATE_REJECTED = 'REJECTED';

    const ATTRIBUTES = [
        'first_name',
        'last_name',
        'graduation_grade',
        'graduation_year',
        'country_code',
        'role',
        'primary_email',
        'secondary_email',
        'student_id',
        'birthday'
    ];

    protected $context;
    protected $methods_cache = null;
    protected $verifications_cache = null;
    protected $verifications_global_cache = null;

    public function __construct(PlatformContext $context) {
        $this->context = $context;
    }

    public function attributes() {
        if($client = $this->context->client()) {
            return $client->verifiable_attributes;
        }
        return [];
    }

    public function methods() {
        if($this->methods_cache === null) {
            if($client = $this->context->client()) {
                $this->methods_cache = $client->verification_methods;
            } else {
                $this->methods_cache = collect();
            }
        }
        return $this->methods_cache;
    }

    public function verifications($user) {
        if($this->verifications_cache === null) {
            $this->verifications_cache = $user->verifications()
                ->whereIn('method_id', $this->methods()->pluck('id'))
                ->get()
                ->map(function($verification) {
                    $verification->state = $this->verificationState($verification);
                    return $verification;
                });
        }
        return $this->verifications_cache;
    }

    public function verificationState($verification) {
        if(!$verification) {
            return self::STATE_NOT_VERIFIED;
        }
        if($this->verificationExpired($verification, true)) {
            return self::STATE_REFRESH_REQUIRED;
        }
        if($this->verificationExpired($verification)) {
            return self::STATE_OBSOLETE;
        }
        if($verification->status == 'pending') {
            $has_action = $verification->method->name == 'peer';
            return $has_action ? self::STATE_ACTION_REQUIRED : self::STATE_IN_PROCESS;
        }
        if($verification->status == 'approved') {
            return self::STATE_VERIFIED;
        }
        return self::STATE_REJECTED;
    }

    public function authReady($user) {
        $unverified_attributes = array_intersect(
            $this->attributes(),
            $this->unverifiedAttributes($user)
        );
        return count($unverified_attributes) == 0;
    }

    public function verifiedAttributes($user) {
        $states = $this->attributesState($user);
        $res = [];
        foreach($states as $attribute => $state) {
            if($state == self::STATE_VERIFIED) {
                $res[] = $attribute;
            }
        }
        return $res;
    }

    public function unverifiedAttributes($user) {
        $states = $this->attributesState($user);
        $res = [];
        foreach($states as $attribute => $state) {
            if($state != self::STATE_VERIFIED) {
                $res[] = $attribute;
            }
        }
        return $res;
    }

    public function verificationsGlobal($user) {
        if($this->verifications_global_cache === null) {
            $this->verifications_global_cache = $user->verifications()
                ->get()
                ->map(function($verification) {
                    $verification->state = $this->verificationState($verification);
                    return $verification;
                });
        }
        return $this->verifications_global_cache;
    }

    public function attributeVerifiedGlobal($user, $attribute) {
        $verifications = $this->verificationsGlobal($user);
        foreach($verifications as $verification) {
            foreach($verification->user_attributes as $attr) {
                if($attr == $attribute && $verification->state == self::STATE_VERIFIED) {
                    return true;
                }
            }
        }
        return false;
    }

    public function attributesState($user) {
        $verifications = $this->verifications($user);
        $res = array_fill_keys($this->attributes(), self::STATE_NOT_VERIFIED);

        foreach($verifications as $verification) {
            foreach($verification->user_attributes as $attribute) {
                if(!isset($res[$attribute])) {
                    $res[$attribute] = self::STATE_NOT_VERIFIED;
                }
                if($res[$attribute] != self::STATE_VERIFIED) {
                    $res[$attribute] = $verification->state;
                };
            }
        }
        return $res;
    }

    private function verificationExpired($verification, $expiration_alert = false) {
        if($verification->status != 'approved' || !$verification->approved_at) {
            return false;
        }

        $methods = $this->methods()->pluck('pivot', 'id');
        if(isset($methods[$verification->method_id])) {
            $expiration = $methods[$verification->method_id]->expiration;
            if(!$expiration) {
                return false;
            }
            if($expiration_alert) {
                $expiration = max(0, $expiration - config('verification.expiration_alert_interval'));
            }
            $expire_at = Carbon::parse($verification->approved_at)->addDays($expiration);
            return Carbon::now()->gt($expire_at);
        }
        return false;
    }

    public static function clear($user, $user_attributes) {
        if(!is_array($user_attributes)) {
            $user_attributes = [$user_attributes];
        }
        $verifications = $user->verifications()->where('status', 'approved')->get();
        foreach($verifications as $verification) {
            $intersection = array_intersect($user_attributes, $verification->user_attributes);
            if(count($intersection) > 0) {
                $verification->delete();
            }
        }
    }

    public static function stateLabel($verification) {
        if($verification->state == self::STATE_VERIFIED) {
            $c = 'label-success';
            $i = 'fas fa-check';
        } else if($verification->state == self::STATE_IN_PROCESS) {
            $c = 'label-warning';
            $i = 'fas fa-clock';
        } else if($verification->state == self::STATE_ACTION_REQUIRED) {
            $c = 'label-info';
            $i = 'fas fa-exclamation';
        } else {
            $c = 'label-danger';
            $i = 'fas fa-bell';
        }
        return
            ''.
                ''.
                trans('verification.states.'.$verification->state).
            '';
    }

}


text:
import os
import sys
import tempfile
import shutil
import logging
from abc import ABCMeta, abstractmethod

from rebuild_tool.graph import PackageGraph
from rebuild_tool.rebuild_metadata import Recipe
from rebuild_tool.exceptions import MissingRecipeException, BuildFailureException
from rebuild_tool import utils

logger = logging.getLogger(__name__)

def check_build(build_fce):
    '''
    Decorator to check if build was successfull or not,
    updates attributes and removes package from graph
    '''

    def inner(self, pkgs, verbose=True):
        if not isinstance(pkgs, list):
            pkgs = [pkgs]
        if build_fce(self, pkgs, verbose):
            for pkg in pkgs:
                if verbose:  # not building recipe
                    self.graph.G.remove_node(pkg)
                self.built_packages.add(pkg)
            return True
        else:
            raise BuildFailureException("Failed to build packages {}.".format(pkgs))
    return inner

class Builder(metaclass=ABCMeta):
    '''
    Abstract superclass of builder classes.
    '''

    def __init__(self, rebuild_metadata, pkg_source):
        self.pkg_source = pkg_source
        self.packages = set(rebuild_metadata['packages'])
        if 'metapackage' in rebuild_metadata:
            self.metapackage = rebuild_metadata['metapackage']
        self.repo = rebuild_metadata['repo']
        self.prefix = rebuild_metadata['prefix']
        self.koji_tag = rebuild_metadata['koji_tag']
        self.path = tempfile.mkdtemp()
        self.built_packages = set()
        self.num_of_deps = {}
        self.circular_deps = []
        self.get_files()
        self.graph = PackageGraph(self.repo, self.pkg_source)
        try:
            self.recipes = rebuild_metadata['recipes']
        except IOError:
            logger.error("Failed to load recipe {0}.".format(rebuild_metadata['recipes']))

    def __del__(self):
        shutil.rmtree(self.path)
        shutil.rmtree(self.__tempdir)

    @property
    def path(self):
        return self.__path

    @path.setter
    def path(self, value):
        self.__tempdir = value
        value += '/rebuild_tool-{0}/'.format(self.repo)
        if not os.path.isdir(value):
            os.makedirs(value)
        self.__path = value

    @property
    def recipes(self):
        return self.__recipes

    @recipes.setter
    def recipes(self, recipe_files):
        if not recipe_files:
            self.__recipes = None
        else:
            self.__recipes = [Recipe(recipe) for recipe in recipe_files]

    def get_relations(self):
        '''
        Runs graph analysis and get dependance tree and circular_deps
        '''
        self.graph.make_graph()
        self.circular_deps = self.graph.get_cycles()
        if self.circular_deps and not self.recipes:
            raise MissingRecipeException(
                "Missing recipes to resolve circular dependencies in graph.")

    def deps_satisfied(self, package):
        '''
        Compares package deps with self.build_packages to
        check if are all dependancies already built
        '''
        if set(self.graph.G.successors(package)) <= self.built_packages:
            return True
        return False

    def recipe_deps_satisfied(self, recipe):
        '''
        Checks if all packages in recipe have satisfied their
        dependencies on packages that are not in recipe
        '''
        deps = set()
        for pkg in recipe.packages:
            if not pkg in self.packages:
                raise KeyError("Package {} from recipe missing in packages list".format(pkg))
            deps |= set(self.graph.G.successors(pkg))

        if (deps - recipe.packages) <= self.built_packages:
            return True
        return False

    @check_build
    def build(self, pkgs, verbose=True):
        for pkg in pkgs:
            if verbose:
                print("Building {0}...".format(pkg))
        return True

    def run_building(self):
        '''
        First builds all packages without deps, then iterates over num_of_deps
        and simulate building of packages in right order
        '''

        # Build and add metapackage to chroots when rebuilding scl
        if hasattr(self, 'metapackage'):
            self.build([self.metapackage])
            self.add_chroot_pkg([self.metapackage])

        while self.packages > self.built_packages:
            zero_deps = self.graph.get_leaf_nodes()
            if zero_deps:
                self.build(zero_deps)
            else:
                for recipe in self.recipes:
                    if list(self.packages - self.built_packages)[1] in recipe.packages and\
                            self.recipe_deps_satisfied(recipe):
                        self.build_following_recipe(recipe)
                        break
                else:
                    sys.stderr.write("Recipe to resolve circular dependencies not found.\n")
                    raise SystemExit(1)

    def find_recipe(self, package):
        '''
        Search for recipe including package in self.recipes
        '''
        for recipe in self.recipes:
            if package in recipe.packages:
                return recipe
        raise MissingRecipeException("Recipe for package {0} not found".format(package))

    def build_following_recipe(self, recipe):
        '''
        Builds packages in order and macro values discribed in given
        recipe.
        '''
        for step in recipe.order:
            if len(step) == 1:
                print("Building package {0}".format(step[0]))
            else:
                (name, macro_value) = step
                print("Building package {0} {1}".format(name, macro_value))
                (macro, value) = macro_value.split(' ')
                utils.check_bootstrap_macro(self.pkg_source[name].full_path_spec, macro)
                utils.edit_bootstrap(self.pkg_source[name].full_path_spec, macro, value)
                self.pkg_source[name].pack()
            self.build([step[0]], False)
        for pkg in {step[0] for step in recipe.order}:
            self.graph.G.remove_node(pkg)
        self.recipes.remove(recipe)

    def get_files(self):
        '''
        Creates SrpmArchive object and downloads files for each package
        '''
        with utils.ChangeDir(self.path):
            for package in self.packages:
                pkg_dir = self.path + package + "_files/"
                if not os.path.exists(pkg_dir):
                    os.mkdir(pkg_dir)
                print("Getting files of {0}.".format(package))
                logger.debug("Getting files of {0}.".format(package))
                self.pkg_source.add(package, pkg_dir, self.repo, self.prefix, self.koji_tag)


text:
<?php defined('C5_EXECUTE') or die("Access Denied.");?>
<form method="post" class="ccm-dashboard-content-form" action="<?php echo $view->action('update_sitename')?>">
	<?php echo $this->controller->token->output('update_sitename')?>

	<fieldset>

		<label for="SITE" class="launch-tooltip control-label" data-placement="right" title="<?php echo t('By default, site name is displayed in the browser title bar. It is also the default name for your project on concrete5.org')?>"><?php echo t('Site Name')?>
		<?php echo $form->text('SITE', $site, array('class' => 'span4'))?>

	</fieldset>

		<button class="pull-right btn btn-primary" type="submit" ><?php echo t('Save')?></button>

</form>


text:
namespace hex {

#define MESSAGE_TEMPLATE_NAME Game
#define MESSAGE_TEMPLATE_INCLUDE_FILE "hexgame/game/message_types.h"
#define MESSAGE_TEMPLATE_START_ID 1000
#include "hexutil/messaging/message_cpp_template.h"

static GameMessageFactory game_messages_factory;

void register_game_messages() {
    MessageTypeRegistry::add_factory(&game_messages_factory);
}

};


text:
package com.kmwllc.brigade.connector.xml;

import com.kmwllc.brigade.connector.AbstractConnector;
import com.kmwllc.brigade.document.Document;
import com.kmwllc.brigade.logging.LoggerFactory;
import com.kmwllc.brigade.utils.RecordingInputStream;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.common.Strings;
import org.slf4j.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.util.Arrays;
import java.util.Stack;
import java.util.UUID;

public class ChunkingXMLHandler implements ContentHandler {

  transient public final static Logger log = LoggerFactory.getLogger(ChunkingXMLHandler.class);

  Stack<String> currentPath = new Stack<String>();
  private AbstractConnector connector;
  private String documentRootPath;
  private String documentIDPath;
  private String docIDPrefix = "";
  private boolean inDocID = false;
  // private boolean inDoc = false;
  private StringBuilder docIDBuilder = new StringBuilder();
  private RecordingInputStream ris;

  @Override
  public void setDocumentLocator(Locator locator) {
    // TODO Auto-generated method stub
  }

  @Override
  public void startDocument() throws SAXException {
    // TODO Auto-generated method stub

  }

  @Override
  public void endDocument() throws SAXException {
    // TODO Auto-generated method stub

  }

  @Override
  public void startPrefixMapping(String prefix, String uri) throws SAXException {
    // TODO Auto-generated method stub

  }

  @Override
  public void endPrefixMapping(String prefix) throws SAXException {
    // TODO Auto-generated method stub

  }

  @Override
  public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
    // push on the stack.
    currentPath.push(qName);
    // log.info("Start element: {}",qName);
    String path = "/" + StringUtils.join(currentPath.toArray(), "/");
    // log.info("{} PATH: {}", documentRootPath, path);
    if (documentRootPath.equals(path)) {
      // this is the start of our page.
      docIDBuilder = new StringBuilder();
      // ok we should clear our input buffer up to the current offset for this
      // start element.
      try {
        ris.clearUpTo("<" + qName);
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

    }
    if (documentIDPath.equals(path)) {
      // this is the start of the document id field.
      inDocID = true;
    }
  }

  @Override
  public void endElement(String uri, String localName, String qName) throws SAXException {
    // we just finished a path. see if it's the doc root that we're looking for.
    String path = "/" + StringUtils.join(currentPath.toArray(), "/");
    if (documentRootPath.equals(path)) {
      // ok, now we want the buffer up to the close tag.
      String xml = "Malformed";
      try {
        xml = ris.returnUpTo("</" + qName + ">");
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }

      // this is the end of our page send the buffer as a document

      // XPath not supported where id is in attribute (e.g. <field name="id">
      // Quick workaround is to use a UUID instead and assign ID elsewhere in workflow
      String id = docIDBuilder.toString();
      if (Strings.isNullOrEmpty(id)) {
        id = UUID.randomUUID().toString();
      }

      Document doc = new Document(docIDPrefix + id);
      doc.setField("xml", xml);
      internalPublishDocument(doc);
    }
    if (documentIDPath.equals(path)) {
      // this is the end of the doc id tag.
      inDocID = false;
    }
    // pop up..
    currentPath.pop();
  }

  private void internalPublishDocument(Document doc) {
    // publish the doc.
    // does this need to be an invoke?
    // always feed a batch
    connector.feed(doc);
  }

  @Override
  public void characters(char[] ch, int start, int length) throws SAXException {
    if (inDocID) {
      docIDBuilder.append(Arrays.copyOfRange(ch, start, start + length));
    }
  }

  @Override
  public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
    // TODO Auto-generated method stub

  }

  @Override
  public void processingInstruction(String target, String data) throws SAXException {
    // TODO Auto-generated method stub

  }

  @Override
  public void skippedEntity(String name) throws SAXException {
    // TODO Auto-generated method stub
  }

  public String getDocumentRootPath() {
    return documentRootPath;
  }

  public void setDocumentRootPath(String documentRootPath) {
    this.documentRootPath = documentRootPath;
  }

  public String getDocumentIDPath() {
    return documentIDPath;
  }

  public void setDocumentIDPath(String documentIDPath) {
    this.documentIDPath = documentIDPath;
  }

  public String getDocIDPrefix() {
    return docIDPrefix;
  }

  public void setDocIDPrefix(String docIDPrefix) {
    this.docIDPrefix = docIDPrefix;
  }

  public void setConnector(AbstractConnector connector) {
    this.connector = connector;
  }

  public RecordingInputStream getRis() {
    return ris;
  }

  public void setRis(RecordingInputStream ris) {
    this.ris = ris;
  }

}


text:
.. _kx_pkgs4bootstrap:

kx_pkgs4bootstrap - Install packages for configure
==================================================

SYNOPSIS
--------
**kx_pkgs4bootstrap**

DESCRIPTION
-----------
Try to install packages (on host) necessary for
bootstrapping **KaarPux**


text:
from ctypes import POINTER, c_char_p, c_int, c_size_t, c_uint, c_bool, c_void_p
import enum

from llvmlite.binding import ffi
from llvmlite.binding.common import _decode_string, _encode_string

class Linkage(enum.IntEnum):
    # The LLVMLinkage enum from llvm-c/Core.h

    external = 0
    available_externally = 1
    linkonce_any = 2
    linkonce_odr = 3
    linkonce_odr_autohide = 4
    weak_any = 5
    weak_odr = 6
    appending = 7
    internal = 8
    private = 9
    dllimport = 10
    dllexport = 11
    external_weak = 12
    ghost = 13
    common = 14
    linker_private = 15
    linker_private_weak = 16

class Visibility(enum.IntEnum):
    # The LLVMVisibility enum from llvm-c/Core.h

    default = 0
    hidden = 1
    protected = 2

class StorageClass(enum.IntEnum):
    # The LLVMDLLStorageClass enum from llvm-c/Core.h

    default = 0
    dllimport = 1
    dllexport = 2

class TypeRef(ffi.ObjectRef):
    """A weak reference to a LLVM type
    """
    @property
    def name(self):
        """
        Get type name
        """
        return ffi.ret_string(ffi.lib.LLVMPY_GetTypeName(self))

    @property
    def is_pointer(self):
        """
        Returns true is the type is a pointer type.
        """
        return ffi.lib.LLVMPY_TypeIsPointer(self)

    @property
    def element_type(self):
        """
        Returns the pointed-to type. When the type is not a pointer,
        raises exception.
        """
        if not self.is_pointer:
            raise ValueError("Type {} is not a pointer".format(self))
        return TypeRef(ffi.lib.LLVMPY_GetElementType(self))

    def __str__(self):
        return ffi.ret_string(ffi.lib.LLVMPY_PrintType(self))

class ValueRef(ffi.ObjectRef):
    """A weak reference to a LLVM value.
    """

    def __init__(self, ptr, kind, parents):
        self._kind = kind
        self._parents = parents
        ffi.ObjectRef.__init__(self, ptr)

    def __str__(self):
        with ffi.OutputString() as outstr:
            ffi.lib.LLVMPY_PrintValueToString(self, outstr)
            return str(outstr)

    @property
    def module(self):
        """
        The module this function or global variable value was obtained from.
        """
        return self._parents.get('module')

    @property
    def function(self):
        """
        The function this argument or basic block value was obtained from.
        """
        return self._parents.get('function')

    @property
    def block(self):
        """
        The block this instruction value was obtained from.
        """
        return self._parents.get('block')

    @property
    def instruction(self):
        """
        The instruction this operand value was obtained from.
        """
        return self._parents.get('instruction')

    @property
    def is_global(self):
        return self._kind == 'global'

    @property
    def is_function(self):
        return self._kind == 'function'

    @property
    def is_block(self):
        return self._kind == 'block'

    @property
    def is_argument(self):
        return self._kind == 'argument'

    @property
    def is_instruction(self):
        return self._kind == 'instruction'

    @property
    def is_operand(self):
        return self._kind == 'operand'

    @property
    def name(self):
        return _decode_string(ffi.lib.LLVMPY_GetValueName(self))

    @name.setter
    def name(self, val):
        ffi.lib.LLVMPY_SetValueName(self, _encode_string(val))

    @property
    def linkage(self):
        return Linkage(ffi.lib.LLVMPY_GetLinkage(self))

    @linkage.setter
    def linkage(self, value):
        if not isinstance(value, Linkage):
            value = Linkage[value]
        ffi.lib.LLVMPY_SetLinkage(self, value)

    @property
    def visibility(self):
        return Visibility(ffi.lib.LLVMPY_GetVisibility(self))

    @visibility.setter
    def visibility(self, value):
        if not isinstance(value, Visibility):
            value = Visibility[value]
        ffi.lib.LLVMPY_SetVisibility(self, value)

    @property
    def storage_class(self):
        return StorageClass(ffi.lib.LLVMPY_GetDLLStorageClass(self))

    @storage_class.setter
    def storage_class(self, value):
        if not isinstance(value, StorageClass):
            value = StorageClass[value]
        ffi.lib.LLVMPY_SetDLLStorageClass(self, value)

    def add_function_attribute(self, attr):
        """Only works on function value

        Parameters
        -----------
        attr : str
            attribute name
        """
        if not self.is_function:
            raise ValueError('expected function value, got %s' % (self._kind,))
        attrname = str(attr)
        attrval = ffi.lib.LLVMPY_GetEnumAttributeKindForName(
            _encode_string(attrname), len(attrname))
        if attrval == 0:
            raise ValueError('no such attribute {!r}'.format(attrname))
        ffi.lib.LLVMPY_AddFunctionAttr(self, attrval)

    @property
    def type(self):
        """
        This value's LLVM type.
        """
        # XXX what does this return?
        return TypeRef(ffi.lib.LLVMPY_TypeOf(self))

    @property
    def is_declaration(self):
        """
        Whether this value (presumably global) is defined in the current
        module.
        """
        if not (self.is_global or self.is_function):
            raise ValueError('expected global or function value, got %s'
                             % (self._kind,))
        return ffi.lib.LLVMPY_IsDeclaration(self)

    @property
    def attributes(self):
        """
        Return an iterator over this value's attributes.
        The iterator will yield a string for each attribute.
        """
        itr = iter(())
        if self.is_function:
            it = ffi.lib.LLVMPY_FunctionAttributesIter(self)
            itr = _AttributeListIterator(it)
        elif self.is_instruction:
            if self.opcode == 'call':
                it = ffi.lib.LLVMPY_CallInstAttributesIter(self)
                itr = _AttributeListIterator(it)
            elif self.opcode == 'invoke':
                it = ffi.lib.LLVMPY_InvokeInstAttributesIter(self)
                itr = _AttributeListIterator(it)
        elif self.is_global:
            it = ffi.lib.LLVMPY_GlobalAttributesIter(self)
            itr = _AttributeSetIterator(it)
        elif self.is_argument:
            it = ffi.lib.LLVMPY_ArgumentAttributesIter(self)
            itr = _AttributeSetIterator(it)
        return itr

    @property
    def blocks(self):
        """
        Return an iterator over this function's blocks.
        The iterator will yield a ValueRef for each block.
        """
        if not self.is_function:
            raise ValueError('expected function value, got %s' % (self._kind,))
        it = ffi.lib.LLVMPY_FunctionBlocksIter(self)
        parents = self._parents.copy()
        parents.update(function=self)
        return _BlocksIterator(it, parents)

    @property
    def arguments(self):
        """
        Return an iterator over this function's arguments.
        The iterator will yield a ValueRef for each argument.
        """
        if not self.is_function:
            raise ValueError('expected function value, got %s' % (self._kind,))
        it = ffi.lib.LLVMPY_FunctionArgumentsIter(self)
        parents = self._parents.copy()
        parents.update(function=self)
        return _ArgumentsIterator(it, parents)

    @property
    def instructions(self):
        """
        Return an iterator over this block's instructions.
        The iterator will yield a ValueRef for each instruction.
        """
        if not self.is_block:
            raise ValueError('expected block value, got %s' % (self._kind,))
        it = ffi.lib.LLVMPY_BlockInstructionsIter(self)
        parents = self._parents.copy()
        parents.update(block=self)
        return _InstructionsIterator(it, parents)

    @property
    def operands(self):
        """
        Return an iterator over this instruction's operands.
        The iterator will yield a ValueRef for each operand.
        """
        if not self.is_instruction:
            raise ValueError('expected instruction value, got %s'
                             % (self._kind,))
        it = ffi.lib.LLVMPY_InstructionOperandsIter(self)
        parents = self._parents.copy()
        parents.update(instruction=self)
        return _OperandsIterator(it, parents)

    @property
    def opcode(self):
        if not self.is_instruction:
            raise ValueError('expected instruction value, got %s'
                             % (self._kind,))
        return ffi.ret_string(ffi.lib.LLVMPY_GetOpcodeName(self))

class _ValueIterator(ffi.ObjectRef):

    kind = None  # derived classes must specify the Value kind value
    # as class attribute

    def __init__(self, ptr, parents):
        ffi.ObjectRef.__init__(self, ptr)
        # Keep parent objects (module, function, etc) alive
        self._parents = parents
        if self.kind is None:
            raise NotImplementedError('%s must specify kind attribute'
                                      % (type(self).__name__,))

    def __next__(self):
        vp = self._next()
        if vp:
            return ValueRef(vp, self.kind, self._parents)
        else:
            raise StopIteration

    next = __next__

    def __iter__(self):
        return self

class _AttributeIterator(ffi.ObjectRef):

    def __next__(self):
        vp = self._next()
        if vp:
            return vp
        else:
            raise StopIteration

    next = __next__

    def __iter__(self):
        return self

class _AttributeListIterator(_AttributeIterator):

    def _dispose(self):
        self._capi.LLVMPY_DisposeAttributeListIter(self)

    def _next(self):
        return ffi.ret_bytes(ffi.lib.LLVMPY_AttributeListIterNext(self))

class _AttributeSetIterator(_AttributeIterator):

    def _dispose(self):
        self._capi.LLVMPY_DisposeAttributeSetIter(self)

    def _next(self):
        return ffi.ret_bytes(ffi.lib.LLVMPY_AttributeSetIterNext(self))

class _BlocksIterator(_ValueIterator):

    kind = 'block'

    def _dispose(self):
        self._capi.LLVMPY_DisposeBlocksIter(self)

    def _next(self):
        return ffi.lib.LLVMPY_BlocksIterNext(self)

class _ArgumentsIterator(_ValueIterator):

    kind = 'argument'

    def _dispose(self):
        self._capi.LLVMPY_DisposeArgumentsIter(self)

    def _next(self):
        return ffi.lib.LLVMPY_ArgumentsIterNext(self)

class _InstructionsIterator(_ValueIterator):

    kind = 'instruction'

    def _dispose(self):
        self._capi.LLVMPY_DisposeInstructionsIter(self)

    def _next(self):
        return ffi.lib.LLVMPY_InstructionsIterNext(self)

class _OperandsIterator(_ValueIterator):

    kind = 'operand'

    def _dispose(self):
        self._capi.LLVMPY_DisposeOperandsIter(self)

    def _next(self):
        return ffi.lib.LLVMPY_OperandsIterNext(self)

# FFI

ffi.lib.LLVMPY_PrintValueToString.argtypes = [
    ffi.LLVMValueRef,
    POINTER(c_char_p)
]

ffi.lib.LLVMPY_GetGlobalParent.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_GetGlobalParent.restype = ffi.LLVMModuleRef

ffi.lib.LLVMPY_GetValueName.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_GetValueName.restype = c_char_p

ffi.lib.LLVMPY_SetValueName.argtypes = [ffi.LLVMValueRef, c_char_p]

ffi.lib.LLVMPY_TypeOf.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_TypeOf.restype = ffi.LLVMTypeRef

ffi.lib.LLVMPY_PrintType.argtypes = [ffi.LLVMTypeRef]
ffi.lib.LLVMPY_PrintType.restype = c_void_p

ffi.lib.LLVMPY_TypeIsPointer.argtypes = [ffi.LLVMTypeRef]
ffi.lib.LLVMPY_TypeIsPointer.restype = c_bool

ffi.lib.LLVMPY_GetElementType.argtypes = [ffi.LLVMTypeRef]
ffi.lib.LLVMPY_GetElementType.restype = ffi.LLVMTypeRef

ffi.lib.LLVMPY_GetTypeName.argtypes = [ffi.LLVMTypeRef]
ffi.lib.LLVMPY_GetTypeName.restype = c_void_p

ffi.lib.LLVMPY_GetLinkage.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_GetLinkage.restype = c_int

ffi.lib.LLVMPY_SetLinkage.argtypes = [ffi.LLVMValueRef, c_int]

ffi.lib.LLVMPY_GetVisibility.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_GetVisibility.restype = c_int

ffi.lib.LLVMPY_SetVisibility.argtypes = [ffi.LLVMValueRef, c_int]

ffi.lib.LLVMPY_GetDLLStorageClass.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_GetDLLStorageClass.restype = c_int

ffi.lib.LLVMPY_SetDLLStorageClass.argtypes = [ffi.LLVMValueRef, c_int]

ffi.lib.LLVMPY_GetEnumAttributeKindForName.argtypes = [c_char_p, c_size_t]
ffi.lib.LLVMPY_GetEnumAttributeKindForName.restype = c_uint

ffi.lib.LLVMPY_AddFunctionAttr.argtypes = [ffi.LLVMValueRef, c_uint]

ffi.lib.LLVMPY_IsDeclaration.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_IsDeclaration.restype = c_int

ffi.lib.LLVMPY_FunctionAttributesIter.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_FunctionAttributesIter.restype = ffi.LLVMAttributeListIterator

ffi.lib.LLVMPY_CallInstAttributesIter.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_CallInstAttributesIter.restype = ffi.LLVMAttributeListIterator

ffi.lib.LLVMPY_InvokeInstAttributesIter.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_InvokeInstAttributesIter.restype = ffi.LLVMAttributeListIterator

ffi.lib.LLVMPY_GlobalAttributesIter.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_GlobalAttributesIter.restype = ffi.LLVMAttributeSetIterator

ffi.lib.LLVMPY_ArgumentAttributesIter.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_ArgumentAttributesIter.restype = ffi.LLVMAttributeSetIterator

ffi.lib.LLVMPY_FunctionBlocksIter.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_FunctionBlocksIter.restype = ffi.LLVMBlocksIterator

ffi.lib.LLVMPY_FunctionArgumentsIter.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_FunctionArgumentsIter.restype = ffi.LLVMArgumentsIterator

ffi.lib.LLVMPY_BlockInstructionsIter.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_BlockInstructionsIter.restype = ffi.LLVMInstructionsIterator

ffi.lib.LLVMPY_InstructionOperandsIter.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_InstructionOperandsIter.restype = ffi.LLVMOperandsIterator

ffi.lib.LLVMPY_DisposeAttributeListIter.argtypes = [
    ffi.LLVMAttributeListIterator]

ffi.lib.LLVMPY_DisposeAttributeSetIter.argtypes = [ffi.LLVMAttributeSetIterator]

ffi.lib.LLVMPY_DisposeBlocksIter.argtypes = [ffi.LLVMBlocksIterator]

ffi.lib.LLVMPY_DisposeInstructionsIter.argtypes = [ffi.LLVMInstructionsIterator]

ffi.lib.LLVMPY_DisposeOperandsIter.argtypes = [ffi.LLVMOperandsIterator]

ffi.lib.LLVMPY_AttributeListIterNext.argtypes = [ffi.LLVMAttributeListIterator]
ffi.lib.LLVMPY_AttributeListIterNext.restype = c_void_p

ffi.lib.LLVMPY_AttributeSetIterNext.argtypes = [ffi.LLVMAttributeSetIterator]
ffi.lib.LLVMPY_AttributeSetIterNext.restype = c_void_p

ffi.lib.LLVMPY_BlocksIterNext.argtypes = [ffi.LLVMBlocksIterator]
ffi.lib.LLVMPY_BlocksIterNext.restype = ffi.LLVMValueRef

ffi.lib.LLVMPY_ArgumentsIterNext.argtypes = [ffi.LLVMArgumentsIterator]
ffi.lib.LLVMPY_ArgumentsIterNext.restype = ffi.LLVMValueRef

ffi.lib.LLVMPY_InstructionsIterNext.argtypes = [ffi.LLVMInstructionsIterator]
ffi.lib.LLVMPY_InstructionsIterNext.restype = ffi.LLVMValueRef

ffi.lib.LLVMPY_OperandsIterNext.argtypes = [ffi.LLVMOperandsIterator]
ffi.lib.LLVMPY_OperandsIterNext.restype = ffi.LLVMValueRef

ffi.lib.LLVMPY_GetOpcodeName.argtypes = [ffi.LLVMValueRef]
ffi.lib.LLVMPY_GetOpcodeName.restype = c_void_p


text:
extern "C" {
  #include <git2.h>
 }

#include <iostream>
#include "../include/functions/copy.h"
#include "../include/revert_options.h"

  #include "../include/merge_options.h"
  #include "../include/checkout_options.h"

using namespace v8;
using namespace node;
using namespace std;

// generated from struct_content.cc
GitRevertOptions::GitRevertOptions() {
   git_revert_options wrappedValue = GIT_REVERT_OPTIONS_INIT;
   this->raw = (git_revert_options*) malloc(sizeof(git_revert_options));
  memcpy(this->raw, &wrappedValue, sizeof(git_revert_options));

  this->ConstructFields();
  this->selfFreeing = true;
}

GitRevertOptions::GitRevertOptions(git_revert_options* raw, bool selfFreeing) {
  this->raw = raw;
  this->ConstructFields();
  this->selfFreeing = selfFreeing;
}

GitRevertOptions::~GitRevertOptions() {

  if (this->selfFreeing) {
    free(this->raw);
  }
}

void GitRevertOptions::ConstructFields() {
                Local<Object> merge_optsTemp = GitMergeOptions::New(
            &this->raw->merge_opts,
            false
          )->ToObject();
          NanAssignPersistent(this->merge_opts, merge_optsTemp);

             Local<Object> checkout_optsTemp = GitCheckoutOptions::New(
            &this->raw->checkout_opts,
            false
          )->ToObject();
          NanAssignPersistent(this->checkout_opts, checkout_optsTemp);

    }

void GitRevertOptions::InitializeComponent(Handle<v8::Object> target) {
  NanScope();

  Local<FunctionTemplate> tpl = NanNew<FunctionTemplate>(JSNewFunction);

  tpl->InstanceTemplate()->SetInternalFieldCount(1);
  tpl->SetClassName(NanNew<String>("RevertOptions"));

      tpl->InstanceTemplate()->SetAccessor(NanNew<String>("version"), GetVersion, SetVersion);
        tpl->InstanceTemplate()->SetAccessor(NanNew<String>("mainline"), GetMainline, SetMainline);
        tpl->InstanceTemplate()->SetAccessor(NanNew<String>("mergeOpts"), GetMergeOpts, SetMergeOpts);
        tpl->InstanceTemplate()->SetAccessor(NanNew<String>("checkoutOpts"), GetCheckoutOpts, SetCheckoutOpts);

  Local<Function> _constructor_template = tpl->GetFunction();
  NanAssignPersistent(constructor_template, _constructor_template);
  target->Set(NanNew<String>("RevertOptions"), _constructor_template);
}

NAN_METHOD(GitRevertOptions::JSNewFunction) {
  NanScope();
  GitRevertOptions* instance;

  if (args.Length() == 0 || !args[0]->IsExternal()) {
    instance = new GitRevertOptions();
  }
  else {
    instance = new GitRevertOptions(static_cast<git_revert_options*>(Handle<External>::Cast(args[0])->Value()), args[1]->BooleanValue());
  }

  instance->Wrap(args.This());

  NanReturnValue(args.This());
}

Handle<v8::Value> GitRevertOptions::New(void* raw, bool selfFreeing) {
  NanEscapableScope();

  Handle<v8::Value> argv[2] = { NanNew<External>((void *)raw), NanNew<Boolean>(selfFreeing) };
  return NanEscapeScope(NanNew<Function>(GitRevertOptions::constructor_template)->NewInstance(2, argv));
}

git_revert_options *GitRevertOptions::GetValue() {
  return this->raw;
}

git_revert_options **GitRevertOptions::GetRefValue() {
  return this->raw == NULL ? NULL : &this->raw;
}

void GitRevertOptions::ClearValue() {
  this->raw = NULL;
}

    NAN_GETTER(GitRevertOptions::GetVersion) {
      NanScope();

      GitRevertOptions *wrapper = ObjectWrap::Unwrap<GitRevertOptions>(args.This());

        NanReturnValue(NanNew<Number>(wrapper->GetValue()->version));
     }

    NAN_SETTER(GitRevertOptions::SetVersion) {
      NanScope();

      GitRevertOptions *wrapper = ObjectWrap::Unwrap<GitRevertOptions>(args.This());

         if (value->IsNumber()) {
          wrapper->GetValue()->version = (unsigned int) value->Int32Value();
        }
     }

      NAN_GETTER(GitRevertOptions::GetMainline) {
      NanScope();

      GitRevertOptions *wrapper = ObjectWrap::Unwrap<GitRevertOptions>(args.This());

        NanReturnValue(NanNew<Number>(wrapper->GetValue()->mainline));
     }

    NAN_SETTER(GitRevertOptions::SetMainline) {
      NanScope();

      GitRevertOptions *wrapper = ObjectWrap::Unwrap<GitRevertOptions>(args.This());

         if (value->IsNumber()) {
          wrapper->GetValue()->mainline = (unsigned int) value->Int32Value();
        }
     }

      NAN_GETTER(GitRevertOptions::GetMergeOpts) {
      NanScope();

      GitRevertOptions *wrapper = ObjectWrap::Unwrap<GitRevertOptions>(args.This());

        NanReturnValue(NanNew(wrapper->merge_opts));

     }

    NAN_SETTER(GitRevertOptions::SetMergeOpts) {
      NanScope();

      GitRevertOptions *wrapper = ObjectWrap::Unwrap<GitRevertOptions>(args.This());

        Handle<Object> merge_opts(value->ToObject());
        NanDisposePersistent(wrapper->merge_opts);

        NanAssignPersistent(wrapper->merge_opts, merge_opts);

        wrapper->raw->merge_opts = *  ObjectWrap::Unwrap<GitMergeOptions>(merge_opts->ToObject())->GetValue() ;

     }

      NAN_GETTER(GitRevertOptions::GetCheckoutOpts) {
      NanScope();

      GitRevertOptions *wrapper = ObjectWrap::Unwrap<GitRevertOptions>(args.This());

        NanReturnValue(NanNew(wrapper->checkout_opts));

     }

    NAN_SETTER(GitRevertOptions::SetCheckoutOpts) {
      NanScope();

      GitRevertOptions *wrapper = ObjectWrap::Unwrap<GitRevertOptions>(args.This());

        Handle<Object> checkout_opts(value->ToObject());
        NanDisposePersistent(wrapper->checkout_opts);

        NanAssignPersistent(wrapper->checkout_opts, checkout_opts);

        wrapper->raw->checkout_opts = *  ObjectWrap::Unwrap<GitCheckoutOptions>(checkout_opts->ToObject())->GetValue() ;

     }

Persistent<Function> GitRevertOptions::constructor_template;


text:
/* This program is free software: you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public License
 as published by the Free Software Foundation, either version 3 of
 the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>. */

package org.opentripplanner.standalone;

import java.util.List;

/**
 * Indicates that a vertex requested by name or lat/long could not be located.
 * This might be thrown if a user enters a location outside the street/transit network.
 */
public class VertexNotFoundException extends RuntimeException {
    private static final long serialVersionUID = 1L;

    List<String> notFound;

    public VertexNotFoundException(List<String> notFound) {
        super("vertices not found: " + notFound.toString());
        this.notFound = notFound;
    }

    public List<String> getMissing() {
        return notFound;
    }

}


text:
package org.modelmapper.bugs;

import static org.testng.Assert.assertEquals;

import org.modelmapper.AbstractTest;
import org.modelmapper.Provider;
import org.testng.annotations.Test;

@Test
public class GH74 extends AbstractTest {
  static class Foo {
    Bar bar;
  }

  static class Bar {
    String value;
  }

  static class FooDTO {
    BarDTO bar;
  }

  static class BarDTO {
    String value;
  }

  public void test() {
    modelMapper.getConfiguration().setProvider(new Provider<Object>() {
      public Object get(ProvisionRequest<Object> request) {
        return null;
      }
    });

    Foo foo = new Foo();
    foo.bar = new Bar();
    foo.bar.value = "test";
    FooDTO dto = modelMapper.map(foo, FooDTO.class);
    assertEquals(dto.bar.value, foo.bar.value);
  }
}


text:
angular.module('starter.services')
  .service('UserService', ['Auth', '$firebaseArray', '$cordovaOauth', 'googleAuthKey',
      function(Auth, $firebaseArray, $cordovaOauth, googleAuthKey) {

    var firebaseDBRef = firebase.database().ref();

    /*
     * NOTE: Redirect/popup auth for Ionic platforms is broken with Firebase 3. Until
     * this is fixed, I need to either switch to handling auth manually or possibly revert
     * to Firebase 2 for auth.
     *
     * See for more details: https://github.com/angular/angularfire2/issues/243
     */

    var login = function() {
      if(ionic.Platform.isWebView()) {
        $cordovaOauth.google(
          googleAuthKey, ["email"])
        .then(function(response) {
          var jsonResponse = JSON.stringify(response);
          // console.log("Response Object -> " + jsonResponse);
          if (jsonResponse) {
            _firebaseSigninWithCredential(response);
          }
        }, function(error) {
          console.log("Error -> " + error);
        });
      } else {
        _firebaseSigninWithRedirect();
      }
    }

    var _firebaseSigninWithCredential = function(token) {
      var credential = firebase.auth.GoogleAuthProvider.credential(token.id_token, token.access_token);

      Auth.$signInWithCredential(credential).then(function(firebaseUser) {
        if (firebaseUser) {
          // console.log("Signed in as:", firebaseUser);
          // TODO: for now, save everyone as admin. remove this later
          firebase.database().ref('/userRoles/' + firebaseUser.uid).set({
            role: 'admin'
          });
        }
      }).catch(function(error) {
        console.error("Authentication failed:", error);
      });
    }

    var _firebaseSigninWithRedirect = function() {
      Auth.$signInWithRedirect("google").then(function(firebaseUser) {
        if (firebaseUser) {
          // console.log("Signed in as:", firebaseUser.user);
          // TODO: for now, save everyone as admin. remove this later
          firebase.database().ref('/userRoles/' + firebaseUser.user.uid).set({
            role: 'admin'
          });
        }
      }).catch(function(error) {
        console.log("Authentication failed:", error);
      });
    }

    var logout = function() {
      Auth.$signOut();
    }

    var closeAccount = function() {
      // Delete the currently signed-in user
      Auth.$deleteUser().then(function() {
        // console.log("User deleted successfully");
      }).catch(function(error) {
        // console.log("Error deleting user:", error);
      });
    }

    var isAdmin = function() {
      var userId = firebase.auth().currentUser.uid;
      firebase.database().ref('/userRoles/' + userId).once('value').then(function(snapshot) {
        var role = snapshot.val().role;
        return role === 'admin';
      });
    }

    return {
      login: login,
      logout: logout,
      closeAccount: closeAccount,
      isAdmin: isAdmin
    };
  }]);


text:
<?php

class M_Customer extends MY_Model
{
	function __construct()
	{
		parent::__construct();
	}

	function addCustomer($data = array())
	{
		$insert_data = ($this->input->post()) ? $this->input->post() : $data;

		$result = $this->db->insert('customer', $insert_data);

		return $result;
	}

	function getCustomers()
	{
		$this->db->where_in('is_active', [0, 1]);
		$query = $this->db->get('customer');

		return $query->result();
	}

	function updateCustomer($customer_id, $update_data = NULL)
	{
		$update_data = ($update_data == NULL) ? $this->input->post() : $update_data;

		$this->db->where('id', $customer_id);

		$result = $this->db->update('customer', $update_data);

		return $result;
	}

	function getCustomerById($id)
	{
		$this->db->where_in('is_active', [0, 1]);
		$query = $this->db->get_where('customer', ['id' => $id]);

		return $query->row();
	}

	function getCustomerMonthUsed($billing_id, $customer_id)
	{
		$this->db->where([
				'billing_id'	=>	$billing_id,
				'customer_id'	=>	$customer_id
			]);

		$query = $this->db->get('customer_billing');

		return $query->row();
	}

	function getTotalDueByCustomer($customer_id)
	{
		$this->db->where([
			'customer_id'	=>	$customer_id,
			'paid'			=>	0
		]);
		$this->db->select_sum('amount');

		$query = $this->db->get('customer_billing');

		return $query->row();
	}
	function clearBill($billing_id)
	{
		$this->db->where('billing_id', $billing_id);
		$this->db->update('customer_billing', ['paid' => 1]);

		return true;
	}
}


text:
#import <UIKit/UIKit.h>
#import "ZUUIRevealController.h"

@interface FrontViewController : UIViewController

@end


text:
"""shader_noise shader function and texture generator
as described in "GPU Gems" chapter 5:

http://http.developer.nvidia.com/GPUGems/gpugems_ch05.html
"""

__version__ = "$Id: shader_noise.py 37 2008-06-27 22:25:39Z casey.duncan $"

from noise import pnoise3
import ctypes
from pyglet.gl import *

class ShaderNoiseTexture:
	"""tiling 3D noise texture with two channels for use by the
	shader noise functions.
	"""

	def __init__(self, freq=8, width=32):
		"""Generate the 3D noise texture.

		freq -- frequency of generated noise over the width of the
		texture.

		width -- Width of the texture in texels. The texture is cubic,
		thus all sides are the same width. Must be a power of two.
		Using a larger width can reduce artifacts caused by linear
		interpolation of the noise texture, at the cost of video
		memory, and possibly slower texture access.
		"""
		self.freq = freq
		self.width = width
		scale = float(freq) / width
		width2 = width**2
		texel = (ctypes.c_ushort * (2 * width**3))()
		for z in range(width):
			for y in range(width):
				for x in range(width):
					texel[(x + (y * width) + (z * width2)) * 2] = int((pnoise3(
						x * scale, y * scale, z * scale,
						repeatx=freq, repeaty=freq, repeatz=freq) + 1.0) * 32767)
					texel[(x + (y * width) + (z * width2)) * 2 + 1] = int((pnoise3(
						x * scale, y * scale, z * scale,
						repeatx=freq, repeaty=freq, repeatz=freq, base=freq + 1) + 1.0) * 32767)
		self.data = texel

	def load(self):
		"""Load the noise texture data into the current texture unit"""
		glTexImage3D(GL_TEXTURE_3D, 0, GL_LUMINANCE16_ALPHA16,
			self.width, self.width, self.width, 0, GL_LUMINANCE_ALPHA,
			GL_UNSIGNED_SHORT, ctypes.byref(self.data))

	def enable(self):
		"""Convenience method to enable 3D texturing state so the texture may be used by the
		ffpnoise shader function
		"""
		glEnable(GL_TEXTURE_3D)
		glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_REPEAT)
		glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_REPEAT)
		glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_REPEAT)
		glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
		glTexParameteri(GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)

shader_noise_glsl = '''
/*
 * GLSL Shader functions for fast fake Perlin 3D noise
 *
 * The required shader_noise_tex texture can be generated using the
 * ShaderNoiseTexture class.  It is a toroidal tiling 3D texture with each texel
 * containing two 16-bit noise source channels. The shader permutes the source
 * texture values by combining the channels such that the noise repeats at a
 * much larger interval than the input texture.
 */

uniform sampler3D shader_noise_tex;
const float twopi = 3.1415926 * 2.0;

/* Simple perlin noise work-alike */
float
pnoise(vec3 position)
{
	vec4 hi = 2.0 * texture3D(shader_noise_tex, position.xyz) - 1.0;
	vec4 lo = 2.0 * texture3D(shader_noise_tex, position.xyz / 9.0) - 1.0;
	return hi.r * cos(twopi * lo.r) + hi.a * sin(twopi * lo.r);
}

/* Multi-octave fractal brownian motion perlin noise */
float
fbmnoise(vec3 position, int octaves)
{
	float m = 1.0;
	vec3 p = position;
	vec4 hi = vec4(0.0);
	/* XXX Loops may not work correctly on all video cards */
	for (int x = 0; x < octaves; x++) {
		hi += (2.0 * texture3D(shader_noise_tex, p.xyz) - 1.0) * m;
		p *= 2.0;
		m *= 0.5;
	}
	vec4 lo = 2.0 * texture3D(shader_noise_tex, position.xyz / 9.0) - 1.0;
	return hi.r * cos(twopi * lo.r) + hi.a * sin(twopi * lo.r);
}

/* Multi-octave turbulent noise */
float
fbmturbulence(vec3 position, int octaves)
{
	float m = 1.0;
	vec3 p = position;
	vec4 hi = vec4(0.0);
	/* XXX Loops may not work correctly on all video cards */
	for (int x = 0; x < octaves; x++) {
		hi += abs(2.0 * texture3D(shader_noise_tex, p.xyz) - 1.0) * m;
		p *= 2.0;
		m *= 0.5;
	}
	vec4 lo = texture3D(shader_noise_tex, position.xyz / 9.0);
	return 2.0 * mix(hi.r, hi.a, cos(twopi * lo.r) * 0.5 + 0.5) - 1.0;
}

'''

if __name__ == '__main__':
	# Demo using a simple noise-textured rotating sphere
	import shader
	win = pyglet.window.Window(width=640, height=640, resizable=True, visible=False)
	vert_shader = shader.VertexShader('stupid', '''
		/* simple vertex shader that stores the vertex position in a varying
		 * for easy access by the frag shader
		 */
		varying vec3 position;

		void main(void) {
			position = gl_Vertex.xyz * 5.0;
			gl_Position = ftransform();
		}
	''')
	frag_shader = shader.FragmentShader('noise_test', shader_noise_glsl + '''
		varying vec3 position;

		void main(void) {
			float v;
			float a = atan(position.y, position.x);
			float arc = 3.14159 / 3.0;
			if (a > -arc && a < arc) {
				v = pnoise(position) * 0.5 + 0.5;
			} else if (a > arc && a < arc * 4.0) {
				v = fbmnoise(position, 4) * 0.5 + 0.5;
			} else {
				v = fbmturbulence(position, 4) * 0.5 + 0.5;
			}
			gl_FragColor = vec4(v, v, v, 1.0);
		}
	''')
	shader_prog = shader.ShaderProgram(vert_shader, frag_shader)
	shader_prog.install()
	tex = ShaderNoiseTexture()
	tex.load()
	tex.enable()
	shader_prog.uset1I('shader_noise_tex', 0)

	quadratic = gluNewQuadric()
	gluQuadricNormals(quadratic, GLU_SMOOTH)
	gluQuadricTexture(quadratic, GL_TRUE)
	glEnable(GL_CULL_FACE)
	global spin
	spin = 0

	def on_resize(width, height):
		glViewport(0, 0, width, height)
		glMatrixMode(GL_PROJECTION)
		glLoadIdentity()
		gluPerspective(70, 1.0*width/height, 0.1, 1000.0)
		glMatrixMode(GL_MODELVIEW)
		glLoadIdentity()
	win.on_resize = on_resize

	@win.event
	def on_draw():
		global spin
		win.clear()
		glLoadIdentity()
		glTranslatef(0, 0, -1.5)
		glRotatef(spin, 1.0, 1.0, 1.0)
		gluSphere(quadratic, 0.65, 60, 60)

	def update(dt):
		global spin
		spin += dt * 10.0
	pyglet.clock.schedule_interval(update, 1.0/30.0)

	win.set_visible()
	pyglet.app.run()


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="pageWrapper" class="com.rwr.utils.PageWrapperImpl"/>

    <bean id="seekerRepository" class="com.rwr.repository.impl.SeekerRepositoryImpl"/>
    <bean id="imsRepository" class="com.rwr.repository.impl.ImsRepositoryImpl"/>
    <bean id="skillsRepository" class="com.rwr.repository.impl.SkillsRepositoryImpl"/>

    <bean id="rwrService" class="com.rwr.service.RwrManagementServiceImpl"/>
</beans>


text:
The simple JSMin algorithm is the most reliable in PHP, but check the [CookBook](CookBook.wiki.md) to plug in other minifiers.

## How fast is it?

If you [serve static files](../static/README.md), it's as fast as your web server, and you should do this for high-traffic sites.

The PHP-based server is not as fast, but still performs well thanks to an internal cache. Tips:

  * **Use a reverse proxy** to cache the Minify URLs. This is by far the most important tip.
  * Revision your Minify URIs (so far-off Expires headers will be sent). One way to do this is using [groups](UserGuide.wiki.md#using-groups-for-nicer-urls) and the [Minify_groupUri()](UserGuide.wiki.md#far-future-expires-headers) utility function. Without this, clients will re-request Minify URLs every 30 minutes to check for updates.
  * Use the [APC/Memcache adapters](CookBook.wiki.md).

## Does it support gzip compression?

Yes. Based on the browser's Accept-Encoding header.

## Does it work with PHP opcode caches?

Yes, and you can also use [APC for content caching](CookBook.wiki.md).

## Can it minify remote files/the output of dynamic scripts?

[Yes](CustomSource.wiki.md#non-file-sources), but it's not a straightforward setup, and probably best avoided.

## Is there a minifier for HTML?

The class `Minify_HTML` can do this (and minify embedded STYLE and SCRIPT elements), but it's too slow to use directly. You'd want to integrate it into a system that caches the output. E.g., in a CMS, keep one copy for editing and one minified for serving.

## How does it ensure that the client can't request files it shouldn't have access to?

Minify allows files to be specified using the URI, or using pre-configured sets of files. With URI-specified files, Minify is very careful to serve only JS/CSS files that are already public on your server, but if you hide public directories--with .htaccess, e.g.--Minify can't know that. Obvious Tip: don't put sensitive info in JS/CSS files inside DOC_ROOT :)

An included option can disable URI-specified files so Minify will serve only the pre-configured file sets.

## Is it used in production by any large-scale websites?

The libraries are used in many CMS's and frameworks, but the use of `index.php` to serve URLs like http://example.com/min/f=hello.js probably is rare. Minify is made to drop in place to boost small to medium sites not already built for performance.

Version 2.1.1 had 54K downloads.

## Can I use it with my commercial website or product?

Yes. Minify is distributed under the [New BSD License](http://www.opensource.org/licenses/bsd-license.php).

## How can I tell if my server cache is working?

The easiest way is to place a Minify URL directly in your browser's address bar and refresh (F5), which should override the client-side caching that Minify specifies and force Minify to send you a complete response. With cache working, this response should take 100ms or so. Without cache, it could be multiple seconds.

If you have file access to the server you can check your cache path directly for filenames beginning with `minify_`.


text:
<#PSScriptInfo
.VERSION 1.0.0
.GUID e1a46ec1-73ff-49e6-849b-81b13917d2b0
.AUTHOR DSC Community
.COMPANYNAME DSC Community
.COPYRIGHT Copyright the DSC Community contributors. All rights reserved.
.TAGS DSCConfiguration
.LICENSEURI https://github.com/dsccommunity/NetworkingDsc/blob/main/LICENSE
.PROJECTURI https://github.com/dsccommunity/NetworkingDsc
.ICONURI
.EXTERNALMODULEDEPENDENCIES
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES First version.
.PRIVATEDATA 2016-Datacenter,2016-Datacenter-Server-Core
#>

#Requires -module NetworkingDsc

<#
    .DESCRIPTION
    Removes the NIC Team 'HostTeam' from the interfaces NIC1, NIC2 and NIC3.
#>
Configuration NetworkTeam_RemoveNetworkTeam_Config
{
    Import-DSCResource -ModuleName NetworkingDsc

    Node localhost
    {
        NetworkTeam RemoveNetworkTeam
        {
            Name        = 'HostTeam'
            Ensure      = 'Absent'
            TeamMembers = 'NIC1', 'NIC2', 'NIC3'
        }
    }
}