text:
package textoutput

import (
	"fmt"
	"io"
	"os"
	"strings"

	"github.com/mgutz/ansi"
)

// CharAttribute is a rune and a color attribute
type CharAttribute struct {
	R rune
	A ANSIColor
}

// TextOutput keeps state about verbosity and if colors are enabled
type TextOutput struct {
	color   bool
	enabled bool
	// Tag replacement structs, for performance
	lightReplacer *strings.Replacer
	darkReplacer  *strings.Replacer
}

// New creates a new TextOutput struct, which is
// enabled by default and with colors turned on.
// If the NO_COLOR environment variable is set, colors are disabled.
func New() *TextOutput {
	// Respect the NO_COLOR environment variable
	color := len(os.Getenv("NO_COLOR")) == 0
	o := &TextOutput{color, true, nil, nil}
	o.initializeTagReplacers()
	return o
}

// NewTextOutput can initialize a new TextOutput struct,
// which can have colors turned on or off and where the
// output can be enabled (verbose) or disabled (silent).
// If NO_COLOR is set, colors are disabled, regardless.
func NewTextOutput(color, enabled bool) *TextOutput {
	// Respect the NO_COLOR environment variable
	if os.Getenv("NO_COLOR") != "" {
		color = false
	}
	o := &TextOutput{color, enabled, nil, nil}
	o.initializeTagReplacers()
	return o
}

// OutputTags will output text that may have tags like "<blue>", "</blue>" or "<off>" for
// enabling or disabling color attributes. Respects the color/enabled settings
// of this TextOutput.
func (o *TextOutput) OutputTags(colors ...string) {
	if o.enabled {
		fmt.Println(o.Tags(colors...))
	}
}

// Given a line with words and several color strings, color the words
// in the order of the colors. The last color will color the rest of the
// words.
func (o *TextOutput) OutputWords(line string, colors ...string) {
	if o.enabled {
		fmt.Println(o.Words(line, colors...))
	}
}

// Write a message to stdout if output is enabled
func (o *TextOutput) Println(msg ...interface{}) {
	if o.enabled {
		fmt.Println(o.InterfaceTags(msg...))
	}
}

// Write a message to the given io.Writer if output is enabled
func (o *TextOutput) Fprintln(w io.Writer, msg ...interface{}) {
	if o.enabled {
		fmt.Fprintln(w, o.InterfaceTags(msg...))
	}
}

// Write a message to stdout if output is enabled
func (o *TextOutput) Printf(msg ...interface{}) {
	if !o.enabled {
		return
	}
	count := len(msg)
	if count == 0 {
		return
	} else if count == 1 {
		if fmtString, ok := msg[0].(string); ok {
			fmt.Print(fmtString)
		}
	} else { // > 1
		if fmtString, ok := msg[0].(string); ok {
			fmt.Printf(o.InterfaceTags(fmtString), msg[1:]...)
		} else {
			// fail
			fmt.Printf("%v", msg...)
		}
	}
}

// Write a message to the given io.Writer if output is enabled
func (o *TextOutput) Fprintf(w io.Writer, msg ...interface{}) {
	if !o.enabled {
		return
	}
	count := len(msg)
	if count == 0 {
		return
	} else if count == 1 {
		if fmtString, ok := msg[0].(string); ok {
			fmt.Fprint(w, fmtString)
		}
	} else { // > 1
		if fmtString, ok := msg[0].(string); ok {
			fmt.Fprintf(w, o.InterfaceTags(fmtString), msg[1:]...)
		} else {
			// fail
			fmt.Fprintf(w, "%v", msg...)
		}
	}
}

// Write a message to stdout if output is enabled
func (o *TextOutput) Print(msg ...interface{}) {
	if o.enabled {
		fmt.Print(o.InterfaceTags(msg...))
	}
}

// Write a message to the given io.Writer if output is enabled
func (o *TextOutput) Fprint(w io.Writer, msg ...interface{}) {
	if o.enabled {
		fmt.Fprint(w, o.InterfaceTags(msg...))
	}
}

// Write an error message in red to stderr if output is enabled
func (o *TextOutput) Err(msg string) {
	if o.enabled {
		if o.color {
			fmt.Fprintln(os.Stderr, ansi.Color(msg, "red"))
		} else {
			fmt.Fprintln(os.Stderr, msg)
		}
	}
}

// Write an error message to stderr and quit with exit code 1
func (o *TextOutput) ErrExit(msg string) {
	o.Err(msg)
	os.Exit(1)
}

// Deprectated
func (o *TextOutput) IsEnabled() bool {
	return o.enabled
}

// Enabled returns true if any output is enabled
func (o *TextOutput) Enabled() bool {
	return o.enabled
}

// Disabled returns true if all output is disabled
func (o *TextOutput) Disabled() bool {
	return !o.enabled
}

func (o *TextOutput) DarkRed(s string) string {
	if o.color {
		return ansi.Color(s, "red")
	}
	return s
}

func (o *TextOutput) DarkGreen(s string) string {
	if o.color {
		return ansi.Color(s, "green")
	}
	return s
}

func (o *TextOutput) DarkYellow(s string) string {
	if o.color {
		return ansi.Color(s, "yellow")
	}
	return s
}

func (o *TextOutput) DarkBlue(s string) string {
	if o.color {
		return ansi.Color(s, "blue")
	}
	return s
}

func (o *TextOutput) DarkPurple(s string) string {
	if o.color {
		return ansi.Color(s, "magenta")
	}
	return s
}

func (o *TextOutput) DarkCyan(s string) string {
	if o.color {
		return ansi.Color(s, "cyan")
	}
	return s
}

func (o *TextOutput) DarkGray(s string) string {
	if o.color {
		return ansi.Color(s, "black")
	}
	return s
}

func (o *TextOutput) LightRed(s string) string {
	if o.color {
		return ansi.Color(s, "red+h")
	}
	return s
}

func (o *TextOutput) LightGreen(s string) string {
	if o.color {
		return ansi.Color(s, "green+h")
	}
	return s
}

func (o *TextOutput) LightYellow(s string) string {
	if o.color {
		return ansi.Color(s, "yellow+h")
	}
	return s
}

func (o *TextOutput) LightBlue(s string) string {
	if o.color {
		return ansi.Color(s, "blue+h")
	}
	return s
}

func (o *TextOutput) LightPurple(s string) string {
	if o.color {
		return ansi.Color(s, "magenta+h")
	}
	return s
}

func (o *TextOutput) LightCyan(s string) string {
	if o.color {
		return ansi.Color(s, "cyan+h")
	}
	return s
}

func (o *TextOutput) White(s string) string {
	if o.color {
		return ansi.Color(s, "white+h")
	}
	return s
}

// Given a line with words and several color strings, color the words
// in the order of the colors. The last color will color the rest of the
// words.
func (o *TextOutput) Words(line string, colors ...string) string {
	if o.color {
		var ok bool
		words := strings.Split(line, " ")
		color := ANSIColor(ansi.ColorCode("black+h")) // LightGray
		coloredWords := make([]string, len(words))
		for i, word := range words {
			if i < len(colors) {
				prevColor := color
				color, ok = LightColorMap[colors[i]]
				if !ok {
					// Use the previous color of this color string was not found
					color = prevColor
				}
			}
			coloredWords[i] = ansi.Color(word, string(color))
		}
		return strings.Join(coloredWords, " ")
	}
	return line
}

// Change the color state in the terminal emulator
func (o *TextOutput) ColorOn(attribute1, attribute2 int) string {
	if !o.color {
		return ""
	}
	return fmt.Sprintf("\033[%d;%dm", attribute1, attribute2)
}

// Change the color state in the terminal emulator
func (o *TextOutput) ColorOff() string {
	if !o.color {
		return ""
	}
	return "\033[0m"
}

// Replace <blue> with starting a light blue color attribute and <off> with using the default attributes.
// </blue> can also be used for using the default attributes.
func (o *TextOutput) LightTags(colors ...string) string {
	return o.lightReplacer.Replace(strings.Join(colors, ""))
}

// Same as LightTags
func (o *TextOutput) Tags(colors ...string) string {
	return o.LightTags(colors...)
}

// InterfaceTags is the same as LightTags, but with interfaces
func (o *TextOutput) InterfaceTags(colors ...interface{}) string {
	var sb strings.Builder
	for _, color := range colors {
		if colorString, ok := color.(string); ok {
			sb.WriteString(colorString)
		} else {
			sb.WriteString(fmt.Sprintf("%s", color))
		}
	}
	return o.LightTags(sb.String())
}

// Replace <blue> with starting a light blue color attribute and <off> with using the default attributes.
// </blue> can also be used for using the default attributes.
func (o *TextOutput) DarkTags(colors ...string) string {
	return o.darkReplacer.Replace(strings.Join(colors, ""))
}

func (o *TextOutput) DisableColors() {
	o.color = false
	o.initializeTagReplacers()
}

func (o *TextOutput) EnableColors() {
	o.color = true
	o.initializeTagReplacers()
}

func (o *TextOutput) Disable() {
	o.enabled = false
}

func (o *TextOutput) Enable() {
	o.enabled = true
}

func (o *TextOutput) initializeTagReplacers() {
	// Initialize tag replacement tables, with as few memory allocations as possible (no append)
	off := ansi.ColorCode("off")
	rs := make([]string, len(LightColorMap)*4+2)
	i := 0
	if o.color {
		for key, value := range LightColorMap {
			rs[i] = "<" + key + ">"
			i++
			rs[i] = string(value)
			i++
			rs[i] = "</" + key + ">"
			i++
			rs[i] = off
			i++
		}
		rs[i] = "<off>"
		i++
		rs[i] = off
	} else {
		for key := range LightColorMap {
			rs[i] = "<" + key + ">"
			i++
			rs[i] = ""
			i++
			rs[i] = "</" + key + ">"
			i++
			rs[i] = ""
			i++
		}
		rs[i] = "<off>"
		i++
		rs[i] = ""
	}
	o.lightReplacer = strings.NewReplacer(rs...)
	// Initialize the replacer for the dark color scheme, while reusing the rs slice
	i = 0
	if o.color {
		for key, value := range DarkColorMap {
			rs[i] = "<" + key + ">"
			i++
			rs[i] = string(value)
			i++
			rs[i] = "</" + key + ">"
			i++
			rs[i] = off
			i++
		}
		rs[i] = "<off>"
		i++
		rs[i] = off
	} else {
		for key := range DarkColorMap {
			rs[i] = "<" + key + ">"
			i++
			rs[i] = ""
			i++
			rs[i] = "</" + key + ">"
			i++
			rs[i] = ""
			i++
		}
		rs[i] = "<off>"
		i++
		rs[i] = ""
	}
	o.darkReplacer = strings.NewReplacer(rs...)
}

