text:
package query

import (
	"fmt"
	"github.com/dchest/uniuri"
	"github.com/jadengore/Ricetta/api/types"
	"github.com/jadengore/goconfig"
	"github.com/jmcvetta/neoism"
	"io/ioutil"
	"time"
)

type QueryStrings struct {
	FindToken         string
	CreateRecipe      string
	ReturnRecipe      string
	FindCurator       string
	AddCuratorRel     string
	CreateIngredient  string
	CreateStep        string
	GetOwnRecipes     string
	GetIngredients    string
	GetSteps          string
	GetTags           string
	GetCuratedRecipes string
	GetOwnRecipe      string
	GetVisibleRecipe  string
	RecipeAuthor      string
	TagExists         string
	CreateNewTag      string
	AddRelationToTag  string
}

// Query is a private type, and stored locally to package.

type Query struct {
	Db *neoism.Database
	Vd *types.RicettaValidator
	Qs QueryStrings
}

const (
	NANOSECONDS_IN_DAY int64 = 86400000000000
	CQL_DIR                  = "service/query/cql/"
)

var (
	expires time.Duration
)

func NewQuery(uri string, config *goconfig.ConfigFile) *Query {
	neo4jdb, err := neoism.Connect(uri)
	panicIfErr(err)

	query := Query{
		neo4jdb,
		types.NewValidator(config),
		QueryStringInit(),
	}

	query.DatabaseInit()
	query.ConstantInit()
	return &query
}

func panicIfErr(err error) {
	if err != nil {
		panic(err)
	}
}

func (q Query) cypherOrPanic(query *neoism.CypherQuery) {
	panicIfErr(q.Db.Cypher(query))
}

func Now() time.Time {
	return time.Now().Local()
}

func NewUUID() string {
	return uniuri.NewLen(uniuri.UUIDLen)
}

func QueryStringInit() QueryStrings {
	return QueryStrings{
		FindToken:         parseQueryString(CQL_DIR + "findtoken.cql"),
		CreateRecipe:      parseQueryString(CQL_DIR + "createrecipenode.cql"),
		ReturnRecipe:      parseQueryString(CQL_DIR + "returnrecipenode.cql"),
		FindCurator:       parseQueryString(CQL_DIR + "findcurator.cql"),
		AddCuratorRel:     parseQueryString(CQL_DIR + "addcuratorrel.cql"),
		CreateIngredient:  parseQueryString(CQL_DIR + "createingredientnode.cql"),
		CreateStep:        parseQueryString(CQL_DIR + "createstepnode.cql"),
		GetOwnRecipes:     parseQueryString(CQL_DIR + "getownrecipes.cql"),
		GetCuratedRecipes: parseQueryString(CQL_DIR + "getcuratedrecipes.cql"),
		GetIngredients:    parseQueryString(CQL_DIR + "getingredients.cql"),
		GetSteps:          parseQueryString(CQL_DIR + "getsteps.cql"),
		GetTags:           parseQueryString(CQL_DIR + "gettags.cql"),
		GetOwnRecipe:      parseQueryString(CQL_DIR + "getownrecipe.cql"),
		GetVisibleRecipe:  parseQueryString(CQL_DIR + "getvisiblerecipe.cql"),
		RecipeAuthor:      parseQueryString(CQL_DIR + "recipeauthor.cql"),
		TagExists:         parseQueryString(CQL_DIR + "tagexists.cql"),
		CreateNewTag:      parseQueryString(CQL_DIR + "createnewtag.cql"),
		AddRelationToTag:  parseQueryString(CQL_DIR + "addrelationtotag.cql"),
	}
}

func parseQueryString(filename string) string {
	queryString, err := ioutil.ReadFile(filename)
	panicIfErr(err)
	return string(queryString)
}

// Initializes the Neo4j Database
func (q Query) DatabaseInit() {
	if curator := q.CreatePublicCurator(); curator == nil {
		fmt.Println("Curator Node not initialized")
	}
}

// Initializes constants needed for query layer
func (q Query) ConstantInit() {
	expires = time.Duration(q.Vd.Constants.AUTH_TOKEN_EXPIRES * NANOSECONDS_IN_DAY)
}

func (q Query) CreatePublicCurator() *neoism.Node {
	if curator, _, err := q.Db.GetOrCreateNode("PublicCurator", "name", neoism.Props{
		"name": "PublicCurator",
	}); err != nil {
		panic(err)
	} else {
		panicIfErr(curator.AddLabel("PublicCurator"))
		return curator
	}
}

func (q Query) HandleUnique(handle string) bool {
	return !q.UserExistsByHandle(handle)
}

func (q Query) EmailUnique(email string) bool {
	return !q.UserExistsByEmail(email)
}

func (q Query) UserExistsByHandle(handle string) bool {
	found := []struct {
		Handle string `json:"u.handle"`
	}{}
	q.cypherOrPanic(&neoism.CypherQuery{
		Statement: `
            MATCH   (u:User)
            WHERE   u.handle = {handle}
            RETURN  u.handle
        `,
		Parameters: neoism.Props{
			"handle": handle,
		},
		Result: &found,
	})
	return len(found) > 0
}

func (q Query) UserExistsByEmail(email string) bool {
	found := []struct {
		Email string `json:"u.email"`
	}{}
	q.cypherOrPanic(&neoism.CypherQuery{
		Statement: `
            MATCH   (u:User)
            WHERE   u.email = {email}
            RETURN  u.email
        `,
		Parameters: neoism.Props{
			"email": email,
		},
		Result: &found,
	})
	return len(found) > 0
}

func (q Query) CreateUser(handle, email, passwordHash string) bool {
	newUser := []struct {
		Handle string    `json:"u.handle"`
		Email  string    `json:"u.email"`
		Joined time.Time `json:"u.joined"`
	}{}
	q.cypherOrPanic(&neoism.CypherQuery{
		Statement: `
            CREATE (u:User {
                handle:   {handle},
                name:     "",
                email:    {email},
                password: {password},
                joined:   {joined}
            })
            RETURN u.handle, u.email, u.joined
        `,
		Parameters: neoism.Props{
			"handle":   handle,
			"email":    email,
			"password": passwordHash,
			"joined":   Now(),
		},
		Result: &newUser,
	})
	return len(newUser) > 0
}

func (q Query) GetHashedPassword(handle string) (hashedPassword []byte, ok bool) {
	found := []struct {
		HashedPassword string `json:"u.password"`
	}{}
	q.cypherOrPanic(&neoism.CypherQuery{
		Statement: `
            MATCH   (u:User)
            WHERE   u.handle = {handle}
            RETURN  u.password
        `,
		Parameters: neoism.Props{
			"handle": handle,
		},
		Result: &found,
	})

	if ok := len(found) > 0; !ok {
		return []byte{}, ok
	} else {
		return []byte(found[0].HashedPassword), ok
	}
}

func (q Query) SetGetNewAuthTokenForUser(handle string) (string, bool) {
	created := []struct {
		Token string `json:"a.value"`
	}{}
	now := Now()
	token := "Token " + NewUUID()
	q.cypherOrPanic(&neoism.CypherQuery{
		Statement: `
                MATCH   (u:User)
                WHERE   u.handle     = {handle}
                WITH    u
                OPTIONAL MATCH (u)<-[old_r:SESSION_OF]-(old_a:AuthToken)
                DELETE  old_r, old_a
                WITH    u
                CREATE  (u)<-[r:SESSION_OF]-(a:AuthToken)
                SET     r.created_at = {now}
                SET     a.value      = {token}
                SET     a.expires    = {time}
                RETURN  a.value
            `,
		Parameters: neoism.Props{
			"handle": handle,
			"token":  token,
			"time":   now.Add(expires),
			"now":    now,
		},
		Result: &created,
	})
	if ok := len(created) > 0; ok {
		return created[0].Token, ok
	} else {
		return "", ok
	}
}

func (q Query) FindAuthToken(token string) bool {
	found := []struct {
		Handle string `json:"u.handle"`
	}{}
	q.cypherOrPanic(&neoism.CypherQuery{
		Statement: q.Qs.FindToken,
		Parameters: neoism.Props{
			"token": token,
			"now":   Now(),
		},
		Result: &found,
	})
	return len(found) == 1
}

func (q Query) DeriveHandleFromAuthToken(token string) (handle string, ok bool) {
	found := []struct {
		Handle string `json:"u.handle"`
	}{}
	q.cypherOrPanic(&neoism.CypherQuery{
		Statement: q.Qs.FindToken,
		Parameters: neoism.Props{
			"token": token,
			"now":   Now(),
		},
		Result: &found,
	})
	if ok = len(found) > 0; ok {
		return found[0].Handle, ok
	} else {
		return "", ok
	}
}

func (q Query) DestroyAuthToken(token string) bool {
	deleted := []struct {
		Handle string `json:"u.handle"`
	}{}
	q.cypherOrPanic(&neoism.CypherQuery{
		Statement: `
            MATCH   (u:User)<-[so:SESSION_OF]-(a:AuthToken)
            WHERE   a.value = {token}
            DELETE  so, a
            RETURN  u.handle
        `,
		Parameters: neoism.Props{
			"token": token,
		},
		Result: &deleted,
	})
	return len(deleted) > 0
}

func (q Query) CreateRecipe(handle string, recipe types.Recipe) (res types.Recipe, ok bool) {
	recipeQuery := q.Qs.CreateRecipe
	if !recipe.Private {
		recipeQuery = q.Qs.FindCurator + recipeQuery + q.Qs.AddCuratorRel
	}
	createdRecipe := []types.Recipe{}
	q.cypherOrPanic(&neoism.CypherQuery{
		Statement: recipeQuery + q.Qs.ReturnRecipe,
		Parameters: neoism.Props{
			"handle":       handle,
			"id":           NewUUID(),
			"now":          Now(),
			"title":        recipe.Title,
			"notes":        recipe.Notes,
			"cooktime":     recipe.CookTime,
			"cooktimeunit": recipe.CookTimeUnit,
			"preptime":     recipe.PrepTime,
			"preptimeunit": recipe.PrepTimeUnit,
			"image":        recipe.Image,
		},
		Result: &createdRecipe,
	})
	if ok = len(createdRecipe) > 0; !ok {
		return types.Recipe{}, ok
	} else {
		recipeid := createdRecipe[0].Id
		createdIngredients := make(types.Ingredients, len(recipe.Ingredients))
		for index, ingredient := range recipe.Ingredients {
			created := types.Ingredients{}
			q.cypherOrPanic(&neoism.CypherQuery{
				Statement: q.Qs.CreateIngredient,
				Parameters: neoism.Props{
					"rid":        recipeid,
					"id":         index + 1,
					"now":        Now(),
					"name":       ingredient.Name,
					"amount":     ingredient.Amount,
					"amountunit": ingredient.AmountUnit,
					"url":        ingredient.URL,
				},
				Result: &created,
			})
			if len(created) > 0 {
				createdIngredients[index] = created[0]
			}
		}
		if ok = (len(createdIngredients) == len(recipe.Ingredients)); !ok {
			return types.Recipe{}, !ok
		} else {
			createdSteps := make(types.Steps, len(recipe.Steps))
			for index, step := range recipe.Steps {
				created := types.Steps{}
				q.cypherOrPanic(&neoism.CypherQuery{
					Statement: q.Qs.CreateStep,
					Parameters: neoism.Props{
						"rid":         recipeid,
						"id":          index + 1,
						"now":         Now(),
						"instruction": step.Instruction,
						"time":        step.Time,
						"timeunit":    step.TimeUnit,
					},
					Result: &created,
				})
				if len(created) > 0 {
					createdSteps[index] = created[0]
				}
			}
			if ok = (len(createdSteps) == len(recipe.Steps)); !ok {
				return types.Recipe{}, !ok
			} else {
				createdTags := make(types.Tags, len(recipe.Tags))
				for index, tag := range recipe.Tags {
					created := types.Tags{}
					exists := types.Tags{}
					q.cypherOrPanic(&neoism.CypherQuery{
						Statement: q.Qs.TagExists,
						Parameters: neoism.Props{
							"name": tag.Name,
						},
						Result: &exists,
					})
					if len(exists) > 0 {
						q.cypherOrPanic(&neoism.CypherQuery{
							Statement: q.Qs.AddRelationToTag,
							Parameters: neoism.Props{
								"name": tag.Name,
								"rid":  recipeid,
							},
							Result: &created,
						})
					} else {
						q.cypherOrPanic(&neoism.CypherQuery{
							Statement: q.Qs.CreateNewTag,
							Parameters: neoism.Props{
								"name": tag.Name,
								"rid":  recipeid,
							},
							Result: &created,
						})
					}
					if len(created) > 0 {
						createdTags[index] = created[0]
					}
				}
				if ok = (len(createdTags) == len(recipe.Tags)); !ok {
					return types.Recipe{}, !ok
				} else {
					result := createdRecipe[0]
					result.Author = handle
					result.Ingredients = createdIngredients
					result.Steps = createdSteps
					result.Tags = createdTags
					return result, ok
				}
			}
		}
	}
}

