text:
initial_quotes = [
    {'q': "Just Keep Swimming", 'by': " Dori"},
    {'q': "No one can make you feel inferior without your consent", 'by': "Eleanor Roosevelt"},
    {'q': "If you are always trying to be normal, you'll never know how amazing you can be", 'by': "Maya Angelou"},
    {'q': "The most effective way to do it, is to do it", 'by': "Amelia Earhart"},
    {'q': "The future belongs to those who believe in the beauty of their dreams", 'by': "Eleanor Roosevelt."},
    {'q': "I never dreamed about success. I worked for it", 'by': "Estée Lauder"},
    {'q': "No matter how plain a woman may be, if truth and honesty are written across her face, she will be beautiful", 'by': "Eleanor Roosevelt"},
    {'q': "I'm not afraid of storms, for I'm learning to sail my ship", 'by': "Louisa May Alcott"},
    {'q': "I think beauty come from knowing who you actually are. That's real beauty to me", 'by': "Ellen DeGeneres"},
    {'q': "You are more powerful than you know; you are beautiful just as you are", 'by': "Melissa Etheridge"},
    {'q': "I can't think of any better representation of beauty than someone who is unafraid to be herself", 'by': "Emma Stone"},
    {'q': "The most common way people give up their power is by thinking they don't have any", 'by': " Alice Walker"},
    {'q': "If you look at what you have in life, you'll always have more. If you look at what you don't have in life, you'll never have enough", 'by': "Oprah Winfrey"},
    {'q': "Quality is not an act, it is a habit", 'by': " Aristotle"},
    {'q': "The secret of getting ahead is getting started", 'by': " Mark Twain"},
    {'q': "Put your heart, mind, and soul into even your smallest acts. This is the secret of success", 'by': "Swami Sivananda"},
    {'q': "Do not go where the path may lead, go instead where there is no path and leave a trail", 'by': "Ralph Waldo Emerson"},
    {'q': "It's not what you look at that matters, it's what you see", 'by': " Henry David Thoreau"},
    {'q': "All of us, at certain moments of our lives, need to take advice and to receive help from other people", 'by': "Alexis Carrel"},
    {'q': "Don't gain the world and lose your soul; wisdom is better than silver or gold", 'by': "Bob Marley"},
    {'q': "Be as you wish to seem", 'by': " Socrates"},
    {'q': "It is far better to grasp the universe as it really is than to persist in delusion, however satisfying and reassuring", 'by': "Carl Sagan"},
    {'q': "Personality is an unbroken series of successful gestures", 'by': "F. Scott Fitzgerald"},
    {'q': "Whatever you are, be a good one", 'by': " Abraham Linccoln"},
    {'q': "Don't wait. The time will never be just right", 'by': " Napoleon Hill"},
    {'q': "If not us, who? If not now, when?", 'by': " John F Kennedy"},
    {'q': "Everything you can imagine is real", 'by': " Pablo Picasso"},
    {'q': "Life is trying things to see if they work", 'by': " Ray Bradbury"},
    {'q': "Do one thing every day that scares you", 'by': " Eleanor Roosevelt"},
    {'q': "The power of imagination makes us inifinite", 'by': " John Muir"},
    {'q': "Eighty percent of success is showing up", 'by': " Woody Allen"},
    {'q': "A jug fills drop by drop", 'by': " Budda"},
    {'q': "The obstacle is the path", 'by': " Zen Proverb"},
    {'q': "All you need is love", 'by': " John Lennon"},
    {'q': "It does not matter how slowly you go as long as you do not stop", 'by': " Confucius"},
    {'q': "It is never to late to be what you might have been", 'by': " Someone"},
    {'q': "If you try to fail, and succeed, which have you done?", 'by': " George Carlin"},
    {'q': "You can't wait for inspiration. You have to go after it with a club", 'by': " Jack London"},
    {'q': "Great spirits have always encountered violent opposition from mediocre minds", 'by': " Albert Einstein"},
    {'q': "A diamond is merely a lump of coal that did well under pressure", 'by': " Someone"},
    {'q': "Try to be like the turtle – at ease in your own shell", 'by': " Bill Copeland"},
    {'q': "There's never enough time to do all the nothing you want", 'by': " Bill Watterson"},
    {'q': "Think of how stupid the average person is, and realize half of them are stupider than that", 'by': " George Carlin"},
    {'q': "The reason I talk to myself is because I'm the only one whose answers I accept", 'by': " George Carlin"},
    {'q': "What you do speaks so loudly tha I cannot hear what you say", 'by': " Ralph Waldo Emerson"},
    {'q': "The best dreams happen when you're awake", 'by': "Cherie Gilderbloom"},
    {'q': "A year from now you may wish you had started today", 'by': "Karen Lamb"},
    {'q': "Do what you can, where you are, with what you have", 'by': "Teddy Roosevelt"},
    {'q': "To avoid criticism, do nothing, say nothing, be nothing", 'by': "Elbert Hubbard"},
    {'q': "Do what you love and the money will follow", 'by': "Marsha Sinetar"},
    {'q': "The purpose of our lives is to be happy", 'by': "Dalai Lama"},
    {'q': "The price of anything is the amount of life you exchange for it", 'by': "Henry David Thoreau"},
    {'q': "There are no shortcuts to any place worth going", 'by': " Beverly Sills"},
    {'q': "Do not take life too seriously. You will never get out of it alive", 'by': "Elbert Hubbard"},
    {'q': "People who think they know everything are a great annoyance to those of us who do", 'by': "Isaac Asimov"},
    {'q': "Roses are red, violets are blue, I'm schizophrenic and so am I ", 'by': " Oscar Levant"},
    {'q': "I always wanted to be somebody, but now I realize I should have been more specific", 'by': "Lilly Tomlin"},
    {'q': "Go to Heaven for the climate, Hell for the company", 'by': "Mark Twain"},
    {'q': "All generalizations are false, including this one", 'by': "Mark Twain"},
    {'q': "For most of history 'Anonymous' was a woman", 'by': "Virginia Wolf"},
    {'q': "Know what? Bitches get stuff done", 'by': "Tina Fey"},
    {'q': "I am a Woman Phenomenally. Phenomenal Woman, that's me", 'by': "Maya Angelou"},
    {'q': "Far away there in the sunshine are my highest aspirations. I may not reach them, but I can look up and see their beauty, believe in them, and try to follow where they lead.", 'by': "Louisa May Alcott"},
    {'q': "Don't compromise yourself, you are all you've got", 'by': "Janis Joplin"},
    {'q': "Never doubt that a small group of thoughtful, committed citizens can change the world; indeed, it's the only thing that ever has", 'by': "Margaret Mead"},
    {'q': "Success is going from failure to failure without losing your enthusiams", 'by': "Winston Churchill"},
    {'q': "Dream big and dare to fail", 'by': "Norman Vaughan"},
    {'q': "There is only one success: to be able to spend your life in your own way", 'by': "Christopher Morley"},
    {'q': "The best way out is always through", 'by': "Robert Frost"},
    {'q': "Make each day your masterpiece", 'by': "John Wooden"},
    {'q': "The best dreams happen whan you're awake", 'by': "Cherie Golderbloomm"},
    {'q': "Every moment is a fresh beginning", 'by': "T.S. Eliot"},
    {'q': "Don't count the days, make the days count", 'by': "Muhammad Ali"},
    {'q': "I don't think women are better than men, I think men are a lot worse than women.", 'by': "Louis CK"},
    {'q': "The only time you look in your neighbor's bowl is to make sure that they have enough. You don't look in your neighbor's bowl to see if you have as much as them", 'by': "Louis CK"},
    {'q': "The most effective way to do it, is to do it", 'by': "Amelia Earhart"},
    {'q': "The future belongs to those who believe in the beauty of their dreams", 'by': "Eleanor Roosevelt"},
    {'q': "It's not your job to like me - it's mine", 'by': "Byron Katie"},
    {'q': "Put on some lipstick and pull yourself together", 'by': "Elizabeth Taylor"},
    {'q': "The most courageous act is still to think for yourself. Aloud.", 'by': "Coco Chanel"},
    {'q': "A lot of people are afraid to say what they want. That's why they don't get what they want", 'by': "Madonna Ciccone"},
    {'q': "I have not failed, I have only found 10000 ways that wont work", 'by': "Thomas Edison"},
    {'q': "People will never forget how you made them feel.", 'by': "Maya Angelou"},
    {'q': "Power to me is having the ability to make a change in a positive way.", 'by': "Victoria Justice"},
    {'q': "I love America. Just because I think gay dudes should be allowed to adopt kids and we should all have hybrid cars doesn't mean I don't love America", 'by': "Liz Lemon"},
    {'q': "I pretty much just do whatever Oprah tells me to", 'by': "Liz Lemon"},
    {'q': "If I have learned anything from my SIMS family: When a child doesn't see his father enough he starts to jump up and down, then his mood level with drop until he pees himself", 'by': "Liz Lemon"},
    {'q': "You are my heroine! And by heroine I mean lady hero. I don't want to inject you and listen to jazz.", 'by': "Liz Lemon"},
    {'q': "As you navigate through the rest of your life, be open to collaboration. Other people and other people's ideas are often better than your own. Find a group of people who challenge and inspire you, spend a lot of time with them, and it will change your life", 'by': "Amy Poehler"},
    {'q': "The earlier you learn that you should focus on what you have, and not obsess about what you don't have, the happier you will be.", 'by': "Amy Poehler"}
]


text:
<?xml version="1.0" encoding="utf-8" ?>
<c2uistate>
    <!--This is a UI state file - its content describes the user interface settings when the project was last open.
It is entirely optional and the project will load without it.  If you are placing the project under source control,
you probably do not want to add any .uistate.xml files to the repository.-->
    <configurations>
        <active>
            <configuration name="HTML5" />
        </active>
        <display name="HTML5" />
    </configurations>
    <open-tabs>
        <layout>Layout 1</layout>
        <event-sheet active="1">Event sheet 1</event-sheet>
    </open-tabs>
    <properties>
        <property expanded="1" name="About" />
        <property expanded="1" name="Project settings" />
        <property expanded="0" name="Window Size" />
        <property expanded="1" name="Configuration Settings" />
    </properties>
    <families-expanded root="1" />
</c2uistate>

redpajama_set_name: RedPajamaGithub


text:
package com.bigmouth.app.ui;

import android.content.Context;
import android.graphics.drawable.Drawable;

/**
 * @author yangyu
 *	¹¦ÄÜÃèÊö£ºµ¯´°ÄÚ²¿×ÓÀàÏ»æÖƱêÌâºÍͼ±ê£©
 */
public class ActionItem {
	//¶¨ÒåͼƬ¶ÔÏó
	public Drawable mDrawable;
	//¶¨ÒåÎı¾¶ÔÏó
	public CharSequence mTitle;

	public ActionItem(Drawable drawable, CharSequence title){
		this.mDrawable = drawable;
		this.mTitle = title;
	}

	public ActionItem(Context context, int titleId, int drawableId){
		this.mTitle = context.getResources().getText(titleId);
		this.mDrawable = context.getResources().getDrawable(drawableId);
	}

	public ActionItem(Context context, CharSequence title, int drawableId) {
		this.mTitle = title;
		this.mDrawable = context.getResources().getDrawable(drawableId);
	}
}


text:
import random