// // Pair takes a string with ANSI codes and returns
// // a slice with two elements.
// func (o *TextOutput) Extract(s string) []CharAttribute {
// 	var (
// 		escaped      bool
// 		colorcode    strings.Builder
// 		word         strings.Builder
// 		cc           = make([]ANSIColor, 0, len(s))
// 		currentColor ANSIColor
// 	)
// 	for _, r := range s {
// 		if r == '\033' {
// 			escaped = true
// 			if len(word.String()) > 0 {
// 				//fmt.Println("cc", cc)
// 				word.Reset()
// 			}
// 			continue
// 		}
// 		if escaped {
// 			if r != 'm' {
// 				colorcode.WriteRune(r)
// 			} else if r == 'm' {
// 				s2 := strings.TrimPrefix(colorcode.String(), "[")
// 				attributeStrings := strings.Split(s2, ";")
// 				if len(attributeStrings) == 1 && attributeStrings[0] == "0" {
// 					currentColor = ""
// 				}
// 				for _, attributeString := range attributeStrings {
// 					attributeNumber, err := strconv.Atoi(attributeString)
// 					if err != nil {
// 						continue
// 					}
// 					currentColor = append(currentColor, byte(attributeNumber))
// 				}
// 				// Strip away leading 0 color attribute, if there are more than 1
// 				if len(currentColor) > 1 && currentColor[0] == 0 {
// 					currentColor = currentColor[1:]
// 				}
// 				// currentColor now contains the last found color attributes,
// 				// but as a vt100.AttributeColor.
// 				colorcode.Reset()
// 				escaped = false
// 			}
// 		} else {
// 			cc = append(cc, CharAttribute{r, currentColor})
// 		}
// 	}
// 	// if escaped is true here, there is something wrong
// 	return cc
//}


text:
package com.m2team.phuotstory.service;

import android.app.IntentService;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.ResultReceiver;
import android.text.TextUtils;
import android.util.Log;
import com.google.android.gms.maps.model.LatLng;
import com.m2team.phuotstory.R;
import com.m2team.phuotstory.common.Common;
import com.m2team.phuotstory.common.Constant;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Created by Hoang Minh on 7/28/2015.
 */
public class FetchAddressService extends IntentService {

    protected ResultReceiver mReceiver;

    public FetchAddressService() {
        super("FetchAddressService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String errorMessage = "";
        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        // Get the location passed to this service through an extra.
        LatLng location = intent.getParcelableExtra(
                Constant.LOCATION_DATA_EXTRA);
        mReceiver = intent.getParcelableExtra(Constant.RECEIVER);

        List<Address> addresses = null;

        try {
            addresses = geocoder.getFromLocation(
                    location.latitude,
                    location.longitude,
                    // In this sample, get just a single address.
                    1);
        } catch (IOException ioException) {
            // Catch network or other I/O problems.
            errorMessage = getString(R.string.service_not_available);
            Log.e(Constant.TAG, errorMessage, ioException);
        } catch (IllegalArgumentException illegalArgumentException) {
            // Catch invalid latitude or longitude values.
            errorMessage = getString(R.string.invalid_lat_long_used);
            Log.e(Constant.TAG, errorMessage + ". " +
                    "Latitude = " + location.latitude +
                    ", Longitude = " +
                    location.longitude, illegalArgumentException);
        }

        // Handle case where no address was found.
        if (addresses == null || addresses.size() == 0) {
            if (errorMessage.isEmpty()) {
                errorMessage = getString(R.string.no_address_found);
                Log.e(Constant.TAG, errorMessage);
            }
            deliverResultToReceiver(Constant.FAILURE_RESULT, errorMessage, location);
        } else {
            Address address = addresses.get(0);
            String result = Common.getAddress(address);
            Log.i(Constant.TAG, getString(R.string.address_found));
            deliverResultToReceiver(Constant.SUCCESS_RESULT, result, location);
        }
    }

    private void deliverResultToReceiver(int resultCode, String message, LatLng latLng) {
        if (mReceiver != null) {
            Bundle bundle = new Bundle();
            bundle.putString(Constant.RESULT_DATA_KEY, message);
            bundle.putDoubleArray(Constant.RESULT_DATA_LOCATION, new double[]{latLng.latitude, latLng.longitude});
            mReceiver.send(resultCode, bundle);
        }
    }

}

redpajama_set_name: RedPajamaGithub


text:
define(function() {
  error_b
});


text:
Packer shell post-processor
=============================

Run shell scripts for post-process images

Usage
-----
Add the post-processor to your packer template:

    {
        "post-processors": [
          {
            "type": "shell",
            "scripts": [
              "script.sh"
            ]
          }
        ]
    }

Available configuration options:

Installation
------------
Run:

    $ go get github.com/kadaan/packer-post-processor-shell
    $ go install github.com/kadaan/packer-post-processor-shell

Add the post-processor to ~/.packerconfig:

    {
      "post-processors": {
        "shell": "packer-post-processor-shell"
      }
    }


text:
RETCODE=$(fw_exists rvm.installed)
[ ! "$RETCODE" == 0 ] || { \
  # Assume single-user installation
  source $HOME/.rvm/scripts/rvm
  return 0;
}

# Never run installation inside of TRAVIS,
# just rely on their default RVM installaton
[ "$TRAVIS" != "true" ] || { \
  source $HOME/.rvm/scripts/rvm
  touch rvm.installed
  return 0;
}

# Run single-user installation and source rvm
\curl -sSL https://get.rvm.io | bash -s stable
source $HOME/.rvm/scripts/rvm

touch $IROOT/rvm.installed


text:
#ifndef BS_LEXER_H
#define BS_LEXER_H

#include "symbol.h"
#include "token.h"
#include "token_stream.h"

#include <map>
#include <string>
#include <istream>

/******************************************************************************
*
******************************************************************************/
class Lexer : public TokenStream
{
	public:
		Lexer(std::istream &input);
		//Lexer(const Lexer &lexer);
		~Lexer();

		const Token &getNext();
		unsigned int getLine() const;
		const std::map <std::string, Token> &keywords();