func (q Query) GetOwnRecipes(handle string) (res types.Recipes, ok bool) {
	recipes := types.Recipes{}
	q.cypherOrPanic(&neoism.CypherQuery{
		Statement: q.Qs.GetOwnRecipes,
		Parameters: neoism.Props{
			"handle": handle,
		},
		Result: &recipes,
	})
	for index, recipe := range recipes {
		q.cypherOrPanic(&neoism.CypherQuery{
			Statement: q.Qs.GetIngredients,
			Parameters: neoism.Props{
				"rid": recipe.Id,
			},
			Result: &recipes[index].Ingredients,
		})
		q.cypherOrPanic(&neoism.CypherQuery{
			Statement: q.Qs.GetSteps,
			Parameters: neoism.Props{
				"rid": recipe.Id,
			},
			Result: &recipes[index].Steps,
		})
		q.cypherOrPanic(&neoism.CypherQuery{
			Statement: q.Qs.GetTags,
			Parameters: neoism.Props{
				"rid": recipe.Id,
			},
			Result: &recipes[index].Tags,
		})
	}
	if ok := len(recipes) > 0; ok {
		return recipes, ok
	} else {
		return types.Recipes{}, ok
	}
}

func (q Query) GetCuratedRecipes() (res types.Recipes, ok bool) {
	recipes := types.Recipes{}
	q.cypherOrPanic(&neoism.CypherQuery{
		Statement: q.Qs.GetCuratedRecipes,
		Result:    &recipes,
	})
	for index, recipe := range recipes {
		q.cypherOrPanic(&neoism.CypherQuery{
			Statement: q.Qs.GetIngredients,
			Parameters: neoism.Props{
				"rid": recipe.Id,
			},
			Result: &recipes[index].Ingredients,
		})
		q.cypherOrPanic(&neoism.CypherQuery{
			Statement: q.Qs.GetSteps,
			Parameters: neoism.Props{
				"rid": recipe.Id,
			},
			Result: &recipes[index].Steps,
		})
		q.cypherOrPanic(&neoism.CypherQuery{
			Statement: q.Qs.GetTags,
			Parameters: neoism.Props{
				"rid": recipe.Id,
			},
			Result: &recipes[index].Tags,
		})
	}
	if ok := len(recipes) > 0; ok {
		return recipes, ok
	} else {
		return types.Recipes{}, ok
	}
}

func (q Query) GetVisibleRecipeById(handle string, id string) (r types.Recipe, ok bool) {
	check := []struct {
		Handle string `json:"handle"`
	}{}
	q.cypherOrPanic(&neoism.CypherQuery{
		Statement: q.Qs.RecipeAuthor,
		Parameters: neoism.Props{
			"handle": handle,
			"rid":    id,
		},
		Result: &check,
	})
	recipe := types.Recipes{}
	if check[0].Handle == handle {
		q.cypherOrPanic(&neoism.CypherQuery{
			Statement: q.Qs.GetOwnRecipe,
			Parameters: neoism.Props{
				"handle": handle,
				"rid":    id,
			},
			Result: &recipe,
		})
	} else {
		q.cypherOrPanic(&neoism.CypherQuery{
			Statement: q.Qs.GetVisibleRecipe,
			Parameters: neoism.Props{
				"rid": id,
			},
			Result: &recipe,
		})
	}
	if ok := len(recipe) > 0; ok {
		r = recipe[0]
		q.cypherOrPanic(&neoism.CypherQuery{
			Statement: q.Qs.GetIngredients,
			Parameters: neoism.Props{
				"rid": r.Id,
			},
			Result: &r.Ingredients,
		})
		q.cypherOrPanic(&neoism.CypherQuery{
			Statement: q.Qs.GetSteps,
			Parameters: neoism.Props{
				"rid": r.Id,
			},
			Result: &r.Steps,
		})
		q.cypherOrPanic(&neoism.CypherQuery{
			Statement: q.Qs.GetTags,
			Parameters: neoism.Props{
				"rid": r.Id,
			},
			Result: &r.Tags,
		})
		return r, ok
	} else {
		return types.Recipe{}, ok
	}
}

func (q Query) GetCuratedRecipeById(id string) (r types.Recipe, ok bool) {
	recipe := types.Recipes{}
	q.cypherOrPanic(&neoism.CypherQuery{
		Statement: q.Qs.GetVisibleRecipe,
		Parameters: neoism.Props{
			"rid": id,
		},
		Result: &recipe,
	})
	if ok := len(recipe) > 0; ok {
		r = recipe[0]
		q.cypherOrPanic(&neoism.CypherQuery{
			Statement: q.Qs.GetIngredients,
			Parameters: neoism.Props{
				"rid": r.Id,
			},
			Result: &r.Ingredients,
		})
		q.cypherOrPanic(&neoism.CypherQuery{
			Statement: q.Qs.GetSteps,
			Parameters: neoism.Props{
				"rid": r.Id,
			},
			Result: &r.Steps,
		})
		q.cypherOrPanic(&neoism.CypherQuery{
			Statement: q.Qs.GetTags,
			Parameters: neoism.Props{
				"rid": r.Id,
			},
			Result: &r.Tags,
		})
		return r, ok
	} else {
		return types.Recipe{}, ok
	}
}


text:
{% extends "bill2myprint/base.html" %}
{% load format_number %}

{% block template_main %}

Facturation étudiant

        <form id="student_form" action="{% url 'student_billing' %}" method="POST">{% csrf_token %}

Rechercher:

                    <input type="text" name="student" placeholder="Numéro sciper">
                    {% if message %}
                        {{ message }}
                    {% endif %}

                    <input type="submit" class="btn btn-info" value="Rechercher">

        </form>

Données personnelles

Nom:

{{ student.name }}

Username:

{{ student.username }}

Sciper:

{{ student.sciper }}

Détails

                    Semestre
                    Faculté
                    Simple
                    Cumulé
                    Facturation

                    Crédit VPSI
                    Crédit Faculté
                    Crédit Étudiant
                    Dépense étudiant
                    Reste étudiant
                    Crédit VPSI
                    Crédit Faculté
                    Crédit Étudiant
                    Dépense étudiant
                    Reste étudiant
                    Simple
                    Cumulé
                    Calculé

                {% for transaction in transactions %}

                    {{ transaction.semester }}
                    {{ transaction.faculty_name }}
                    {{ transaction.vpsi|format_number_norm }}
                    {{ transaction.faculty|format_number_norm }}
                    {{ transaction.added|format_number_norm }}
                    {{ transaction.spent|format_number_norm }}
                    {{ transaction.remain|format_number_norm }}
                    {{ transaction.cum_vpsi|format_number_norm }}
                    {{ transaction.cum_faculty|format_number_norm }}
                    {{ transaction.cum_added|format_number_norm }}
                    {{ transaction.cum_spent|format_number_norm }}
                    {{ transaction.cum_remain|format_number_norm }}
                    {{ transaction.billing|format_number_norm }}
                    {{ transaction.cum_amount|format_number_norm }}

                        {% for key, value in transaction.facs_billing.items %}
                            {{ key }} : {{ value|format_number_norm }}

                        {% endfor %}

                {% endfor %}

{% endblock %}

redpajama_set_name: RedPajamaGithub


text:
package de.tu_berlin.cit.rwx4j.xmpp.packet;

import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import java.io.StringWriter;

/**
 * An XMPP packet (also referred to as a stanza). Each packet is backed by a
 * DOM4J Element. A set of convenience methods allows easy manipulation of
 * the Element, or the Element can be accessed directly and manipulated.

 *
 * There are three core packet types:

 *
{@link Message} -- used to send data between users.
 *
{@link Presence} -- contains user presence information or is used
 *          to manage presence subscriptions.
 *
{@link IQ} -- exchange information and perform queries using a
 *          request/response protocol.
 *

 *
 * @author Matt Tucker
 */
public abstract class Packet {

    protected static final DocumentFactory docFactory = DocumentFactory.getInstance();

    protected Element element;

    // Cache to and from JIDs
    protected JID toJID;
    protected JID fromJID;

    /**
     * Constructs a new Packet. The TO address contained in the XML Element will only be
     * validated. In other words, stringprep operations will only be performed on the TO JID to
     * verify that it is well-formed. The FROM address is assigned by the server so there is no
     * need to verify it.
     *
     * @param element the XML Element that contains the packet contents.
     */
    public Packet(Element element) {
        this(element, false);
    }

    /**
     * Constructs a new Packet. The JID address contained in the XML Element may not be
     * validated. When validation can be skipped then stringprep operations will not be performed
     * on the JIDs to verify that addresses are well-formed. However, when validation cannot be
     * skipped then <tt>only</tt> the TO address will be verified. The FROM address is assigned by
     * the server so there is no need to verify it.
     *
     * @param element the XML Element that contains the packet contents.
     * @param skipValidation true if stringprep should not be applied to the TO address.
     */
    public Packet(Element element, boolean skipValidation) {
        this.element = element;
        // Apply stringprep profiles to the "to" and "from" values.
        String to = element.attributeValue("to");
        if (to != null) {
            if (to.length() == 0) {
                // Remove empty TO values
                element.addAttribute("to", null);
            }
            else {
                String[] parts = JID.getParts(to);
                toJID = new JID(parts[0], parts[1], parts[2], skipValidation);
                element.addAttribute("to", toJID.toString());
            }
        }
        String from = element.attributeValue("from");
        if (from != null) {
            if (from.length() == 0) {
                // Remove empty FROM values
                element.addAttribute("from", null);
            }
            else {
                String[] parts = JID.getParts(from);
                fromJID = new JID(parts[0], parts[1], parts[2], true);
                element.addAttribute("from", fromJID.toString());
            }
        }
    }

    /**
     * Constructs a new Packet with no element data. This method is used by
     * extensions of this class that require a more optimized path for creating
     * new packets.
     */
    protected Packet() {

    }

    /**
     * Returns the packet ID, or <tt>null</tt> if the packet does not have an ID.
     * Packet ID's are optional, except for IQ packets.
     *
     * @return the packet ID.
     */
    public String getID() {
        return element.attributeValue("id");
    }

    /**
     * Sets the packet ID. Packet ID's are optional, except for IQ packets.
     *
     * @param ID the packet ID.
     */
    public void setID(String ID) {
        element.addAttribute("id", ID);
    }

    /**
     * Returns the XMPP address (JID) that the packet is addressed to, or <tt>null</tt>
     * if the "to" attribute is not set. The XMPP protocol often makes the "to"
     * attribute optional, so it does not always need to be set.
     *
     * @return the XMPP address (JID) that the packet is addressed to, or <tt>null</tt>
     *      if not set.
     */
    public JID getTo() {
        String to = element.attributeValue("to");
        if (to == null || to.length() == 0) {
            return null;
        }
        else {
            if (toJID != null && to.equals(toJID.toString())) {
                return toJID;
            }
            else {
                // Return a new JID that bypasses stringprep profile checking.
                // This improves speed and is safe as long as the user doesn't
                // directly manipulate the attributes of the underlying Element
                // that represent JID's.
                String[] parts = JID.getParts(to);
                toJID = new JID(parts[0], parts[1], parts[2], true);
                return toJID;
            }
        }
    }

    /**
     * Sets the XMPP address (JID) that the packet is addressed to. The XMPP protocol
     * often makes the "to" attribute optional, so it does not always need to be set.
     *
     * @param to the XMPP address (JID) that the packet is addressed to.
     */
    public void setTo(String to) {
        // Apply stringprep profiles to value.
        if (to !=  null) {
            toJID = new JID(to);
            to = toJID.toString();
        } else {
        	toJID = null;
        }
        element.addAttribute("to", to);
    }