dictionary = []
def find_word(word):
    word=word.lower()
    result=False
    for i in dictionary:
        if(i==word):
	    result=True
            break
    return result

def load_dict(level):
    dict_file="dict_"+str(level)+".txt"
    f=open(dict_file, "r")
    l=f.readlines()
    for a in l:
        dictionary.append(a[:-2])
    f.close()

def get_word():
    return random.choise(dictionary)


text:
package goblet

import (
	"context"
	"io"
	"strings"
	"time"

	"github.com/go-git/go-git/v5/plumbing"
	"github.com/google/gitprotocolio"
	"go.opencensus.io/stats"
	"go.opencensus.io/tag"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

const (
	checkFrequency = 1 * time.Second
)

type gitProtocolErrorReporter interface {
	reportError(context.Context, time.Time, error)
}

func handleV2Command(ctx context.Context, reporter gitProtocolErrorReporter, repo *managedRepository, command []*gitprotocolio.ProtocolV2RequestChunk, w io.Writer) bool {
	startTime := time.Now()
	var err error
	ctx, err = tag.New(ctx, tag.Upsert(CommandTypeKey, command[0].Command))
	if err != nil {
		reporter.reportError(ctx, startTime, err)
		return false
	}

	cacheState := "locally-served"
	ctx, err = tag.New(ctx, tag.Upsert(CommandCacheStateKey, cacheState))
	if err != nil {
		reporter.reportError(ctx, startTime, err)
		return false
	}
	switch command[0].Command {
	case "ls-refs":
		ctx, err = tag.New(ctx, tag.Update(CommandCacheStateKey, "queried-upstream"))
		if err != nil {
			reporter.reportError(ctx, startTime, err)
			return false
		}

		resp, err := repo.lsRefsUpstream(command)
		if err != nil {
			reporter.reportError(ctx, startTime, err)
			return false
		}

		refs, err := parseLsRefsResponse(resp)
		if err != nil {
			reporter.reportError(ctx, startTime, err)
			return false
		}

		if hasUpdate, err := repo.hasAnyUpdate(refs); err != nil {
			reporter.reportError(ctx, startTime, err)
			return false
		} else if hasUpdate {
			go repo.fetchUpstream()
		}

		writeResp(w, resp)
		reporter.reportError(ctx, startTime, nil)
		return true

	case "fetch":
		wantHashes, wantRefs, err := parseFetchWants(command)
		if err != nil {
			reporter.reportError(ctx, startTime, err)
			return false
		}

		if hasAllWants, err := repo.hasAllWants(wantHashes, wantRefs); err != nil {
			reporter.reportError(ctx, startTime, err)
			return false
		} else if !hasAllWants {
			ctx, err = tag.New(ctx, tag.Update(CommandCacheStateKey, "queried-upsteam"))
			if err != nil {
				reporter.reportError(ctx, startTime, err)
				return false
			}

			fetchStartTime := time.Now()
			fetchDone := make(chan error, 1)
			go func() {
				fetchDone <- repo.fetchUpstream()
			}()
			timer := time.NewTimer(checkFrequency)
		LOOP:
			for {
				select {
				case <-ctx.Done():
					reporter.reportError(ctx, startTime, ctx.Err())
					return false
				case err := <-fetchDone:
					if hasAllWants, checkErr := repo.hasAllWants(wantHashes, wantRefs); checkErr != nil {
						reporter.reportError(ctx, startTime, checkErr)
						return false
					} else if !hasAllWants {
						reporter.reportError(ctx, startTime, err)
						return false
					}
					break LOOP
				case <-timer.C:
					if hasAllWants, err := repo.hasAllWants(wantHashes, wantRefs); err != nil {
						reporter.reportError(ctx, startTime, err)
						return false
					} else if hasAllWants {
						break LOOP
					}
					timer.Reset(checkFrequency)
				}
			}
			stats.Record(ctx, UpstreamFetchWaitingTime.M(int64(time.Now().Sub(fetchStartTime)/time.Millisecond)))
		}

		if err := repo.serveFetchLocal(command, w); err != nil {
			reporter.reportError(ctx, startTime, err)
			return false
		}
		reporter.reportError(ctx, startTime, nil)
		return true
	}
	reporter.reportError(ctx, startTime, status.Error(codes.InvalidArgument, "unknown command"))
	return false
}

func parseLsRefsResponse(chunks []*gitprotocolio.ProtocolV2ResponseChunk) (map[string]plumbing.Hash, error) {
	m := map[string]plumbing.Hash{}
	for _, ch := range chunks {
		if ch.Response == nil {
			continue
		}
		ss := strings.Split(string(ch.Response), " ")
		if len(ss) < 2 {
			return nil, status.Errorf(codes.Internal, "cannot parse the upstream ls-refs response: got %d component, want at least 2", len(ss))
		}
		m[strings.TrimSpace(ss[1])] = plumbing.NewHash(ss[0])
	}
	return m, nil
}

func parseFetchWants(chunks []*gitprotocolio.ProtocolV2RequestChunk) ([]plumbing.Hash, []string, error) {
	hashes := []plumbing.Hash{}
	refs := []string{}
	for _, ch := range chunks {
		if ch.Argument == nil {
			continue
		}
		s := string(ch.Argument)
		if strings.HasPrefix(s, "want ") {
			ss := strings.Split(s, " ")
			if len(ss) < 2 {
				return nil, nil, status.Errorf(codes.InvalidArgument, "cannot parse the fetch request: got %d component, want at least 2", len(ss))
			}
			hashes = append(hashes, plumbing.NewHash(strings.TrimSpace(ss[1])))
		} else if strings.HasPrefix(s, "want-ref ") {
			ss := strings.Split(s, " ")
			if len(ss) < 2 {
				return nil, nil, status.Errorf(codes.InvalidArgument, "cannot parse the fetch request: got %d component, want at least 2", len(ss))
			}
			refs = append(refs, strings.TrimSpace(ss[1]))
		}
	}
	return hashes, refs, nil
}


text:
package com.codespair.mockstocks.service.kafka.stream;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.kafka.common.errors.SerializationException;
import org.apache.kafka.common.serialization.Serializer;

import java.util.Map;

public class JsonPojoSerializer<T> implements Serializer<T> {
  private final ObjectMapper objectMapper = new ObjectMapper();

  /**
   * Default constructor needed by Kafka
   */
  public JsonPojoSerializer() {
  }

  @Override
  public void configure(Map<String, ?> props, boolean isKey) {
  }

  @Override
  public byte[] serialize(String topic, T data) {
    if (data == null)
      return null;

    try {
      return objectMapper.writeValueAsBytes(data);
    } catch (Exception e) {
      throw new SerializationException("Error serializing JSON message", e);
    }
  }

  @Override
  public void close() {
  }

}


text:
package demoapp.dom._infra.utils;

import lombok.experimental.UtilityClass;

@UtilityClass
public class LogUtils {

    public static String emphasize(String string) {
        return new StringBuilder()
                .append("\n====================================================\n")
                .append(string)
                .append("\n====================================================\n")
                .toString();
    }

}


text:
#ifndef _MItMeshFaceVertex
#define _MItMeshFaceVertex
//
//-
// ==========================================================================
// Copyright (C) 1995 - 2005 Alias Systems Corp. and/or its licensors.  All
// rights reserved.
//
// The coded instructions, statements, computer programs, and/or related
// material (collectively the "Data") in these files contain unpublished
// information proprietary to Alias Systems Corp. ("Alias") and/or its
// licensors, which is protected by Canadian and US federal copyright law and
// by international treaties.
//
// The Data may not be disclosed or distributed to third parties or be copied
// or duplicated, in whole or in part, without the prior written consent of
// Alias.
//
// THE DATA IS PROVIDED "AS IS". ALIAS HEREBY DISCLAIMS ALL WARRANTIES RELATING
// TO THE DATA, INCLUDING, WITHOUT LIMITATION, ANY AND ALL EXPRESS OR IMPLIED
// WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE. IN NO EVENT SHALL ALIAS BE LIABLE FOR ANY DAMAGES
// WHATSOEVER, WHETHER DIRECT, INDIRECT, SPECIAL, OR PUNITIVE, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, OR IN EQUITY,
// ARISING OUT OF ACCESS TO, USE OF, OR RELIANCE UPON THE DATA.
// ==========================================================================
//+
//
// CLASS:    MItMeshFaceVertex
//
// *****************************************************************************
//
// CLASS DESCRIPTION (MItMeshFaceVertex)
//
//	This class is the iterator for polygonal surfaces - iterates over
//  face vertices.
//
//	The iterator functions in two modes depending on whether a component
//	is specified. When a component is not given or is NULL the iteration
//	will be over all polygons for the surface.  When a component is given
//	this iterator will iterate over the polygons specified in the component.
//	When iterating over components a DAG path to the surface must also be
//	supplied.
//
// *****************************************************************************

#if defined __cplusplus

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

// INCLUDED HEADER FILES

#include <maya/MFnDagNode.h>
#include <maya/MObject.h>
#include <maya/MVector.h>
#include <maya/MPoint.h>
#include <maya/MColor.h>
#include <maya/MFloatArray.h>
#include <maya/MFloatVectorArray.h>
#include <maya/MVectorArray.h>
#include <maya/MColorArray.h>
#include <maya/MString.h>

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

// DECLARATIONS

class MPointArray;
class MDoubleArray;
class MIntArray;
class MDGModifier;

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

// CLASS DECLARATION (MItMeshFaceVertex)

/// Face vertex iterator
/**
  Iterate over face vertices of polygonal surfaces
*/
#ifdef _WIN32
#pragma warning(disable: 4522)
#endif // _WIN32

class OPENMAYA_EXPORT MItMeshFaceVertex
{
public:
	///
    MItMeshFaceVertex( const MObject & polyObject, MStatus * ReturnStatus = NULL );
    ///
    MItMeshFaceVertex( const MDagPath &polyObject,
					MObject & component = MObject::kNullObj,
					MStatus * ReturnStatus = NULL );
	///
	virtual ~MItMeshFaceVertex();
    ///
    bool        isDone( MStatus * ReturnStatus = NULL );
    ///
    MStatus     next();
    ///
    MStatus     reset();
    ///
    MStatus     reset( const MObject & polyObject );
    ///
    MStatus     reset( const MDagPath &polyObject,
						MObject & component = MObject::kNullObj );
    ///
    int         vertId( MStatus * ReturnStatus = NULL ) const;
	///
    int         faceId( MStatus * ReturnStatus = NULL ) const;
    ///
    int         faceVertId( MStatus * ReturnStatus = NULL ) const;
	///
	MObject		faceVertex(MStatus * ReturnStatus = NULL) const;

    ///
    MPoint      position( MSpace::Space space = MSpace::kObject,
						  MStatus * ReturnStatus = NULL );

    /// Get/Set methods for normals.
    MStatus     getNormal( MVector & normal,
						   MSpace::Space space = MSpace::kObject );
	///
    int         normalId( MStatus * ReturnStatus = NULL );

	///
    MVector     getTangent( MSpace::Space space = MSpace::kObject,
						    const MString * uvSet = NULL,
						    MStatus * ReturnStatus = NULL);

	///
    MVector     getBinormal( MSpace::Space space = MSpace::kObject,
						     const MString * uvSet = NULL,
						     MStatus * ReturnStatus = NULL);

	// UV methods. Mention sharing in docs when setUVs
	///
	bool		hasUVs( MStatus * ReturnStatus = NULL ) const;
    ///
    bool        hasUVs( const MString & uvSet,
						MStatus * ReturnStatus = NULL ) const;
    ///
    MStatus     getUV( float2 & uvPoint, const MString * uvSet = NULL) const;
    ///
    MStatus     getUVIndex( int & index, const MString *uvSet = NULL );
    ///
    MStatus     getUVIndex( int & index, float & u, float & v,
							const MString *uvSet = NULL);

	// Color methods. Mention sharing in docs when setUVs
	///
	bool		hasColor(MStatus * ReturnStatus = NULL ) const;
	///
	MStatus		getColor(MColor &color, const MString *colorSetName = NULL);
	///
	MStatus		getColorIndex( int & colorIndex, const MString *colorSetName = NULL );

    ///
    MStatus     updateSurface();
    ///
    MStatus     geomChanged();
	///
	MStatus		setIndex(int faceId, int vertFaceId,
					     int &prevFaceId, int &prevVertId );

protected:
    bool		getUVSetIndex( const MString * uvSetName,
							   int & uvSet) const;

	bool		updateColorSet(const MString *colorSetName, int& prevSetId);

	void		resetColorSetToPrevious(const MString *colorSetName, int prevSetId);

private:

    static const char*  className();
    MPtrBase *      f_shape;
    void 	 *      f_path;
    void 	 *      f_geom;
	void	 *		f_ref;

	void	 *		fCompIter;		// face vertex component iterator
	void     *      fElements;		// pointer to the vertex face component list

};

#ifdef _WIN32
#pragma warning(default: 4522)
#endif // _WIN32

// *****************************************************************************
#endif /* __cplusplus */
#endif /* _MItMeshFaceVertex */


text:
<?php namespace Mysql\Queue;

use Illuminate\Database\Connection;
use Illuminate\Database\Query\Expression;
use Illuminate\Support\Facades\DB;
use Illuminate\Queue\Queue;
use Illuminate\Queue\QueueInterface;
use Mysql\Queue\Jobs\MysqlQueueJob;

/**
 * Mysql Queue class
 *
 * @author Ismael
 */
class MysqlQueue extends Queue implements QueueInterface{

  /**
   * The name of the default queue.
   *
   * @var \Illuminate\Database\Connection
   */
  protected $default;

  /**
   * The database table that holds the jobs.
   *
   * @var string
   */
  protected $table;

  /**
   * Create a new mysql queue instance.
   *
   * @param  string  $connection
   * @param  string  $default
   * @return void
   */
  public function __construct($table = "jobs", $default = 'default')
  {
    $this->default = $default;
    $this->table = $table;
  }

  /**
   * Push a new job onto the queue.
   *
   * @param  string  $job
   * @param  mixed   $data
   * @param  string  $queue
   * @return int
   */
  public function push($job, $data = '', $queue = null)
  {
    $options = array('name' => $job);
    return $this->pushRaw($this->createPayload($job, $data), $queue, $options);
  }

  /**
   * Push a new job onto the queue after a delay.
   *
   * @param  DateTime|int  $delay either string in "Y-m-d H:i:s" format or int for seconds
   * @param  string  $job
   * @param  mixed   $data
   * @param  string  $queue
   * @return void
   */
  public function later($delay, $job, $data = '', $queue = null)
  {
    $options = array("delay" => $this->getSeconds($delay), 'name' => $job);
    return $this->pushRaw($this->createPayload($job, $data), $queue, $options);
  }

  /**
   * Release a reserved job back onto the queue.
   *
   * @param  string  $queue
   * @param  string  $payload
   * @param  int  $delay
   * @param  int  $attempts
   * @return void
   */
  public function release($queue, $job, $delay)
  {
    $options = array("attempts" => $job['attempts'], "delay" => $this->getSeconds($delay));
    $this->pushRaw($job['payload'], $queue, $options);
  }

  public function pop($queue = null)
  {

    $queue = $this->getQueue($queue);

    try {
      DB::beginTransaction();
      $job = DB::table($this->table)
        ->lockForUpdate()
        ->where('queue', $this->getQueue($queue))
        ->where('status', MysqlQueueJob::STATUS_PENDING)
        ->where('run_at', '<=', date("Y-m-d H:i:s"))
        ->orderBy('id', 'asc')
        ->first();

      if (!is_null($job)) {
        DB::table($this->table)->where('id', $job['id'])->update([
          'status' => MysqlQueueJob::STATUS_STARTED,
          'time_started' => date('Y-m-d H:i:s'),
        ]);
      }
      DB::commit();

    } catch (\Exception $e) {
      DB::rollback();
      throw $e;
    }
    if(!is_null($job)){
      return new MysqlQueueJob($this->container, $this, $job, $queue);
    }
  }

  /**
   * Delete a reserved job from the queue.
   *
   * @param  string  $queue
   * @param  string  $id
   * @return void
   */
  public function deleteStarted($queue, $id)
  {
    DB::table($this->table)->where('id', $id)->delete();
  }

  /**
   * Push a raw payload onto the queue.
   *
   * @param  string  $payload
   * @param  string  $queue
   * @param  array   $options
   * @return mixed
   */
  public function pushRaw($payload, $queue = null, array $options = array())
  {
    return $this->createJob(
      array_get($options, 'name', $this->getJobName($payload)),
      $payload,
      $queue,
      $this->getSeconds(array_get($options, 'delay', 0)),
      array_get($options, 'attempts', 0)
    );
  }

  /**
   * Create a new job in the database
   * @param  string  $jobName  name of the job for easier manual look ups
   * @param  mixed  $payload  payload for the job
   * @param  string  $queue    name of the bucket for the job to go in to
   * @param  integer $delay    amount od seconds to delay the job
   * @param  integer $attempts number of attempts
   * @return int            id of job just created
   */
  protected function createJob($jobName, $payload, $queue, $delay = 0, $attempts = 0){

    return DB::table($this->table)->insertGetId([
      'name' => $jobName,
      'queue' => $this->getQueue($queue),
      'payload' => $payload,
      'status' => MysqlQueueJob::STATUS_PENDING,
      'attempts' => $attempts,
      'run_at' => $this->getFireDatetime($delay),
      'created_at' => date('Y-m-d H:i:s'),
      'updated_at' => date('Y-m-d H:i:s')
    ]);
  }

  /**
   * Get the queue or return the default.
   *
   * @param  string|null  $queue
   * @return string
   */
  protected function getQueue($queue)
  {
    return ($queue ?: $this->default);
  }

  /**
   * Get the appropriate mysql database datetime string format given any delay in seconds
   *
   * @param  int $delay time to delay job in seconds
   * @return string
   */
  protected function getFireDatetime($delay)
  {
    return date('Y-m-d H:i:s', strtotime('+'.$delay.'seconds'));
  }

  /**
   * Extract the name of the job for release functionality
   * @param  mixed $payload job payload
   * @return string          name of the job
   */
  protected function getJobName($payload)
  {
    return json_decode($payload, true)['job'];
  }
}


text:
from .serializers import StarSerializer, StarBulkSerializer
from .serializers import StarTopEmployeeLists, StarEmployeeCategoriesSerializer, StarEmployeeKeywordsSerializer
from .serializers import StarKeywordList, StarInputSerializer, StarSmallSerializer
from .serializers import EmployeeBadgeListSerializer, EmployeeBadgeSerializer, EmployeeGroupedListSerializer
from .models import Badge, EmployeeBadge, Star
from constance import config
from activities.models import Activity
from employees.models import Employee
from categories.models import Category, Keyword
from django.db.models import Count, Q
from django.shortcuts import get_object_or_404
from rest_framework import status
from rest_framework.decorators import api_view, permission_classes
from rest_framework.exceptions import APIException
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import IsAuthenticated, IsAdminUser
from rest_framework.response import Response
from utils.send_messages import send_push_notification

@api_view(['POST', ])
@permission_classes((IsAuthenticated,))
def give_star_to(request, from_employee_id, to_employee_id):
    """
    This endpoint saves stars on both employees (from and to).
    ---
    response_serializer: stars.serializers.StarInputSerializer
    responseMessages:
    - code: 400
      message: Bad request
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found (from_employee_id or to_employee_id or category or subcategory)
    - code: 406
      message: User is unable to give stars to itself.
    parameters:
    - name: category
      description: category id
      required: true
      paramType: string
    - name: keyword
      description: keyword id
      required: true
      paramType: string
    """
    if from_employee_id == to_employee_id:
        content = {'detail': config.USER_UNABLE_TO_GIVE_STARS_ITSELF}
        return Response(content, status=status.HTTP_406_NOT_ACCEPTABLE)
    elif request.method == 'POST':
        # Set values from request.data from POST
        text = (request.data['text'] if 'text' in request.data.keys() else None)
        from_user = get_object_or_404(Employee, pk=from_employee_id)
        to_user = get_object_or_404(Employee, pk=to_employee_id)
        category = get_object_or_404(Category, pk=request.data['category'])
        keyword = get_object_or_404(Keyword, pk=request.data['keyword'])

        if from_user.is_blocked:
            content = {'detail': config.USER_BLOCKED_TO_GIVE_STARS}
            return Response(content, status=status.HTTP_406_NOT_ACCEPTABLE)
        elif to_user.is_blocked:
            content = {'detail': config.USER_BLOCKED_TO_RECEIVED_STARS}
            return Response(content, status=status.HTTP_406_NOT_ACCEPTABLE)

        # Create data object to save
        data = {"category": category.id,
                "keyword": keyword.id,
                "text": text,
                "from_user": from_user.id,
                "to_user": to_user.id}

        # Validate serializer with data provided.
        serializer = StarInputSerializer(data=data)
        if serializer.is_valid():
            # Save recommendation
            serializer.save()

            # Add 1 to employee given points
            from_user.add_stars_given(1)
            from_user.save()

            current_level = to_user.level

            # Add points to to_user according category weight
            if from_user.position:
                weight = from_user.position.weight
            else:
                weight = 1
            to_user.add_stars(weight)
            message = config.RECOMMENDATION_MESSAGE % (weight, from_user.first_name, from_user.last_name)
            send_push_notification(to_user, message)
            to_user.evaluate_level()
            to_user.save()

            # Add activity log if user level up
            if to_user.level != current_level:
                message = config.LEVEL_UP_TEXT % (to_user.first_name, to_user.last_name, to_user.level)
                activity = Activity.objects.create(text=message, to_user=to_user)
                send_push_notification(to_user, message)
                activity.save()

            return Response(serializer.data, status=status.HTTP_201_CREATED)

        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

@api_view(['POST', ])
@permission_classes((IsAuthenticated,))
def give_star_to_many(request, from_employee_id):
    """
    This endpoint saves stars on many employees.
    ---
    response_serializer: stars.serializers.StarSerializer
    responseMessages:
    - code: 400
      message: Bad request
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found (from_employee_id or to_users or category or subcategory)
    - code: 406
      message: User is unable to give stars to itself.
    parameters:
    - name: body
      required: true
      paramType: body
      pytype: stars.serializers.StarBulkSerializer
    """
    if request.method == 'POST':
        serializer_bulk = StarBulkSerializer(data=request.data)
        errors = []
        stars_added = 0
        if serializer_bulk.is_valid():
            text = (request.data['text'] if 'text' in request.data.keys() else None)
            from_user = get_object_or_404(Employee, pk=from_employee_id)
            category = get_object_or_404(Category, pk=request.data['category'])
            keyword = get_object_or_404(Keyword, pk=request.data['keyword'])

            # Create data object to save
            data = {"category": category.id,
                    "keyword": keyword.id,
                    "text": text,
                    "from_user": from_user.id}

            for user_pk in request.data['to_users']:
                data.update({"to_user": int(user_pk)})
                serializer = StarSerializer(data=data)
                if serializer.is_valid():
                    serializer.save()
                    stars_added += 1

                    # Add points
                    to_user = get_object_or_404(Employee, pk=user_pk)
                    from_user.add_stars_given(1)
                    from_user.save()

                    current_level = to_user.level

                    # Add points to to_user according category weight
                    if from_user.position:
                        weight = from_user.position.weight
                    else:
                        weight = 1

                    to_user.add_stars(weight)
                    message = config.RECOMMENDATION_MESSAGE % (weight, from_user.first_name, from_user.last_name)
                    send_push_notification(to_user, message)
                    to_user.evaluate_level()
                    to_user.save()

                    # Add activity log if user level up
                    if to_user.level != current_level:
                        message = config.LEVEL_UP_TEXT % (to_user.first_name, to_user.last_name, to_user.level)
                        activity = Activity.objects.create(text=message, to_user=to_user)
                        activity.save()

                else:
                    errors.append(serializer.errors)
        else:
            errors.append(serializer_bulk.errors)

        if len(errors) == 0:
            content = {'detail': config.SUCCESSFULLY_STARS_ADDED}
            return Response(content, status=status.HTTP_201_CREATED)
        else:
            stars_results = {"stars_added": stars_added}
            detail = {'detail': errors}
            content = stars_results.copy()
            content.update(detail)
            return Response(content, status=status.HTTP_406_NOT_ACCEPTABLE)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def star(request, star_id):
    """
    Returns star detail
    ---
    serializer: stars.serializers.StarSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        star = get_object_or_404(Star, pk=star_id)
        serializer = StarSerializer(star)
        return Response(serializer.data, status=status.HTTP_200_OK)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def stars_employee_list(request, employee_id):
    """
    Returns stars list from employee
    ---
    serializer: stars.serializers.StarSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        employee_stars = Star.objects.filter(to_user=employee)
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(employee_stars, request)
        serializer = StarSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def stars_employee_list_group_by_category(request, employee_id):
    """
    Returns stars list from employee grouped by categories
    ---
    serializer: stars.serializers.StarEmployeeCategoriesSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        employee_stars = Star.objects.filter(to_user=employee).values(
            'category__pk',
            'category__name').annotate(num_stars=Count('category')).order_by('-num_stars', 'category__name')
        paginator = PageNumberPagination()
        result = paginator.paginate_queryset(employee_stars, request)
        serializer = StarEmployeeCategoriesSerializer(result, many=True)
        return paginator.get_paginated_response(serializer.data)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def stars_employee_list_group_by_keyword(request, employee_id):
    """
    Returns stars list from employee grouped by categories
    ---
    serializer: stars.serializers.StarEmployeeKeywordsSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        employee_stars = Star.objects.filter(to_user=employee).values(
            'keyword__pk',
            'keyword__name').annotate(num_stars=Count('keyword')).order_by('-num_stars', 'keyword__name')
        paginator = PageNumberPagination()
        result = paginator.paginate_queryset(employee_stars, request)
        serializer = StarEmployeeKeywordsSerializer(result, many=True)
        return paginator.get_paginated_response(serializer.data)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def stars_employee_list_group_by_category_detail(request, employee_id, category_id):
    """
    Returns stars list detail from employee divided by category
    ---
    serializer: stars.serializers.StarSmallSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        category = get_object_or_404(Category, pk=category_id)
        stars = Star.objects.filter(to_user=employee, category=category).order_by('-date')
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(stars, request)
        serializer = StarSmallSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def stars_employee_list_group_by_keyword_detail(request, employee_id, keyword_id):
    """
    Returns stars list detail from employee divided by keyword
    ---
    serializer: stars.serializers.StarSmallSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        keyword = get_object_or_404(Keyword, pk=keyword_id)
        stars = Star.objects.filter(to_user=employee, keyword=keyword).order_by('-date')
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(stars, request)
        serializer = StarSmallSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def stars_top_employee_lists(request, top_number, kind, id):
    """
    Returns stars top {top_number} list according to {kind} (category, keyword) {id} (kind_id)
    ---
    serializer: stars.serializers.StarTopEmployeeLists
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    - code: 412
      message: Precondition failed, kind should be category or subcategory
    """
    try:
        if request.method == 'GET':
            if kind == 'category':
                top_list = Star.objects.filter(category__id=id).values(
                    'to_user__pk',
                    'to_user__username',
                    'to_user__first_name',
                    'to_user__last_name',
                    'to_user__level'
                    'to_user__avatar').annotate(num_stars=Count('to_user')).order_by('-num_stars')[:top_number]
            elif kind == 'keyword':
                top_list = Star.objects.filter(keyword__id=id).values(
                    'to_user__pk',
                    'to_user__username',
                    'to_user__first_name',
                    'to_user__last_name',
                    'to_user__level',
                    'to_user__avatar').annotate(num_stars=Count('to_user')).order_by('-num_stars')[:top_number]
            else:
                return Response(status=status.HTTP_412_PRECONDITION_FAILED)
            serializer = StarTopEmployeeLists(top_list, many=True)
            return Response(serializer.data, status=status.HTTP_200_OK)
    except Exception as e:
        raise APIException(e)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def stars_keyword_list(request):
    """
    Returns stars list grouped by keyword or result list if you use ?search=
    ---
    serializer: stars.serializers.StarKeywordList
    parameters:
    - name: search
      required: false
      type: string
      paramType: query
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        if request.GET.get('search'):
            search_term = request.GET.get('search')
            star_list = Star.objects.filter(
                Q(keyword__name__icontains=search_term)).values(
                    'keyword__pk',
                    'keyword__name').annotate(num_stars=Count('keyword')).order_by('-num_stars')
        else:
            star_list = Star.objects.all().values(
                'keyword__pk',
                'keyword__name').annotate(num_stars=Count('keyword')).order_by('-num_stars')
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(star_list, request)
        serializer = StarKeywordList(results, many=True)
        return paginator.get_paginated_response(serializer.data)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def stars_keyword_list_detail(request, keyword_id):
    """
    Returns stars list detail for keyword id.
    ---
    response_serializer: stars.serializers.StarTopEmployeeLists
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        keyword = get_object_or_404(Keyword, pk=keyword_id)
        stars = Star.objects.filter(keyword=keyword).values(
            'to_user__pk',
            'to_user__username',
            'to_user__first_name',
            'to_user__last_name',
            'to_user__level',
            'to_user__avatar').annotate(num_stars=Count('keyword')).order_by('-num_stars')
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(stars, request)
        serializer = StarTopEmployeeLists(results, many=True)
        return paginator.get_paginated_response(serializer.data)

@api_view(['POST', ])
@permission_classes((IsAuthenticated, IsAdminUser))
def give_badge_to(request, badge_id, to_employee_id, from_employee_id):
    """
    This endpoint saves badge assignation to employee
    ---
    response_serializer: stars.serializers.EmployeeBadgeSerializer
    responseMessages:
    - code: 400
      message: Bad request
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found (from_employee_id or to_employee_id or badge_id)
    - code: 406
      message: User is unable to give stars to itself.
    """
    if to_employee_id == from_employee_id:
        content = {'detail': config.USER_UNABLE_TO_GIVE_BADGES_ITSELF}
        return Response(content, status=status.HTTP_406_NOT_ACCEPTABLE)
    elif request.method == 'POST':
        badge = get_object_or_404(Badge, pk=badge_id)
        to_employee = get_object_or_404(Employee, pk=to_employee_id)
        from_employee = get_object_or_404(Employee, pk=from_employee_id)
        try:
            employee_badge = EmployeeBadge.objects.create(to_user=to_employee, assigned_by=from_employee, badge=badge)
        except Exception as e:
            print(e)
            content = {'detail': config.BADGE_UNIQUE_CONSTRAINT_FAILED}
            return Response(content, status=status.HTTP_406_NOT_ACCEPTABLE)
        serializer = EmployeeBadgeSerializer(employee_badge)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def badges_employee_list(request, employee_id):
    """
    Returns badge list from employee
    ---
    response_serializer: stars.serializers.EmployeeBadgeSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        employee = get_object_or_404(Employee, pk=employee_id)
        employee_bages = EmployeeBadge.objects.filter(to_user=employee)
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(employee_bages, request)
        serializer = EmployeeBadgeSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def employee_list_group_by_badges(request):
    """
    Returns badge list with employee counter or result list if you use ?search=
    ---
    response_serializer: stars.serializers.EmployeeBadgeListSerializer
    parameters:
    - name: search
      required: false
      type: string
      paramType: query
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        if request.GET.get('search'):
            search_term = request.GET.get('search')
            badge_list = EmployeeBadge.objects.filter(
                Q(badge__name__icontains=search_term)).values(
                    'badge__pk',
                    'badge__name').annotate(num_employees=Count('to_user')).order_by('-num_employees')
        else:
            badge_list = EmployeeBadge.objects.all().values(
                'badge__pk',
                'badge__name').annotate(num_employees=Count('to_user')).order_by('-num_employees')
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(badge_list, request)
        serializer = EmployeeBadgeListSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)