		Lexer & operator=(const Lexer &lexer);
	private:
		Lexer(const Lexer &lexer); //non-copyable
		std::istream *mInput;
		unsigned int  mLineNum;
		Token         mToken;

};

#endif //ifndef BS_LEXER_H


text:
One of the login options for dex uses the Bitbucket OAuth2 flow to identify the end user through their Bitbucket account.

When a client redeems a refresh token through dex, dex will re-query Bitbucket to update user information in the ID Token. To do this, __dex stores a readonly Bitbucket access token in its backing datastore.__ Users that reject dex's access through Bitbucket will also revoke all dex clients which authenticated them through Bitbucket.

## Configuration

Register a new OAuth consumer with [Bitbucket](https://confluence.atlassian.com/bitbucket/oauth-on-bitbucket-cloud-238027431.html) ensuring the callback URL is `(dex issuer)/callback`. For example if dex is listening at the non-root path `https://auth.example.com/dex` the callback would be `https://auth.example.com/dex/callback`.

The application requires the user to grant the `Read Account` and `Read Team membership` permissions. The latter is required only if group membership is a desired claim.

The following is an example of a configuration for `examples/config-dev.yaml`:

```yaml
connectors:
- type: bitbucket-cloud
  # Required field for connector id.
  id: bitbucket-cloud
  # Required field for connector name.
  name: Bitbucket Cloud
  config:
    # Credentials can be string literals or pulled from the environment.
    clientID: $BITBUCKET_CLIENT_ID
    clientSecret: $BITBUCKET_CLIENT_SECRET
    redirectURI: http://127.0.0.1:5556/dex/callback
    # Optional teams whitelist, communicated through the "groups" scope.
    # If `teams` is omitted, all of the user's Bitbucket teams are returned when the groups scope is present.
    # If `teams` is provided, this acts as a whitelist - only the user's Bitbucket teams that are in the configured `teams` below will go into the groups claim.  Conversely, if the user is not in any of the configured `teams`, the user will not be authenticated.
    teams:
    - my-team
```


text:
import statsd
import decimal

class Gauge(statsd.Client):
    '''Class to implement a statsd gauge

    '''

    def send(self, subname, value):
        '''Send the data to statsd via self.connection

        :keyword subname: The subname to report the data to (appended to the
            client name)
        :keyword value: The gauge value to send
        '''
        assert isinstance(value, (int, long, float, decimal.Decimal))
        name = self._get_name(self.name, subname)
        self.logger.info('%s: %s', name, value)
        return statsd.Client._send(self, {name: '%s|g' % value})


text:
Landing = {

    init: function(data){
        if(typeof data != 'undefined'){
            var attributes = [

            ];

            $.each(attributes, function(index, element){
                if(typeof data[element] != 'undefined')
                    Landing[element] = data[element];
            });
        }

        Landing.setHandlers();
    },

    setHandlers: function(){

    }

}


text:
#ifndef CHDB_H
#define CHDB_H

#include <stdint.h>

#define CHDB_VERSION 0

typedef struct __chdb chdb_t;

/**
 * Memory-maps a chdb file.
 * Returns a handle to the opened chdb, or sets errno and returns
 * NULL in case of error.
 */
chdb_t *chdb_open(const char *pathname);

/**
 * Closes a memory-mapped chdb file.
 */
void chdb_close(chdb_t *chdb);

/**
 * Performs a search for the given 'key' of length 'key_len' in 'chdb'.
 * Sets 'value' and 'value_len' and returns 0 in case of success,
 * or returns -1 and sets errno otherwise.
 * Note that the area of memory 'value' points to after a successful
 * call to this function is read-only.
 */
int chdb_get(chdb_t *chdb, const void *key, uint32_t key_len,
             const void **value, uint32_t *value_len);

/**
 * Provides a set of key-value pairs to be indexed by chdb.
 * This structure should be filled in by the user code and passed to
 * chdb_create to generate a chdb file.
 * - private: a pointer to user data, ignored by chdb
 * - count: the number of key-value pairs to be indexed
 * - next: a pointer to the iterator function that provides the next
 *         key-value pair
 * - rewind: a pointer to a function that should rewind the reader
 *           back to the beginning of the set
 */
struct chdb_reader {
	void *private;
	uint32_t count;
	void (*next)(struct chdb_reader *reader,
	             const void **key, uint32_t *key_len,
	             const void **value, uint32_t *value_len);
	void (*rewind)(struct chdb_reader *reader);
};

/**
 * Generates a chdb file at the given 'pathname' containing the data
 * provided by 'reader'.
 * Returns 0 in case of success, or sets errno and returns -1 otherwise.
 */
int chdb_create(struct chdb_reader *reader, const char *pathname);

#endif


text:
package org.orekit.propagation.analytical.gnss;

import org.hipparchus.geometry.euclidean.threed.Vector3D;
import org.hipparchus.util.FastMath;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.orekit.Utils;
import org.orekit.data.DataContext;
import org.orekit.errors.OrekitException;
import org.orekit.errors.OrekitMessages;
import org.orekit.frames.Frame;
import org.orekit.frames.Frames;
import org.orekit.frames.FramesFactory;
import org.orekit.gnss.SatelliteSystem;
import org.orekit.propagation.analytical.gnss.data.GNSSConstants;
import org.orekit.propagation.analytical.gnss.data.SBASNavigationMessage;
import org.orekit.propagation.analytical.gnss.data.SBASOrbitalElements;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.GNSSDate;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.CartesianDerivativesFilter;
import org.orekit.utils.Constants;
import org.orekit.utils.IERSConventions;
import org.orekit.utils.PVCoordinates;
import org.orekit.utils.TimeStampedPVCoordinates;

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

public class SBASPropagatorTest {

    /** Threshold for test validation. */
    private static double eps = 1.0e-15;

    /** SBAS orbital elements. */
    private SBASNavigationMessage soe;
    private Frames frames;

    @BeforeEach
    public void setUp() {
        // Reference data are taken from IGS file brdm0370.17p
        soe = new SBASNavigationMessage();
        soe.setPRN(127);
        soe.setTime(1.23303e+05);;
        soe.setDate(new GNSSDate(1935, 1.23303e+05 * 1000.0, SatelliteSystem.SBAS).getDate());
        soe.setX(2.406022248000e+07);
        soe.setXDot(-2.712500000000e-01);
        soe.setXDotDot(3.250000000000e-04);
        soe.setY(3.460922568000e+07);
        soe.setYDot(3.063125000000e-00);
        soe.setYDotDot(-1.500000000000e-04);
        soe.setZ(1.964040000000e+04);
        soe.setZDot(1.012000000000e-00);
        soe.setZDotDot(-1.250000000000e-04);
        frames = DataContext.getDefault().getFrames();
    }

    @BeforeAll
    public static void setUpBeforeClass() {
        Utils.setDataRoot("gnss");
    }

    @Test
    public void testPropagationAtReferenceTime() {
        // SBAS propagator
        final SBASPropagator propagator = new SBASPropagatorBuilder(soe, frames).
                        attitudeProvider(Utils.defaultLaw()).
                        mu(GNSSConstants.SBAS_MU).
                        mass(SBASPropagator.DEFAULT_MASS).
                        eci(FramesFactory.getEME2000()).
                        ecef(FramesFactory.getITRF(IERSConventions.IERS_2010, true)).
                        build();
        // Propagation
        final PVCoordinates pv = propagator.propagateInEcef(soe.getDate());
        // Position/Velocity/Acceleration
        final Vector3D position = pv.getPosition();
        final Vector3D velocity = pv.getVelocity();
        final Vector3D acceleration = pv.getAcceleration();
        // Verify
        Assertions.assertEquals(soe.getX(),       position.getX(),     eps);
        Assertions.assertEquals(soe.getY(),       position.getY(),     eps);
        Assertions.assertEquals(soe.getZ(),       position.getZ(),     eps);
        Assertions.assertEquals(soe.getXDot(),    velocity.getX(),     eps);
        Assertions.assertEquals(soe.getYDot(),    velocity.getY(),     eps);
        Assertions.assertEquals(soe.getZDot(),    velocity.getZ(),     eps);
        Assertions.assertEquals(soe.getXDotDot(), acceleration.getX(), eps);
        Assertions.assertEquals(soe.getYDotDot(), acceleration.getY(), eps);
        Assertions.assertEquals(soe.getZDotDot(), acceleration.getZ(), eps);
    }

    @Test
    public void testPropagation() {
        // SBAS propagator
        final SBASPropagator propagator = new SBASPropagatorBuilder(soe, frames).build();
        // Propagation
        final PVCoordinates pv = propagator.propagateInEcef(soe.getDate().shiftedBy(1.0));
        // Position/Velocity/Acceleration
        final Vector3D position = pv.getPosition();
        final Vector3D velocity = pv.getVelocity();
        final Vector3D acceleration = pv.getAcceleration();
        // Verify
        Assertions.assertEquals(24060222.2089125, position.getX(),     eps);
        Assertions.assertEquals(34609228.7430500, position.getY(),     eps);
        Assertions.assertEquals(19641.4119375,    position.getZ(),     eps);
        Assertions.assertEquals(-0.270925,        velocity.getX(),     eps);
        Assertions.assertEquals(3.062975,         velocity.getY(),     eps);
        Assertions.assertEquals(1.011875,         velocity.getZ(),     eps);
        Assertions.assertEquals(soe.getXDotDot(), acceleration.getX(), eps);
        Assertions.assertEquals(soe.getYDotDot(), acceleration.getY(), eps);
        Assertions.assertEquals(soe.getZDotDot(), acceleration.getZ(), eps);
    }

    @Test
    public void testFrames() {
        // Builds the SBAS propagator from the ephemeris
        final SBASPropagator propagator = new SBASPropagatorBuilder(soe, frames).build();
        Assertions.assertEquals("EME2000", propagator.getFrame().getName());
        Assertions.assertEquals(3.986005e+14, propagator.getMU(), 1.0e6);
        Assertions.assertEquals(propagator.getECI().getName(), propagator.getFrame().getName());
        // Defines some date
        final AbsoluteDate date = new AbsoluteDate(2017, 2, 3, 12, 0, 0., TimeScalesFactory.getUTC());
        // Get PVCoordinates at the date in the ECEF
        final PVCoordinates pv0 = propagator.propagateInEcef(date);
        // Get PVCoordinates at the date in the ECEF
        final PVCoordinates pv1 = propagator.getPVCoordinates(date, propagator.getECEF());

        // Checks
        Assertions.assertEquals(0., pv0.getPosition().distance(pv1.getPosition()), 7.7e-9);
        Assertions.assertEquals(0., pv0.getVelocity().distance(pv1.getVelocity()), 3.8e-12);
    }

    @Test
    public void testDerivativesConsistency() {

        final Frame eme2000 = FramesFactory.getEME2000();
        double errorP = 0;
        double errorV = 0;
        double errorA = 0;
        final SBASPropagator propagator = new SBASPropagatorBuilder(soe, frames).build();
        SBASOrbitalElements elements = propagator.getSBASOrbitalElements();
        AbsoluteDate t0 = new GNSSDate(elements.getWeek(), 1000.0 * elements.getTime(), SatelliteSystem.SBAS).getDate();
        for (double dt = 0; dt < Constants.JULIAN_DAY; dt += 600) {
            final AbsoluteDate central = t0.shiftedBy(dt);
            final PVCoordinates pv = propagator.getPVCoordinates(central, eme2000);
            final double h = 10.0;
            List<TimeStampedPVCoordinates> sample = new ArrayList<TimeStampedPVCoordinates>();
            for (int i = -3; i <= 3; ++i) {
                sample.add(propagator.getPVCoordinates(central.shiftedBy(i * h), eme2000));
            }
            final PVCoordinates interpolated =
                            TimeStampedPVCoordinates.interpolate(central,
                                                                 CartesianDerivativesFilter.USE_P,
                                                                 sample);
            errorP = FastMath.max(errorP, Vector3D.distance(pv.getPosition(), interpolated.getPosition()));
            errorV = FastMath.max(errorV, Vector3D.distance(pv.getVelocity(), interpolated.getVelocity()));
            errorA = FastMath.max(errorA, Vector3D.distance(pv.getAcceleration(), interpolated.getAcceleration()));
        }
        Assertions.assertEquals(0.0, errorP, 1.5e-11);
        Assertions.assertEquals(0.0, errorV, 7.2e-3);
        Assertions.assertEquals(0.0, errorA, 1.7e-3);

    }

    @Test
    public void testNoReset() {
        try {
            final SBASPropagator propagator = new SBASPropagatorBuilder(soe, frames).build();
            propagator.resetInitialState(propagator.getInitialState());
            Assertions.fail("an exception should have been thrown");
        } catch (OrekitException oe) {
            Assertions.assertEquals(OrekitMessages.NON_RESETABLE_STATE, oe.getSpecifier());
        }
        try {
            final SBASPropagator propagator = new SBASPropagatorBuilder(soe, frames).build();
            propagator.resetIntermediateState(propagator.getInitialState(), true);
            Assertions.fail("an exception should have been thrown");
        } catch (OrekitException oe) {
            Assertions.assertEquals(OrekitMessages.NON_RESETABLE_STATE, oe.getSpecifier());
        }
    }
}


text:
/**
 * Internal dependencies
 */
import getTimeTracker from '../getTimeTracker';
import { config } from '../shared';
import trackEvent from '../trackEvent';

jest.mock('../trackEvent');

jest
  .spyOn(performance, 'now')
  .mockImplementationOnce(() => 150)
  .mockImplementationOnce(() => 200);

describe('getTimeTracker', () => {
  afterEach(() => {
    config.trackingAllowed = false;
    config.trackingEnabled = false;
    config.appName = '';

    jest.clearAllMocks();
  });

  it('sends two separate tracking events', () => {
    config.appName = 'Foo App';
    config.trackingAllowed = true;
    config.trackingEnabled = true;
    config.trackingId = 'UA-12345678-1';
    config.trackingIdGA4 = 'G-ABC1234567';

    const trackTime = getTimeTracker('load_dependencies');
    trackTime();

    expect(trackEvent).toHaveBeenCalledTimes(2);
    expect(trackEvent).toHaveBeenNthCalledWith(1, 'timing_complete', {
      name: 'load_dependencies',
      value: 50,
      send_to: 'UA-12345678-1',
    });
    expect(trackEvent).toHaveBeenNthCalledWith(2, 'load_dependencies', {
      value: 50,
      send_to: 'G-ABC1234567',
    });
  });
});


text:
// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0
#ifndef OPENTITAN_HW_IP_OTBN_DV_MODEL_OTBN_MODEL_DPI_H_
#define OPENTITAN_HW_IP_OTBN_DV_MODEL_OTBN_MODEL_DPI_H_

// The DPI exports for OtbnModel. See also otbn_model_dpi.svh, where
// they are declared for the SystemVerilog side.
//
// These are defined in a separate file from otbn_model.h because otherwise
// something like otbn_top_sim.cc will see both these defines and the
// auto-generated ones that Verilator produces in e.g. Votbn_top_sim__Dpi.h. The
// latter use void* for all the chandle arguments and some versions of GCC treat
// the resulting signatures as incompatible.

extern "C" {

// Create an OtbnModel object. Will always succeed.
OtbnModel *otbn_model_init(const char *mem_scope, const char *design_scope);

// Delete an OtbnModel
void otbn_model_destroy(OtbnModel *model);

// Take loop warps from an OtbnMemUtil
void otbn_take_loop_warps(OtbnModel *model, OtbnMemUtil *memutil);

// Returns non-zero if an OtbnMemUtil contains loop warps
int otbn_has_loop_warps(OtbnMemUtil *memutil);

// Flush URND and RND EDN data from model because of edn_rst_n signal. Returns
// 0 on success; -1 on error.
int otbn_model_edn_flush(OtbnModel *model);

// Call edn_rnd_step function of OtbnModel. Returns 0 on success; -1 on error.
int otbn_model_edn_rnd_step(OtbnModel *model,
                            svLogicVecVal *edn_rnd_data /* logic [31:0] */,
                            unsigned char fips_err);

// Call edn_urnd_step function of OtbnModel. Returns 0 on success; -1 on error.
int otbn_model_edn_urnd_step(OtbnModel *model,
                             svLogicVecVal *edn_urnd_data /* logic [31:0] */);

// Signal RTL is finished processing RND data to Model. Returns 0 on success;
// -1 on error.
int otbn_model_rnd_cdc_done(OtbnModel *model);

// Signal RTL is finished processing EDN data for URND to Model. Returns 0 on
// success; -1 on error.
int otbn_model_urnd_cdc_done(OtbnModel *model);

// Signal RTL is finished processing OTP key to the Model. Returns 0 on
// success; -1 on error.
int otbn_model_otp_key_cdc_done(OtbnModel *model);

// Pass keymgr data to model. Returns 0 on success; -1 on error.
int otbn_model_set_keymgr_value(OtbnModel *model, svLogicVecVal *key0,
                                svLogicVecVal *key1, unsigned char valid);

// The main entry point to the OTBN model, exported from here and used in
// otbn_core_model.sv.
//
// This communicates state with otbn_core_model.sv through the model_state
// parameter, which has the following bits:
//
//    Bit 0:      running       True if the model is currently running
//    Bit 1:      check_due     True if the model finished running last cycle
//    Bit 2:      failed_step   Something failed when trying to start/step ISS
//
// The otbn_model_step function should only be called when either the model is
// running (bit 0 of model_state), has a check due (bit 1 of model_state), or
// when start is asserted. At other times, it will return immediately (but
// wastes a DPI call).
//
// If the model is running and start is false, otbn_model_step steps the ISS by
// a single cycle. If something goes wrong, it will set failed_step to true and
// running to false. Otherwise, it writes the new value of otbn.INSN_CNT to
// *insn_cnt.
//
// If nothing goes wrong and the ISS finishes its run, we set running to false,
// write out err_bits and stop_pc and set check_due to ensure otbn_model_check
// runs on the next negedge of the clock.
//
unsigned otbn_model_step(OtbnModel *model, unsigned model_state,
                         svBitVecVal *cmd /* bit [7:0] */,
                         svBitVecVal *status /* bit [7:0] */,
                         svBitVecVal *insn_cnt /* bit [31:0] */,
                         svBitVecVal *rnd_req /* bit [0:0] */,
                         svBitVecVal *err_bits /* bit [31:0] */,
                         svBitVecVal *stop_pc /* bit [31:0] */);

// This gets run if the otbn_model_step function sets the check_due bit in its
// model_state bitfield (see above). If the model's design_scope is non-empty,
// it should be the scope of an RTL implementation. In that case, we compare
// register and memory contents with that implementation, printing to stderr
// and setting the failed_cmp bit if there are any mismatches. If the model's
// design_scope is the empty string, we grab the contents of DMEM from the ISS
// and inject them into the simulation memory.
//
// Returns 1 on success; 0 on failure.
int otbn_model_check(OtbnModel *model, svBitVecVal *mismatch /* bit [0:0] */);

// Tell the model to mark all of IMEM as invalid so that any fetch causes an
// integrity error. Returns 0 on success or -1 on failure.
int otbn_model_invalidate_imem(OtbnModel *model);

// Tell the model to mark all of DMEM as invalid so that any load causes an
// integrity error. Returns 0 on success or -1 on failure.
int otbn_model_invalidate_dmem(OtbnModel *model);

// Tell the model to set software_errs_fatal bit in ctrl register. Once this bit
// is set, any software error will be ellevated to fatal error from recoverable
// error.
int otbn_model_set_software_errs_fatal(OtbnModel *model, unsigned char new_val);

// Tell the model to not execute checks to see if secure wiping has written
// random data to all registers before wiping them with zeroes.
int otbn_set_no_sec_wipe_chk(OtbnModel *model);

// Disable stack integrity checks
int otbn_disable_stack_check(OtbnModel *model);

// Step the CRC calculation for item
//
// state is an inout parameter and should be updated in-place. This is
// a "pure" function: there isn't actually any model state that gets
// updated by calling it. Returns 0 on success or -1 on failure.
int otbn_model_step_crc(OtbnModel *model, svBitVecVal *item /* bit [47:0] */,
                        svBitVecVal *state /* inout bit [31:0] */);

// Flush any information in the model. Returns 0 on success; -1 on error.
int otbn_model_reset(OtbnModel *model, svBitVecVal *status /* bit [7:0] */,
                     svBitVecVal *insn_cnt /* bit [31:0] */,
                     svBitVecVal *rnd_req /* bit [0:0] */,
                     svBitVecVal *err_bits /* bit [31:0] */,
                     svBitVecVal *stop_pc /* bit [31:0] */);

// React to an error escalation. Returns 0 on success or -1 on failure.
int otbn_model_send_err_escalation(OtbnModel *model,
                                   svBitVecVal *err_val /* bit [31:0] */,
                                   svBit lock_immediately);

// Trigger RMA request in model
int otbn_model_send_rma_req(OtbnModel *model);

// Trigger initial secure wipe.
int otbn_model_initial_secure_wipe(OtbnModel *model);
}

#endif  // OPENTITAN_HW_IP_OTBN_DV_MODEL_OTBN_MODEL_DPI_H_


text:
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.integrations.javaee;

import com.intellij.openapi.externalSystem.model.DataNode;
import com.intellij.openapi.externalSystem.model.ProjectKeys;
import com.intellij.openapi.externalSystem.model.project.*;
import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
import com.intellij.openapi.externalSystem.util.Order;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.util.NotNullLazyValue;
import com.intellij.openapi.util.Pair;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.Function;
import com.intellij.util.containers.ContainerUtil;
import gnu.trove.THashMap;
import org.gradle.tooling.model.idea.IdeaModule;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.plugins.gradle.model.ExternalDependency;
import org.jetbrains.plugins.gradle.model.ExternalProject;
import org.jetbrains.plugins.gradle.model.ExternalSourceSet;
import org.jetbrains.plugins.gradle.model.data.*;
import org.jetbrains.plugins.gradle.model.ear.EarConfiguration;
import org.jetbrains.plugins.gradle.model.web.WebConfiguration;
import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension;
import org.jetbrains.plugins.gradle.service.project.LibraryDataNodeSubstitutor;
import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext;
import org.jetbrains.plugins.gradle.util.GradleConstants;

import java.io.File;
import java.util.*;

import static com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.findAllRecursively;
import static com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil.toCanonicalPath;
import static org.jetbrains.plugins.gradle.service.project.GradleProjectResolver.*;
import static org.jetbrains.plugins.gradle.service.project.GradleProjectResolverUtil.buildDependencies;

/**
 * {@link JavaEEGradleProjectResolverExtension} provides JavaEE project info based on gradle tooling API models.
 *
 * @author Vladislav.Soroka
 */
@Order(ExternalSystemConstants.UNORDERED)
public class JavaEEGradleProjectResolverExtension extends AbstractProjectResolverExtension {
  private static final Key<Map<String/* artifact path */, String /* module id*/>> ARCHIVES_ARTIFACTS = Key.create("archivesArtifactsMap");
  private static final Key<List<Pair<DataNode<? extends ModuleData>, EarConfiguration>>> EAR_CONFIGURATIONS =
    Key.create("earConfigurations");

  @Override
  public void populateModuleExtraModels(@NotNull IdeaModule gradleModule, @NotNull final DataNode<ModuleData> ideModule) {
    DataNode<ProjectData> projectDataNode = ideModule.getParent(ProjectData.class);
    NotNullLazyValue<DataNode<? extends ModuleData>> findTargetModuleNode = new NotNullLazyValue<DataNode<? extends ModuleData>>() {
      @NotNull
      @Override
      protected DataNode<? extends ModuleData> compute() {
        final String mainSourceSetModuleId = ideModule.getData().getId() + ":main";
        DataNode<? extends ModuleData> targetModuleNode =
          ExternalSystemApiUtil.find(ideModule, GradleSourceSetData.KEY, node -> mainSourceSetModuleId.equals(node.getData().getId()));
        if (targetModuleNode == null) {
          targetModuleNode = ideModule;
        }
        return targetModuleNode;
      }
    };

    Map<String/* artifact path */, String /* module id*/> archivesMap;
    if (projectDataNode != null) {
      archivesMap = projectDataNode.getUserData(ARCHIVES_ARTIFACTS);
      if (archivesMap == null) {
        archivesMap = new THashMap<>(FileUtil.PATH_HASHING_STRATEGY);
        projectDataNode.putUserData(ARCHIVES_ARTIFACTS, archivesMap);
      }

      ExternalProject externalProject = resolverCtx.getExtraProject(gradleModule, ExternalProject.class);
      if (externalProject != null) {
        if (externalProject.getArtifactsByConfiguration().get("archives") != null) {
          final Set<File> archivesArtifacts = new HashSet<>(externalProject.getArtifactsByConfiguration().get("archives"));
          final Set<File> testsArtifacts = externalProject.getArtifactsByConfiguration().get("tests");
          if (testsArtifacts != null) {
            archivesArtifacts.removeAll(testsArtifacts);
          }

          for (File artifactFile : archivesArtifacts) {
            archivesMap.put(toCanonicalPath(artifactFile.getAbsolutePath()), findTargetModuleNode.getValue().getData().getId());
          }
        }
      }
    }

    final WebConfiguration webConfiguration = resolverCtx.getExtraProject(gradleModule, WebConfiguration.class);

    if (webConfiguration != null) {
      final List<War> warModels = ContainerUtil.map(webConfiguration.getWarModels(), (Function<WebConfiguration.WarModel, War>)model -> {
        War war = new War(model.getWarName(), model.getWebAppDirName(), model.getWebAppDir());
        war.setWebXml(model.getWebXml());
        war.setWebResources(mapWebResources(model.getWebResources()));
        war.setClasspath(model.getClasspath());
        war.setManifestContent(model.getManifestContent());
        war.setArchivePath(model.getArchivePath());
        return war;
      });
      findTargetModuleNode.getValue().createChild(
        WebConfigurationModelData.KEY, new WebConfigurationModelData(GradleConstants.SYSTEM_ID, warModels));
    }

    final EarConfiguration earConfiguration = resolverCtx.getExtraProject(gradleModule, EarConfiguration.class);
    if (earConfiguration != null) {
      if (projectDataNode != null) {
        List<Pair<DataNode<? extends ModuleData>, EarConfiguration>> ears = projectDataNode.getUserData(EAR_CONFIGURATIONS);
        if (ears == null) {
          ears = new ArrayList<>();
          projectDataNode.putUserData(EAR_CONFIGURATIONS, ears);
        }
        ears.add(Pair.create(findTargetModuleNode.getValue(), earConfiguration));
      }
    }
    nextResolver.populateModuleExtraModels(gradleModule, ideModule);
  }

  @NotNull
  @Override
  public Set<Class<?>> getExtraProjectModelClasses() {
    return ContainerUtil.set(WebConfiguration.class, EarConfiguration.class);
  }

  @Override
  public void resolveFinished(@NotNull DataNode<ProjectData> projectDataNode) {
    List<Pair<DataNode<? extends ModuleData>, EarConfiguration>> earConfigurations = projectDataNode.getUserData(EAR_CONFIGURATIONS);
    if (earConfigurations == null) return;
    for (Pair<DataNode<? extends ModuleData>, EarConfiguration> pair : earConfigurations) {
      DataNode<? extends ModuleData> moduleNode = pair.first;
      EarConfiguration earConfiguration = pair.second;
      final List<Ear> warModels = ContainerUtil.map(earConfiguration.getEarModels(), (Function<EarConfiguration.EarModel, Ear>)model -> {
        Ear ear = new Ear(model.getEarName(), model.getAppDirName(), model.getLibDirName());
        ear.setManifestContent(model.getManifestContent());
        ear.setDeploymentDescriptor(model.getDeploymentDescriptor());
        ear.setResources(mapEarResources(model.getResources()));
        ear.setArchivePath(model.getArchivePath());
        return ear;
      });

      final Collection<DependencyData> deployDependencies = getDependencies(
        resolverCtx, projectDataNode, moduleNode, earConfiguration.getDeployDependencies());
      final Collection<DependencyData> earlibDependencies = getDependencies(
        resolverCtx, projectDataNode, moduleNode, earConfiguration.getEarlibDependencies());
      moduleNode.createChild(EarConfigurationModelData.KEY,
                             new EarConfigurationModelData(GradleConstants.SYSTEM_ID, warModels, deployDependencies, earlibDependencies));
    }
  }

  private static List<WebResource> mapWebResources(List<WebConfiguration.WebResource> webResources) {
    return ContainerUtil.mapNotNull(webResources, resource -> {
      if (resource == null) return null;

      final WarDirectory warDirectory = WarDirectory.fromPath(resource.getWarDirectory());
      return new WebResource(warDirectory, resource.getRelativePath(), resource.getFile());
    });
  }

  private static List<EarResource> mapEarResources(List<EarConfiguration.EarResource> resources) {
    return ContainerUtil.mapNotNull(resources, resource -> {
      if (resource == null) return null;

      return new EarResource(resource.getEarDirectory(), resource.getRelativePath(), resource.getFile());
    });
  }

  @SuppressWarnings("unchecked")
  private static Collection<DependencyData> getDependencies(@NotNull ProjectResolverContext resolverCtx,
                                                            @NotNull DataNode<ProjectData> ideProject,
                                                            @NotNull DataNode<? extends ModuleData> moduleDataNode,
                                                            @NotNull Collection<ExternalDependency> dependencies)
    throws IllegalStateException {

    final Map<String, Pair<String, ExternalSystemSourceType>> moduleOutputsMap =
      ideProject.getUserData(MODULES_OUTPUTS);
    assert moduleOutputsMap != null;

    final Map<String, Pair<DataNode<GradleSourceSetData>, ExternalSourceSet>> sourceSetMap =
      ideProject.getUserData(RESOLVED_SOURCE_SETS);
    assert sourceSetMap != null;

    final Map<String, String> artifactsMap = ideProject.getUserData(CONFIGURATION_ARTIFACTS);
    assert artifactsMap != null;

    final Map<String, String> allArtifactsMap;
    final Map<String, String> archivesMap = ideProject.getUserData(ARCHIVES_ARTIFACTS);
    if (archivesMap != null && !archivesMap.isEmpty()) {
      allArtifactsMap = new THashMap<>(FileUtil.PATH_HASHING_STRATEGY);
      allArtifactsMap.putAll(artifactsMap);
      allArtifactsMap.putAll(archivesMap);
    }
    else {
      allArtifactsMap = artifactsMap;
    }

    DataNode fakeNode = new DataNode(moduleDataNode.getKey(), moduleDataNode.getData(), null);
    buildDependencies(resolverCtx, sourceSetMap, allArtifactsMap, fakeNode, dependencies, null);

    LibraryDataNodeSubstitutor librarySubstitutor =
      new LibraryDataNodeSubstitutor(resolverCtx, null, null, null, sourceSetMap, moduleOutputsMap, artifactsMap);
    final Collection<DataNode<LibraryDependencyData>> libraryDependencies = findAllRecursively(fakeNode, ProjectKeys.LIBRARY_DEPENDENCY);
    for (DataNode<LibraryDependencyData> libraryDependencyDataNode : libraryDependencies) {
      librarySubstitutor.run(libraryDependencyDataNode);
    }

    final Collection<DataNode<?>> dataNodes = findAllRecursively(fakeNode, node -> node.getData() instanceof DependencyData);
    return ContainerUtil.map(dataNodes, node -> (DependencyData)node.getData());
  }
}


text:
package shugal.com.mattendance;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Calendar;
import java.util.List;

public class TodayAttendance extends AppCompatActivity {

    ListView lectureList;
    TextView mark;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_today_attendance);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("Mark Todays's attendance");

        mark = (TextView) findViewById(R.id.mark);
        Typeface tf= Typeface.createFromAsset(getAssets(), "fonts/empty_list.ttf");
        mark.setTypeface(tf);

        lectureList = (ListView) findViewById(R.id.list_of_lectures);
        printLectures();

        lectureList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                LectureData data = (LectureData) parent.getItemAtPosition(position);
                startEditDialog(data);
            }
        });

    }

    String makeDate(int day_of_month, int month, int year) {
        String date = day_of_month + " " + makeMonth(month) + " " + year;
        return date;
    }

    private String makeMonth(int month) {
        String mMonth = "";
        if (month == 1) {
            mMonth = "January";
        } else if (month == 2) {
            mMonth = "February";
        } else if (month == 3) {
            mMonth = "March";
        } else if (month == 4){
            mMonth = "April";
        } else if (month == 5) {
            mMonth = "May";
        } else if (month == 6) {
            mMonth = "June";
        } else if (month == 7) {
            mMonth = "July";
        } else if (month == 8) {
            mMonth = "August";
        } else if (month == 9) {
            mMonth = "September";
        } else if (month == 10) {
            mMonth = "October";
        } else if (month == 11) {
            mMonth = "November";
        } else if (month == 12) {
            mMonth = "December";
        }

        return mMonth;
    }

    private void startEditDialog(final LectureData data) {
        final Context context = this;
        LayoutInflater inflater = LayoutInflater.from(context);

        Calendar calender = Calendar.getInstance();
        int Year = calender.get(Calendar.YEAR),
                Month = calender.get(Calendar.MONTH),
                Day = calender.get(Calendar.DAY_OF_MONTH);

        String date = makeDate(Day, (Month + 1), Year);

        View dialogView = inflater.inflate(R.layout.attendance_dialog, null);

        final AlertDialog.Builder customEventDialog = new AlertDialog.Builder(context);

        final RadioButton presentBtn = (RadioButton) dialogView.findViewById(R.id.presentBtn);
        final RadioButton absentBtn = (RadioButton) dialogView.findViewById(R.id.absentBtn);

        final DatewiseData ddta = new DatewiseData();
        ddta.setSubject(data.get_lecture_name());
        ddta.setDate(date);
        customEventDialog.setView(dialogView);
        customEventDialog.setTitle(data.get_lecture_name());
        customEventDialog.setCancelable(true);
        customEventDialog.setPositiveButton("Mark", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                DatabaseHelper db = new DatabaseHelper(context);
                if (presentBtn.isChecked()) {
                    Toast.makeText(getApplicationContext(), "Present Marked", Toast.LENGTH_SHORT).show();
                    ddta.setStatus("Present");
                    db.addDatewiseDatta(ddta);
                    db.updatePresents(data);
                } else if (absentBtn.isChecked()) {
                    Toast.makeText(getApplicationContext(), "Absent Marked", Toast.LENGTH_SHORT).show();
                    ddta.setStatus("Absent");
                    db.addDatewiseDatta(ddta);
                    db.updateAbsents(data);
                } else {
                    Toast.makeText(getApplicationContext(), "No Class for Today", Toast.LENGTH_SHORT).show();
                }
                db.close();
                printLectures();
            }
        }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        customEventDialog.create().show();
    }

    private void printLectures() {

        DatabaseHelper db = new DatabaseHelper(this);

        //Gets date from this activity

        View emptyLinearLayout = findViewById(R.id.frame);

        if (db.isLectureListEmpty()) {
            lectureList.setVisibility(View.GONE);
            emptyLinearLayout.setVisibility(View.VISIBLE);
            TextView emptyText = (TextView) findViewById(R.id.emptyListText);
            Typeface tf= Typeface.createFromAsset(getAssets(), "fonts/empty_list.ttf");
            emptyText.setTypeface(tf);

        } else {
            emptyLinearLayout.setVisibility(View.GONE);
            lectureList.setVisibility(View.VISIBLE);
            List<LectureData> contacts = db.showAllLectures();

            TodayAttendanceCustomListAdapter adapter =
                    new TodayAttendanceCustomListAdapter(getApplicationContext(), contacts);
            lectureList.setAdapter(adapter);
        }

        db.close();
    }

}