    /**
     * Sets the XMPP address (JID) that the packet is address to. The XMPP protocol
     * often makes the "to" attribute optional, so it does not always need to be set.
     *
     * @param to the XMPP address (JID) that the packet is addressed to.
     */
    public void setTo(JID to) {
        toJID = to;
        if (to == null) {
            element.addAttribute("to", null);
        }
        else {
            element.addAttribute("to", to.toString());
        }
    }

    /**
     * Returns the XMPP address (JID) that the packet is from, or <tt>null</tt>
     * if the "from" attribute is not set. The XMPP protocol often makes the "from"
     * attribute optional, so it does not always need to be set.
     *
     * @return the XMPP address that the packet is from, or <tt>null</tt>
     *      if not set.
     */
    public JID getFrom() {
        String from = element.attributeValue("from");
        if (from == null || from.length() == 0) {
            return null;
        }
        else {
            if (fromJID != null && from.equals(fromJID.toString())) {
                return fromJID;
            }
            else {
                // Return a new JID that bypasses stringprep profile checking.
                // This improves speed and is safe as long as the user doesn't
                // directly manipulate the attributes of the underlying Element
                // that represent JID's.
                String[] parts = JID.getParts(from);
                fromJID = new JID(parts[0], parts[1], parts[2], true);
                return fromJID;
            }
        }
    }

    /**
     * Sets the XMPP address (JID) that the packet comes from. The XMPP protocol
     * often makes the "from" attribute optional, so it does not always need to be set.
     *
     * @param from the XMPP address (JID) that the packet comes from.
     */
    public void setFrom(String from) {
        // Apply stringprep profiles to value.
        if (from != null) {
            fromJID = new JID(from);
            from = fromJID.toString();
        } else {
        	fromJID = null;
        }
        element.addAttribute("from", from);
    }

    /**
     * Sets the XMPP address (JID) that the packet comes from. The XMPP protocol
     * often makes the "from" attribute optional, so it does not always need to be set.
     *
     * @param from the XMPP address (JID) that the packet comes from.
     */
    public void setFrom(JID from) {
        fromJID = from;
        if (from == null) {
            element.addAttribute("from", null);
        }
        else {
            element.addAttribute("from", from.toString());
        }
    }

    /**
     * Returns the packet error, or <tt>null</tt> if there is no packet error.
     *
     * @return the packet error.
     */
    public PacketError getError() {
        Element error = element.element("error");
        if (error != null) {
            return new PacketError(error);
        }
        return null;
    }

    /**
     * Sets the packet error. Calling this method will automatically set
     * the packet "type" attribute to "error".
     *
     * @param error the packet error.
     */
    public void setError(PacketError error) {
        if (element == null) {
            throw new NullPointerException("Error cannot be null");
        }
        // Force the packet type to "error".
        element.addAttribute("type", "error");
        // Remove an existing error packet.
        if (element.element("error") != null) {
            element.remove(element.element("error"));
        }
        // Add the error element.
        element.add(error.getElement());
    }

    /**
     * Sets the packet error using the specified condition. Calling this
     * method will automatically set the packet "type" attribute to "error".
     * This is a convenience method equivalent to calling:
     *
     * <tt>setError(new PacketError(condition));</tt>
     *
     * @param condition the error condition.
     */
    public void setError(PacketError.Condition condition) {
       setError(new PacketError(condition));
    }

    /**
     * Creates a deep copy of this packet.
     *
     * @return a deep copy of this packet.
     */
    public abstract Packet createCopy();

    /**
     * Returns the DOM4J Element that backs the packet. The element is the definitive
     * representation of the packet and can be manipulated directly to change
     * packet contents.
     *
     * @return the DOM4J Element that represents the packet.
     */
    public Element getElement() {
        return element;
    }

    /**
     * Returns the textual XML representation of this packet.
     *
     * @return the textual XML representation of this packet.
     */
    public String toXML() {
        return element.asXML();
    }

    public String toString() {
        StringWriter out = new StringWriter();
        XMLWriter writer = new XMLWriter(out, OutputFormat.createPrettyPrint());
        try {
            writer.write(element);
        }
        catch (Exception e) {
            // Ignore.
        }
        return out.toString();
    }
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Porsche Le Mans</title>
    <link rel="stylesheet" type="text/css" href="css/style.css" />

Porsche Le Mans

The Race

Monitoring

My Stand

Fuel


text:
package main

import (
	"errors"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
)

const VERSION = "0.1"

var configFile = flag.String("c", "", "the location of the server configuration")
var debug *bool = flag.Bool("d", false, "enable debug logging")

// Load the configuration and do the necessary error handling.
func loadConfigFile(path string) (*DTopConfiguration, error) {
	if path == "" {
		return nil, errors.New("Please supply a valid configuration file (-c).")
	}

	if _, err := os.Stat(path); os.IsNotExist(err) {
		return nil, errors.New(fmt.Sprintf("The configuration file does not exist: %s", path))
	}

	jsonBlob, err := ioutil.ReadFile(path)

	if err != nil {
		return nil, errors.New(fmt.Sprintf("Error reading configuration file: %s", err.Error()))
	}

	cfg, err := DeserializeDTopConfigurationFromJson(jsonBlob)

	if err != nil {
		return nil, errors.New(fmt.Sprintf("Error parsing configuration file: %s", err.Error()))
	}

	if valid, err := cfg.IsValid(); !valid {
		return cfg, errors.New(fmt.Sprintf("Invalid configuration: %s", err.Error()))
	}

	return cfg, nil
}

// entry point
func main() {
	// parse cli args
	flag.Parse()

	log.Printf("Reading configuration from '%s'", *configFile)
	cfg, cfgError := loadConfigFile(*configFile)

	if cfgError != nil {
		panic(cfgError)
	}

	auth := NewAuthenticator(cfg)

	// registered publishers
	eventPublishers := [...]EventPublisher{memory, uptime, loadavg, cpuinfo, users, processinfo, basicinfo, disk, services(cfg.Services)}

	// start publishers.
	events := make(chan Event)
	for _, eventPublisher := range eventPublishers {
		go FailSafe(eventPublisher)(events)
	}

	eventServer := NewEventServer(events, jsonEventSerializer)

	// start fanout and monitor goroutines.
	go eventServer.fanOut()
	go eventServer.monitor()

	// register http resources
	http.Handle("/", http.FileServer(http.Dir(cfg.StaticFolder)))
	http.Handle("/events", http.HandlerFunc(eventServer.handler))
	http.Handle("/auth", http.HandlerFunc(authHandler(eventServer, cfg, auth)))

	log.Printf("starting server at 0.0.0.0:%d", cfg.Port)
	err := http.ListenAndServe(fmt.Sprintf(":%d", cfg.Port), nil)

	if err != nil {
		panic("error running server: " + err.Error())
	}
}

// the authHandler function decorator checks for credentials.
func authHandler(eventServer *EventServer, cfg *DTopConfiguration, auth *Authenticator) func(http.ResponseWriter, *http.Request) {
	return func(w http.ResponseWriter, r *http.Request) {
		if r.Method == "POST" {
			username := r.FormValue("username")
			password := r.FormValue("password")

			if success, token := auth.Login(username, password); success {
				eventServer.eventListeners[token] = nil
				w.Write([]byte(token))
			} else {
				log.Printf("received wrong login attempt (user=%s)", username)
				http.Error(w, "bad credentials", 401)
				return
			}
		} else if r.Method == "GET" {
			// TODO: serialize object iso manually creating string here...
			msg := "{\"Name\":\"%s\",\"Auth\":%t,\"Description\":\"%s\",\"Version\":\"%s\"}"
			auth := cfg.IsAuth()
			msg = fmt.Sprintf(msg, cfg.Name, auth, cfg.Description, VERSION)
			w.Write([]byte(msg))
		}
	}
}

// Debug when configured.
func Debugf(format string, args ...interface{}) {
	if *debug {
		log.Printf("DEBUG "+format, args)
	}
}


text:
#include "rotate.h"

#include "cpu_id.h"
#include "convert.h"
#include "planar_functions.h"
#include "row.h"

#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif

// ARGBScale has a function to copy pixels to a row, striding each source
// pixel by a constant.
#if !defined(LIBYUV_DISABLE_X86) && \
    (defined(_M_IX86) || \
    (defined(__x86_64__) && !defined(__native_client__)) || defined(__i386__))
#define HAS_SCALEARGBROWDOWNEVEN_SSE2
void ScaleARGBRowDownEven_SSE2(const uint8* src_ptr, int src_stride,
                               int src_stepx, uint8* dst_ptr, int dst_width);
#endif
#if !defined(LIBYUV_DISABLE_NEON) && !defined(__native_client__) && \
    (defined(__ARM_NEON__) || defined(LIBYUV_NEON) || defined(__aarch64__))
#define HAS_SCALEARGBROWDOWNEVEN_NEON
void ScaleARGBRowDownEven_NEON(const uint8* src_ptr, int src_stride,
                               int src_stepx, uint8* dst_ptr, int dst_width);
#endif

void ScaleARGBRowDownEven_C(const uint8* src_ptr, int,
                            int src_stepx, uint8* dst_ptr, int dst_width);

static void ARGBTranspose(const uint8* src, int src_stride,
                          uint8* dst, int dst_stride, int width, int height) {
  int i;
  int src_pixel_step = src_stride >> 2;
  void (*ScaleARGBRowDownEven)(const uint8* src_ptr, int src_stride,
      int src_step, uint8* dst_ptr, int dst_width) = ScaleARGBRowDownEven_C;
#if defined(HAS_SCALEARGBROWDOWNEVEN_SSE2)
  if (TestCpuFlag(kCpuHasSSE2) && IS_ALIGNED(height, 4)) {  // Width of dest.
    ScaleARGBRowDownEven = ScaleARGBRowDownEven_SSE2;
  }
#endif
#if defined(HAS_SCALEARGBROWDOWNEVEN_NEON)
  if (TestCpuFlag(kCpuHasNEON) && IS_ALIGNED(height, 4)) {  // Width of dest.
    ScaleARGBRowDownEven = ScaleARGBRowDownEven_NEON;
  }
#endif

  for (i = 0; i < width; ++i) {  // column of source to row of dest.
    ScaleARGBRowDownEven(src, 0, src_pixel_step, dst, height);
    dst += dst_stride;
    src += 4;
  }
}

void ARGBRotate90(const uint8* src, int src_stride,
                  uint8* dst, int dst_stride, int width, int height) {
  // Rotate by 90 is a ARGBTranspose with the source read
  // from bottom to top. So set the source pointer to the end
  // of the buffer and flip the sign of the source stride.
  src += src_stride * (height - 1);
  src_stride = -src_stride;
  ARGBTranspose(src, src_stride, dst, dst_stride, width, height);
}

void ARGBRotate270(const uint8* src, int src_stride,
                    uint8* dst, int dst_stride, int width, int height) {
  // Rotate by 270 is a ARGBTranspose with the destination written
  // from bottom to top. So set the destination pointer to the end
  // of the buffer and flip the sign of the destination stride.
  dst += dst_stride * (width - 1);
  dst_stride = -dst_stride;
  ARGBTranspose(src, src_stride, dst, dst_stride, width, height);
}

void ARGBRotate180(const uint8* src, int src_stride,
                   uint8* dst, int dst_stride, int width, int height) {
  // Swap first and last row and mirror the content. Uses a temporary row.
  align_buffer_64(row, width * 4);
  const uint8* src_bot = src + src_stride * (height - 1);
  uint8* dst_bot = dst + dst_stride * (height - 1);
  int half_height = (height + 1) >> 1;
  int y;
  void (*ARGBMirrorRow)(const uint8* src, uint8* dst, int width) =
      ARGBMirrorRow_C;
  void (*CopyRow)(const uint8* src, uint8* dst, int width) = CopyRow_C;
#if defined(HAS_ARGBMIRRORROW_NEON)
  if (TestCpuFlag(kCpuHasNEON)) {
    ARGBMirrorRow = ARGBMirrorRow_Any_NEON;
    if (IS_ALIGNED(width, 4)) {
      ARGBMirrorRow = ARGBMirrorRow_NEON;
    }
  }
#endif
#if defined(HAS_ARGBMIRRORROW_SSE2)
  if (TestCpuFlag(kCpuHasSSE2)) {
    ARGBMirrorRow = ARGBMirrorRow_Any_SSE2;
    if (IS_ALIGNED(width, 4)) {
      ARGBMirrorRow = ARGBMirrorRow_SSE2;
    }
  }
#endif
#if defined(HAS_ARGBMIRRORROW_AVX2)
  if (TestCpuFlag(kCpuHasAVX2)) {
    ARGBMirrorRow = ARGBMirrorRow_Any_AVX2;
    if (IS_ALIGNED(width, 8)) {
      ARGBMirrorRow = ARGBMirrorRow_AVX2;
    }
  }
#endif
#if defined(HAS_ARGBMIRRORROW_MSA)
  if (TestCpuFlag(kCpuHasMSA)) {
    ARGBMirrorRow = ARGBMirrorRow_Any_MSA;
    if (IS_ALIGNED(width, 16)) {
      ARGBMirrorRow = ARGBMirrorRow_MSA;
    }
  }
#endif
#if defined(HAS_COPYROW_SSE2)
  if (TestCpuFlag(kCpuHasSSE2)) {
    CopyRow = IS_ALIGNED(width * 4, 32) ? CopyRow_SSE2 : CopyRow_Any_SSE2;
  }
#endif
#if defined(HAS_COPYROW_AVX)
  if (TestCpuFlag(kCpuHasAVX)) {
    CopyRow = IS_ALIGNED(width * 4, 64) ? CopyRow_AVX : CopyRow_Any_AVX;
  }
#endif
#if defined(HAS_COPYROW_ERMS)
  if (TestCpuFlag(kCpuHasERMS)) {
    CopyRow = CopyRow_ERMS;
  }
#endif
#if defined(HAS_COPYROW_NEON)
  if (TestCpuFlag(kCpuHasNEON)) {
    CopyRow = IS_ALIGNED(width * 4, 32) ? CopyRow_NEON : CopyRow_Any_NEON;
  }
#endif
#if defined(HAS_COPYROW_MIPS)
  if (TestCpuFlag(kCpuHasMIPS)) {
    CopyRow = CopyRow_MIPS;
  }
#endif

  // Odd height will harmlessly mirror the middle row twice.
  for (y = 0; y < half_height; ++y) {
    ARGBMirrorRow(src, row, width);  // Mirror first row into a buffer
    ARGBMirrorRow(src_bot, dst, width);  // Mirror last row into first row
    CopyRow(row, dst_bot, width * 4);  // Copy first mirrored row into last
    src += src_stride;
    dst += dst_stride;
    src_bot -= src_stride;
    dst_bot -= dst_stride;
  }
  free_aligned_buffer_64(row);
}

LIBYUV_API
int ARGBRotate(const uint8* src_argb, int src_stride_argb,
               uint8* dst_argb, int dst_stride_argb, int width, int height,
               enum RotationMode mode) {
  if (!src_argb || width <= 0 || height == 0 || !dst_argb) {
    return -1;
  }