@api_view(['GET', ])
@permission_classes((IsAuthenticated,))
def employee_list_group_by_badges_detail(request, badge_id):
    """
    Returns employee list grouped by badge, you should provide badge_id
    ---
    response_serializer: stars.serializers.EmployeeGroupedListSerializer
    responseMessages:
    - code: 401
      message: Unauthorized. Authentication credentials were not provided. Invalid token.
    - code: 403
      message: Forbidden, authentication credentials were not provided
    - code: 404
      message: Not found
    """
    if request.method == 'GET':
        badge = get_object_or_404(Badge, pk=badge_id)
        employee_list = EmployeeBadge.objects.filter(badge=badge).values(
            'to_user__pk',
            'to_user__username',
            'to_user__first_name',
            'to_user__last_name',
            'to_user__level',
            'to_user__avatar')
        paginator = PageNumberPagination()
        results = paginator.paginate_queryset(employee_list, request)
        serializer = EmployeeGroupedListSerializer(results, many=True)
        return paginator.get_paginated_response(serializer.data)


text:
import random

from django.conf import settings
from django.contrib.auth.models import AnonymousUser, Group, User
from django.db import connection

import mock
from nose.tools import eq_
from test_utils import RequestFactory

from test_app import views
import waffle
from waffle.middleware import WaffleMiddleware
from waffle.models import Flag, Sample, Switch
from waffle.tests.base import TestCase