text:
    if (typeof define === 'function' && define.amd) {
        define("c3", ["d3"], function () { return c3; });
    } else if ('undefined' !== typeof exports && 'undefined' !== typeof module) {
        module.exports = c3;
    } else {
        window.c3 = c3;
    }

})(window);


text:
int pnpoly(int nvert, float *vertx, float *verty, float testx, float testy)
{
  int i, j, c = 0;
  for (i = 0, j = nvert-1; i < nvert; j = i++) {
    if ( ((verty[i]>testy) != (verty[j]>testy)) &&
	 (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
       c = !c;
  }
  return c;
}

Argument	Meaning
nvert 	Number of vertices in the polygon. Whether to repeat the first vertex at the end is discussed below.
vertx, verty 	Arrays containing the x- and y-coordinates of the polygon's vertices.
testx, testy	X- and y-coordinate of the test point.


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<title>Essence - ReactJS Material Design Framework</title>
	<link rel="stylesheet" type="text/css" href="app.css">
  <link href='https://fonts.googleapis.com/css?family=Roboto:400,700,700italic,300italic,300,500,500italic,100italic,100,400italic' rel='stylesheet' type='text/css'>
  <link href='https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700,700italic,300italic,400italic' rel='stylesheet' type='text/css'>


text:
using PetCenter.Referencias.Dominio.Administracion.DTOs.Registros.Solicitud;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PetCenter.Referencias.Dominio.Administracion.DTOs.Registros.Convenio
{
    public class RegistrarConvenioDto
    {
        public ConvenioDto Convenio { get; set; }
        public SolicitudDto Solicitud { get; set; }
    }
}


text:
title: Partials and Layouts
---

## Render Partials

For the following template files:

```
// file: color.liquid
color: '{{ color }}' shape: '{{ shape }}'

// file: theme.liquid
{% assign shape = 'circle' %}
{% render 'color.liquid' %}
{% render 'color.liquid' with 'red' %}
{% render 'color.liquid', color: 'yellow', shape: 'square' %}
```

The output will be:

```
color: '' shape: 'circle'
color: 'red' shape: 'circle'
color: 'yellow' shape: 'square'
```

More details please refer to the [render](../tags/render.html) tag.

{% note tip The ".liquid" Extension %}
The ".liquid" extension in layout, render and include an be omitted if Liquid instance is created using `extname: ".liquid"` option. See the extname option for details.
{% endnote %}

## Layout Templates (Extends)

For the following template files:

```
// file: default-layout.liquid
Header
{% block content %}My default content{% endblock %}
Footer

// file: page.liquid
{% layout "default-layout.liquid" %}
{% block content %}My page content{% endblock %}
```

The output of `page.liquid`:

```
Header
My page content
Footer
```

More details please refer to the [layout](../tags/layout.html) tag.


text:
'use strict';

import {describe, it} from 'mocha';
import {expect} from 'chai';
import Strings from '../../src/main/Strings';

/**
 * @test {Strings.asString}
 */
describe('Testing static function Objects.asString', () => {
    it('should return an empty string if the input is undefined', () =>
        expect(Strings.asString(undefined))
                .to.eql('')
    );

    it('should return an empty string if the input is null', () =>
        expect(Strings.asString(null))
                .to.eql('')
    );

    it('should return an empty string if the input is an empty string', () =>
        expect(Strings.asString(''))
                .to.eql('')
    );

    it('should return an equal string if the input is a non-empty string', () =>
        expect(Strings.asString('some-text'))
                .to.eql('some-text')
    );

    it('should integer numbers to their corresponding string representations', () =>
        expect(Strings.asString(42))
                .to.eql('42')
    );

    it('should floating-point numbers to their corresponding string representations', () =>
        expect(Strings.asString(42.420))
                .to.eql('42.42')
    );

    it('should return the result of the toString method if the input is a real object', () =>
        expect(Strings.asString({toString: () => 'the-toString-result'}))
                .to.eql('the-toString-result')
    );

    it('should return a string even if the toString method of the input objects itself does not return a string', () =>
        expect(Strings.asString({toString: () => undefined}))
                .to.eql('')
    );
});

/**
 * @test {String.trim}
 */
describe('Testing static function Strings.trim', () => {
    it('should trim a non-empty string correctly', () =>
        expect(Strings.trim('   some-text  '))
                .to.eql('some-text')
    );

    it('should return an equal string if the input string does not have leading or trailing whitespace', () =>
        expect(Strings.trim('some-text'))
                .to.eql('some-text')
    );

    it('should return an empty string if the input is undefined', () =>
        expect(Strings.trim(undefined))
                .to.eql('')
    );

    it('should return an empty string if the input is an empty string', () =>
        expect(Strings.trim(''))
                .to.eql('')
    );

    it('should return an empty string if the input is null', () =>
        expect(Strings.trim(null))
                .to.eql('')
    );

    it('should return the result of the toString() method if a real object is provided as input', () =>
        expect(Strings.trim({toString: () => 'the-toString-result'}))
                .to.eql('the-toString-result')
    );
});

/**
 * @test {Strings.trimToNull}
 */
describe('Testing static function Strings.trimToNull', () => {
    it('should trim a non-empty string with leading or trailing whitespace correctly', () =>
        expect(Strings.trimToNull('   some-text  '))
              .to.eql('some-text')
    );

    it('should return an equal string if the input string does not have leading or trailing whitespace', () =>
        expect(Strings.trimToNull('some-text'))
                .to.eql('some-text')
    );

    it('should return null if the input is undefined', () =>
        expect(Strings.trimToNull(undefined))
                .to.eql(null)
    );

    it('should return null if the input is an empty string', () =>
        expect(Strings.trimToNull(''))
                .to.eql(null)
    );

    it('should return null if the input is null', () =>
        expect(Strings.trimToNull(null))
                .to.eql(null)
    );

    it('should return the result of the toString() method if a real object is provided as input', () =>
        expect(Strings.trimToNull({toString: () => 'the-toString-result'}))
                .to.eql('the-toString-result')
    );
});


text:
import controller from './ngbBlastWholeGenomeView.controller';

export default {
    bindings: {
        chromosomes: '<',
        blastResult:'<',
    },
    restrict: 'EA',
    template: require('./ngbBlastWholeGenomeView.tpl.html'),
    controller: controller.UID,
};


text:
using System.IO;

namespace LegendaryClient.Logic.SWF.SWFTypes
{
    public class End : Tag
    {
        public End()
        {
            this.TagCode = (int)TagCodes.End;
        }

        public override void ReadData(byte version, BinaryReader binaryReader)
        {
            RecordHeader rh = new RecordHeader();
            rh.ReadData(binaryReader);
        }
    }
}


text:
<?php

declare(strict_types=1);

namespace App\Form\Type;

use App\Entity\Group;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Vich\UploaderBundle\Form\Type\VichImageType;

class GroupType extends AbstractType
{
    /**
     * @inheritDoc
     */
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('description', TextareaType::class, [
                'required' => true,
                'attr' => [
                    'maxlength' => 200,
                    'rows' => 3,
                    'autofocus' => true,
                ],
                'help' => 'Máximo 200 caracteres.',
            ])
            ->add('imageFile', VichImageType::class, [
                'label' => 'Imagen de perfil (relación 2:1, min. 1200x600)',
                'required' => true,
                'allow_delete' => false,
                'delete_label' => '¿Borrar?',
                'download_label' => 'Descargar',
                'download_uri' => false,
                'image_uri' => false,
                'imagine_pattern' => 'opengraph_thumbnail',
            ]);
    }

    public function configureOptions(OptionsResolver $resolver): void
    {
        $resolver
            ->setDefaults([
                'data_class' => Group::class,
            ]);
    }
}


text:
var path = require("path");
var url = require("url");
var processor = require("./processor");

// This middleware works with Express to compile LESS files.
//
// Options:
//  - "middleware_match": ...
//  - "middleware_map"  : ...
//  - "base" : The base input directory to map URLs to LESS files.  See the [tests](./test/middleware.js) for usage details.
//  - "base_out" : The base output directory to map URLs to CSS files.
//  - "less" : An object passed directly to the [less Parser](https://github.com/less/less.js/#configuration).
/* Middleware */

// Default configuration
var _defaults = {
    // default matcher assumes requests for CSS
    "middleware_match": function(raw_url) {
        return /\.css$/.test(url.parse(raw_url).pathname);
    },
    // default mapper assumes CSS and LESS are side-by-side in directory
    "middleware_map": function(raw_url, pathname) {
        return {
            "input": path.join(__dirname, pathname).replace(/\.css$/, ".less"),
            "output": path.join(__dirname, pathname)
        };
    },
    "less": {}
};

function map_generator(base_in, base_out) {
    return function(raw_url, pathname) {
        return {
            "input": path.join(base_in, pathname).replace(/\.css$/, ".less"),
            "output": path.join(base_out || base_in, pathname)
        };
    };
}

module.exports = function(options) {

    // ensure options
    options = options || {};

    // helper function can generate a mapper, given some base directories
    if(!options.hasOwnProperty("middleware_map") && options.base) {
        options["middleware_map"] = map_generator(options.base, options.base_out);
    }

    // copy defaults onto options
    for(var p in _defaults) {
        if(_defaults.hasOwnProperty(p) && !options.hasOwnProperty(p)) { options[p] = _defaults[p]; }
    }

    // return handler
    return function (req, res, next) {

        var pathname = url.parse(req.url).pathname;
        if(options.middleware_match(req.url)) {

            var io = options.middleware_map(req.url, pathname);
            processor.generate(io.input, io.output, options, next);
        } else {
            next();
        }
    };
}


text:
<?php

namespace JDare\Acetone;

use Illuminate\Support\ServiceProvider;

class AcetoneServiceProvider extends ServiceProvider {

	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = false;

	/**
	 * Bootstrap the application events.
	 *
	 * @return void
	 */
	public function boot()
	{
		$this->package('jdare/acetone');
	}

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
        $this->app->booting(function()
        {
            $loader = \Illuminate\Foundation\AliasLoader::getInstance();
            $loader->alias('Acetone', 'JDare\Acetone\Facades\Acetone');
        });

        $this->app['acetone'] = $this->app->share(function($app)
        {
            return new Acetone;
        });
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides()
	{
		return array("acetone");
	}

}


text:
<?php
/**
 * User: Joe Linn
 * Date: 3/20/2014
 * Time: 3:00 PM
 */

error_reporting(E_ALL | E_STRICT);

//composer autoloader
$autoloader = require dirname(__DIR__) . '/../../autoload.php';

// doctrine annotations autoloader for serializer
\Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespace('JMS\Serializer\Annotation', dirname(__DIR__) . '/vendor/jms/serializer/src');


text:
package org.codemucker.jmutate.transform;

import static com.google.common.base.Preconditions.checkNotNull;

import java.io.IOException;
import java.io.InputStream;
import java.util.Comparator;

import org.apache.commons.io.IOUtils;
import org.codemucker.jmutate.DefaultMutateContext;
import org.codemucker.jmutate.JMutateContext;
import org.codemucker.jmutate.JMutateException;
import org.codemucker.jmutate.SourceTemplate;
import org.codemucker.jmutate.util.SourceAsserts;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.junit.Test;

public class CleanImportsTransformTest {

	JMutateContext ctxt = DefaultMutateContext.with().defaults().build();

	@Test
	public void test_add_imports(){
		testTransform("add_imports");
	}

	@Test
	public void test_existing_imports_only(){
		CleanImportsTransform transform = ctxt.obtain(CleanImportsTransform.class).addMissingImports(false);
		testTransform("existing_imports_only",transform);
	}

	@Test
	public void bug_import_full_name_for_static_inner_classes(){
		testTransform("inner_class_imports");
	}

	@Test
	public void bug_clean_annotations(){
		testTransform("annotation_imports");
	}

	@Test
	public void qualified_fieldtype(){
		testTransform("qualified_fieldtype");
	}

	@Test
	public void array_types(){
		testTransform("array_types");
	}

	@Test
	public void ignore_if_local_types_clash(){
		testTransform("ignore_if_local_types_clash");
	}

	@Test
	public void ignore_if_inner_types_clash(){
		testTransform("ignore_if_inner_types_clash");
	}

	@Test
	public void nested_classes(){
		testTransform("nested_classes");
	}

	private void testTransform(String filename){
		CleanImportsTransform transform = ctxt.obtain(CleanImportsTransform.class);
		testTransform(filename,transform);
	}

	private void testTransform(String filename, CleanImportsTransform transform){
		CompilationUnit actual = readTemplate(filename + ".before").asResolvedCompilationUnitNamed(null);
		CompilationUnit expected = readTemplate(filename + ".after").asResolvedCompilationUnitNamed(null);

		//do the actual import clean
		transform
			.nodeToClean(actual)
			.transform();

		SourceAsserts.assertAstsMatch(expected, actual);
	}

//	@Test
//	public  void genCode(){
//		System.out.println("runnign code gen");
//		ClassScanner scanner = ClassScanner.with()
//				.scanRoots(Roots.with().all().build())
//				.filter(ClassFilter.where()
//						.resourceMatches(ARootResource.with().packageName("org.eclipse.jdt.core.dom"))
//						.classMatches(AClass.that().isASubclassOf(ASTNode.class).isNotAbstract()))
//				.build();
//		List<Class<?>> classes = scanner.findClasses().toList();
//		Collections.sort(classes, new ClassNameSorter());
//		for(Class<?> c:classes){
//			System.out.println("else if( node instanceof " + c.getName() + ") { return visit(("+ c.getName()+")node);}");
//		}
//	}

	static class ClassNameSorter implements Comparator<Class<?>> {

		@Override
		public int compare(Class<?> left, Class<?> right) {
			return left.getSimpleName().compareTo(right.getSimpleName());
		}

	}

	private SourceTemplate readTemplate(String template){
		return ctxt.newSourceTemplate().p(readTemplateAsString(template));
	}

	private String readTemplateAsString(String template){
		String path = getClass().getSimpleName() + ".java." + template;
		InputStream is = null;
		try {
			is = getClass().getResourceAsStream(path);
			checkNotNull(is,"couldn't find template:" + path);
			return IOUtils.toString(is,"UTF-8");
		} catch (IOException e){
			throw new JMutateException("error reading template path:" + path,e);
		} finally {
			IOUtils.closeQuietly(is);
		}
	}
}


text:
"""
RSDK Smoke Test Execution
"""
import sys
import time
import argparse
import re
import socket
import traceback

import rospy

from baxter_tools import smoketests

def run_test(tname, fname, proceed):
    """
    Execution of the tests where starting, finishing and error handeling
    occurs.
    """
    try:
        cur_test = getattr(smoketests, tname)(tname)
    except AttributeError:
        print("Exiting: %s is not a valid smoke test." % tname)
        sys.exit(1)
    except:
        print("Exiting: failed during intialization.")
        traceback.print_exc()
        sys.exit(1)

    cur_test.start_test()
    cur_test.finish_test(fname)
    if (not proceed and cur_test.result[0] == False or
    'KeyboardInterrupt' in cur_test.result[1]):
        print("Exiting: Failed Test %s" % tname)
        sys.exit(1)

def test_help():
    """
    Help text for argparse describing available sdk tests.
    """
    return """Specify an individual test for execution
    TESTS:
    Enable    - Verify ability to enable, check state and disable baxter
    Messages  - Verify messages being published and ability to subscribe
    Services  - Verify services available and ability to make calls as client
    Head      - Move the head pan and tilt, display image to screen
    MoveArms  - Move both arms through entire joint range
    Grippers  - Calibrate and move grippers using position and velocity control
    BlinkLEDs - Blink Navigator LEDs
    Cameras   - Verify camera publishing and visualization
    """

def get_version():
    """
    Get current software version number from param server.
    """
    try:
        version = rospy.get_param('/rethink/software_version').rsplit('.', 1)[0]
    except socket.error:
        print("Exiting: Could not communicate with ROS Master to determine " +
              "Software version")
        sys.exit(1)
    except:
        print("Exiting: Could not determine SW version from param " +
            "'/rethink/software_version'")
        sys.exit(1)
    return version

def ros_init():
    """
    Initialize rsdk_smoke_test ros node.
    """
    print("Initializing node 'rsdk_smoke_test'\n")
    rospy.init_node('rsdk_smoke_test', disable_signals=True)

def main():
    format = argparse.RawTextHelpFormatter
    parser = argparse.ArgumentParser(formatter_class=format)
    parser.add_argument('-p', '--proceed', action='store_true',
        help="Continue testing after a failed test until all tests complete")
    parser.add_argument('-t', '--test', help=test_help())
    args = parser.parse_args(rospy.myargv()[1:])

    test_dict = {
        'version': None,
        'valid_tests': {
            '0.7.0': ['Enable', 'Messages', 'Services', 'Head', 'BlinkLEDs',
                      'Cameras'],
            '1.0.0': ['Enable', 'Messages', 'Services', 'Head', 'MoveArms',
                      'Grippers', 'BlinkLEDs', 'Cameras'],
            '1.1.0': ['Enable', 'Messages', 'Services', 'Head', 'MoveArms',
                      'Grippers', 'BlinkLEDs', 'Cameras'],
            '1.1.1': ['Enable', 'Messages', 'Services', 'Head', 'MoveArms',
                      'Grippers', 'BlinkLEDs', 'Cameras'],
            '1.2.0': ['Enable', 'Messages', 'Services', 'Head', 'MoveArms',
                      'Grippers', 'BlinkLEDs', 'Cameras'],
            }
        }

    test_dict['version'] = get_version()
    if not test_dict['version'] in test_dict['valid_tests'].keys():
        print("Exiting: No tests specified for your software version: %s" %
            (test_dict['version']))
        return 1

    try:
        raw_input("Press <Enter> to Begin Smoke Test\n")
    except Exception:
        print("\nExiting.")
        return 1

    serial = rospy.get_param("manifest/robot_serial")
    cur_time = time.localtime()
    filename = ("%s-%s.%s.%s-rsdk-%s.smoketest" %
                (serial, cur_time.tm_mon, cur_time.tm_mday,
                 cur_time.tm_year, test_dict['version'],)
                )
    if args.test == None:
        print 'Performing All Tests'
        ros_init()
        for t in test_dict['valid_tests'][test_dict['version']]:
            run_test(t, filename, args.proceed)
    elif args.test in test_dict['valid_tests'][test_dict['version']]:
        ros_init()
        run_test(args.test, filename, args.proceed)
    else:
        print("Exiting: Invalid test provided: %s for %s version software" %
              (args.test, test_dict['version']))
        parser.print_help()

    return 0

if __name__ == '__main__':
    sys.exit(main())


text:
"use strict";

const webpack = require("webpack");
const path = require("path");

// ********************
// Common configuration
// ********************

const config = {
	entry: {
		"js/bundle.js": path.resolve(__dirname, "client/js/lounge.js"),
	},
	devtool: "source-map",
	output: {
		path: path.resolve(__dirname, "client"),
		filename: "[name]",
		publicPath: "/"
	},
	module: {
		rules: [
			{
				test: /\.js$/,
				include: [
					path.resolve(__dirname, "client"),
				],
				use: {
					loader: "babel-loader",
					options: {
						presets: [
							["env", {
								targets: {
									browsers: "last 2 versions"
								}
							}]
						]
					}
				}
			},
			{
				test: /\.tpl$/,
				include: [
					path.resolve(__dirname, "client/views"),
				],
				use: {
					loader: "handlebars-loader",
					options: {
						helperDirs: [
							path.resolve(__dirname, "client/js/libs/handlebars")
						],
						extensions: [
							".tpl"
						],
					}
				}
			},
		]
	},
	externals: {
		json3: "JSON", // socket.io uses json3.js, but we do not target any browsers that need it
	},
	plugins: [
		// socket.io uses debug, we don't need it
		new webpack.NormalModuleReplacementPlugin(/debug/, path.resolve(__dirname, "scripts/noop.js")),
		// automatically split all vendor dependancies into a separate bundle
		new webpack.optimize.CommonsChunkPlugin({
			name: "js/bundle.vendor.js",
			minChunks: (module) => module.context && module.context.indexOf("node_modules") !== -1
		})
	]
};

// *********************************
// Production-specific configuration
// *********************************

if (process.env.NODE_ENV === "production") {
	config.plugins.push(new webpack.optimize.UglifyJsPlugin({
		sourceMap: true,
		comments: false
	}));
} else {
	console.log("Building in development mode, bundles will not be minified.");
}

module.exports = config;


text:
using FakeItEasy;
using Microsoft.Xna.Framework;
using NUnit.Framework;
using Shouldly;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CellSpacePartitionLib.Tests
{
	[TestFixture]
	public class AddEntityTests
	{
		[Test]
		public void AddEntity()
		{
			var partition = new TestCellSpacePartition(new Vector2(0, 0), 10, 10, 10);

			//create a fake item
			var entity = A.Fake<Mover>();
			A.CallTo(() => entity.Position).Returns(new Vector2(25.0f, 15.0f));

			//add the item
			partition.Add(entity);

			//make sure it went in the correct spot
			partition.TestCells[12].Items.Count.ShouldBe(1);
		}

		[TestCase(-25f, 15f)]
		[TestCase(25f, -15f)]
		[TestCase(-25f, -15f)]
		[TestCase(250f, 15f)]
		[TestCase(25f, 150f)]
		[TestCase(250f, 150f)]
		public void AddEntityFloater(float x, float y)
		{
			var partition = new TestCellSpacePartition(new Vector2(0, 0), 10, 10, 10);

			//create a fake item
			var entity = A.Fake<Mover>();
			A.CallTo(() => entity.Position).Returns(new Vector2(x, y));

			//add the item
			partition.Add(entity);

			//make sure it went in the correct spot
			partition.TestCells[12].Items.Count.ShouldBe(0);
			partition.TestFloaters.Count.ShouldBe(1);
		}

		[Test]
		public void RemoveEntity()
		{
			var partition = new TestCellSpacePartition(new Vector2(0, 0), 10, 10, 10);

			var entity = A.Fake<Mover>();
			A.CallTo(() => entity.Position).Returns(new Vector2(25.0f, 15.0f));
			partition.Add(entity);

			//remove the item
			partition.Remove(entity);

			//make sure it went in the correct spot
			Assert.AreEqual(0, partition.TestCells[12].Items.Count);
		}

		[Test]
		public void UpdateEntityRemoveOld()
		{
			var partition = new TestCellSpacePartition(new Vector2(0, 0), 10, 10, 10);

			//create a fake item
			var entity = A.Fake<Mover>();
			A.CallTo(() => entity.Position).Returns(new Vector2(25.0f, 15.0f));

			//add the item
			partition.Add(entity);

			//make sure it went in the correct spot
			Assert.AreEqual(1, partition.TestCells[12].Items.Count);

			//move the entity
			A.CallTo(() => entity.OldPosition).Returns(new Vector2(25.0f, 15.0f));
			A.CallTo(() => entity.Position).Returns(new Vector2(35.0f, 15.0f));
			partition.Update(entity);

			//make sure it removed the old object and added the new spot
			Assert.AreEqual(0, partition.TestCells[12].Items.Count);
		}

		[Test]
		public void UpdateEntityAddToNewSpot()
		{
			var partition = new TestCellSpacePartition(new Vector2(0, 0), 10, 10, 10);

			//create a fake item
			var entity = A.Fake<Mover>();
			A.CallTo(() => entity.Position).Returns(new Vector2(25.0f, 15.0f));

			//add the item
			partition.Add(entity);

			//make sure it went in the correct spot
			Assert.AreEqual(1, partition.TestCells[12].Items.Count);

			//move the entity
			A.CallTo(() => entity.OldPosition).Returns(new Vector2(25.0f, 15.0f));
			A.CallTo(() => entity.Position).Returns(new Vector2(35.0f, 15.0f));
			partition.Update(entity);

			//make sure it removed the old object and added the new spot
			Assert.AreEqual(0, partition.TestCells[12].Items.Count);
			Assert.AreEqual(1, partition.TestCells[13].Items.Count);
		}

		[Test]
		public void UpdateEntityToFloater()
		{
			var partition = new TestCellSpacePartition(new Vector2(0, 0), 10, 10, 10);

			//create a fake item
			var entity = A.Fake<Mover>();
			A.CallTo(() => entity.Position).Returns(new Vector2(25.0f, 15.0f));

			//add the item
			partition.Add(entity);

			//make sure it went in the correct spot
			Assert.AreEqual(1, partition.TestCells[12].Items.Count);

			//move the entity
			A.CallTo(() => entity.OldPosition).Returns(new Vector2(25.0f, 15.0f));
			A.CallTo(() => entity.Position).Returns(new Vector2(-35.0f, 15.0f));
			partition.Update(entity);

			//make sure it removed the old object and added the new spot
			partition.TestCells[12].Items.Count.ShouldBe(0);
			partition.TestFloaters.Count.ShouldBe(1);
		}

		[Test]
		public void UpdateFloaterToNewSpot()
		{
			var partition = new TestCellSpacePartition(new Vector2(0, 0), 10, 10, 10);

			//create a fake item
			var entity = A.Fake<Mover>();
			A.CallTo(() => entity.Position).Returns(new Vector2(-25.0f, 15.0f));

			//add the item
			partition.Add(entity);

			//make sure it went in the correct spot
			partition.TestFloaters.Count.ShouldBe(1);

			//move the entity
			A.CallTo(() => entity.OldPosition).Returns(new Vector2(-25.0f, 15.0f));
			A.CallTo(() => entity.Position).Returns(new Vector2(35.0f, 15.0f));
			partition.Update(entity);

			//make sure it removed the old object and added the new spot
			partition.TestFloaters.Count.ShouldBe(0);
			partition.TestCells[13].Items.Count.ShouldBe(1);
		}

		[Test]
		public void UpdateEntityNotAdded()
		{
			var partition = new TestCellSpacePartition(new Vector2(0, 0), 10, 10, 10);

			//create a fake item
			var entity = A.Fake<Mover>();
			A.CallTo(() => entity.Position).Returns(new Vector2(25.0f, 15.0f));

			//move the entity
			A.CallTo(() => entity.OldPosition).Returns(new Vector2(25.0f, 15.0f));
			A.CallTo(() => entity.Position).Returns(new Vector2(35.0f, 15.0f));
			partition.Update(entity);

			//make sure it removed the old object and added the new spot
			Assert.AreEqual(0, partition.TestCells[12].Items.Count);
			Assert.AreEqual(1, partition.TestCells[13].Items.Count);
		}
	}
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.01.16 at 12:57:08 PM IST
//

package org.akomantoso.schema.v3.csd13;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <extension base="{http://docs.oasis-open.org/legaldocml/ns/akn/3.0/CSD13}anyOtherType">
 *       <attribute name="frozen" type="{http://www.w3.org/2001/XMLSchema}boolean" />
 *       <anyAttribute processContents='lax' namespace='##other'/>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "condition")
public class Condition
    extends AnyOtherType
{

    @XmlAttribute(name = "frozen")
    protected Boolean frozen;

    /**
     * Gets the value of the frozen property.
     *
     * @return
     *     possible object is
     *     {@link Boolean }
     *
     */
    public Boolean isFrozen() {
        return frozen;
    }

    /**
     * Sets the value of the frozen property.
     *
     * @param value
     *     allowed object is
     *     {@link Boolean }
     *
     */
    public void setFrozen(Boolean value) {
        this.frozen = value;
    }

}


text:
class Solution:
    def numSmallerByFrequency(self, queries: List[str], words: List[str]) -> List[int]:
        freqCounts = [0] * 12

        for word in words:
            freq = word.count(min(word))
            freqCounts[freq] += 1

        for i in range(len(freqCounts) - 2, -1, -1):
            freqCounts[i] += freqCounts[i + 1]

        answer = [0] * len(queries)
        for i, query in enumerate(queries):
            freq = query.count(min(query))
            answer[i] = freqCounts[freq + 1]

        return answer


text:
<?php

final class DifferentialRevisionListController extends DifferentialController
  implements PhabricatorApplicationSearchResultsControllerInterface {

  private $queryKey;

  public function shouldRequireLogin() {
    return !$this->allowsAnonymousAccess();
  }

  public function shouldAllowPublic() {
    return true;
  }

  public function willProcessRequest(array $data) {
    $this->queryKey = idx($data, 'queryKey');
  }

  public function processRequest() {
    $request = $this->getRequest();
    $controller = id(new PhabricatorApplicationSearchController($request))
      ->setQueryKey($this->queryKey)
      ->setSearchEngine(new DifferentialRevisionSearchEngine())
      ->setNavigation($this->buildSideNavView());

    return $this->delegateToController($controller);
  }

  public function renderResultsList(
    array $revisions,
    PhabricatorSavedQuery $query) {
    assert_instances_of($revisions, 'DifferentialRevision');

    $user = $this->getRequest()->getUser();
    $template = id(new DifferentialRevisionListView())
      ->setUser($user)
      ->setFields(DifferentialRevisionListView::getDefaultFields($user));

    $views = array();
    if ($query->getQueryKey() == 'active') {
        $split = DifferentialRevisionQuery::splitResponsible(
          $revisions,
          $query->getParameter('responsiblePHIDs'));
        list($blocking, $active, $waiting) = $split;

      $views[] = id(clone $template)
        ->setHeader(pht('Blocking Others'))
        ->setNoDataString(
          pht('No revisions are blocked on your action.'))
        ->setHighlightAge(true)
        ->setRevisions($blocking)
        ->setHandles(array())
        ->loadAssets();

      $views[] = id(clone $template)
        ->setHeader(pht('Action Required'))
        ->setNoDataString(
          pht('No revisions require your action.'))
        ->setHighlightAge(true)
        ->setRevisions($active)
        ->setHandles(array())
        ->loadAssets();

      $views[] = id(clone $template)
        ->setHeader(pht('Waiting on Others'))
        ->setNoDataString(
          pht('You have no revisions waiting on others.'))
        ->setRevisions($waiting)
        ->setHandles(array())
        ->loadAssets();
    } else {
      $views[] = id(clone $template)
        ->setRevisions($revisions)
        ->setHandles(array())
        ->loadAssets();
    }

    $phids = array_mergev(mpull($views, 'getRequiredHandlePHIDs'));
    $handles = $this->loadViewerHandles($phids);

    foreach ($views as $view) {
      $view->setHandles($handles);
    }

    if (count($views) == 1) {
      // Reduce this to a PhabricatorObjectItemListView so we can get the free
      // support from ApplicationSearch.
      return head($views)->render();
    } else {
      return $views;
    }
  }

}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources xmlns:tools="http://schemas.android.com/tools">

    <style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorAccent">@color/accent</item>
        <item name="preferenceTheme">@style/PreferenceThemeOverlay</item>
        <item name="android:colorBackground">@color/background</item>
        <item name="android:windowBackground">?android:colorBackground</item>
        <item name="buttonStyle">@style/ButtonStyle</item>
        <item name="bg_config_card">@drawable/bg_config_card</item>
        <item name="textColorPrimary">@color/text_primary</item>
        <item name="textColorSecondary">@color/text_secondary</item>
        <item name="android:forceDarkAllowed" tools:targetApi="q">false</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="actionOverflowMenuStyle">@style/Widget.AppTheme.OverflowMenu</item>
        <item name="textAppearancePopupMenuHeader">@style/PopupMenuTextAppearanceHeader</item>
        <item name="textAppearanceSmallPopupMenu">@style/PopupMenuTextAppearanceSmall</item>
        <item name="textAppearanceLargePopupMenu">@style/PopupMenuTextAppearanceLarge</item>
    </style>

    <style name="Widget.AppTheme.OverflowMenu" parent="Widget.AppCompat.Light.PopupMenu.Overflow">
        <item name="android:popupBackground">@color/background</item>
        <item name="overlapAnchor">false</item>
    </style>

    <style name="PopupMenuTextAppearanceHeader" parent="TextAppearance.AppCompat.Widget.PopupMenu.Header">
        <item name="android:textColor">@color/text_primary</item>
    </style>

    <style name="PopupMenuTextAppearanceSmall" parent="TextAppearance.AppCompat.Widget.PopupMenu.Small">
        <item name="android:textColor">@color/text_primary</item>
    </style>

    <style name="PopupMenuTextAppearanceLarge" parent="TextAppearance.AppCompat.Widget.PopupMenu.Large">
        <item name="android:textColor">@color/text_primary</item>
    </style>

    <style name="FilePickerTheme" parent="Theme.AppCompat.DayNight.DialogWhenLarge">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primary_dark</item>
        <item name="colorAccent">@color/file_picker_accent</item>
        <item name="android:colorBackground">@color/background</item>
        <item name="android:windowBackground">@color/background</item>
        <item name="nnf_toolbarTheme">@style/ThemeOverlay.AppCompat.Dark.ActionBar</item>
        <item name="alertDialogTheme">@style/FilePickerAlertDialogTheme</item>
        <item name="nnf_separator_color">@color/nnf_separator_color</item>
        <item name="nnf_save_icon_color">?attr/colorAccent</item>
        <item name="nnf_dir_icon_color">?attr/colorAccent</item>

        <!-- These are important. Handled by toolbar. -->
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="android:forceDarkAllowed" tools:targetApi="q">false</item>
    </style>

    <style name="FilePickerAlertDialogTheme" parent="Theme.AppCompat.DayNight.Dialog.Alert">
        <item name="colorAccent">@color/file_picker_accent</item>
        <item name="android:forceDarkAllowed" tools:targetApi="q">false</item>
    </style>

    <style name="ConfigTitleTextStyle">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">40dp</item>
        <item name="android:textSize">18sp</item>
        <item name="android:textColor">?attr/textColorPrimary</item>
        <item name="android:gravity">center</item>
    </style>

    <style name="SwitchStyle">
        <item name="android:textSize">15sp</item>
        <item name="android:textColor">?textColorSecondary</item>
        <item name="android:minHeight">40dp</item>
    </style>

    <style name="EditTextStyle">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:minHeight">38dp</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textSize">16sp</item>
        <item name="android:textColorHint">#b0b0b0</item>
        <item name="android:textColor">?attr/textColorPrimary</item>
    </style>

    <style name="ButtonStyle" parent="Widget.AppCompat.Button.Colored">
        <item name="android:minHeight">38dp</item>
        <item name="android:paddingLeft">6dp</item>
        <item name="android:paddingRight">6dp</item>
        <item name="android:elevation" tools:targetApi="lollipop">1dp</item>
        <item name="android:background">@drawable/bg_button</item>
    </style>

    <style name="ImageButtonStyle" parent="Widget.AppCompat.ImageButton">
        <item name="android:minHeight">38dp</item>
        <item name="android:background">@android:color/transparent</item>
        <item name="android:tint">?colorAccent</item>
    </style>

    <style name="TextViewVendor" parent="Widget.AppCompat.TextView" >
    </style>

</resources>


text:
package info.florianwiesner.txtreestore.mgmt;

import info.florianwiesner.txtreestore.TreeStoreSession;
import info.florianwiesner.txtreestore.changelog.ChangelogRegistry;
import info.florianwiesner.txtreestore.exceptions.JTASubsystemTreeStoreException;
import info.florianwiesner.txtreestore.impl.TreeStoreSessionImpl;

import javax.transaction.Transaction;

/**
 * @author Florian Wiesner
 */
public class TreeStoreManager {

    private static TreeStoreManager treeStoreManager;
    private final ChangelogRegistry changelogRegistry;

    private TreeStoreManager(final ChangelogRegistry changelogRegistry) {
        this.changelogRegistry = changelogRegistry;
    }

    public static TreeStoreManager getInstance() {
        return treeStoreManager;
    }

    public static void init() {
        treeStoreManager = new TreeStoreManager(new ChangelogRegistry());
    }

    public TreeStoreSession getNewTreeStoreSession(final Transaction tx) throws JTASubsystemTreeStoreException {
        return new TreeStoreSessionImpl(tx, this.changelogRegistry);
    }

}


text:
package workout_tracker;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ImportCSV {
	public static final int NUM_EXERCISES = 1299;
	public static final int NUM_ROWS = 4;

	// check for row numbers from csv
	public static boolean isNumber(String str) {
		try {
			double d = Double.parseDouble(str);
		}
		catch (NumberFormatException nfe) {
			return false;
		}
		return true;
	}

	// imports csv data into 2d array
	public static String[][] importFile(String fileName) throws FileNotFoundException {

		String[][] dataArrs = new String[NUM_EXERCISES][NUM_ROWS]; // return arrays
		boolean header = true; // ignore header
		int rowNum = 0; // row number
		int dataNum = 0; // data column number

		Scanner fileScanner = new Scanner(new File(fileName));

		// double scanner, one for lines, one for the data for each line
		while (fileScanner.hasNextLine()) {

			String lineData = fileScanner.nextLine();
			Scanner lineScanner = new Scanner(lineData);
			lineScanner.useDelimiter("\t");

			dataNum = 0; // reset column

			while (lineScanner.hasNext()) {

				String data = lineScanner.next();
				if (!isNumber(data)) {

					// set data for all non header rows
					if (!header) {
						dataArrs[rowNum - 1][dataNum - 1] = data;
					}
				}
				dataNum++;
			}

			rowNum++;
			lineScanner.close();

			if (header) {
				header = false;
			}
		}

		fileScanner.close();
		return dataArrs;
	}

	public static void main(String[] args) throws FileNotFoundException {

		// import csv database
		String[][] dataArrays = importFile("exercise_database.csv");

		// print out all exercises
		for (int i = 0; i < dataArrays.length; i++) {
			for (int j = 0; j < dataArrays[i].length; j++) {
				System.out.print(dataArrays[i][j] + " | ");
			}
			System.out.println();
		}
	}

}


text:
Credentials

				Posted on

				by

    	No Credentials yet, why don't you create one?


text:
using Content.Shared.Physics;

namespace Content.Shared.Audio;

public abstract class SharedContentAudioSystem : EntitySystem
{
    [Dependency] private readonly SharedAudioSystem _audio = default!;

    public override void Initialize()
    {
        base.Initialize();
        _audio.OcclusionCollisionMask = (int) CollisionGroup.Impassable;
    }
}


text: <!DOCTYPE html>


text:
package com.codecompiler.vo;

import java.util.Date;

public class Submission {

	private String queueId;
	private Date submittedTime;
	private int status;

	public Submission(String queueId, Date submittedTime, int status) {
		this.queueId = queueId;
		this.submittedTime = submittedTime;
		this.status = status;
	}

	public String getQueueId() {
		return queueId;
	}

	public Date getSubmittedTime() {
		return submittedTime;
	}

	public int getStatus() {
		return status;
	}
}