  // Negative height means invert the image.
  if (height < 0) {
    height = -height;
    src_argb = src_argb + (height - 1) * src_stride_argb;
    src_stride_argb = -src_stride_argb;
  }

  switch (mode) {
    case kRotate0:
      // copy frame
      return ARGBCopy(src_argb, src_stride_argb,
                      dst_argb, dst_stride_argb,
                      width, height);
    case kRotate90:
      ARGBRotate90(src_argb, src_stride_argb,
                   dst_argb, dst_stride_argb,
                   width, height);
      return 0;
    case kRotate270:
      ARGBRotate270(src_argb, src_stride_argb,
                    dst_argb, dst_stride_argb,
                    width, height);
      return 0;
    case kRotate180:
      ARGBRotate180(src_argb, src_stride_argb,
                    dst_argb, dst_stride_argb,
                    width, height);
      return 0;
    default:
      break;
  }
  return -1;
}

#ifdef __cplusplus
}  // extern "C"
}  // namespace libyuv
#endif


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/ads/googleads/v12/resources/conversion_value_rule.proto

namespace Google\Ads\GoogleAds\V12\Resources\ConversionValueRule;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Action applied when rule is applied.
 *
 * Generated from protobuf message google.ads.googleads.v12.resources.ConversionValueRule.ValueRuleAction
 */
class ValueRuleAction extends \Google\Protobuf\Internal\Message
{
    /**
     * Specifies applied operation.
     *
     * Generated from protobuf field .google.ads.googleads.v12.enums.ValueRuleOperationEnum.ValueRuleOperation operation = 1;
     */
    protected $operation = 0;
    /**
     * Specifies applied value.
     *
     * Generated from protobuf field double value = 2;
     */
    protected $value = 0.0;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type int $operation
     *           Specifies applied operation.
     *     @type float $value
     *           Specifies applied value.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Ads\GoogleAds\V12\Resources\ConversionValueRule::initOnce();
        parent::__construct($data);
    }

    /**
     * Specifies applied operation.
     *
     * Generated from protobuf field .google.ads.googleads.v12.enums.ValueRuleOperationEnum.ValueRuleOperation operation = 1;
     * @return int
     */
    public function getOperation()
    {
        return $this->operation;
    }

    /**
     * Specifies applied operation.
     *
     * Generated from protobuf field .google.ads.googleads.v12.enums.ValueRuleOperationEnum.ValueRuleOperation operation = 1;
     * @param int $var
     * @return $this
     */
    public function setOperation($var)
    {
        GPBUtil::checkEnum($var, \Google\Ads\GoogleAds\V12\Enums\ValueRuleOperationEnum\ValueRuleOperation::class);
        $this->operation = $var;

        return $this;
    }

    /**
     * Specifies applied value.
     *
     * Generated from protobuf field double value = 2;
     * @return float
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Specifies applied value.
     *
     * Generated from protobuf field double value = 2;
     * @param float $var
     * @return $this
     */
    public function setValue($var)
    {
        GPBUtil::checkDouble($var);
        $this->value = $var;

        return $this;
    }

}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(ValueRuleAction::class, \Google\Ads\GoogleAds\V12\Resources\ConversionValueRule_ValueRuleAction::class);


text:
<?php

class Users_model extends CI_Model {