def get(**kw):
    request = RequestFactory().get('/foo', data=kw)
    request.user = AnonymousUser()
    return request

def process_request(request, view):
    response = view(request)
    return WaffleMiddleware().process_response(request, response)

class WaffleTests(TestCase):
    def test_persist_active_flag(self):
        Flag.objects.create(name='myflag', percent='0.1')
        request = get()

        # Flag stays on.
        request.COOKIES['dwf_myflag'] = 'True'
        response = process_request(request, views.flag_in_view)
        eq_('on', response.content)
        assert 'dwf_myflag' in response.cookies
        eq_('True', response.cookies['dwf_myflag'].value)

    def test_persist_inactive_flag(self):
        Flag.objects.create(name='myflag', percent='99.9')
        request = get()

        # Flag stays off.
        request.COOKIES['dwf_myflag'] = 'False'
        response = process_request(request, views.flag_in_view)
        eq_('off', response.content)
        assert 'dwf_myflag' in response.cookies
        eq_('False', response.cookies['dwf_myflag'].value)

    def test_no_set_unused_flag(self):
        """An unused flag shouldn't have its cookie reset."""
        request = get()
        request.COOKIES['dwf_unused'] = 'True'
        response = process_request(request, views.flag_in_view)
        assert not 'dwf_unused' in response.cookies

    def test_superuser(self):
        """Test the superuser switch."""
        Flag.objects.create(name='myflag', superusers=True)
        request = get()
        response = process_request(request, views.flag_in_view)
        eq_('off', response.content)
        assert not 'dwf_myflag' in response.cookies

        superuser = User(username='foo', is_superuser=True)
        request.user = superuser
        response = process_request(request, views.flag_in_view)
        eq_('on', response.content)
        assert not 'dwf_myflag' in response.cookies

        non_superuser = User(username='bar', is_superuser=False)
        non_superuser.save()
        request.user = non_superuser
        response = process_request(request, views.flag_in_view)
        eq_('off', response.content)
        assert not 'dwf_myflag' in response.cookies

    def test_staff(self):
        """Test the staff switch."""
        Flag.objects.create(name='myflag', staff=True)
        request = get()
        response = process_request(request, views.flag_in_view)
        eq_('off', response.content)
        assert not 'dwf_myflag' in response.cookies

        staff = User(username='foo', is_staff=True)
        request.user = staff
        response = process_request(request, views.flag_in_view)
        eq_('on', response.content)
        assert not 'dwf_myflag' in response.cookies

        non_staff = User(username='foo', is_staff=False)
        non_staff.save()
        request.user = non_staff
        response = process_request(request, views.flag_in_view)
        eq_('off', response.content)
        assert not 'dwf_myflag' in response.cookies

    def test_languages(self):
        Flag.objects.create(name='myflag', languages='en,fr')
        request = get()
        response = process_request(request, views.flag_in_view)
        eq_('off', response.content)

        request.LANGUAGE_CODE = 'en'
        response = process_request(request, views.flag_in_view)
        eq_('on', response.content)

        request.LANGUAGE_CODE = 'de'
        response = process_request(request, views.flag_in_view)
        eq_('off', response.content)

    def test_user(self):
        """Test the per-user switch."""
        user = User.objects.create(username='foo')
        flag = Flag.objects.create(name='myflag')
        flag.users.add(user)

        request = get()
        request.user = user
        response = process_request(request, views.flag_in_view)
        eq_('on', response.content)
        assert not 'dwf_myflag' in response.cookies

        request.user = User.objects.create(username='someone_else')
        response = process_request(request, views.flag_in_view)
        eq_('off', response.content)
        assert not 'dwf_myflag' in response.cookies

    def test_group(self):
        """Test the per-group switch."""
        group = Group.objects.create(name='foo')
        user = User.objects.create(username='bar')
        user.groups.add(group)

        flag = Flag.objects.create(name='myflag')
        flag.groups.add(group)

        request = get()
        request.user = user
        response = process_request(request, views.flag_in_view)
        eq_('on', response.content)
        assert not 'dwf_myflag' in response.cookies

        request.user = User(username='someone_else')
        request.user.save()
        response = process_request(request, views.flag_in_view)
        eq_('off', response.content)
        assert not 'dwf_myflag' in response.cookies

    def test_authenticated(self):
        """Test the authenticated/anonymous switch."""
        Flag.objects.create(name='myflag', authenticated=True)

        request = get()
        response = process_request(request, views.flag_in_view)
        eq_('off', response.content)
        assert not 'dwf_myflag' in response.cookies

        request.user = User(username='foo')
        assert request.user.is_authenticated()
        response = process_request(request, views.flag_in_view)
        eq_('on', response.content)
        assert not 'dwf_myflag' in response.cookies

    def test_everyone_on(self):
        """Test the 'everyone' switch on."""
        Flag.objects.create(name='myflag', everyone=True)

        request = get()
        request.COOKIES['dwf_myflag'] = 'False'
        response = process_request(request, views.flag_in_view)
        eq_('on', response.content)
        assert not 'dwf_myflag' in response.cookies

        request.user = User(username='foo')
        assert request.user.is_authenticated()
        response = process_request(request, views.flag_in_view)
        eq_('on', response.content)
        assert not 'dwf_myflag' in response.cookies

    def test_everyone_off(self):
        """Test the 'everyone' switch off."""
        Flag.objects.create(name='myflag', everyone=False,
                            authenticated=True)

        request = get()
        request.COOKIES['dwf_myflag'] = 'True'
        response = process_request(request, views.flag_in_view)
        eq_('off', response.content)
        assert not 'dwf_myflag' in response.cookies

        request.user = User(username='foo')
        assert request.user.is_authenticated()
        response = process_request(request, views.flag_in_view)
        eq_('off', response.content)
        assert not 'dwf_myflag' in response.cookies

    def test_percent(self):
        """If you have no cookie, you get a cookie!"""
        Flag.objects.create(name='myflag', percent='50.0')
        request = get()
        response = process_request(request, views.flag_in_view)
        assert 'dwf_myflag' in response.cookies

    @mock.patch.object(random, 'uniform')
    def test_reroll(self, uniform):
        """Even without a cookie, calling flag_is_active twice should return
        the same value."""
        Flag.objects.create(name='myflag', percent='50.0')
        # Make sure we're not really random.
        request = get()  # Create a clean request.
        assert not hasattr(request, 'waffles')
        uniform.return_value = '10'  # < 50. Flag is True.
        assert waffle.flag_is_active(request, 'myflag')
        assert hasattr(request, 'waffles')  # We should record this flag.
        assert 'myflag' in request.waffles
        assert request.waffles['myflag'][0]
        uniform.return_value = '70'  # > 50. Normally, Flag would be False.
        assert waffle.flag_is_active(request, 'myflag')
        assert request.waffles['myflag'][0]

    def test_undefined(self):
        """Undefined flags are always false."""
        request = get()
        assert not waffle.flag_is_active(request, 'foo')

    @mock.patch.object(settings._wrapped, 'WAFFLE_FLAG_DEFAULT', True)
    def test_undefined_default(self):
        """WAFFLE_FLAG_DEFAULT controls undefined flags."""
        request = get()
        assert waffle.flag_is_active(request, 'foo')

    @mock.patch.object(settings._wrapped, 'WAFFLE_OVERRIDE', True)
    def test_override(self):
        request = get(foo='1')
        Flag.objects.create(name='foo')  # Off for everyone.
        assert waffle.flag_is_active(request, 'foo')

    def test_testing_flag(self):
        Flag.objects.create(name='foo', testing=True)
        request = get(dwft_foo='1')
        assert waffle.flag_is_active(request, 'foo')
        assert 'foo' in request.waffle_tests
        assert request.waffle_tests['foo']

        # GET param should override cookie
        request = get(dwft_foo='0')
        request.COOKIES['dwft_foo'] = 'True'
        assert not waffle.flag_is_active(request, 'foo')
        assert 'foo' in request.waffle_tests
        assert not request.waffle_tests['foo']

    def test_testing_disabled_flag(self):
        Flag.objects.create(name='foo')
        request = get(dwft_foo='1')
        assert not waffle.flag_is_active(request, 'foo')
        assert not hasattr(request, 'waffle_tests')

        request = get(dwft_foo='0')
        assert not waffle.flag_is_active(request, 'foo')
        assert not hasattr(request, 'waffle_tests')

    def test_set_then_unset_testing_flag(self):
        Flag.objects.create(name='myflag', testing=True)
        response = self.client.get('/flag_in_view?dwft_myflag=1')
        eq_('on', response.content)

        response = self.client.get('/flag_in_view')
        eq_('on', response.content)

        response = self.client.get('/flag_in_view?dwft_myflag=0')
        eq_('off', response.content)

        response = self.client.get('/flag_in_view')
        eq_('off', response.content)

        response = self.client.get('/flag_in_view?dwft_myflag=1')
        eq_('on', response.content)

class SwitchTests(TestCase):
    def test_switch_active(self):
        switch = Switch.objects.create(name='myswitch', active=True)
        assert waffle.switch_is_active(switch.name)

    def test_switch_inactive(self):
        switch = Switch.objects.create(name='myswitch', active=False)
        assert not waffle.switch_is_active(switch.name)

    def test_switch_active_from_cache(self):
        """Do not make two queries for an existing active switch."""
        switch = Switch.objects.create(name='myswitch', active=True)
        # Get the value once so that it will be put into the cache
        assert waffle.switch_is_active(switch.name)
        queries = len(connection.queries)
        assert waffle.switch_is_active(switch.name)
        eq_(queries, len(connection.queries), 'We should only make one query.')

    def test_switch_inactive_from_cache(self):
        """Do not make two queries for an existing inactive switch."""
        switch = Switch.objects.create(name='myswitch', active=False)
        # Get the value once so that it will be put into the cache
        assert not waffle.switch_is_active(switch.name)
        queries = len(connection.queries)
        assert not waffle.switch_is_active(switch.name)
        eq_(queries, len(connection.queries), 'We should only make one query.')

    def test_undefined(self):
        assert not waffle.switch_is_active('foo')

    @mock.patch.object(settings._wrapped, 'WAFFLE_SWITCH_DEFAULT', True)
    def test_undefined_default(self):
        assert waffle.switch_is_active('foo')

    @mock.patch.object(settings._wrapped, 'DEBUG', True)
    def test_no_query(self):
        """Do not make two queries for a non-existent switch."""
        assert not Switch.objects.filter(name='foo').exists()
        queries = len(connection.queries)
        assert not waffle.switch_is_active('foo')
        assert len(connection.queries) > queries, 'We should make one query.'
        queries = len(connection.queries)
        assert not waffle.switch_is_active('foo')
        eq_(queries, len(connection.queries), 'We should only make one query.')

class SampleTests(TestCase):
    def test_sample_100(self):
        sample = Sample.objects.create(name='sample', percent='100.0')
        assert waffle.sample_is_active(sample.name)

    def test_sample_0(self):
        sample = Sample.objects.create(name='sample', percent='0.0')
        assert not waffle.sample_is_active(sample.name)

    def test_undefined(self):
        assert not waffle.sample_is_active('foo')

    @mock.patch.object(settings._wrapped, 'WAFFLE_SAMPLE_DEFAULT', True)
    def test_undefined_default(self):
        assert waffle.sample_is_active('foo')


text:
\hypertarget{dir_32a9b0e961bc7ec6b2f2d76f5f54738c}{}\section{Zona/paper\+\_\+exp Directory Reference}
\label{dir_32a9b0e961bc7ec6b2f2d76f5f54738c}\index{Zona/paper\+\_\+exp Directory Reference@{Zona/paper\+\_\+exp Directory Reference}}
\subsection*{Files}
\begin{DoxyCompactItemize}
\item
file \hyperlink{paper__exp_2clear_8py}{clear.\+py}
\item
file \hyperlink{clear__hybrid_8py}{clear\+\_\+hybrid.\+py}
\end{DoxyCompactItemize}