    function validate_login() {
        $username = $this->input->post('user_name');
        $password = $this->input->post('user_password');
        //заявка към БД
        $this->db->where('user_name', $username);
        $this->db->where('user_password', $password);
        $query = $this->db->get('users');
        //ако резултата е 1 ред вярно
        if ($query->num_rows() == 1) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

    function check_username() {
        $username = $this->input->post('user_name');

        $this->db->select('user_name');
        $this->db->where('user_name', $username);
        $query = $this->db->get('users');

        if ($query->num_rows() != 0) {
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function check_email() {
        $email = $this->input->post('user_email');

        $this->db->select('user_email');
        $this->db->where('user_email', $email);
        $query = $this->db->get('users');

        if ($query->num_rows() != 0) {
            return FALSE;
        } else {
            return TRUE;
        }
    }

    function insert_user() {
        $data = array(
            'user_name' => $this->input->post('user_name'),
            'user_password' => $this->input->post('user_password'),
            'user_fname' => $this->input->post('user_fname'),
            'user_lname' => $this->input->post('user_lname'),
            'user_email' => $this->input->post('user_email')
        );

        $query = $this->db->insert('users', $data);

        if ($this->db->affected_rows() == 1) {
            return TRUE;
        } else {
            return FALSE;
        }
    }

}

?>


text:
package example;

import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class ModelFormatterImpl implements ModelFormatter {

    private final GreetingFormatter greetingFormatter;
    private final ClockFormatter clockFormatter;

    @Inject
    public ModelFormatterImpl(GreetingFormatter greetingFormatter, ClockFormatter clockFormatter) {
        this.greetingFormatter = greetingFormatter;
        this.clockFormatter = clockFormatter;
    }

    @Override
    public String formatClock(ClockModel clockModel) {
        return clockFormatter.format(clockModel);
    }

    @Override
    public String formatGreeter(GreeterModel greeterModel) {
        return greetingFormatter.format(greeterModel);
    }
}


text:
using System;
using System.Collections.Generic;
using TravelAgent.IDAL;
using TravelAgent.IService;
using TravelAgent.Model;

namespace TravelAgent.BLL
{
    public class QueryReferencesService:ServiceBase<Int32>,IQueryReferencesService
    {
        public IList<Model.References> GetRefsBySchoolName(string school_name)
        {
            ISchoolDao schDao = GetDao<ISchoolDao>("SchoolDao");
            IReferencesDao refsDao = GetDao<IReferencesDao>("ReferencesDao");

            IList<School> schs = schDao.Get(string.Format("Name like '%{0}%'",school_name));

            if(schs == null || schs.Count <= 0)
            {
                return new List<References>();
            }

            string ids =  "";
            ((List<School>)schs).ForEach(s=>{
                if(string.IsNullOrEmpty(ids))
                {
                    ids += s.Id;
                }
                else
                {
                    ids += (","+s.Id);
                }
            });

            IList<References> refs = refsDao.Get(string.Format("SchoolId in({0})",ids));
            return refs;
        }
    }
}


text:
LR1Item *createLR1Item(Rule *rule, char *lookahead)
{
  LR1Item *item = calloc(1, sizeof(LR1Item));
  item->rule = rule;
  item->dotPosition = arrayListCount(rule->symbols) == 1 && strcmp(arrayListGet(rule->symbols, 0), EMPTY) == 0 ? 1 : 0;
  item->lookahead = lookahead;

  return item;
}

LR1ItemList *createLR1Items(ArrayList *productions)
{
  LR1ItemList *list = calloc(1, sizeof(LR1ItemList));
  list->items = arrayListCreate(10, sizeof(LR1Item *));

  for(int i =0; i < arrayListCount(productions); i++)
  {
    arrayListPush(list->items, createLR1Item(arrayListGet(productions, i), END));
  }

  return list;
}

bool containsSymbol(ArrayList *symbols, char *symbol)
{
  for(int i = 0; i < symbols->used; i++)
  {
    if(strcmp(symbols->items[i], symbol) == 0) return true;
  }

  return false;
}

char *getDotSymbol(LR1Item *item)
{
  if(item->dotPosition == arrayListCount(item->rule->symbols)) return NULL;

  return arrayListGet(item->rule->symbols, item->dotPosition);
}

ArrayList *getSymbolsFollowingDot(LR1ItemList *list)
{
  ArrayList *following = arrayListCreate(10, sizeof(char *));

  for(int i = 0; i < arrayListCount(list->items); i++)
  {
    LR1Item *item = arrayListGet(list->items, i);
    char *symbol = getDotSymbol(item);

    if(symbol != NULL && !containsSymbol(following, symbol))
    {
      arrayListPush(following, symbol);
    }
  }

  return following;
}

char *getNextSymbol(LR1Item *item)
{
  if(item->dotPosition < arrayListCount(item->rule->symbols))
  {
    return arrayListGet(item->rule->symbols, item->dotPosition);
  }

  return NULL;
}

int getLookaheadSymbolsSize(LR1Item *item)
{
  return arrayListCount(item->rule->symbols) - item->dotPosition;
}

char **getLookaheadSymbols(LR1Item *item, char *lookahead)
{
  int remainingSymbols = getLookaheadSymbolsSize(item);
  char **lookaheadsSymbols = malloc(sizeof(char *) * remainingSymbols);

  int lookaheadPosition = 0;
  for(int i = item->dotPosition + 1; i < arrayListCount(item->rule->symbols); i++)
  {
    lookaheadsSymbols[lookaheadPosition++] = arrayListGet(item->rule->symbols, i);
  }

  lookaheadsSymbols[lookaheadPosition] = lookahead;

  return lookaheadsSymbols;
}

bool areLR1ItemsSame(LR1Item *first, LR1Item *second)
{
  if(first->dotPosition != second->dotPosition) return false;
  if(first->rule != second->rule) return false;
  if(strcmp(first->lookahead, second->lookahead) != 0) return false;
  return true;
}

bool itemListContainsItem(ArrayList *list, LR1Item *searchItem)
{
  for(int i = 0; i < arrayListCount(list); i++)
  {
    LR1Item *item = arrayListGet(list, i);

    if(areLR1ItemsSame(item, searchItem)) return true;
  }

  return false;
}

LR1Item *copyLR1Item(LR1Item *item)
{
  LR1Item *newItem = malloc(sizeof(LR1Item));
  newItem->dotPosition = item->dotPosition;
  newItem->rule = item->rule;
  newItem->lookahead = item->lookahead;
  return newItem;
}

bool addLR1ItemToList(LR1ItemList *list, LR1Item *item)
{
  if(itemListContainsItem(list->items, item)) return false;
  arrayListPush(list->items, item);
  return true;
}

int nextItemListNumber()
{
  static int number = 0;
  return number++;
}

LR1ItemList *copyLR1ItemList(LR1ItemList *list)
{
  LR1ItemList *newList = calloc(1, sizeof(LR1ItemList));
  newList->items = arrayListCreate(arrayListCount(list->items), sizeof(LR1Item *));

  for(int i = 0; i < arrayListCount(list->items); i++)
  {
    arrayListPush(newList->items, copyLR1Item(arrayListGet(list->items, i)));
  }

  return newList;
}

LR1ItemList *closure(LR1ItemList *list, Grammar *grammar, HashMap *sets)
{
  LR1ItemList *newList = copyLR1ItemList(list);
  Queue *worklist = queueCreate();

  for(int i = 0; i < arrayListCount(newList->items); i++) queueEnqueue(worklist, arrayListGet(newList->items, i));

  LR1Item *item;
  while((item = queueDequeue(worklist)) != NULL)
  {;
    ArrayList *production = getProductionForSymbol(grammar, getNextSymbol(item));

    if(production == NULL) continue;

    FirstSet *set = getFirstSetForLookaheads(getLookaheadSymbols(item, item->lookahead), getLookaheadSymbolsSize(item), sets);

    for(int j = 0; j < arrayListCount(production); j++)
    {
      Rule *rule = arrayListGet(production, j);

      for(int k = 0; k < arrayListCount(set->terminals); k++)
      {
        LR1Item *ruleItem = createLR1Item(rule, arrayListGet(set->terminals, k));
        if(addLR1ItemToList(newList, ruleItem)) queueEnqueue(worklist, ruleItem);
      }
    }
  }

  return newList;
}

LR1ItemList *goTo(LR1ItemList *list, char *symbol, Grammar *grammar, HashMap *firstSets)
{
  LR1ItemList *moved = calloc(1, sizeof(LR1ItemList));
  moved->items = arrayListCreate(10, sizeof(LR1Item *));

  for(int i = 0; i < arrayListCount(list->items); i++)
  {
    LR1Item *item = arrayListGet(list->items, i);
    char *nextSymbol = getDotSymbol(item);

    if(nextSymbol != NULL && strcmp(nextSymbol, symbol) == 0)
    {
      LR1Item *movedDotItem = copyLR1Item(item);
      movedDotItem->dotPosition++;
      addLR1ItemToList(moved, movedDotItem);
    }
  }

  return closure(moved, grammar, firstSets);
}

char *createStringFromLR1Item(LR1Item *item)
{
  StringBuilder s = stringBuilderCreateFull(50);

  appendChars(&s, item->rule->productionName);
  appendChars(&s, item->lookahead);

  char buffer[12];
  snprintf(buffer, 12, "%i", item->dotPosition);
  appendChars(&s, buffer);

  for(int i = 0; i < arrayListCount(item->rule->symbols); i++)
  {
    appendChars(&s, arrayListGet(item->rule->symbols, i));
  }

  return s.string;
}

int itemListCompare(const void *a, const void *b)
{
  LR1Item *first = *(void **)a;
  LR1Item *second = *(void **)b;
  return strcmp(createStringFromLR1Item(first), createStringFromLR1Item(second));
}

bool areLR1ItemListSame(LR1ItemList *first, LR1ItemList *second)
{
  if(arrayListCount(first->items) != arrayListCount(second->items)) return false;

  for(int i = 0; i < arrayListCount(first->items); i++)
  {
    if(!itemListContainsItem(second->items, arrayListGet(first->items, i))) return false;
  }

  return true;
}

bool ccCompare(void *a, void *b)
{
  return areLR1ItemListSame(a, b);
}

uint32_t ccHash(void *hashable)
{
  LR1ItemList *list = (LR1ItemList *)hashable;
  StringBuilder builder = createStringBuilder();

  for(int i = 0; i < arrayListCount(list->items); i++)
  {
    LR1Item *item = arrayListGet(list->items, i);
    appendChars(&builder, createStringFromLR1Item(item));
  }

  char *key = builder.string;
  size_t len = builder.used;
  uint32_t hash = 0;
  uint32_t i = 0;

  for(hash = i = 0; i < len; ++i)
  {
      hash += key[i];
      hash += (hash << 10);
      hash ^= (hash >> 6);
  }

  hash += (hash << 3);
  hash ^= (hash >> 11);
  hash += (hash << 15);

  return hash;
}

static uint32_t transitionsHash(void *a)
{
  return ((LR1ItemList *)a)->number;
}

bool transitionsCompare(void *a, void *b)
{
  return ((HashMap *)a) == ((HashMap *)b);
}

CC *buildCanonicalCollection(HashMap *sets, Grammar *grammar, char *goalProduction)
{
  HashSet *itemLists = hashSetCreateFull(0, 0.0f, ccCompare, ccHash);
  HashMap *transitions = hashMapCreateFull(0, 0.0f, transitionsCompare, transitionsHash);
  LR1ItemList *cc0 = closure(createLR1Items(hashMapGet(grammar->productions, goalProduction)), grammar, sets);
  cc0->number = nextItemListNumber();
  hashSetPut(itemLists, cc0);

  Queue *worklist = queueCreate();
  queueEnqueue(worklist, cc0);

  LR1ItemList *itemList = NULL;
  while((itemList = queueDequeue(worklist)) != NULL)
  {
    ArrayList *following = getSymbolsFollowingDot(itemList);

    for(int i = 0; i < arrayListCount(following); i++)
    {
      char *symbol = arrayListGet(following, i);
      LR1ItemList *temp = goTo(itemList, symbol, grammar, sets);
      arrayListQSort(temp->items, itemListCompare);
      LR1ItemList *existing = hashSetGetExisting(itemLists, temp);

      if(existing == NULL)
      {
        hashSetPut(itemLists, temp);
        queueEnqueue(worklist, temp);
        existing = temp;
        temp->number = nextItemListNumber();
      }

      HashMap *transitionsForItemList = hashMapGet(transitions, itemList);
      if(transitionsForItemList == NULL) transitionsForItemList = hashMapCreate();
      hashMapSet(transitionsForItemList, symbol, existing);
      hashMapSet(transitions, itemList, transitionsForItemList);
    }
  }

  CC *cc = malloc(sizeof(CC));
  cc->itemLists = itemLists;
  cc->transitions = transitions;

  return cc;
}


text:
#pragma once
#include <memory>
#include <lua.hpp>

namespace lean {
/**
   \brief Wrapper for lua_State objects which contains all Lean bindings.
*/
class script_state {
public:
    struct imp;
private:
    std::shared_ptr<imp> m_ptr;
    friend script_state to_script_state(lua_State * L);
    friend class data_channel;
public:
    static void set_check_interrupt_freq(unsigned count);

    typedef std::weak_ptr<imp> weak_ref;

    script_state();
    script_state(weak_ref const & r);
    ~script_state();

    weak_ref to_weak_ref() const { return weak_ref(m_ptr); }

    /**
       \brief Execute the file with the given name.
       This method throws an exception if an error occurs.
    */
    void dofile(char const * fname);
    /**
       \brief Execute the given string.
       This method throws an exception if an error occurs.
    */
    void dostring(char const * str);
    /**
       \brief Import file \c fname from the LEAN_PATH.
       If the file was already included, then nothing happens, and method returns false.
    */
    bool import(char const * fname);
    /**
       \brief Import file \c fname. \c fname is the explicit path to the file.
       If the file was already included, then nothing happens, and method returns false.
    */
    bool import_explicit(char const * fname);

    lua_State * get_state();

    typedef void (*reg_fn)(lua_State *); // NOLINT
    static void register_module(reg_fn f);
};
/**
   \brief Return a reference to the script_state object that is wrapping \c L.
*/
script_state to_script_state(lua_State * L);
void initialize_script_state();
void finalize_script_state();
}


text:
/*
    You may incorporate this sample code into your applications without
    restriction, though the sample code has been provided "AS IS" and the
    responsibility for its operation is 100% yours.  However, what you are
    not permitted to do is to redistribute the source as "DSC Sample Code"
    after having made changes. If you're going to re-distribute the source,
    we require that you make it clear in the source that the code was
    descended from Apple Sample Code, but that you've made changes.
*/

/*
    IMPORTANT NOTE:

    The use of full pathnames is strongly discouraged. Full pathnames are
    particularly unreliable as a means of identifying files, directories
    or volumes within your application, for two primary reasons:

    ¥   The user can change the name of any element in the path at
        virtually any time.
    ¥   Volume names on the Macintosh are *not* unique. Multiple
        mounted volumes can have the same name. For this reason, the use of
        a full pathname to identify a specific volume may not produce the
        results you expect. If more than one volume has the same name and
        a full pathname is used, the File Manager currently uses the first
        mounted volume it finds with a matching name in the volume queue.

    In general, you should use a fileÕs name, parent directory ID, and
    volume reference number to identify a file you want to open, delete,
    or otherwise manipulate.

    If you need to remember the location of a particular file across
    subsequent system boots, use the Alias Manager to create an alias
    record describing the file. If the Alias Manager is not available, you
    can save the fileÕs name, its parent directory ID, and the name of the
    volume on which itÕs located. Although none of these methods is
    foolproof, they are much more reliable than using full pathnames to
    identify files.

    Nonetheless, it is sometimes useful to display a fileÕs full pathname
    to the user. For example, a backup utility might display a list of full
    pathnames of files as it copies them onto the backup medium. Or, a
    utility might want to display a dialog box showing the full pathname of
    a file when it needs the userÕs confirmation to delete the file. No
    matter how unreliable full pathnames may be from a file-specification
    viewpoint, users understand them more readily than volume reference
    numbers or directory IDs. (Hint: Use the TruncString function from
    TextUtils.h with truncMiddle as the truncWhere argument to shorten
    full pathnames to a displayable length.)

    The following technique for constructing the full pathname of a file is
    intended for display purposes only. Applications that depend on any
    particular structure of a full pathname are likely to fail on alternate
    foreign file systems or under future system software versions.
*/

#ifndef __FULLPATH__
#define __FULLPATH__

#ifndef __MACTYPES__
#include <MacTypes.h>
#endif

#ifndef __FILES__
#include <Files.h>
#endif

#include "Optimization.h"

#if PRAGMA_ONCE
#pragma once
#endif

#ifdef __cplusplus
extern "C" {
#endif

#if PRAGMA_IMPORT
#pragma import on
#endif

#if PRAGMA_STRUCT_ALIGN
    #pragma options align=mac68k
#elif PRAGMA_STRUCT_PACKPUSH
    #pragma pack(push, 2)
#elif PRAGMA_STRUCT_PACK
    #pragma pack(2)
#endif

/*****************************************************************************/

EXTERN_API( OSErr )
GetFullPath(
  short              vRefNum,
  long               dirID,
  ConstStr255Param   name,
  short *            fullPathLength,
  Handle *           fullPath);

/*
    The GetFullPath function builds a full pathname to the specified
    object. The full pathname is returned in the newly created handle
    fullPath and the length of the full pathname is returned in
    fullPathLength. Your program is responsible for disposing of the
    fullPath handle.

    Note that a full pathname can be made to a file/directory that does not
    yet exist if all directories up to that file/directory exist. In this case,
    GetFullPath will return a fnfErr.

    vRefNum         input:  Volume specification.
    dirID           input:  Directory ID.
    name            input:  Pointer to object name, or nil when dirID
                            specifies a directory that's the object.
    fullPathLength  output: The number of characters in the full pathname.
                            If the function fails to create a full
                            pathname, it sets fullPathLength to 0.
    fullPath        output: A handle to the newly created full pathname
                            buffer. If the function fails to create a
                            full pathname, it sets fullPath to NULL.

    Result Codes
        noErr               0       No error
        nsvErr              -35     No such volume
        ioErr               -36     I/O error
        bdNamErr            -37     Bad filename
        fnfErr              -43     File or directory does not exist (fullPath
                                    and fullPathLength are still valid)
        paramErr            -50     No default volume
        memFullErr          -108    Not enough memory
        dirNFErr            -120    Directory not found or incomplete pathname
        afpAccessDenied     -5000   User does not have the correct access
        afpObjectTypeErr    -5025   Directory not found or incomplete pathname

    __________

    See also:   FSpGetFullPath
*/

/*****************************************************************************/

EXTERN_API( OSErr )
FSpGetFullPath(
  const FSSpec *  spec,
  short *         fullPathLength,
  Handle *        fullPath);

/*
    The GetFullPath function builds a full pathname to the specified
    object. The full pathname is returned in the newly created handle
    fullPath and the length of the full pathname is returned in
    fullPathLength. Your program is responsible for disposing of the
    fullPath handle.

    Note that a full pathname can be made to a file/directory that does not
    yet exist if all directories up to that file/directory exist. In this case,
    FSpGetFullPath will return a fnfErr.

    IMPORTANT: The definition of a FSSpec is a volume reference number (not a
    drive number, working directory number, or 0), a parent directory ID (not 0),
    and the name of a file or folder (not an empty name, a full pathname, or
    a partial pathname containing one or more colon (:) characters).
    FSpGetFullPath assumes it is getting a FSSpec that matches the rules.
    If you have an FSSpec record that wasn't created by FSMakeFSSpec (or
    FSMakeFSSpecCompat from FSpCompat in MoreFiles which correctly builds
    FSSpecs), you should call GetFullPath instead of FSpGetFullPath.

    spec            input:  An FSSpec record specifying the object.
    fullPathLength  output: The number of characters in the full pathname.
                            If the function fails to create a full pathname,
                            it sets fullPathLength to 0.
    fullPath        output: A handle to the newly created full pathname
                            buffer. If the function fails to create a
                            full pathname, it sets fullPath to NULL.

    Result Codes
        noErr               0       No error
        nsvErr              -35     No such volume
        ioErr               -36     I/O error
        bdNamErr            -37     Bad filename
        fnfErr              -43     File or directory does not exist (fullPath
                                    and fullPathLength are still valid)
        paramErr            -50     No default volume
        memFullErr          -108    Not enough memory
        dirNFErr            -120    Directory not found or incomplete pathname
        afpAccessDenied     -5000   User does not have the correct access
        afpObjectTypeErr    -5025   Directory not found or incomplete pathname

    __________

    See also:   GetFullPath
*/

/*****************************************************************************/

EXTERN_API( OSErr )
FSpLocationFromFullPath(
  short         fullPathLength,
  const void *  fullPath,
  FSSpec *      spec);

/*
    The FSpLocationFromFullPath function returns a FSSpec to the object
    specified by full pathname. This function requires the Alias Manager.

    fullPathLength  input:  The number of characters in the full pathname
                            of the target.
    fullPath        input:  A pointer to a buffer that contains the full
                            pathname of the target. The full pathname
                            starts with the name of the volume, includes
                            all of the directory names in the path to the
                            target, and ends with the target name.
    spec            output: An FSSpec record specifying the object.

    Result Codes
        noErr               0       No error
        nsvErr              -35     The volume is not mounted
        fnfErr              -43     Target not found, but volume and parent
                                    directory found
        paramErr            -50     Parameter error
        usrCanceledErr      -128    The user canceled the operation

    __________

    See also:   LocationFromFullPath
*/

/*****************************************************************************/

EXTERN_API( OSErr )
LocationFromFullPath(
  short         fullPathLength,
  const void *  fullPath,
  short *       vRefNum,
  long *        parID,
  Str31         name);

/*
    The LocationFromFullPath function returns the volume reference number,
    parent directory ID and name of the object specified by full pathname.
    This function requires the Alias Manager.

    fullPathLength  input:  The number of characters in the full pathname
                            of the target.
    fullPath        input:  A pointer to a buffer that contains the full
                            pathname of the target. The full pathname starts
                            with the name of the volume, includes all of
                            the directory names in the path to the target,
                            and ends with the target name.
    vRefNum         output: The volume reference number.
    parID           output: The parent directory ID of the specified object.
    name            output: The name of the specified object.

    Result Codes
        noErr               0       No error
        nsvErr              -35     The volume is not mounted
        fnfErr              -43     Target not found, but volume and parent
                                    directory found
        paramErr            -50     Parameter error
        usrCanceledErr      -128    The user canceled the operation

    __________

    See also:   FSpLocationFromFullPath
*/

/*****************************************************************************/

#include "OptimizationEnd.h"

#if PRAGMA_STRUCT_ALIGN
    #pragma options align=reset
#elif PRAGMA_STRUCT_PACKPUSH
    #pragma pack(pop)
#elif PRAGMA_STRUCT_PACK
    #pragma pack()
#endif

#ifdef PRAGMA_IMPORT_OFF
#pragma import off
#elif PRAGMA_IMPORT
#pragma import reset
#endif

#ifdef __cplusplus
}
#endif

#endif /* __FULLPATH__ */


text:
import Ember from 'ember';
import WavesMixin from '../../../mixins/waves';
import { module, test } from 'qunit';

module('Unit | Mixin | waves');

// Replace this with your real tests.
test('it works', function(assert) {
  var WavesObject = Ember.Object.extend(WavesMixin);
  var subject = WavesObject.create();
  assert.ok(subject);
});


text:
<html>
<body>
Contains all the actions for the video view.
</body>
</html>


text:
                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#app-navbar-collapse">
                    Toggle Navigation

                </button>

Inicio

FAQ

                    @if (Auth::guest())

 Login

                                Registro

 Estudiante

 Profesor

 Empresa

                    @else

                                carpeta . '/' .  \Auth::user()->image) }}" alt="Imagen de perfil" class="img-responsive img-circle img-navegador">

rol . config('routes.curriculum')) }}">Crear Curriculum

Cambiar contraseña

Logout

                    @endif


text:
#if !defined(BOOST_SPIRIT_SEQUENTIAL_OR_HPP)
#define BOOST_SPIRIT_SEQUENTIAL_OR_HPP

#include <boost/spirit/core/parser.hpp>
#include <boost/spirit/core/primitives/primitives.hpp>
#include <boost/spirit/core/composite/composite.hpp>
#include <boost/spirit/meta/as_parser.hpp>

namespace boost { namespace spirit {

    ///////////////////////////////////////////////////////////////////////////
    //
    //  sequential-or class
    //
    //      Handles expressions of the form:
    //
    //          a || b
    //
    //      Equivalent to
    //
    //          a | b | a >> b;
    //
    //      where a and b are parsers. The expression returns a composite
    //      parser that matches matches a or b in sequence. One (not both) of
    //      the operands may be a literal char, wchar_t or a primitive string
    //      char const*, wchar_t const*.
    //
    ///////////////////////////////////////////////////////////////////////////
    struct sequential_or_parser_gen;

    template <typename A, typename B>
    struct sequential_or : public binary<A, B, parser<sequential_or<A, B> > >
    {
        typedef sequential_or<A, B>             self_t;
        typedef binary_parser_category          parser_category_t;
        typedef sequential_or_parser_gen        parser_generator_t;
        typedef binary<A, B, parser<self_t> >   base_t;

        sequential_or(A const& a, B const& b)
        : base_t(a, b) {}

        template <typename ScannerT>
        typename parser_result<self_t, ScannerT>::type
        parse(ScannerT const& scan) const
        {
            typedef typename parser_result<self_t, ScannerT>::type result_t;
            typedef typename ScannerT::iterator_t iterator_t;
            { // scope for save
                iterator_t save = scan.first;
                if (result_t ma = this->left().parse(scan))
                {
                    save = scan.first;
                    if (result_t mb = this->right().parse(scan))
                    {
                        // matched a b
                        scan.concat_match(ma, mb);
                        return ma;
                    }
                    else
                    {
                        // matched a
                        scan.first = save;
                        return ma;
                    }
                }
                scan.first = save;
            }

            // matched b
            return this->right().parse(scan);
        }
    };

    struct sequential_or_parser_gen
    {
        template <typename A, typename B>
        struct result
        {
            typedef
                sequential_or<
                    typename as_parser<A>::type
                  , typename as_parser<B>::type
                >
            type;
        };

        template <typename A, typename B>
        static sequential_or<
            typename as_parser<A>::type
          , typename as_parser<B>::type
        >
        generate(A const& a, B const& b)
        {
            return sequential_or<BOOST_DEDUCED_TYPENAME as_parser<A>::type,
                BOOST_DEDUCED_TYPENAME as_parser<B>::type>
                    (as_parser<A>::convert(a), as_parser<B>::convert(b));
        }
    };

    template <typename A, typename B>
    sequential_or<A, B>
    operator||(parser<A> const& a, parser<B> const& b);

    template <typename A>
    sequential_or<A, chlit<char> >
    operator||(parser<A> const& a, char b);

    template <typename B>
    sequential_or<chlit<char>, B>
    operator||(char a, parser<B> const& b);

    template <typename A>
    sequential_or<A, strlit<char const*> >
    operator||(parser<A> const& a, char const* b);

    template <typename B>
    sequential_or<strlit<char const*>, B>
    operator||(char const* a, parser<B> const& b);

    template <typename A>
    sequential_or<A, chlit<wchar_t> >
    operator||(parser<A> const& a, wchar_t b);

    template <typename B>
    sequential_or<chlit<wchar_t>, B>
    operator||(wchar_t a, parser<B> const& b);

    template <typename A>
    sequential_or<A, strlit<wchar_t const*> >
    operator||(parser<A> const& a, wchar_t const* b);

    template <typename B>
    sequential_or<strlit<wchar_t const*>, B>
    operator||(wchar_t const* a, parser<B> const& b);

}} // namespace boost::spirit

#endif

#include <boost/spirit/core/composite/impl/sequential_or.ipp>


text:
'use strict';

var grunt = require('grunt');

exports.nodeunit = {
  please_work: function(test) {
    test.expect(1);
    test.ok(true, 'this had better work.');
    test.done();
  },
  fail: function(test) {
    test.expect(2);
    grunt.util.spawn({
      grunt: true,
      args: ['test:fail', '--no-color'],
    }, function(err, result) {
      test.ok(result.stdout.indexOf('Message: this value should be truthy') !== -1, 'Message should have been displayed.');
      test.ok(result.stdout.indexOf('Error: undefined == true') !== -1, 'Error should have been displayed.');
      test.done();
    });
  },
};


text:
Insert a single document into a collection.

```javascript
db.movies.insertOne({ "title": "Deadpool", "year": 2016 });
```

## db.collection.insertMany

Insert multiple documents into a collection.

``` javascript
db.movies.insertMany(
  [
    { "_id": 1, "title": "Deadpool", "year": 2016 },
    { "_id": 1, "title": "Scarface", "year": 1983 }, // has the same id that Deadpool
    { "_id": 2, "title": "Avatar", "year": 2009 },
  ]
);
```

By default, `insertMany` insert all the documents with the parameter `ordered` set to true,
this means that mongo will insert all the documents one by one from top to bottom but
if in the middle of the operation mongo finds an error with at least one document, the process will stop.

```javascript
db.movies.insertMany(
  [
    { "_id": 1, "title": "Deadpool", "year": 2016 },
    { "_id": 1, "title": "Scarface", "year": 1983 }, // has the same id that Deadpool
    { "_id": 2, "title": "Avatar", "year": 2009 },
  ]
);
```

Using the parameter `ordered` with `false` as value, mongo will skip the error (if exist) and
will insert successfuly all the documents that have no errors.

```javascript
db.movies.insertMany(
  [
    { "title": "Deadpool", "year": 2016 },
    { "title": "Scarface", "year": 1983 }
  ],
  { "ordered": false }
);
```

## db.collection.insert

```javascript
db.movies.insert({ "title": "Deadpool", "year": 2016 });
```


text:
> [Introduced][ee-1283] in [GitLab Premium][eep] 9.0.