text:
require 'simplecov'
SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
    SimpleCov::Formatter::HTMLFormatter
]
SimpleCov.start

require 'rubygems'
require 'bundler/setup'

require 'ostruct'
require 'json'
require 'looker-sdk'

require 'minitest/autorun'
require 'minitest/spec'
require 'minitest/mock'
require 'mocha/mini_test'
require "rack/test"
require "rack/request"

def fixture_path
  File.expand_path("../fixtures", __FILE__)
end

def fix_netrc_permissions(path)
  s = File.stat(path)
  raise "'#{path}'' not a file" unless s.file?
  File.chmod(0600, path) unless s.mode.to_s(8)[3..5] == "0600"
end

begin
  fix_netrc_permissions(File.join(fixture_path, '.netrc'))
rescue => e
  puts e
end

def setup_sdk
  LookerSDK.reset!

  base_url = ENV['LOOKERSDK_BASE_URL'] || 'https://localhost:20000'
  verify_ssl = case ENV['LOOKERSDK_VERIFY_SSL']
               when /false/i
                 false
               when /f/i
                 false
               when '0'
                 false
               else
                 true
               end
  api_version = ENV['LOOKERSDK_API_VERSION'] || '4.0'
  client_id = ENV['LOOKERSDK_CLIENT_ID']
  client_secret = ENV['LOOKERSDK_CLIENT_SECRET']

  LookerSDK.configure do |c|
    c.lazy_swagger = true
    c.connection_options = {:ssl => {:verify => false}} unless verify_ssl
    if (client_id && client_secret) then
      c.client_id = client_id
      c.client_secret = client_secret
      c.api_endpoint = "#{base_url}/api/#{api_version}"
    else
      c.netrc = true
      c.netrc_file =  File.join(fixture_path, '.netrc')
    end
  end
end

def teardown_sdk
  setup_sdk  # put back initial config
  LookerSDK.logout
end


text:
package io.anw.Survivor.Listeners.Game.Sessions.Armor.Helmet;

import io.anw.Core.Bukkit.Utils.Chat.StringUtils;
import io.anw.Core.Bukkit.Utils.ItemStack.ItemUtils;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

import java.util.ArrayList;

public enum HelmetType {

    LEATHER_HELMET("&eLeather Helmet", "&6&lLeather Helmet", Material.LEATHER_HELMET, 0, false, "A &6Leather Helmet &7to use as armor!"),
    GOLDEN_HELMET("&eGolden Helmet", "&e&lGolden Helmet", Material.GOLD_HELMET, 1000, false, "A &6Golden Helmet &7to use as armor!"),
    IRON_HELMET("&eIron Helmet", "&f&lIron Helmet", Material.IRON_HELMET, 1500, false, "An &fIron Helmet &7to use as armor!"),
    DIAMOND_HELMET("&eDiamond Helmet", "&b&lDiamond Helmet", Material.DIAMOND_HELMET, 2000, true, "An &bDiamond Helmet &7to use as armor!");

    /**
     * Get an item stack by a fuzzy search
     *
     * @param checkStack Item stack to check
     * @return Fuzzy searched shop item
     */
    public static HelmetType getItemByItemStack(ItemStack checkStack) {
        if (!checkStack.hasItemMeta()) {
            return null;
        }

        for (HelmetType item : values()) {
            ItemStack itemStack = item.getItemStack();
            if (checkStack.getItemMeta().getDisplayName().contains(itemStack.getItemMeta().getDisplayName()) && itemStack.getType() == checkStack.getType() && itemStack.getDurability() == checkStack.getDurability() && itemStack.getAmount() == checkStack.getAmount()) {
                return item;
            }
        }
        return null;
    }

    private String name;
    private String itemStackName;
    private Material material;
    private int cost;
    private boolean vip;
    private ArrayList<String> lore;

    HelmetType(String name, String itemStackName, Material material, int cost, boolean vip, String... lore) {
        this.name = name;
        this.itemStackName = itemStackName;
        this.material = material;
        this.cost = cost;
        this.vip = vip;
        constructLore(lore);
    }

    /**
     * Get the menu name for the ability
     *
     * @return Menu name for the ability
     */
    public String getName() {
        return this.name;
    }

    /**
     * Get the ItemStack name for the ability
     *
     * @return ItemStack name for the ability
     */
    public String getItemStackName() {
        return this.itemStackName;
    }

    /**
     * Get the material of the shop item itemstack
     *
     * @return Material of shop item
     */
    public Material getMaterial() {
        return this.material;
    }

    /**
     * Get the cost of the weapon
     *
     * @return Cost of the weapon
     */
    public int getCost() {
        return this.cost;
    }

    /**
     * Get the lore of the shop item
     *
     * @return Shop item's lore
     */
    public ArrayList<String> getLore() {
        return this.lore;
    }

    /**
     * Check if a model type is only for donators
     *
     * @return True if the model is for donators
     */
    public boolean isDonator() {
        return this.vip;
    }

    private void constructLore(String[] description) {
        this.lore = new ArrayList<>();
        for (String descriptionLine : description) {
            getLore().add(StringUtils.colorize("&7" + descriptionLine));
        }
        getLore().add("");
        getLore().add("&7Item Type: &6Armor");
        getLore().add("&7VIP Item?: &6" + (isDonator() ? "Yes" : "No"));
        getLore().add("&7Price: &6" + getCost() + " Tokens");
    }

    /**
     * Get the item stack representing the shop item in the menus
     *
     * @return Shop Item's item stack
     */
    public ItemStack getItemStack() {
        return ItemUtils.createItemStack(
                getItemStackName(),
                getLore(),
                getMaterial()
        );

        //return stack;
    }

    /**
     * Get the item stack with no lore
     *
     * @return Shop Item's item stack with no lore
     */
    public ItemStack getItemStackNoLore() {
        ItemStack stack = getItemStack();
        ItemMeta meta = stack.getItemMeta();
        meta.setLore(null);
        stack.setItemMeta(meta);

        return stack;
    }

}


text:
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE NoMonadFailDesugaring #-}

-- | Tests for EmbeddingOps.
module Main where

import Control.Monad.IO.Class (liftIO)
import Data.Int (Int32, Int64)
import Data.List (genericLength)
import TensorFlow.EmbeddingOps (embeddingLookup)
import Test.Framework (defaultMain, Test)
import Test.Framework.Providers.QuickCheck2 (testProperty)
import Test.HUnit ((@=?))
import Test.Framework.Providers.HUnit (testCase)
import Test.QuickCheck (Arbitrary(..), Property, choose, vectorOf)
import Test.QuickCheck.Monadic (monadicIO, run)
import TensorFlow.Test (assertAllClose)

import qualified Data.Vector as V
import qualified TensorFlow.GenOps.Core as CoreOps
import qualified TensorFlow.Ops as TF
import qualified TensorFlow.Session as TF
import qualified TensorFlow.Tensor as TF
import qualified TensorFlow.Types as TF
import qualified TensorFlow.Gradient as TF
import qualified TensorFlow.Build as TF

-- | Tries to perform a simple embedding lookup, with two partitions.
testEmbeddingLookupHasRightShapeWithPartition :: Test
testEmbeddingLookupHasRightShapeWithPartition =
        testCase "testEmbeddingLookupHasRightShapeWithPartition" $ do
    let embShape     = TF.Shape [1, 3] -- Consider a 3-dim embedding of two items.
    let embedding1  = [1, 1, 1 :: Int32]
    let embedding2  = [0, 0, 0 :: Int32]

    let idValues  = [0, 1 :: Int32]

    (values, shape) <- TF.runSession $ do
        embedding   <- mapM TF.render [ TF.constant embShape embedding1
                        , TF.constant embShape embedding2
                        ]
        let ids     = TF.constant (TF.Shape [1, 2]) idValues
        vs          <- embeddingLookup embedding ids
        TF.run (vs, TF.shape vs)

    -- This is the shape that is returned in the equiv. Python.
    shape  @=? V.fromList [1, 2, 3]

    -- "[0, 1]" should pull out the resulting vector.
    values @=? V.fromList [1, 1, 1, 0, 0, 0]

-- | Tries to perform a simple embedding lookup, with only a single partition.
testEmbeddingLookupHasRightShape :: Test
testEmbeddingLookupHasRightShape =
        testCase "testEmbeddingLookupHasRightShape" $ do
    -- Consider a 3-dim embedding of two items
    let embShape      = TF.Shape [2, 3]
    let embeddingInit = [ 1, 1, 1
                        , 0, 0, 0 :: Int32
                        ]

    let idValues  = [0, 1 :: Int32]

    (values, shape) <- TF.runSession $ do
        embedding <- TF.render $ TF.constant embShape embeddingInit
        let ids = TF.constant (TF.Shape [1, 2]) idValues
        vs <- embeddingLookup [embedding] ids
        TF.run (vs, TF.shape vs)

    -- This is the shape that is returned in the equiv. Python.
    shape  @=? V.fromList [1, 2, 3]

    -- "[0, 1]" should pull out the resulting vector.
    values @=? V.fromList [1, 1, 1, 0, 0, 0]

-- | Check that we can calculate gradients w.r.t embeddings.
testEmbeddingLookupGradients :: Test
testEmbeddingLookupGradients = testCase "testEmbeddingLookupGradients" $ do
    -- Agrees with "embedding", so gradient should be zero.
    let xVals = V.fromList ([20, 20 :: Float])
    let shape = TF.Shape [2]

    gs <- TF.runSession $ do
            let embShape      = TF.Shape [2, 1]
            let embeddingInit = [1, 20 ::Float]
            let idValues      = [1, 1 :: Int32]
            let ids           = TF.constant (TF.Shape [1, 2]) idValues

            x <- TF.placeholder (TF.Shape [2])
            embedding <- TF.initializedVariable
                            (TF.constant embShape embeddingInit)

            op <- embeddingLookup [embedding] ids
            let twoNorm = CoreOps.square $ TF.abs (op `TF.sub` x)
                loss    = TF.mean twoNorm (TF.scalar (0 :: Int32))

            grad <- fmap head (TF.gradients loss [embedding])
            TF.runWithFeeds
                [TF.feed x $ TF.encodeTensorData shape xVals]
                grad
    -- Gradients should be zero (or close)
    assertAllClose gs (V.fromList ([0, 0 :: Float]))

-- Verifies that direct gather is the same as dynamic split into
-- partitions, followed by embedding lookup.
testEmbeddingLookupUndoesSplit ::
    forall a. (TF.TensorDataType V.Vector a, Show a, Eq a)
    => LookupExample a -> Property
testEmbeddingLookupUndoesSplit
    (LookupExample numParts
                   shape@(TF.Shape (firstDim : restDims))
                   values
                   indices) = monadicIO $ run $ TF.runSession $ do
    let shapedValues = TF.constant shape values
    indicesVector <- TF.render $ TF.vector indices
    let directs = CoreOps.gather shapedValues indicesVector
    let cyclicCounter :: TF.Tensor TF.Build Int32 =
            TF.vector [0..fromIntegral firstDim-1]
            `CoreOps.mod` fromIntegral numParts
    modShardedValues :: [TF.Tensor TF.Value a] <-
            mapM TF.render $ CoreOps.dynamicPartition numParts shapedValues cyclicCounter
    embeddings <- embeddingLookup modShardedValues indicesVector
    (shapeOut, got, want :: V.Vector a) <-
            TF.run (TF.cast (TF.shape embeddings), embeddings, directs)
    -- Checks the explicitly documented invariant of embeddingLookup.
    liftIO $ shapeOut @=? V.fromList (genericLength indices : restDims)
    liftIO $ got @=? want
testEmbeddingLookupUndoesSplit _ = error "Bug in Arbitrary (LookupExample)"

-- | Consistent set of parameters for EmbeddingLookupUndoesSplit.
data LookupExample a = LookupExample
                       Int64  -- ^ number of ways to split.
                       TF.Shape  -- ^ shape of the generated tensor
                       [a]       -- ^ data for the tensor
                       [Int32]   -- ^ indices to split the tensor by
    deriving Show

instance Arbitrary a => Arbitrary (LookupExample a) where
    arbitrary = do
        rank <- choose (1, 4)
        -- Takes rank-th root of 100 to cap the tensor size.
        let maxDim = fromIntegral (ceiling doubleMaxDim :: Int64)
            doubleMaxDim :: Double
            doubleMaxDim = 100 ** (1 / fromIntegral rank)
        shape@(firstDim : _) <- vectorOf rank (choose (1, maxDim))
        values <- vectorOf (fromIntegral $ product shape) arbitrary
        numParts <- choose (2, 15)
        indSize <- choose (0, fromIntegral $ firstDim - 1)
        indices <- vectorOf indSize (choose (0, fromIntegral firstDim - 1))
        return $ LookupExample numParts (TF.Shape shape) values indices

main :: IO ()
main = defaultMain
       [ testProperty "EmbeddingLookupUndoesSplit"
         (testEmbeddingLookupUndoesSplit :: LookupExample Double -> Property)
       , testEmbeddingLookupHasRightShape
       , testEmbeddingLookupHasRightShapeWithPartition
       , testEmbeddingLookupGradients
       ]


text:
==============================
Test Project for django-setman
==============================

``django-setman`` comes with simple test project that made for check how
library works.

Initialization
==============

Bootstrap testproject with::

    $ cd testproject
    $ python bootstrap.py

Then init database and setman migrations::

    $ python manage.py syncdb --noinput
    $ python manage.py migrate --noinput

And finally you can to get pair of oDesk keys and setup it to
``local_settings.py`` module. After, feel free to run development server::

    $ python manage.py runserver <port>

and check how ``django-setman`` works.

Run tests
=========

For running tests, check that project already bootstrapped. If all ok, just
run standard Django test command::

    $ python manage.py test core setman

.. note:: We don't need to provide custom test settings module. All necessary
   options setup at ``testproject.settings`` and your ``local_settings``.

Also project has **Jenkins** support (via ``django-jenkins`` app). So to run
complete Jenkins tasks, execute::

    $ python manage.py jenkins

and then check for data in ``reports/`` directory.


text:
import json
import httplib
import logging
from datetime import datetime

from modularodm import Q
from modularodm.exceptions import ModularOdmException

from framework.exceptions import HTTPError
from framework.flask import redirect
from framework.transactions.context import TokuTransaction
from framework.transactions.handlers import no_auto_transaction

from website import settings
from website.models import Node, Tag
from website.util import web_url_for
from website.mails import send_mail
from website.files.models import StoredFileNode
from website.mails import CONFERENCE_SUBMITTED, CONFERENCE_INACTIVE, CONFERENCE_FAILED

from website.conferences import utils, signals
from website.conferences.message import ConferenceMessage, ConferenceError
from website.conferences.model import Conference

logger = logging.getLogger(__name__)

@no_auto_transaction
def meeting_hook():
    """View function for email conference submission.
    """
    message = ConferenceMessage()

    try:
        message.verify()
    except ConferenceError as error:
        logger.error(error)
        raise HTTPError(httplib.NOT_ACCEPTABLE)

    try:
        conference = Conference.get_by_endpoint(message.conference_name, active=False)
    except ConferenceError as error:
        logger.error(error)
        raise HTTPError(httplib.NOT_ACCEPTABLE)

    if not conference.active:
        send_mail(
            message.sender_email,
            CONFERENCE_INACTIVE,
            fullname=message.sender_display,
            presentations_url=web_url_for('conference_view', _absolute=True),
        )
        raise HTTPError(httplib.NOT_ACCEPTABLE)

    add_poster_by_email(conference=conference, message=message)

def add_poster_by_email(conference, message):
    """
    :param Conference conference:
    :param ConferenceMessage message:
    """
    # Fail if no attachments
    if not message.attachments:
        return send_mail(
            message.sender_email,
            CONFERENCE_FAILED,
            fullname=message.sender_display,
        )

    created = []

    with TokuTransaction():
        user, user_created = utils.get_or_create_user(
            message.sender_display,
            message.sender_email,
            message.is_spam,
        )
        if user_created:
            created.append(user)
            user.system_tags.append('osf4m')
            set_password_url = web_url_for(
                'reset_password',
                verification_key=user.verification_key,
                _absolute=True,
            )
            user.date_last_login = datetime.utcnow()
            user.save()
        else:
            set_password_url = None

        node, node_created = utils.get_or_create_node(message.subject, user)
        if node_created:
            created.append(node)
            node.system_tags.append('osf4m')
            node.save()

        utils.provision_node(conference, message, node, user)
        utils.record_message(message, created)

    utils.upload_attachments(user, node, message.attachments)

    download_url = node.web_url_for(
        'addon_view_or_download_file',
        path=message.attachments[0].filename,
        provider='osfstorage',
        action='download',
        _absolute=True,
    )

    # Send confirmation email
    send_mail(
        message.sender_email,
        CONFERENCE_SUBMITTED,
        conf_full_name=conference.name,
        conf_view_url=web_url_for(
            'conference_results',
            meeting=message.conference_name,
            _absolute=True,
        ),
        fullname=message.sender_display,
        user_created=user_created,
        set_password_url=set_password_url,
        profile_url=user.absolute_url,
        node_url=node.absolute_url,
        file_url=download_url,
        presentation_type=message.conference_category.lower(),
        is_spam=message.is_spam,
    )
    if node_created and user_created:
        signals.osf4m_user_created.send(user, conference=conference, node=node)

def _render_conference_node(node, idx, conf):
    try:
        record = next(
            x for x in
            StoredFileNode.find(
                Q('node', 'eq', node) &
                Q('is_file', 'eq', True)
            ).limit(1)
        ).wrapped()
        download_count = record.get_download_count()

        download_url = node.web_url_for(
            'addon_view_or_download_file',
            path=record.path.strip('/'),
            provider='osfstorage',
            action='download',
            _absolute=True,
        )
    except StopIteration:
        download_url = ''
        download_count = 0

    author = node.visible_contributors[0]
    tags = [tag._id for tag in node.tags]

    return {
        'id': idx,
        'title': node.title,
        'nodeUrl': node.url,
        'author': author.family_name,
        'authorUrl': node.creator.url,
        'category': 'talk' if 'talk' in node.system_tags else 'poster',
        'download': download_count,
        'downloadUrl': download_url,
        'dateCreated': str(node.date_created),
        'confName': conf.name,
        'confUrl': web_url_for('conference_results', meeting=conf.endpoint),
        'tags': ' '.join(tags)
    }

def conference_data(meeting):
    try:
        conf = Conference.find_one(Q('endpoint', 'iexact', meeting))
    except ModularOdmException:
        raise HTTPError(httplib.NOT_FOUND)

    nodes = Node.find(
        Q('tags', 'iexact', meeting) &
        Q('is_public', 'eq', True) &
        Q('is_deleted', 'eq', False)
    )

    ret = [
        _render_conference_node(each, idx, conf)
        for idx, each in enumerate(nodes)
    ]
    return ret

def redirect_to_meetings(**kwargs):
    return redirect('/meetings/')

def conference_results(meeting):
    """Return the data for the grid view for a conference.

    :param str meeting: Endpoint name for a conference.
    """
    try:
        conf = Conference.find_one(Q('endpoint', 'iexact', meeting))
    except ModularOdmException:
        raise HTTPError(httplib.NOT_FOUND)

    data = conference_data(meeting)

    return {
        'data': json.dumps(data),
        'label': meeting,
        'meeting': conf.to_storage(),
        # Needed in order to use base.mako namespace
        'settings': settings,
    }

def conference_view(**kwargs):
    meetings = []
    submissions = []
    for conf in Conference.find():
        # For efficiency, we filter by tag first, then node
        # instead of doing a single Node query
        projects = set()
        for tag in Tag.find(Q('_id', 'iexact', conf.endpoint)):
            for node in tag.node__tagged:
                if not node:
                    continue
                if not node.is_public or node.is_deleted:
                    continue
                projects.add(node)

        for idx, node in enumerate(projects):
            submissions.append(_render_conference_node(node, idx, conf))
        num_submissions = len(projects)
        if num_submissions < settings.CONFERENCE_MIN_COUNT:
            continue
        meetings.append({
            'name': conf.name,
            'active': conf.active,
            'url': web_url_for('conference_results', meeting=conf.endpoint),
            'count': num_submissions,
        })

    submissions.sort(key=lambda submission: submission['dateCreated'], reverse=True)
    meetings.sort(key=lambda meeting: meeting['count'], reverse=True)

    return {'meetings': meetings, 'submissions': submissions}


text:
package com.evanxie.donut.commons.exception;

public class ApplicationException extends Exception{
		/**
		 *
		 */
		private static final long serialVersionUID = 1L;

		public ApplicationException() {
	    }

	    public ApplicationException(String message) {
	        super(message);
	    }

	    public ApplicationException(String message, Throwable cause) {
	        super(message, cause);
	    }

	    public ApplicationException(Throwable cause) {
	        super(cause);
	    }

	    public ApplicationException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
	        super(message, cause, enableSuppression, writableStackTrace);
	    }
	}


text:
//
//  SAViewController.m
//  CoolSnail
//
//  Created by quqi on 15/10/10.
//  Copyright © 2015年 牵着蜗牛走的我. All rights reserved.
//

#import "SAViewController.h"

@interface SAViewController ()

@end

@implementation SAViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
     self.navigationBar.barTintColor = [UIColor colorWithRed: 249.0/255.0 green: 120.0/255.0 blue: 103.0/255.0 alpha:1.0];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
  <button class='g-signin'
		  data-scope='https://www.googleapis.com/auth/plus.login'
		  data-requestvisibleactions='http://schemas.google.com/AddActivity'
		  data-clientId='324761820866-rsbet58bhvf0tm7laq2kkjvimtpj2vrf.apps.googleusercontent.com'
		  data-callback='onSignInCallback'
		  data-theme='dark'
		  data-cookiepolicy='single_host_origin'>
  </button>


text:
.class final Lcom/android/internal/net/VpnConfig$1;
.super Ljava/lang/Object;
.source "VpnConfig.java"