Distribute read-only queries among multiple database servers.

## Overview

Database load balancing improves the distribution of database workloads across
multiple computing resources. Load balancing aims to optimize resource use,
maximize throughput, minimize response time, and avoid overload of any single
resource. Using multiple components with load balancing instead of a single
component may increase reliability and availability through redundancy.
[_Wikipedia article_][wikipedia]

When database load balancing is enabled in GitLab, the load is balanced using
a simple round-robin algorithm, without any external dependencies such as Redis.
Load balancing is not enabled for Sidekiq as this would lead to consistency
problems, and Sidekiq mostly performs writes anyway.

In the following image, you can see the load is balanced rather evenly among
all the secondaries (`db4`, `db5`, `db6`). Because `SELECT` queries are not
sent to the primary (unless necessary), the primary (`db3`) hardly has any load.

![DB load balancing graph](img/db_load_balancing_postgres_stats.png)

## Requirements

For load balancing to work you will need at least PostgreSQL 9.2 or newer,
[**MySQL is not supported**][db-req]. You also need to make sure that you have
at least 1 secondary in [hot standby][hot-standby] mode.

Load balancing also requires that the configured hosts **always** point to the
primary, even after a database failover. Furthermore, the additional hosts to
balance load among must **always** point to secondary databases. This means that
you should put a load balance in front of every database, and have GitLab connect
to those load balancers.

For example, say you have a primary (`db1.gitlab.com`) and two secondaries,
`db2.gitlab.com` and `db3.gitlab.com`. For this setup you will need to have 3
load balancers, one for every host. For example:

* `primary.gitlab.com` forwards to `db1.gitlab.com`
* `secondary1.gitlab.com` forwards to `db2.gitlab.com`
* `secondary2.gitlab.com` forwards to `db3.gitlab.com`

Now let's say that a failover happens and db2 becomes the new primary. This
means forwarding should now happen as follows:

* `primary.gitlab.com` forwards to `db2.gitlab.com`
* `secondary1.gitlab.com` forwards to `db1.gitlab.com`
* `secondary2.gitlab.com` forwards to `db3.gitlab.com`

GitLab does not take care of this for you, so you will need to do so yourself.