# interfaces
.implements Landroid/os/Parcelable$Creator;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/android/internal/net/VpnConfig;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0x8
    name = null
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "Ljava/lang/Object;",
        "Landroid/os/Parcelable$Creator",
        "<",
        "Lcom/android/internal/net/VpnConfig;",
        ">;"
    }
.end annotation

# direct methods
.method constructor <init>()V
    .locals 0

    .prologue
    .line 88
    invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V

    return-void
.end method

# virtual methods
.method public createFromParcel(Landroid/os/Parcel;)Lcom/android/internal/net/VpnConfig;
    .locals 3
    .parameter "in"

    .prologue
    .line 91
    new-instance v0, Lcom/android/internal/net/VpnConfig;

    invoke-direct {v0}, Lcom/android/internal/net/VpnConfig;-><init>()V

    .line 92
    .local v0, config:Lcom/android/internal/net/VpnConfig;
    invoke-virtual {p1}, Landroid/os/Parcel;->readString()Ljava/lang/String;

    move-result-object v1

    iput-object v1, v0, Lcom/android/internal/net/VpnConfig;->user:Ljava/lang/String;

    .line 93
    invoke-virtual {p1}, Landroid/os/Parcel;->readString()Ljava/lang/String;

    move-result-object v1

    iput-object v1, v0, Lcom/android/internal/net/VpnConfig;->interfaze:Ljava/lang/String;

    .line 94
    invoke-virtual {p1}, Landroid/os/Parcel;->readString()Ljava/lang/String;

    move-result-object v1

    iput-object v1, v0, Lcom/android/internal/net/VpnConfig;->session:Ljava/lang/String;

    .line 95
    invoke-virtual {p1}, Landroid/os/Parcel;->readInt()I

    move-result v1

    iput v1, v0, Lcom/android/internal/net/VpnConfig;->mtu:I

    .line 96
    invoke-virtual {p1}, Landroid/os/Parcel;->readString()Ljava/lang/String;

    move-result-object v1

    iput-object v1, v0, Lcom/android/internal/net/VpnConfig;->addresses:Ljava/lang/String;

    .line 97
    invoke-virtual {p1}, Landroid/os/Parcel;->readString()Ljava/lang/String;

    move-result-object v1

    iput-object v1, v0, Lcom/android/internal/net/VpnConfig;->routes:Ljava/lang/String;

    .line 98
    invoke-virtual {p1}, Landroid/os/Parcel;->createStringArrayList()Ljava/util/ArrayList;

    move-result-object v1

    iput-object v1, v0, Lcom/android/internal/net/VpnConfig;->dnsServers:Ljava/util/List;

    .line 99
    invoke-virtual {p1}, Landroid/os/Parcel;->createStringArrayList()Ljava/util/ArrayList;

    move-result-object v1

    iput-object v1, v0, Lcom/android/internal/net/VpnConfig;->searchDomains:Ljava/util/List;

    .line 100
    const/4 v1, 0x0

    invoke-virtual {p1, v1}, Landroid/os/Parcel;->readParcelable(Ljava/lang/ClassLoader;)Landroid/os/Parcelable;

    move-result-object v1

    check-cast v1, Landroid/app/PendingIntent;

    iput-object v1, v0, Lcom/android/internal/net/VpnConfig;->configureIntent:Landroid/app/PendingIntent;

    .line 101
    invoke-virtual {p1}, Landroid/os/Parcel;->readLong()J

    move-result-wide v1

    iput-wide v1, v0, Lcom/android/internal/net/VpnConfig;->startTime:J

    .line 102
    return-object v0
.end method

.method public bridge synthetic createFromParcel(Landroid/os/Parcel;)Ljava/lang/Object;
    .locals 1
    .parameter "x0"

    .prologue
    .line 88
    invoke-virtual {p0, p1}, Lcom/android/internal/net/VpnConfig$1;->createFromParcel(Landroid/os/Parcel;)Lcom/android/internal/net/VpnConfig;

    move-result-object v0

    return-object v0
.end method

.method public newArray(I)[Lcom/android/internal/net/VpnConfig;
    .locals 1
    .parameter "size"

    .prologue
    .line 107
    new-array v0, p1, [Lcom/android/internal/net/VpnConfig;

    return-object v0
.end method

.method public bridge synthetic newArray(I)[Ljava/lang/Object;
    .locals 1
    .parameter "x0"

    .prologue
    .line 88
    invoke-virtual {p0, p1}, Lcom/android/internal/net/VpnConfig$1;->newArray(I)[Lcom/android/internal/net/VpnConfig;

    move-result-object v0

    return-object v0
.end method


text:
'use strict'

const assert = require('assert')
const context = require('../../test-helpers/context')

describe('ctx.get(name)', () => {
  it('should get a field value, case insensitive', () => {
    const ctx = context()
    ctx.set('X-Foo', 'bar')
    assert.strictEqual(ctx.response.get('x-FOO'), 'bar')
  })

  it('should have the same behavior as ctx.res.getHeader on undefined and null values', () => {
    const ctx = context()
    ctx.res.setHeader('X-Foo', undefined)
    ctx.response.header['x-boo'] = null
    assert.strictEqual(ctx.response.get('x-FOO'), ctx.res.getHeader('X-FOO'))
    assert.strictEqual(ctx.response.get('x-bOO'), ctx.res.getHeader('X-BOO'))
  })

  it('should not convert header value type', () => {
    const ctx = context()
    ctx.res.setHeader('Foo-date', new Date())
    ctx.response.header['foo-map'] = new Map()
    ctx.res.setHeader('Foo-empty-string', '')
    ctx.res.setHeader('Foo-number', 0)
    ctx.res.setHeader('Foo-null', null)
    ctx.res.setHeader('Foo-undefined', undefined)
    assert.ok(ctx.response.get('foo-Date') instanceof Date)
    assert.ok(ctx.response.get('foo-Map') instanceof Map)
    assert.strictEqual(ctx.response.get('Foo-empty-String'), '')
    assert.strictEqual(ctx.response.get('Foo-Number'), 0)
    assert.ok(ctx.response.get('foo-NULL') === null)
    assert.ok(typeof ctx.response.get('FOO-undefined') === 'undefined')
  })
})


text:
```dart
import 'package:keyclic_sdk_api/api.dart';
```

## Properties
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**href** | **String** | The URI of the category associated to the given report. | [optional] [default to null]
**iriTemplate** | [**ReportLinksCategoryIriTemplate**](ReportLinksCategoryIriTemplate.md) |  | [optional] [default to null]

[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md)


text:
<?php

namespace Grocy\Controllers\Users;

use Grocy\Services\DatabaseService;
use LessQL\Result;

class User
{
	const PERMISSION_ADMIN = 'ADMIN';

	const PERMISSION_BATTERIES = 'BATTERIES';

	const PERMISSION_BATTERIES_TRACK_CHARGE_CYCLE = 'BATTERIES_TRACK_CHARGE_CYCLE';

	const PERMISSION_BATTERIES_UNDO_CHARGE_CYCLE = 'BATTERIES_UNDO_CHARGE_CYCLE';

	const PERMISSION_CALENDAR = 'CALENDAR';

	const PERMISSION_CHORES = 'CHORES';

	const PERMISSION_CHORE_TRACK_EXECUTION = 'CHORE_TRACK_EXECUTION';

	const PERMISSION_CHORE_UNDO_EXECUTION = 'CHORE_UNDO_EXECUTION';

	const PERMISSION_EQUIPMENT = 'EQUIPMENT';

	const PERMISSION_MASTER_DATA_EDIT = 'MASTER_DATA_EDIT';

	const PERMISSION_RECIPES = 'RECIPES';

	const PERMISSION_RECIPES_MEALPLAN = 'RECIPES_MEALPLAN';

	const PERMISSION_SHOPPINGLIST = 'SHOPPINGLIST';

	const PERMISSION_SHOPPINGLIST_ITEMS_ADD = 'SHOPPINGLIST_ITEMS_ADD';

	const PERMISSION_SHOPPINGLIST_ITEMS_DELETE = 'SHOPPINGLIST_ITEMS_DELETE';

	const PERMISSION_STOCK = 'STOCK';

	const PERMISSION_STOCK_CONSUME = 'STOCK_CONSUME';

	const PERMISSION_STOCK_EDIT = 'STOCK_EDIT';

	const PERMISSION_STOCK_INVENTORY = 'STOCK_INVENTORY';

	const PERMISSION_STOCK_OPEN = 'STOCK_OPEN';

	const PERMISSION_STOCK_PURCHASE = 'STOCK_PURCHASE';

	const PERMISSION_STOCK_TRANSFER = 'STOCK_TRANSFER';

	const PERMISSION_TASKS = 'TASKS';

	const PERMISSION_TASKS_MARK_COMPLETED = 'TASKS_MARK_COMPLETED';

	const PERMISSION_TASKS_UNDO_EXECUTION = 'TASKS_UNDO_EXECUTION';

	const PERMISSION_USERS = 'USERS';

	const PERMISSION_USERS_CREATE = 'USERS_CREATE';

	const PERMISSION_USERS_EDIT = 'USERS_EDIT';

	const PERMISSION_USERS_EDIT_SELF = 'USERS_EDIT_SELF';

	const PERMISSION_USERS_READ = 'USERS_READ';

	public function __construct()
	{
		$this->db = DatabaseService::getInstance()->GetDbConnection();
	}

	/**
	 * @var \LessQL\Database|null
	 */
	protected $db;

	public static function PermissionList()
	{
		$user = new self();
		return $user->getPermissionList();
	}

	public static function checkPermission($request, string ...$permissions): void
	{
		$user = new self();

		foreach ($permissions as $permission)
		{
			if (!$user->hasPermission($permission))
			{
				throw new PermissionMissingException($request, $permission);
			}
		}
	}

	public function getPermissionList()
	{
		return $this->db->uihelper_user_permissions()->where('user_id', GROCY_USER_ID);
	}

	public function hasPermission(string $permission): bool
	{
		return $this->getPermissions()->where('permission_name', $permission)->fetch() !== null;
	}

	public static function hasPermissions(string ...$permissions)
	{
		$user = new self();

		foreach ($permissions as $permission)
		{
			if (!$user->hasPermission($permission))
			{
				return false;
			}
		}

		return true;
	}

	protected function getPermissions(): Result
	{
		return $this->db->user_permissions_resolved()->where('user_id', GROCY_USER_ID);
	}
}


text:
<?php

namespace directapi\services\campaigns\models;

use directapi\components\constraints as DirectApiAssert;
use directapi\components\Model;
use Symfony\Component\Validator\Constraints as Assert;

class CpmBannerCampaignItem extends Model
{
    /**
     * @var CpmBannerCampaignStrategy
     * @Assert\Valid()
     * @Assert\Type(type="directapi\services\campaigns\models\CpmBannerCampaignStrategy")
     */
    public $BiddingStrategy;

    /**
     * @var CpmCampaignSetting[]
     * @Assert\Valid()
     * @DirectApiAssert\ArrayOf(type="directapi\services\campaigns\models\CpmCampaignSetting")
     */
    public $Settings;

    /**
     * @var \directapi\common\containers\ArrayOfInteger
     * @Assert\Type(type="directapi\common\containers\ArrayOfInteger")
     */
    public $CounterIds;

    /**
     * @var FrequencyCapSetting
     * @Assert\Type(type="directapi\services\campaigns\models\FrequencyCapSetting")
     */
    public $FrequencyCap;
}