Finally, load balancing requires that GitLab can connect to all hosts using the
same credentials and port as configured in the
[Enabling load balancing](#enabling-load-balancing) section. Using
different ports or credentials for different hosts is not supported.

## Use cases

- For GitLab instances with thousands of users and high traffic, you can use
  database load balancing to reduce the load on the primary database and
  increase responsiveness, thus resulting in faster page load inside GitLab.

## Enabling load balancing

For the environment in which you want to use load balancing, you'll need to add
the following. This will balance the load between `host1.example.com` and
`host2.example.com`.

**In Omnibus installations:**

1. Edit `/etc/gitlab/gitlab.rb` and add the following line:

    ```ruby
    gitlab_rails['db_load_balancing'] = { 'hosts' => ['host1.example.com', 'host2.example.com'] }
    ```

1. Save the file and [reconfigure GitLab][] for the changes to take effect.

---

**In installations from source:**

1. Edit `/home/git/gitlab/config/database.yml` and add or amend the following lines:

    ```yaml
    production:
      username: gitlab
      database: gitlab
      encoding: unicode
      load_balancing:
        hosts:
          - host1.example.com
          - host2.example.com
    ```

1. Save the file and [restart GitLab][] for the changes to take effect.

## Service Discovery

> [Introduced][ee-5883] in [GitLab Premium][eep] 11.0.

Service discovery allows GitLab to automatically retrieve a list of secondary
databases to use, instead of having to manually specify these in the
`database.yml` configuration file. Service discovery works by periodically
checking a DNS A record, using the IPs returned by this record as the addresses
for the secondaries. For service discovery to work, all you need is a DNS server
and an A record containing the IP addresses of your secondaries.

To use service discovery you need to change your `database.yml` configuration
file so it looks like the following:

```yaml
production:
  username: gitlab
  database: gitlab
  encoding: unicode
  load_balancing:
    discover:
      nameserver: localhost
      record: secondary.postgresql.service.consul
      port: 8600
      interval: 60
      disconnect_timeout: 120
```

Here the `discover:` section specifies the configuration details to use for
service discovery.

### Configuration

The following options can be set:

| Option               | Description                                                                                | Default   |
|----------------------|---------------------------------------------------------------------------------------------------|-----------|
| `nameserver`         | The nameserver to use for looking up the DNS record.                                              | localhost |
| `record`             | The A record to look up. This option is required for service discovery to work.                   |           |
| `port`               | The port of the nameserver.                                                                       | 8600      |
| `interval`           | The minimum time in seconds between checking the DNS record.                                      | 60        |
| `disconnect_timeout` | The time in seconds after which an old connection is closed, after the list of hosts was updated. | 120       |
| `use_tcp`            | Lookup DNS resources using TCP instead of UDP                                                     | false     |

The `interval` value specifies the _minimum_ time between checks. If the A
record has a TTL greater than this value, then service discovery will honor said
TTL. For example, if the TTL of the A record is 90 seconds, then service
discovery will wait at least 90 seconds before checking the A record again.

When the list of hosts is updated, it might take a while for the old connections
to be terminated. The `disconnect_timeout` setting can be used to enforce an
upper limit on the time it will take to terminate all old database connections.

Some nameservers (like [Consul][consul-udp]) can return a truncated list of hosts when
queried over UDP. To overcome this issue, you can use TCP for querying by setting
`use_tcp` to `true`.

### Forking

If you use an application server that forks, such as Unicorn, you _have to_
update your Unicorn configuration to start service discovery _after_ a fork.
Failure to do so will lead to service discovery only running in the parent
process. If you are using Unicorn, then you can add the following to your
Unicorn configuration file:

```ruby
after_fork do |server, worker|
  defined?(Gitlab::Database::LoadBalancing) &&
    Gitlab::Database::LoadBalancing.start_service_discovery
end
```

This will ensure that service discovery is started in both the parent and all
child processes.

## Balancing queries

Read-only `SELECT` queries will be balanced among all the secondary hosts.
Everything else (including transactions) will be executed on the primary.
Queries such as `SELECT ... FOR UPDATE` are also executed on the primary.

## Prepared statements

Prepared statements don't work well with load balancing and are disabled
automatically when load balancing is enabled. This should have no impact on
response timings.

## Primary sticking

After a write has been performed, GitLab will stick to using the primary for a
certain period of time, scoped to the user that performed the write. GitLab will
revert back to using secondaries when they have either caught up, or after 30
seconds.

## Failover handling

In the event of a failover or an unresponsive database, the load balancer will
try to use the next available host. If no secondaries are available the
operation is performed on the primary instead.

In the event of a connection error being produced when writing data, the
operation will be retried up to 3 times using an exponential back-off.

When using load balancing, you should be able to safely restart a database server
without it immediately leading to errors being presented to the users.

## Logging

The load balancer logs various messages, such as:

* When a host is marked as offline
* When a host comes back online
* When all secondaries are offline

Each log message contains the tag `[DB-LB]` to make searching/filtering of such
log entries easier. For example:

```
[DB-LB] Host 10.123.2.5 came back online
[DB-LB] Marking host 10.123.2.7 as offline
[DB-LB] Marking host 10.123.2.7 as offline
[DB-LB] Marking host 10.123.2.7 as offline
[DB-LB] Marking host 10.123.2.7 as offline
[DB-LB] Marking host 10.123.2.7 as offline
[DB-LB] Host 10.123.2.6 came back online
[DB-LB] Marking host 10.123.2.7 as offline
[DB-LB] Marking host 10.123.2.7 as offline
[DB-LB] Marking host 10.123.2.7 as offline
[DB-LB] Host 10.123.2.7 came back online
[DB-LB] Host 10.123.2.7 came back online
```

## Handling Stale Reads

> [Introduced][ee-3526] in [GitLab Premium][eep] 10.3.

To prevent reading from an outdated secondary the load balancer will check if it
is in sync with the primary. If the data is determined to be recent enough the
secondary can be used, otherwise it will be ignored. To reduce the overhead of
these checks we only perform these checks at certain intervals.

There are three configuration options that influence this behaviour:

| Option                       | Description                                                                                | Default    |
|------------------------------|----------------------------------------------------------------------------------------------------------------|------------|
| `max_replication_difference` | The amount of data (in bytes) a secondary is allowed to lag behind when it hasn't replicated data for a while. | 8 MB       |
| `max_replication_lag_time`   | The maximum number of seconds a secondary is allowed to lag behind before we stop using it.                    | 60 seconds |
| `replica_check_interval`     | The minimum number of seconds we have to wait before checking the status of a secondary.                       | 60 seconds |

The defaults should be sufficient for most users. Should you want to change them
you can specify them in `config/database.yml` like so:

```yaml
production:
  username: gitlab
  database: gitlab
  encoding: unicode
  load_balancing:
    hosts:
      - host1.example.com
      - host2.example.com
    max_replication_difference: 16777216 # 16 MB
    max_replication_lag_time: 30
    replica_check_interval: 30
```

[hot-standby]: https://www.postgresql.org/docs/9.6/static/hot-standby.html
[ee-1283]: https://gitlab.com/gitlab-org/gitlab-ee/merge_requests/1283
[eep]: https://about.gitlab.com/pricing/
[reconfigure gitlab]: restart_gitlab.md#omnibus-gitlab-reconfigure "How to reconfigure Omnibus GitLab"
[restart gitlab]: restart_gitlab.md#installations-from-source "How to restart GitLab"
[wikipedia]: https://en.wikipedia.org/wiki/Load_balancing_(computing)
[db-req]: ../install/requirements.md#database
[ee-3526]: https://gitlab.com/gitlab-org/gitlab-ee/merge_requests/3526
[ee-5883]: https://gitlab.com/gitlab-org/gitlab-ee/merge_requests/5883
[consul-udp]: https://www.consul.io/docs/agent/dns.html#udp-based-dns-queries


text:
SCRIPT=`readlink -f $0`
DIRNAME=`dirname $SCRIPT`
STARTDIR=`dirname $DIRNAME`

##################################################################################
# Get config
##################################################################################

if [ $# -ne 1 ]; then
    echo "usage: $0 servername"
    exit 1
fi
TARGET=$1

cd $STARTDIR
if [ ! -f deploy/$TARGET.conf ]; then
    echo "No config file available: deploy/${TARGET}.conf"
    exit 1
fi

cd $STARTDIR
. deploy/${TARGET}.conf
echo "Deploying to ${TARGETUSER}@${TARGETSERVER}:${TARGETDIR}"

. deploy/sources.conf
echo "Deploying ${SOURCES}"

##################################################################################
# Build server infrastructure directories
##################################################################################

#
# Check user account
#
cd $STARTDIR
echo "Checking ${TARGETUSER} account and creating if required"
ssh root@${TARGETSERVER} "
    if [ ! -d /home/${TARGETUSER} ]; then
        adduser -c 'Web site owner' -G $WEBGROUP $TARGETUSER
        mkdir -p /home/${TARGETUSER}/.ssh
        cp /root/.ssh/authorized_keys /home/${TARGETUSER}/.ssh
        chown -R ${TARGETUSER} /home/${TARGETUSER}
    fi
"

#
# Set up deployment directories
#
echo "Setting up target directories $TARGETDIR and $TARGETSTORAGE"
ssh root@${TARGETSERVER} "
    mkdir -p $TARGETDIR
    mkdir -p $TARGETSTORAGE
    chown -R ${TARGETUSER} $TARGETDIR
    chgrp -R ${WEBGROUP} $TARGETDIR
"

##################################################################################
# Deploy web site software
##################################################################################

#
# Make a backup before starting
#
if [ "$TARGETDEPLOYDB" != "new" ]; then
    echo "Backing up existing web files and database on $TARGETSERVER"
    BACKDATE=`date '+%Y%m%d_%H%M'`
    DIR=`basename $TARGETDIR`
    BACKDIR=${BACKDATE}_${DIR}
    ssh root@${TARGETSERVER} "
        cd $TARGETDIR
        cd ..
        mkdir -p backups
        cp -a $TARGETDIR backups/$BACKDIR
        if [ "$DBBACKUP" = "yes" ]; then
            mysqldump -u $TARGETDBUSER --password=$TARGETDBPASS -h ${TARGETDBHOST} ${TARGETDBNAME} | gzip > backups/${BACKDATE}_${TARGETDBNAME}.sql.gz
        else
            echo "Database backup disabled on $TARGETSERVER. Change DBBACKUP=yes in your config file to enable"
        fi
    "
fi

#
# Deploy web software files
#
cd $STARTDIR
echo "Syncing web files to $TARGETDIR"
rsync -vaz --delete $SOURCES ${TARGETUSER}@${TARGETSERVER}:${TARGETDIR}

#
# Deploy modified config files
#
echo "Deploying config files in ${STARTDIR}/deploy/${TARGETSERVER}"
cd ${STARTDIR}/deploy/${TARGET}
for file in *; do
    TARGETFILE=`echo $file | sed -e 's;+;/;g' -e 's/DOT/\./g'`
    echo "Copying $file to ${TARGETSERVER}:${TARGETDIR}/${TARGETFILE}"
    scp $file ${TARGETUSER}@${TARGETSERVER}:${TARGETDIR}/${TARGETFILE}
done

#
# Install root config files.
#
echo "Installing root configuration files on ${TARGETSERVER}"
cd ${STARTDIR}/deploy/root/${TARGET}
for file in *; do
    TARGETFILE=`echo $file | sed 's;+;/;g'`
    echo "Copying $file to ${TARGETSERVER}:/${TARGETFILE}"
    scp $file root@${TARGETSERVER}:/${TARGETFILE}
done

#
# Web user config post install
#
ssh ${TARGETUSER}@${TARGETSERVER} "
    cd $TARGETDIR
    if [ -f composer.lock ]; then
        composer install
    else
        composer update
    fi
    if [ -f bower.json ]; then
        bower install
    fi
    if [ -f gulpfile.js ]; then
        npm install --quiet --save-dev gulp
        npm install --quiet
        ./node_modules/.bin/gulp
    fi
"

##################################################################################
# Deploy database
##################################################################################

if [ "$TARGETDEPLOYDB" = "new" ]; then
    echo "Creating new database"
    #
    # Drop and recreate the database to ensure it's clean.
    #
    ssh ${TARGETUSER}@${TARGETSERVER} "
        cd ${TARGETDIR}
        mysql -u root --password=$TARGETDBAPASS -h ${TARGETDBHOST} << EOFDB
        SET FOREIGN_KEY_CHECKS=0;
        DROP DATABASE IF EXISTS ${TARGETDBNAME};
        CREATE DATABASE ${TARGETDBNAME} CHARACTER SET utf8;
        GRANT ALL ON ${TARGETDBNAME}.* TO ${TARGETDBUSER}@localhost IDENTIFIED BY '${TARGETDBPASS}';
EOFDB
    "
fi

#
# Run the database migration.
#
if [ "$TARGETDEPLOYDB" != "none" ]; then
    echo "Running database migration"
    ssh ${TARGETUSER}@${TARGETSERVER} "
        cd ${TARGETDIR}
        chmod -R g-w .
        php artisan migrate
    "
fi

#
# Run the database seed only on a new database.
#
if [ "$TARGETDEPLOYDB" = "new" ]; then
    echo "Running database seed"
    ssh ${TARGETUSER}@${TARGETSERVER} "
        cd ${TARGETDIR}
        php artisan db:seed
        php artisan keylists:loadtimezones
        php artisan keylists:loadiso3166countries
        php artisan keylists:loadusdrates
        php artisan cache:clear
        php artisan view:clear
    "
fi

#
# Reset permissions
#
echo "Fixing permissions"
ssh root@${TARGETSERVER} "
    chown -R ${TARGETUSER} ${TARGETDIR}
    chgrp -R ${WEBGROUP} ${TARGETDIR}
    chmod -R g-w ${TARGETDIR}
    chmod -R g+rX ${TARGETDIR}
    chmod -R o-rwx ${TARGETDIR}
    find ${TARGETDIR} -type d -exec chmod g+s {} \;
    chown -R ${WEBUSER} ${TARGETSTORAGE}
    chgrp -R ${WEBGROUP} ${TARGETSTORAGE}
    chmod -R g+rwX ${TARGETSTORAGE}
    chmod -R o-rwx ${TARGETSTORAGE}
    find ${TARGETSTORAGE} -type d -exec chmod g+ws {} \;
"


text:
<?php

/**
 * Template Name: bbPress - User Login
 *
 * @package bbPress
 * @subpackage Theme
 */

// No logged in users
bbp_logged_in_redirect();
get_header();
st_before_content($columns='');

do_action( 'bbp_template_notices' );
// Begin Template
	while ( have_posts() ) : the_post(); ?>

<?php the_title(); ?>

				<?php the_content(); ?>

				<?php // this just clutters things - bbp_breadcrumb(); ?>

				<?php bbp_get_template_part( 'bbpress/form', 'user-login' ); ?>

	<?php endwhile;
		st_after_content();
		get_sidebar('bbpress');
		get_footer();
	?>


text:
package test;

import java.util.Random;

public class Carreer {
	static final int PEOPLE = 6,
			WEREWOLFNUMINIT=1,VILLAGERNUMINIT=5;
	Random randomGenerator;
	public int werewolfNum= WEREWOLFNUMINIT;
	public int villagerNum= VILLAGERNUMINIT;
	villager vi[];
	public Carreer(User[] user){
		vi = new villager[PEOPLE] ;
		randomGenerator = new Random();
		int randomInt = randomGenerator.nextInt(6);
		for(int i = 0 ; i < PEOPLE ;i++)
			if(i!=randomInt)
				vi[i] = new villager(user[i].IDnum,"villager");
			else
				vi[i] = new Werewolf(user[i].IDnum,"werewolf");
	}
	public int getWerewolfNum(){
		return werewolfNum;
	}
	public int getVillagerNum() {
		return villagerNum;
	}
}


text:
@interface CommonRequestModel : NSObject

@property(copy,nonatomic,readonly) NSString *device_id;
@property(copy,nonatomic,readonly) NSString *version;
@property(copy,nonatomic,readonly) NSString *channel;

@end


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

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.7"/>
<title>App Engine Python SDK: google.appengine.tools.devappserver2.python.sandbox.PathOverrideImportHook Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

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

App Engine Python SDK
    v1.6.9 rev.445

The Python runtime is available as an experimental Preview feature.

google

appengine

tools

devappserver2

python

sandbox

PathOverrideImportHook

Public Member Functions |
Public Attributes |
List of all members

google.appengine.tools.devappserver2.python.sandbox.PathOverrideImportHook Class Reference

Inheritance diagram for google.appengine.tools.devappserver2.python.sandbox.PathOverrideImportHook:

  <map id="google.appengine.tools.devappserver2.python.sandbox.PathOverrideImportHook_map" name="google.appengine.tools.devappserver2.python.sandbox.PathOverrideImportHook_map">
<area href="classgoogle_1_1appengine_1_1tools_1_1devappserver2_1_1python_1_1sandbox_1_1_base_import_hook.html" alt="google.appengine.tools.devappserver2.python.sandbox.BaseImportHook" shape="rect" coords="0,56,469,80"/>
</map>

Public Member Functions

def 	__init__

def 	find_module

def 	load_module

 Public Member Functions inherited from google.appengine.tools.devappserver2.python.sandbox.BaseImportHook

def 	is_package

def 	get_source

def 	get_code

Public Attributes

 	extra_accessible_paths

 	extra_sys_paths

Detailed Description

An import hook that imports enabled modules from predetermined paths.

Imports handled by this hook ignore the paths in sys.path, instead using paths
discovered at initialization time.

Attributes:
  extra_sys_paths: A list of paths that should be added to sys.path.
  extra_accessible_paths: A list of paths that should be accessible by
      sandboxed code.

The documentation for this class was generated from the following file:

code/googleappengine-read-only/python/google/appengine/tools/devappserver2/python/sandbox.py

<address class="footer">
    Maintained by tzmartin
</address>


text:
#include <string>
#include <vector>

#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/tpu/kernels/tpu_compilation_cache_interface.h"
#include "tensorflow/core/tpu/kernels/tpu_op_consts.h"
#include "tensorflow/core/tpu/tpu_configuration.h"

namespace tensorflow {

class TpuHandleToProtoKeyOp : public OpKernel {
 public:
  explicit TpuHandleToProtoKeyOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}
  ~TpuHandleToProtoKeyOp() override = default;
  TpuHandleToProtoKeyOp(const TpuHandleToProtoKeyOp&) = delete;
  TpuHandleToProtoKeyOp& operator=(const TpuHandleToProtoKeyOp&) = delete;

  void Compute(OpKernelContext* ctx) override {
    VLOG(1) << "TpuHandleToProtoKeyOp::Compute " << ctx->op_kernel().name()
            << " on device " << ctx->op_kernel().requested_device();
    const Tensor& uid = ctx->input(0);

    ResourceMgr* rm = GetTPUConfigResourceMgr();
    tpu::TpuCompilationCacheInterface* cache;
    OP_REQUIRES_OK(ctx, rm->Lookup<tpu::TpuCompilationCacheInterface>(
                            rm->default_container(),
                            tpu::kCompilationCacheResourceName, &cache));
    core::ScopedUnref cache_unref(cache);

    std::vector<std::string> keys;
    OP_REQUIRES_OK(ctx, cache->GetKeysFromUid(uid.scalar<int64_t>()(), &keys));

    TensorShape output_shape;
    output_shape.AddDim(keys.size());
    Tensor* result = nullptr;
    OP_REQUIRES_OK(ctx, ctx->allocate_output(0, output_shape, &result));
    for (int i = 0; i < keys.size(); ++i) {
      result->vec<tstring>()(i) = keys[i];
    }
  };
};

REGISTER_KERNEL_BUILDER(Name("TpuHandleToProtoKey").Device(DEVICE_CPU),
                        TpuHandleToProtoKeyOp);

}  // namespace tensorflow


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.github.somi92.sqldbb.query.builder;

import com.github.somi92.sqldbb.entity.DatabaseEntity;
import com.github.somi92.sqldbb.entity.processor.EntityProcessor;
import com.github.somi92.sqldbb.query.Query;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;

/**
 *
 * @author milos
 */
public abstract class AbstractQueryBuilder {

    protected Query query;

    protected void setPSValue(DatabaseEntity dbe, String column, int i, PreparedStatement ps) throws SQLException {

        String field = dbe.getColumnFieldMapping().get(column);
        Object fieldValue = dbe.getFieldValues().get(field);
        Class fieldType = dbe.getFieldTypes().get(field);

        switch(fieldType.getSimpleName()) {
            case "byte":
                ps.setByte(i+1, (byte) fieldValue);
                break;
            case "short":
                ps.setShort(i+1, (short) fieldValue);
                break;
            case "int":
                ps.setInt(i+1, (int) fieldValue);
                break;
            case "String":
                ps.setString(i+1, (String) fieldValue);
                break;
            case "long":
                ps.setLong(i+1, (long) fieldValue);
                break;
            case "float":
                ps.setFloat(i+1, (float) fieldValue);
                break;
            case "double":
                ps.setDouble(i+1, (double) fieldValue);
                break;
            case "boolean":
                ps.setBoolean(i+1, (boolean) fieldValue);
                break;
            case "char":
                ps.setString(i+1, (String) (fieldValue.toString().charAt(0)+""));
                break;
            case "Date":
                Date d = (Date) fieldValue;
                Timestamp t = new Timestamp(d.getTime());
                ps.setTimestamp(i+1, t);
                break;
            default: {
                DatabaseEntity.ForeignKeyEntity fke = dbe.getReferences().get(column);
                DatabaseEntity newDbe = fke.getDbe();
                String referencingColumn = fke.getReferencingColumn();
                EntityProcessor.setEntityFieldValues(newDbe, fieldValue);
                setPSValue(newDbe, referencingColumn, i, ps);
            }
        }
    }

    public abstract void setKeywords();
    public abstract void setQueryFormat();
    public abstract void formatQuery(DatabaseEntity dbe);
    public abstract void fillPreparedStatement(PreparedStatement ps, DatabaseEntity dbe) throws SQLException;

    public Query getQuery() {
        return query;
    }
}