text:
#ifndef _JERASURE_H
#define _JERASURE_H

/* This uses procedures from the Galois Field arithmetic library */

#include "galois.h"

/* ------------------------------------------------------------ */
/* In all of the routines below:

   k = Number of data devices
   m = Number of coding devices
   w = Word size

   data_ptrs = An array of k pointers to data which is size bytes.
               Size must be a multiple of sizeof(long).
               Pointers must also be longword aligned.

   coding_ptrs = An array of m pointers to coding data which is size bytes.

   packetsize = The size of a coding block with bitmatrix coding.
                When you code with a bitmatrix, you will use w packets
                of size packetsize.

   matrix = an array of k*m integers.
            It represents an m by k matrix.
            Element i,j is in matrix[i*k+j];

   bitmatrix = an array of k*m*w*w integers.
            It represents an mw by kw matrix.
            Element i,j is in matrix[i*k*w+j];

   erasures = an array of id's of erased devices.
              Id's are integers between 0 and k+m-1.
              Id's 0 to k-1 are id's of data devices.
              Id's k to k+m-1 are id's of coding devices:
                  Coding device id = id-k.
              If there are e erasures, erasures[e] = -1.

   schedule = an array of schedule operations.

              If there are m operations, then schedule[m][0] = -1.

   operation = an array of 5 integers:

          0 = operation: 0 for copy, 1 for xor (-1 for end)
          1 = source device (0 - k+m-1)
          2 = source packet (0 - w-1)
          3 = destination device (0 - k+m-1)
          4 = destination packet (0 - w-1)
 */

/* ---------------------------------------------------------------  */
/* Bitmatrices / schedules ---------------------------------------- */
/*
 - jerasure_matrix_to_bitmatrix turns a m X k matrix in GF(2^w) into a
                              wm X wk bitmatrix (in GF(2)).  This is
                              explained in the Cauchy Reed-Solomon coding
                              paper.

 - jerasure_dumb_bitmatrix_to_schedule turns a bitmatrix into a schedule
                              using the straightforward algorithm -- just
                              schedule the dot products defined by each
                              row of the matrix.

 - jerasure_smart_bitmatrix_to_schedule turns a bitmatrix into a schedule,
                              but tries to use previous dot products to
                              calculate new ones.  This is the optimization
                              explained in the original Liberation code paper.

 - jerasure_generate_schedule_cache precalcalculate all the schedule for the
                              given distribution bitmatrix.  M must equal 2.

 - jerasure_free_schedule frees a schedule that was allocated with
                              jerasure_XXX_bitmatrix_to_schedule.

 - jerasure_free_schedule_cache frees a schedule cache that was created with
                              jerasure_generate_schedule_cache.
 */

int *jerasure_matrix_to_bitmatrix(int k, int m, int w, int *matrix);
int **jerasure_dumb_bitmatrix_to_schedule(int k, int m, int w, int *bitmatrix);
int **jerasure_smart_bitmatrix_to_schedule(int k, int m, int w, int *bitmatrix);
int ***jerasure_generate_schedule_cache(int k, int m, int w, int *bitmatrix, int smart);

void jerasure_free_schedule(int **schedule);
void jerasure_free_schedule_cache(int k, int m, int ***cache);

/* ------------------------------------------------------------ */
/* Encoding - these are all straightforward.  jerasure_matrix_encode only
   works with w = 8|16|32.  */

void jerasure_do_parity(int k, char **data_ptrs, char *parity_ptr, int size);

void jerasure_matrix_encode(int k, int m, int w, int *matrix,
                          char **data_ptrs, char **coding_ptrs, int size);

void jerasure_bitmatrix_encode(int k, int m, int w, int *bitmatrix,
                            char **data_ptrs, char **coding_ptrs, int size, int packetsize);

void jerasure_schedule_encode(int k, int m, int w, int **schedule,
                                  char **data_ptrs, char **coding_ptrs, int size, int packetsize);

/* ------------------------------------------------------------ */
/* Decoding. -------------------------------------------------- */

/* These return integers, because the matrix may not be invertible.

   The parameter row_k_ones should be set to 1 if row k of the matrix
   (or rows kw to (k+1)w+1) of th distribution matrix are all ones
   (or all identity matrices).  Then you can improve the performance
   of decoding when there is more than one failure, and the parity
   device didn't fail.  You do it by decoding all but one of the data
   devices, and then decoding the last data device from the data devices
   and the parity device.

   jerasure_schedule_decode_lazy generates the schedule on the fly.

   jerasure_matrix_decode only works when w = 8|16|32.

   jerasure_make_decoding_matrix/bitmatrix make the k*k decoding matrix
         (or wk*wk bitmatrix) by taking the rows corresponding to k
         non-erased devices of the distribution matrix, and then
         inverting that matrix.

         You should already have allocated the decoding matrix and
         dm_ids, which is a vector of k integers.  These will be
         filled in appropriately.  dm_ids[i] is the id of element
         i of the survivors vector.  I.e. row i of the decoding matrix
         times dm_ids equals data drive i.

         Both of these routines take "erased" instead of "erasures".
         Erased is a vector with k+m elements, which has 0 or 1 for
         each device's id, according to whether the device is erased.

   jerasure_erasures_to_erased allocates and returns erased from erasures.

 */

int jerasure_matrix_decode(int k, int m, int w,
                          int *matrix, int row_k_ones, int *erasures,
                          char **data_ptrs, char **coding_ptrs, int size);

int jerasure_bitmatrix_decode(int k, int m, int w,
                            int *bitmatrix, int row_k_ones, int *erasures,
                            char **data_ptrs, char **coding_ptrs, int size, int packetsize);

int jerasure_schedule_decode_lazy(int k, int m, int w, int *bitmatrix, int *erasures,
                            char **data_ptrs, char **coding_ptrs, int size, int packetsize,
                            int smart);

int jerasure_schedule_decode_cache(int k, int m, int w, int ***scache, int *erasures,
                            char **data_ptrs, char **coding_ptrs, int size, int packetsize);

int jerasure_make_decoding_matrix(int k, int m, int w, int *matrix, int *erased,
                                  int *decoding_matrix, int *dm_ids);

int jerasure_make_decoding_bitmatrix(int k, int m, int w, int *matrix, int *erased,
                                  int *decoding_matrix, int *dm_ids);

int *jerasure_erasures_to_erased(int k, int m, int *erasures);

/* ------------------------------------------------------------ */
/* These perform dot products and schedules. -------------------*/
/*
   src_ids is a matrix of k id's (0 - k-1 for data devices, k - k+m-1
   for coding devices) that identify the source devices.  Dest_id is
   the id of the destination device.

   jerasure_matrix_dotprod only works when w = 8|16|32.

   jerasure_do_scheduled_operations executes the schedule on w*packetsize worth of
   bytes from each device.  ptrs is an array of pointers which should have as many
   elements as the highest referenced device in the schedule.

 */

void jerasure_matrix_dotprod(int k, int w, int *matrix_row,
                          int *src_ids, int dest_id,
                          char **data_ptrs, char **coding_ptrs, int size);

void jerasure_bitmatrix_dotprod(int k, int w, int *bitmatrix_row,
                             int *src_ids, int dest_id,
                             char **data_ptrs, char **coding_ptrs, int size, int packetsize);

void jerasure_do_scheduled_operations(char **ptrs, int **schedule, int packetsize);

/* ------------------------------------------------------------ */
/* Matrix Inversion ------------------------------------------- */
/*
   The two matrix inversion functions work on rows*rows matrices of
   ints.  If a bitmatrix, then each int will just be zero or one.
   Otherwise, they will be elements of gf(2^w).  Obviously, you can
   do bit matrices with crs_invert_matrix() and set w = 1, but
   crs_invert_bitmatrix will be more efficient.

   The two invertible functions return whether a matrix is invertible.
   They are more efficient than the inverstion functions.

   Mat will be destroyed when the matrix inversion or invertible
   testing is done.  Sorry.

   Inv must be allocated by the caller.

   The two invert_matrix functions return 0 on success, and -1 if the
   matrix is uninvertible.

   The two invertible function simply return whether the matrix is
   invertible.  (0 or 1). Mat will be destroyed.
 */

int jerasure_invert_matrix(int *mat, int *inv, int rows, int w);
int jerasure_invert_bitmatrix(int *mat, int *inv, int rows);
int jerasure_invertible_matrix(int *mat, int rows, int w);
int jerasure_invertible_bitmatrix(int *mat, int rows);

/* ------------------------------------------------------------ */
/* Basic matrix operations -------------------------------------*/
/*
   Each of the print_matrix routines require a w.  In jerasure_print_matrix,
   this is to calculate the field width.  In jerasure_print_bitmatrix, it is
   to put spaces between the bits.

   jerasure_matrix_multiply is a simple matrix multiplier in GF(2^w).  It returns a r1*c2
   matrix, which is the product of the two input matrices.  It allocates
   the product.  Obviously, c1 should equal r2.  However, this is not
   validated by the procedure.
*/

void jerasure_print_matrix(int *matrix, int rows, int cols, int w);
void jerasure_print_bitmatrix(int *matrix, int rows, int cols, int w);

int *jerasure_matrix_multiply(int *m1, int *m2, int r1, int c1, int r2, int c2, int w);

/* ------------------------------------------------------------ */
/* Stats ------------------------------------------------------ */
/*
  jerasure_get_stats fills in a vector of three doubles:

      fill_in[0] is the number of bytes that have been XOR'd
      fill_in[1] is the number of bytes that have been copied
      fill_in[2] is the number of bytes that have been multiplied
                 by a constant in GF(2^w)

  When jerasure_get_stats() is called, it resets its values.
 */

void jerasure_get_stats(double *fill_in);

int jerasure_autoconf_test();

#endif


text:
FileList
========

HTML5 FileAPI `FileList` for Node.js

See <https://github.com/node-file-api/file-api>

redpajama_set_name: RedPajamaGithub


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using Azure.Core;

namespace Azure.AI.Translation.Document
{
    /// <summary>
    /// Storage type of the input documents source.
    /// </summary>
    [CodeGenModel("StorageInputType")]
    public enum StorageInputType
    {
        /// <summary>
        /// File
        /// </summary>
        File,
        /// <summary>
        /// Folder
        /// </summary>
        Folder
    }
}


text:
{% extends "real_base.html" %}
{% load i18n %}

{% block content %}
NO IMPLEMENTADO AUN

Lo sentimos pero a�n no hemos desarrollado esta opci�n.
 Contactenos para cualquier sugerencia.

{% endblock %}


text:
package org.assertj.core.error;

import java.util.Date;

import org.assertj.core.internal.*;

/**
 * Creates an error message indicating that an assertion that verifies that a {@link Date} is in the past failed.
 *
 * @author Joel Costigliola
 */
public class ShouldBeInThePast extends BasicErrorMessageFactory {

  /**
   * Creates a new {@link ShouldBeInThePast}.
   * @param actual the actual value in the failed assertion.
   * @param comparisonStrategy the {@link ComparisonStrategy} used to evaluate assertion.
   * @return the created {@code ErrorMessageFactory}.
   */
  public static ErrorMessageFactory shouldBeInThePast(Date actual, ComparisonStrategy comparisonStrategy) {
    return new ShouldBeInThePast(actual, comparisonStrategy);
  }

  /**
   * Creates a new {@link ShouldBeInThePast}.
   * @param actual the actual value in the failed assertion.
   * @return the created {@code ErrorMessageFactory}.
   */
  public static ErrorMessageFactory shouldBeInThePast(Date actual) {
    return new ShouldBeInThePast(actual, StandardComparisonStrategy.instance());
  }

  private ShouldBeInThePast(Date actual, ComparisonStrategy comparisonStrategy) {
    super("%nExpecting:%n <%s>%nto be in the past%s but was not.", actual, comparisonStrategy);
  }
}


text:
 [![travis-ci](https://travis-ci.org/toefel18/patan.svg?branch=master "build")](https://travis-ci.org/toefel18/patan) [![codecov.io](https://codecov.io/github/toefel18/patan/coverage.svg?branch=master "coverage")](https://codecov.io/github/toefel18/patan) [![coverity](https://scan.coverity.com/projects/7773/badge.svg "Coverity Scan Build Status")](https://scan.coverity.com/projects/toefel18-patan) [![Stories in Progress](https://badge.waffle.io/toefel18/patan.svg?label=patan%3Ain%20progress&title=In%20Progress)](http://waffle.io/toefel18/patan) [ ![Download](https://api.bintray.com/packages/toefel18/maven/patan/images/download.svg) ](https://bintray.com/toefel18/maven/patan/_latestVersion)

There are multiple ways for measuring the performance of code, sampling and instrumentation. Instrumentation modifies the original program's byte code by inserting measurement code. Sampling is done by programming the measurement code manually.

This is a sampling library that provides:
  - counters; keeping track of how many times *something* has taken place
  - sampling; collecting samples and describing their distribution
  - durations; measuring the duration of a task as a special case of sampling
  - no transitive dependencies!

The library provides an API and comes with a default implementation safe to be used in a multi-threaded environment.

Java 6+

Some examples:

```java
 // you can expose this instance application wide using an Enum, Singleton or perhaps as a spring-bean
 public static final Statistics STATISTICS = StatisticsFactory.createThreadsafeStatistics();
 ...

 // counters
 public void onMessage(Message message) {
    STATISTICS.addOccurrence("jms.message.received");
 }

 // durations
 public void onMessage(Message message) {
    Stopwatch onMessageStopwatch = STATISTICS.startStopwatch();

    //expensive method that takes long
    processMessage(message);

    long elapsedTime = STATISTICS.recordElapsedTime("jms.message.received.duration", onMessageStopwatch);

    // elapsedTime is the value read from the onMessageStopwatch.
 }

 // samples
 public void onLogin(Message message) {
    int loggedInUsers = System.countUsersLoggedIn();
    STATISTICS.addSample("users.logged.in", loggedInUsers);
 }

 // retrieve results
 public void printResults() {
    Snapshot snapshot = STATISTICS.getSnapshot();

    snapshot.getOccurrences();   // each key has a Long with the corresponding value of "timesOccurred"
    snapshot.getDurations();     // each key has a corresponding statistic which provides samplecount/min/max/avg/variance/standarddeviation
    snapshot.getSamples();       // each key has a corresponding statistic which provides samplecount/min/max/avg/variance/standarddeviation
 }

```

Java 8 users can measure the duration of a lambda:

```java
// measuring durations of methods without a return type
public void onMessage(Message message) {
    STATISTICS.recordElapsedTime("jms.message.received.duration", () -> processMessage(message));
}

// measuring durations of methods with a return type
public Result convert(Message message) {
    return STATISTICS.recordElapsedTime("jms.message.convertion.duration", () -> return convertMessageIntoResult(message));
}

public Result convertMessageIntoResult(Message message) {
    return new Result(expensiveTransform(message));
}

```


text:
#include <stdlib.h>
#include <malloc.h>
#include <pspdisplay.h>
#include <psputils.h>
#include <png.h>
#include <pspgu.h>

#include "graphics.h"
#include "framebuffer.h"

#define IS_ALPHA(color) (((color)&0xff000000)==0xff000000?0:1)
#define FRAMEBUFFER_SIZE (PSP_LINE_SIZE*SCREEN_HEIGHT*4)
#define MAX(X, Y) ((X) > (Y) ? (X) : (Y))

typedef struct
{
	unsigned short u, v;
	short x, y, z;
} Vertex;

extern u8 msx[];

unsigned int __attribute__((aligned(16))) list[262144];
static int dispBufferNumber;
static int initialized = 0;

static int getNextPower2(int width)
{
	int b = width;
	int n;
	for (n = 0; b != 0; n++) b >>= 1;
	b = 1 << n;
	if (b == 2 * width) b >>= 1;
	return b;
}

Color* getVramDrawBuffer()
{
	Color* vram = (Color*) g_vram_base;
	if (dispBufferNumber == 0) vram += FRAMEBUFFER_SIZE / sizeof(Color);
	return vram;
}

Color* getVramDisplayBuffer()
{
	Color* vram = (Color*) g_vram_base;
	if (dispBufferNumber == 1) vram += FRAMEBUFFER_SIZE / sizeof(Color);
	return vram;
}

void user_warning_fn(png_structp png_ptr, png_const_charp warning_msg)
{
}

Image* loadImage(const char* filename)
{
	png_structp png_ptr;
	png_infop info_ptr;
	unsigned int sig_read = 0;
	png_uint_32 width, height;
	int bit_depth, color_type, interlace_type, x, y;
	u32* line;
	FILE *fp;
	Image* image = (Image*) malloc(sizeof(Image));
	if (!image) return NULL;

	if ((fp = fopen(filename, "rb")) == NULL) return NULL;
	png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	if (png_ptr == NULL) {
		free(image);
		fclose(fp);
		return NULL;;
	}
	png_set_error_fn(png_ptr, (png_voidp) NULL, (png_error_ptr) NULL, user_warning_fn);
	info_ptr = png_create_info_struct(png_ptr);
	if (info_ptr == NULL) {
		free(image);
		fclose(fp);
		png_destroy_read_struct(&png_ptr, png_infopp_NULL, png_infopp_NULL);
		return NULL;
	}
	png_init_io(png_ptr, fp);
	png_set_sig_bytes(png_ptr, sig_read);
	png_read_info(png_ptr, info_ptr);
	png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, int_p_NULL, int_p_NULL);
	if (width > 512 || height > 512) {
		free(image);
		fclose(fp);
		png_destroy_read_struct(&png_ptr, png_infopp_NULL, png_infopp_NULL);
		return NULL;
	}
	image->imageWidth = width;
	image->imageHeight = height;
	image->textureWidth = getNextPower2(width);
	image->textureHeight = getNextPower2(height);
	png_set_strip_16(png_ptr);
	png_set_packing(png_ptr);
	if (color_type == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png_ptr);
	if (color_type == PNG_COLOR_TYPE_GRAY && bit_depth < 8) png_set_gray_1_2_4_to_8(png_ptr);
	if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png_ptr);
	png_set_filler(png_ptr, 0xff, PNG_FILLER_AFTER);
	image->data = (Color*) memalign(16, image->textureWidth * image->textureHeight * sizeof(Color));
	if (!image->data) {
		free(image);
		fclose(fp);
		png_destroy_read_struct(&png_ptr, png_infopp_NULL, png_infopp_NULL);
		return NULL;
	}
	line = (u32*) malloc(width * 4);
	if (!line) {
		free(image->data);
		free(image);
		fclose(fp);
		png_destroy_read_struct(&png_ptr, png_infopp_NULL, png_infopp_NULL);
		return NULL;
	}
	for (y = 0; y < height; y++) {
		png_read_row(png_ptr, (u8*) line, png_bytep_NULL);
		for (x = 0; x < width; x++) {
			u32 color = line[x];
			image->data[x + y * image->textureWidth] =  color;
		}
	}
	free(line);
	png_read_end(png_ptr, info_ptr);
	png_destroy_read_struct(&png_ptr, &info_ptr, png_infopp_NULL);
	fclose(fp);
	return image;
}

void blitImageToImage(int sx, int sy, int width, int height, Image* source, int dx, int dy, Image* destination)
{
	Color* destinationData = &destination->data[destination->textureWidth * dy + dx];
	int destinationSkipX = destination->textureWidth - width;
	Color* sourceData = &source->data[source->textureWidth * sy + sx];
	int sourceSkipX = source->textureWidth - width;
	int x, y;
	for (y = 0; y < height; y++, destinationData += destinationSkipX, sourceData += sourceSkipX) {
		for (x = 0; x < width; x++, destinationData++, sourceData++) {
			*destinationData = *sourceData;
		}
	}
}

void blitImageToScreen(int sx, int sy, int width, int height, Image* source, int dx, int dy)
{
	if (!initialized) return;
	Color* vram = getVramDrawBuffer();
	sceKernelDcacheWritebackInvalidateAll();
	guStart();
	sceGuCopyImage(GU_PSM_8888, sx, sy, width, height, source->textureWidth, source->data, dx, dy, PSP_LINE_SIZE, vram);
	sceGuFinish();
	sceGuSync(0,0);
}

void blitAlphaImageToImage(int sx, int sy, int width, int height, Image* source, int dx, int dy, Image* destination)
{
	// TODO Blend!
	Color* destinationData = &destination->data[destination->textureWidth * dy + dx];
	int destinationSkipX = destination->textureWidth - width;
	Color* sourceData = &source->data[source->textureWidth * sy + sx];
	int sourceSkipX = source->textureWidth - width;
	int x, y;
	for (y = 0; y < height; y++, destinationData += destinationSkipX, sourceData += sourceSkipX) {
		for (x = 0; x < width; x++, destinationData++, sourceData++) {
			Color color = *sourceData;
			if (!IS_ALPHA(color)) *destinationData = color;
		}
	}
}

void blitAlphaImageToScreen(int sx, int sy, int width, int height, Image* source, int dx, int dy)
{
	if (!initialized) return;

	sceKernelDcacheWritebackInvalidateAll();
	guStart();
	sceGuTexImage(0, source->textureWidth, source->textureHeight, source->textureWidth, (void*) source->data);
	float u = 1.0f / ((float)source->textureWidth);
	float v = 1.0f / ((float)source->textureHeight);
	sceGuTexScale(u, v);

	int j = 0;
	while (j < width) {
		Vertex* vertices = (Vertex*) sceGuGetMemory(2 * sizeof(Vertex));
		int sliceWidth = 64;
		if (j + sliceWidth > width) sliceWidth = width - j;
		vertices[0].u = sx + j;
		vertices[0].v = sy;
		vertices[0].x = dx + j;
		vertices[0].y = dy;
		vertices[0].z = 0;
		vertices[1].u = sx + j + sliceWidth;
		vertices[1].v = sy + height;
		vertices[1].x = dx + j + sliceWidth;
		vertices[1].y = dy + height;
		vertices[1].z = 0;
		sceGuDrawArray(GU_SPRITES, GU_TEXTURE_16BIT | GU_VERTEX_16BIT | GU_TRANSFORM_2D, 2, 0, vertices);
		j += sliceWidth;
	}

	sceGuFinish();
	sceGuSync(0, 0);
}

Image* createImage(int width, int height)
{
	Image* image = (Image*) malloc(sizeof(Image));
	if (!image) return NULL;
	image->imageWidth = width;
	image->imageHeight = height;
	image->textureWidth = getNextPower2(width);
	image->textureHeight = getNextPower2(height);
	image->data = (Color*) memalign(16, image->textureWidth * image->textureHeight * sizeof(Color));
	if (!image->data) return NULL;
	memset(image->data, 0, image->textureWidth * image->textureHeight * sizeof(Color));
	return image;
}

void freeImage(Image* image)
{
	free(image->data);
	free(image);
}

void clearImage(Color color, Image* image)
{
	int i;
	int size = image->textureWidth * image->textureHeight;
	Color* data = image->data;
	for (i = 0; i < size; i++, data++) *data = color;
}

void clearScreen(Color color)
{
	if (!initialized) return;
	guStart();
	sceGuClearDepth(0);
	sceGuClear(GU_COLOR_BUFFER_BIT|GU_DEPTH_BUFFER_BIT);
	sceGuFinish();
	sceGuSync(0, 0);
}

void fillImageRect(Color color, int x0, int y0, int width, int height, Image* image)
{
	int skipX = image->textureWidth - width;
	int x, y;
	Color* data = image->data + x0 + y0 * image->textureWidth;
	for (y = 0; y < height; y++, data += skipX) {
		for (x = 0; x < width; x++, data++) *data = color;
	}
}

void fillScreenRect(Color color, int x0, int y0, int width, int height)
{
	if (!initialized) return;
	int skipX = PSP_LINE_SIZE - width;
	int x, y;
	Color* data = getVramDrawBuffer() + x0 + y0 * PSP_LINE_SIZE;
	for (y = 0; y < height; y++, data += skipX) {
		for (x = 0; x < width; x++, data++) *data = color;
	}
}

void putPixelScreen(Color color, int x, int y)
{
	Color* vram = getVramDrawBuffer();
	vram[PSP_LINE_SIZE * y + x] = color;
}

void putPixelImage(Color color, int x, int y, Image* image)
{
	image->data[x + y * image->textureWidth] = color;
}

Color getPixelScreen(int x, int y)
{
	Color* vram = getVramDrawBuffer();
	return vram[PSP_LINE_SIZE * y + x];
}

Color getPixelImage(int x, int y, Image* image)
{
	return image->data[x + y * image->textureWidth];
}

void printTextScreen(int x, int y, const char* text, u32 color)
{
	int c, i, j, l;
	u8 *font;
	Color *vram_ptr;
	Color *vram;

	if (!initialized) return;

	for (c = 0; c < strlen(text); c++) {
		if (x < 0 || x + 8 > SCREEN_WIDTH || y < 0 || y + 8 > SCREEN_HEIGHT) break;
		char ch = text[c];
		vram = getVramDrawBuffer() + x + y * PSP_LINE_SIZE;

		font = &msx[ (int)ch * 8];
		for (i = l = 0; i < 8; i++, l += 8, font++) {
			vram_ptr  = vram;
			for (j = 0; j < 8; j++) {
				if ((*font & (128 >> j))) *vram_ptr = color;
				vram_ptr++;
			}
			vram += PSP_LINE_SIZE;
		}
		x += 8;
	}
}

void printTextImage(int x, int y, const char* text, u32 color, Image* image)
{
	int c, i, j, l;
	u8 *font;
	Color *data_ptr;
	Color *data;

	if (!initialized) return;

	for (c = 0; c < strlen(text); c++) {
		if (x < 0 || x + 8 > image->imageWidth || y < 0 || y + 8 > image->imageHeight) break;
		char ch = text[c];
		data = image->data + x + y * image->textureWidth;

		font = &msx[ (int)ch * 8];
		for (i = l = 0; i < 8; i++, l += 8, font++) {
			data_ptr  = data;
			for (j = 0; j < 8; j++) {
				if ((*font & (128 >> j))) *data_ptr = color;
				data_ptr++;
			}
			data += image->textureWidth;
		}
		x += 8;
	}
}

void saveImage(const char* filename, Color* data, int width, int height, int lineSize, int saveAlpha)
{
	png_structp png_ptr;
	png_infop info_ptr;
	FILE* fp;
	int i, x, y;
	u8* line;

	if ((fp = fopen(filename, "wb")) == NULL) return;
	png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
	if (!png_ptr) return;
	info_ptr = png_create_info_struct(png_ptr);
	if (!info_ptr) {
		png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
		return;
	}
	png_init_io(png_ptr, fp);
	png_set_IHDR(png_ptr, info_ptr, width, height, 8,
		saveAlpha ? PNG_COLOR_TYPE_RGBA : PNG_COLOR_TYPE_RGB,
		PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_DEFAULT, PNG_FILTER_TYPE_DEFAULT);
	png_write_info(png_ptr, info_ptr);
	line = (u8*) malloc(width * (saveAlpha ? 4 : 3));
	for (y = 0; y < height; y++) {
		for (i = 0, x = 0; x < width; x++) {
			Color color = data[x + y * lineSize];
			u8 r = color & 0xff;
			u8 g = (color >> 8) & 0xff;
			u8 b = (color >> 16) & 0xff;
			u8 a = saveAlpha ? (color >> 24) & 0xff : 0xff;
			line[i++] = r;
			line[i++] = g;
			line[i++] = b;
			if (saveAlpha) line[i++] = a;
		}
		png_write_row(png_ptr, line);
	}
	free(line);
	png_write_end(png_ptr, info_ptr);
	png_destroy_write_struct(&png_ptr, (png_infopp)NULL);
	fclose(fp);
}

void flipScreen()
{
	if (!initialized) return;
	sceGuSwapBuffers();
	dispBufferNumber ^= 1;
}

static void drawLine(int x0, int y0, int x1, int y1, int color, Color* destination, int width)
{
	int dy = y1 - y0;
	int dx = x1 - x0;
	int stepx, stepy;

	if (dy < 0) { dy = -dy;  stepy = -width; } else { stepy = width; }
	if (dx < 0) { dx = -dx;  stepx = -1; } else { stepx = 1; }
	dy <<= 1;
	dx <<= 1;

	y0 *= width;
	y1 *= width;
	destination[x0+y0] = color;
	if (dx > dy) {
		int fraction = dy - (dx >> 1);
		while (x0 != x1) {
			if (fraction >= 0) {
				y0 += stepy;
				fraction -= dx;
			}
			x0 += stepx;
			fraction += dy;
			destination[x0+y0] = color;
		}
	} else {
		int fraction = dx - (dy >> 1);
		while (y0 != y1) {
			if (fraction >= 0) {
				x0 += stepx;
				fraction -= dy;
			}
			y0 += stepy;
			fraction += dx;
			destination[x0+y0] = color;
		}
	}
}

void drawLineScreen(int x0, int y0, int x1, int y1, Color color)
{
	drawLine(x0, y0, x1, y1, color, getVramDrawBuffer(), PSP_LINE_SIZE);
}

void drawLineImage(int x0, int y0, int x1, int y1, Color color, Image* image)
{
	drawLine(x0, y0, x1, y1, color, image->data, image->textureWidth);
}

#define BUF_WIDTH (512)
#define SCR_WIDTH (480)
#define SCR_HEIGHT (272)
#define PIXEL_SIZE (4) /* change this if you change to another screenmode */
#define FRAME_SIZE (BUF_WIDTH * SCR_HEIGHT * PIXEL_SIZE)
#define ZBUF_SIZE (BUF_WIDTH SCR_HEIGHT * 2) /* zbuffer seems to be 16-bit? */

void initGraphics()
{
	dispBufferNumber = 0;

	sceGuInit();

	guStart();
	sceGuDrawBuffer(GU_PSM_8888, (void*)FRAMEBUFFER_SIZE, PSP_LINE_SIZE);
	sceGuDispBuffer(SCREEN_WIDTH, SCREEN_HEIGHT, (void*)0, PSP_LINE_SIZE);
	sceGuClear(GU_COLOR_BUFFER_BIT | GU_DEPTH_BUFFER_BIT);
	sceGuDepthBuffer((void*) (FRAMEBUFFER_SIZE*2), PSP_LINE_SIZE);
	sceGuOffset(2048 - (SCREEN_WIDTH / 2), 2048 - (SCREEN_HEIGHT / 2));
	sceGuViewport(2048, 2048, SCREEN_WIDTH, SCREEN_HEIGHT);
	sceGuDepthRange(0xc350, 0x2710);
	sceGuScissor(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
	sceGuEnable(GU_SCISSOR_TEST);
	sceGuAlphaFunc(GU_GREATER, 0, 0xff);
	sceGuEnable(GU_ALPHA_TEST);
	sceGuDepthFunc(GU_GEQUAL);
	sceGuEnable(GU_DEPTH_TEST);
	sceGuFrontFace(GU_CW);
	sceGuShadeModel(GU_SMOOTH);
	sceGuEnable(GU_CULL_FACE);
	sceGuEnable(GU_TEXTURE_2D);
	sceGuEnable(GU_CLIP_PLANES);
	sceGuTexMode(GU_PSM_8888, 0, 0, 0);
	sceGuTexFunc(GU_TFX_REPLACE, GU_TCC_RGBA);
	sceGuTexFilter(GU_NEAREST, GU_NEAREST);
	sceGuAmbientColor(0xffffffff);
	sceGuEnable(GU_BLEND);
	sceGuBlendFunc(GU_ADD, GU_SRC_ALPHA, GU_ONE_MINUS_SRC_ALPHA, 0, 0);
	sceGuFinish();
	sceGuSync(0, 0);

	sceDisplayWaitVblankStart();
	sceGuDisplay(GU_TRUE);
	initialized = 1;
}

void disableGraphics()
{
	initialized = 0;
}

void guStart()
{
	sceGuStart(GU_DIRECT, list);
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Forms;
using OsEngine.Entity;
using OsEngine.Language;
using OsEngine.Logging;
using OsEngine.Market.Servers.Tester;

namespace OsEngine.Market.Servers.Optimizer
{
    /// <summary>
	/// Interaction logic for TesterServerUi.xaml
    /// Логика взаимодействия для TesterServerUi.xaml
    /// </summary>
    public partial class OptimizerDataStorageUi
    {
        /// <summary>
		/// constructor
        /// конструктор
        /// </summary>
        /// <param name="server">server/сервер</param>
        /// <param name="log">log/лог</param>
        public OptimizerDataStorageUi(OptimizerDataStorage server, Log log)
        {
            InitializeComponent();
            _server = server;

            log.StartPaint(Host);

            _server.SecuritiesChangeEvent += _server_SecuritiesChangeEvent;

            CreateGrid();
            PaintGrid();

            TextBoxFrom.TextChanged += TextBoxFrom_TextChanged;
            TextBoxTo.TextChanged += TextBoxTo_TextChanged;

            // progress-bar/прогресс бар

            List<string> sets = _server.Sets;

            // sets/сеты

            for (int i = 0; sets != null && sets.Count != 0 && i < sets.Count; i++)
            {
                ComboBoxSets.Items.Add(sets[i]);
            }
            if (!string.IsNullOrEmpty(_server.ActiveSet) &&
                _server.ActiveSet.Split('_').Length == 2)
            {
                ComboBoxSets.SelectedItem = _server.ActiveSet.Split('_')[1];
            }

            ComboBoxSets.SelectionChanged += ComboBoxSets_SelectionChanged;

            // testing data/данные для тестирования

            ComboBoxDataType.Items.Add(TesterDataType.Candle);
            ComboBoxDataType.Items.Add(TesterDataType.TickOnlyReadyCandle);
            ComboBoxDataType.Items.Add(TesterDataType.MarketDepthOnlyReadyCandle);
            ComboBoxDataType.SelectedItem = _server.TypeTesterData;
            ComboBoxDataType.SelectionChanged += ComboBoxDataType_SelectionChanged;

            TextBoxDataPath.Text = _server.PathToFolder;
            ComboBoxDataSourseType.Items.Add(TesterSourceDataType.Folder);
            ComboBoxDataSourseType.Items.Add(TesterSourceDataType.Set);
            ComboBoxDataSourseType.SelectedItem = _server.SourceDataType;
            ComboBoxDataSourseType.SelectionChanged += ComboBoxDataSourseType_SelectionChanged;

            Title = OsLocalization.Market.TitleTester;
            Label22.Header = OsLocalization.Market.Label22;
            Label23.Header = OsLocalization.Market.Label23;
            Label24.Content = OsLocalization.Market.Label24;
            Label25.Content = OsLocalization.Market.Label25;
            LabelFrom.Content = OsLocalization.Market.Label26;
            LabelTo.Content = OsLocalization.Market.Label27;
            Label28.Content = OsLocalization.Market.Label28;
            ButtonSetDataFromPath.Content = OsLocalization.Market.ButtonSetFolder;
        }

        /// <summary>
		/// data source has changed. Folder or set
        /// источник данных изменился. Папка или Сет
        /// </summary>
        void ComboBoxDataSourseType_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            TesterSourceDataType sourceDataType;
            Enum.TryParse(ComboBoxDataSourseType.SelectedItem.ToString(), out sourceDataType);
            _server.SourceDataType = sourceDataType;
        }

        /// <summary>
		/// data type has changed
        /// изменился тип транслируемых данных
        /// </summary>
        void ComboBoxDataType_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            TesterDataType type;
            Enum.TryParse(ComboBoxDataType.SelectedItem.ToString(), out type);
            _server.TypeTesterData = type;
            _server.Save();

            PaintGrid();
        }

        /// <summary>
		/// data set has changed
        /// сет данных изменился
        /// </summary>
        void ComboBoxSets_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            _server.SetNewSet(ComboBoxSets.SelectedItem.ToString());
            PaintGrid();
        }

		// server
        // сервер

        /// <summary>
		/// test server
        /// тестовый сервер
        /// </summary>
        private OptimizerDataStorage _server;

        /// <summary>
		/// server instruments have changed
        /// изменились инструменты в сервере
        /// </summary>
        void _server_SecuritiesChangeEvent(List<Security> securities)
        {
            PaintGrid();
        }

		// table with instruments
        //  таблица с инструментами

        /// <summary>
		/// table with instruments
        /// таблица с инструментами
        /// </summary>
        private DataGridView _myGridView;

        /// <summary>
		/// create table with instruments
        /// создать таблицу с инструментами
        /// </summary>
        private void CreateGrid()
        {
            _myGridView = DataGridFactory.GetDataGridDataSource();

            _myGridView.DoubleClick += _myGridView_DoubleClick;
            _myGridView.CellValueChanged += _myGridView_CellValueChanged;
            HostSecurities.Child = _myGridView;
            HostSecurities.Child.Show();
            _myGridView.Rows.Add();
        }

        /// <summary>
		/// paint table with instruments
        /// прорисовать таблицу с инструментами
        /// </summary>
        private void PaintGrid()
        {
            if (_myGridView.InvokeRequired)
            {
                _myGridView.Invoke(new Action(PaintGrid));
                return;
            }

            SliderFrom.ValueChanged -= SliderFrom_ValueChanged;
            SliderTo.ValueChanged -= SliderTo_ValueChanged;

            _myGridView.Rows.Clear();

            List<SecurityTester> securities = _server.SecuritiesTester;

            if (securities != null && securities.Count != 0)
            {
                for (int i = 0; i < securities.Count; i++)
                {
                    DataGridViewRow nRow = new DataGridViewRow();
                    nRow.Cells.Add(new DataGridViewTextBoxCell());
                    nRow.Cells[0].Value = securities[i].FileAdress;
                    nRow.Cells.Add(new DataGridViewTextBoxCell());
                    nRow.Cells[1].Value = securities[i].Security.Name;

                    if (securities[i].DataType == SecurityTesterDataType.Candle)
                    {
                        DataGridViewComboBoxCell comboBox = new DataGridViewComboBoxCell();

                        comboBox.Items.Add(TimeFrame.Day.ToString());
                        comboBox.Items.Add(TimeFrame.Hour1.ToString());
                        comboBox.Items.Add(TimeFrame.Hour2.ToString());
                        comboBox.Items.Add(TimeFrame.Hour4.ToString());
                        comboBox.Items.Add(TimeFrame.Min1.ToString());
                        comboBox.Items.Add(TimeFrame.Min2.ToString());
                        comboBox.Items.Add(TimeFrame.Min5.ToString());
                        comboBox.Items.Add(TimeFrame.Min3.ToString());
                        comboBox.Items.Add(TimeFrame.Min10.ToString());
                        comboBox.Items.Add(TimeFrame.Min15.ToString());
                        comboBox.Items.Add(TimeFrame.Min30.ToString());
                        comboBox.Items.Add(TimeFrame.Min45.ToString());

                        nRow.Cells.Add(comboBox);
                        nRow.Cells[2].Value = securities[i].TimeFrame.ToString();
                    }
                    else
                    {
                        nRow.Cells.Add(new DataGridViewTextBoxCell());
                        nRow.Cells[2].Value = securities[i].DataType;
                    }

                    nRow.Cells.Add(new DataGridViewTextBoxCell());
                    nRow.Cells[3].Value = securities[i].Security.PriceStep.ToStringWithNoEndZero();
                    nRow.Cells.Add(new DataGridViewTextBoxCell());
                    nRow.Cells[4].Value = securities[i].TimeStart;
                    nRow.Cells.Add(new DataGridViewTextBoxCell());
                    nRow.Cells[5].Value = securities[i].TimeEnd;

                    _myGridView.Rows.Add(nRow);
                }
            }

            TextBoxFrom.Text = _server.TimeStart.ToString(new CultureInfo("RU-ru"));
            TextBoxTo.Text = _server.TimeEnd.ToString(new CultureInfo("RU-ru"));

            SliderFrom.Minimum = (_server.TimeMin - DateTime.MinValue).TotalMinutes;
            SliderFrom.Maximum = (_server.TimeMax - DateTime.MinValue).TotalMinutes;
            SliderFrom.Value = (_server.TimeStart - DateTime.MinValue).TotalMinutes;

            SliderTo.Minimum = (_server.TimeMin - DateTime.MinValue).TotalMinutes;
            SliderTo.Maximum = (_server.TimeMax - DateTime.MinValue).TotalMinutes;
            SliderTo.Value = (_server.TimeMin - DateTime.MinValue).TotalMinutes;

            SliderFrom.ValueChanged += SliderFrom_ValueChanged;
            SliderTo.ValueChanged += SliderTo_ValueChanged;
        }

        private void _myGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            List<SecurityTester> securities = _server.SecuritiesTester;

            for (int i = 0; i < securities.Count && i < _myGridView.Rows.Count; i++)
            {
                TimeFrame frame;

                if (Enum.TryParse(_myGridView.Rows[i].Cells[2].Value.ToString(), out frame))
                {
                    securities[i].TimeFrame = frame;
                }
            }
        }

        /// <summary>
        /// double click on table with instruments
        /// двойной клик по таблице с инструментами
        /// </summary>
        void _myGridView_DoubleClick(object sender, EventArgs e)
        {
            DataGridViewRow row = null;
            try
            {
                row = _myGridView.SelectedRows[0];
            }
            catch (Exception)
            {
                // ignore
            }

            if (row == null)
            {
                return;
            }

            string str = row.Cells[1].Value.ToString();

            Security security = _server.Securities.Find(s => s.Name == str);

            if (security == null)
            {
                return;
            }

            int rowNum = row.Index;

            SecurityUi ui = new SecurityUi(security);
            ui.ShowDialog();

            if (ui.IsChanged)
            {
                security = _server.SecuritiesTester[rowNum].Security;

                for (int i = 0; i < _server.SecuritiesTester.Count; i++)
                {
                    if (_server.SecuritiesTester[i].Security.Name == security.Name)
                    {
                        _server.SecuritiesTester[i].Security = security;
                    }
                }

                _server.SaveSecurityDopSettings(security);
            }

            PaintGrid();
        }

        // sliders. Set the start and finish test times
        // слайдеры. Установка начального и конечного времени тестирования

        private void SliderTo_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            TextBoxTo.TextChanged -= TextBoxTo_TextChanged;

            DateTime to = DateTime.MinValue.AddMinutes(SliderFrom.Minimum + SliderFrom.Maximum - SliderTo.Value);
            _server.TimeEnd = to;
            TextBoxTo.Text = to.ToString(new CultureInfo("RU-ru"));

            if (SliderFrom.Minimum + SliderFrom.Maximum - SliderTo.Value < SliderFrom.Value)
            {
                SliderFrom.Value = SliderFrom.Minimum + SliderFrom.Maximum - SliderTo.Value;
            }
            TextBoxTo.TextChanged += TextBoxTo_TextChanged;
        }

        void SliderFrom_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            TextBoxFrom.TextChanged -= TextBoxFrom_TextChanged;

            DateTime from = DateTime.MinValue.AddMinutes(SliderFrom.Value);
            _server.TimeStart = from;
            TextBoxFrom.Text = from.ToString(new CultureInfo("RU-ru"));

            if (SliderFrom.Minimum + SliderFrom.Maximum - SliderTo.Value < SliderFrom.Value)
            {
                SliderTo.Value = SliderFrom.Minimum + SliderFrom.Maximum - SliderFrom.Value;
            }

            TextBoxFrom.TextChanged += TextBoxFrom_TextChanged;
        }

        void TextBoxTo_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            DateTime to;
            try
            {
                to = Convert.ToDateTime(TextBoxTo.Text);

                if (to < _server.TimeMin ||
                    to > _server.TimeMax)
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                TextBoxTo.Text = _server.TimeEnd.ToString(new CultureInfo("RU-ru"));
                return;
            }

            _server.TimeEnd = to;
            // SliderTo.Value = SliderFrom.Minimum + SliderFrom.Maximum - to.Minute;
            // SliderFrom.Minimum + SliderFrom.Maximum - SliderTo.Value
            SliderTo.Value = SliderFrom.Minimum + SliderTo.Maximum - (to - DateTime.MinValue).TotalMinutes;
        }

        void TextBoxFrom_TextChanged(object sender, System.Windows.Controls.TextChangedEventArgs e)
        {
            DateTime from;
            try
            {
                from = Convert.ToDateTime(TextBoxFrom.Text);

                if (from < _server.TimeMin ||
                    from > _server.TimeMax)
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                TextBoxFrom.Text = _server.TimeStart.ToString(new CultureInfo("RU-ru"));
                return;
            }

            _server.TimeStart = from;
            SliderFrom.Value = (_server.TimeStart - DateTime.MinValue).TotalMinutes;
        }

        private void ButtonSetDataFromPath_Click(object sender, RoutedEventArgs e)
        {
            _server.ShowPathSenderDialog();
            TextBoxDataPath.Text = _server.PathToFolder;
        }

    }
}


text:
layout: page
title: About
permalink: /about/
---

General Assembly NYC Data Science Stuent

### More Information

A place to include any other types of information that you'd like to include about yourself.

### Contact me

[samuels.andrew@gmail.com](mailto:samuels.andrew@gmail.com)


text:
<?php

namespace common\models\db;

use Yii;

/**
 * This is the model class for table "packed".
 *
 * @property integer $id
 * @property integer $dt_add
 * @property string $idStock
 * @property integer $address_id
 * @property integer $price
 * @property string $number
 * @property string $comment
 * @property string $status
 */
class Packed extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'packed';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['dt_add', 'address_id', 'price'], 'integer'],
            [['idStock', 'number', 'comment'], 'string', 'max' => 255],
            [['status'], 'string', 'max' => 2],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'dt_add' => 'Dt Add',
            'idStock' => 'Id Stock',
            'address_id' => 'Address ID',
            'price' => 'Price',
            'number' => 'Number',
            'comment' => 'Comment',
            'status' => 'Status',
        ];
    }
}


text:
	%include templates/parts/head.html

	%include templates/parts/navBar.html

						Assignment 2: Serafini

						Thanks to Julie Zelenski, Jerry Cain and Marty Stepp; Random Writer comes from Joe Zachary.

						October 7th, 2016

Images from Codex Seraphinianus by Serafini

					This Serafini in reference to Luigi Serafini who wrote a book called the Codex Seraphinianus. The codex is filled with scientific looking writing and figures, all of which are believed to be the product of Serafini's imagination. Two features that Serafini's work primarily embody are morphings—many objects in the codex change from one to another—and random writing.

					As such, this assignment consists of two parts (A) Word Ladders where you find ways to morph one word into another and (B) Random Writter where your program stochastically generates text. Each part can be programmed separately, but they should be submitted together.
					The starter code for this project is availible as a ZIP archive:

					Starter Code

                                        Due Date: Serafini is due October 15th (Saturday) at 12:00pm (noon).

					Y.E.A.H hours (will be recorded):

					Fri, Oct. 7th

					4-5pm

					420-041.

					Last Quarter's Slides

					Turn in only the following files:

wordladder.cpp, the C++ code for the Part A Word Ladder program (including a main function)

ngrams.cpp, the C++ code for the Part B N-grams program (including a main function)

myinput.txt, your own unique Part B input file representing text to read in as your program's input

                                This is a not a pair assignment (soon!). You must work on your code alone, although as always you
                                are allowed to talk about the problems with other students, on Piazza, in LaIR, office hours, etc.

					Part A: Word Ladder

					A word ladder is a connection from one word to another formed by changing one letter at a time with the constraint that at each step the sequence of letters still forms a valid word. For example, here is a word ladder connecting the word "code" to the word "data". Each changed letter is underlined as an illustration:

					code
					→
					cade
					→
					cate
					→
					date
					→
					data

					There are many other word ladders that connect these two words, but this one is the shortest. That is, there might
be others of the same length, but none with fewer steps than this one.

					In the first part of this assignment, write a program that repeatedly prompts the user for two words and finds a minimum-length ladder between the words. You must use the Stack and Queue collections from Chapter 5, along with following a particular provided algorithm to find the shortest word ladder. This part is simpler than Part B. Here is an example log of interaction between your program and the user (with console input underlined):

Example Run:

							Here is an example log of interaction between your program and the user (with console input in red).

Welcome to CS 106X Word Ladder.
Please give me two English words, and I will change the
first into the second by changing one letter at a time.

Dictionary file name? dictionary.txt

Word #1 (or Enter to quit): code
Word #2 (or Enter to quit): data
A ladder from data back to code:
data date cate cade code

Word #1 (or Enter to quit):
Have a nice day.

					Notice that the word ladder prints out in reverse order, from the second word back to the first. If there are multiple valid word ladders of the same length between a given starting and ending word, your program would not need to generate exactly the ladder shown in this log, but you must generate one of minimum length.

					Your code should ignore case; in other words, the user should be able to type uppercase, lowercase, mixed case, etc. words and the ladders should still be found and displayed in lowercase. You should also check for several kinds of user input errors, and not assume that the user will type valid input. Specifically, you should check that both words typed by the user are valid words found in the dictionary, that they are the same length, and that they are not the same word. If invalid input occurs, your program should print an error message and re-prompt the user. See the logs of execution on the course web site for examples of proper program output for such cases.
                                        You will need to keep a dictionary of all English words. We provide a file dictionary.txt that contains these words, one per line. We also suggest using the Stanford library's Lexicon class to store the dictionary. Using the Lexicon class is not hard -- please see the Lexicon class reference for details. You will need to read in the dictionary of words and then you should simply use the contains() method to determine if a word is in the dictionary when you need that functionality.

					Your program should prompt the user to enter a dictionary file name and use that file as the source of the English words. (If the user types a file name that does not exist, reprompt them; see the second execution log on the next page.) Read the file a single time in your program, and choose an efficient collection to store and look up words. Note that you should not ever need to loop over the dictionary as part of solving this problem.

Here are a few more example runs:

									Ladder Run #1

									Ladder Run #2

									Ladder Run #3

									Ladder Run #4

Algorithm:

					Finding a word ladder is a specific instance of a shortest-path problem of finding a path from a start position to a goal. Shortest-path problems come up in routing Internet packets, comparing gene mutations, Google Maps, and so on. The strategy we will use for finding a shortest path is called breadth-first search ("BFS"), a search process that expands out from a start position, considering all possibilities that are one step away, then two steps away, and so on, until a solution is found. BFS guarantees that the first solution you find will be as short as any other.

					For word ladders, start by examining ladders that are one step away from the original word, where only one letter is changed. Then check all ladders that are two steps away, where two letters have been changed. Then three, four, etc. We implement the breadth-first algorithm using a queue to store partial ladders that represent possibilities to explore. Each partial ladder is a stack, which means that your overall collection is a queue of stacks.

Here is a partial pseudocode description of the algorithm to solve the word-ladder problem:

Finding a word ladder between words w1 and w2:
	Create an empty queue of stacks.
  	Create/add a stack containing {w1} to the queue.
  	While the queue is not empty:
		Dequeue the partial-ladder stack from the front of the queue.
		For each valid English word that is a "neighbor" (differs by 1 letter)
		of the word on top of the stack:
			If that neighbor word has not already been used in a ladder before:
				If the neighbor word is w2:
					Hooray! we have found a solution (and it is the stack you are working on in the queue).
				Otherwise:
					Create a copy of the current partial-ladder stack.
					Put the neighbor word on top of the copy stack.
					Add the copy stack to the end of the queue.

					Some of the pseudocode corresponds almost one-to-one with actual C++ code. One part that is more abstract is the part that instructs you to examine each "neighbor" of a given word. A neighbor of a given word w is a word of the same length as w that differs by exactly 1 letter from w. For example, "date" and "data" are neighbors.

					It is not appropriate to look for neighbors by looping over the entire dictionary every time; this is way too slow. To find all neighbors of a given word, use two nested loops: one that goes through each character index in the word, and one that loops through the letters of the alphabet from a-z, replacing the character in that index position with each of the 26 letters in turn. For example, when examining neighbors of "date", you'd try:

							aate,bate,cate,...,zate	← all possible neighbors where only the 1st letter is changed.

							date,dbte,dcte,...,dzte	← all possible neighbors where only the 2nd letter is changed.

							...

							data,datb,datc,...,datz ← all possible neighbors where only the 4th letter is changed.

					Note that many of the possible words along the way (aate, dbte, datz, etc.) are not valid English words. Your algorithm has access to an English dictionary, and each time you generate a word using this looping process, you should look it up in the dictionary to make sure that it is actually a legal English word.

					Another way of visualizing the search for neighboring words is to think of each letter index in the word as being a "spinner" that you can spin up and down to try all values A-Z for that letter. The diagram below tries to depict this:

					Another subtle issue is that you do not reuse words that have been included in a previous shorter ladder. For example, suppose that you have the partial ladder cat → cot → cog → to the queue. Lateron, if your code is processing ladder cat → cot → con, one neighbor of con is cog, so you might want to examine cat → cot → con → cog. But doing so is unnecessary. If there is a word ladder that begins with these four words, then there must be a shorter one that, in effect, cuts out the middleman by eliminating the unnecessary word con. As soon as you've enqueued a ladder ending with a specific word, you've found a minimum-length path from the starting word to the end word in the ladder, so you never have to enqueue that end word again.

					To implement this strategy, keep track of the set of words that have already been used in any ladder. Ignore those words if they come up again. Keeping track of what words you've used also eliminates the possibility of getting trapped in an infinite loop by building a circular ladder, such as cat → cot → cog → bog → bag → bat → cat.

					It is helpful to test your program on smaller dictionary files first to find bugs or issues related to your dictionary or word searching.

					Part B: Random Writter

                                In the second part of this assignment, you will write a program that reads an input file and uses it to build a large data structure of word groups called "N- grams" as a basis for randomly generating new text that sounds like it came from the same author as that file. You will use the Map and Vector collections from Chapter 5.
Bellow is an example log of interaction between your program and the user (console input underlined). But what, you may ask, is an N-gram?

Welcome to CS 106X Random Writer ('N-Grams').
This program makes random text based on a document.
Give me an input file and an 'N' value for groups
of words, and I'll create random text for you.

Input file name? hamlet.txt
Value of N? 3

# of random words to generate (0 to quit)? 40
... chapel. Ham. Do not believe his tenders, as you
go to this fellow. Whose grave's this, sirrah?
Clown. Mine, sir. [Sings] O, a pit of clay for to
the King that's dead. Mar. Thou art a scholar; speak
to it. ...

# of random words to generate (0 to quit)? 20
... a foul disease, To keep itself from noyance; but
much more handsome than fine. One speech in't I
chiefly lov'd. ...

# of random words to generate (0 to quit)? 0
Exiting.

                                The "Infinite Monkey Theorem" states that an infinite number of monkeys typing random keys forever would eventually produce the works of William Shakespeare. (See here) That's silly, but could a monkey randomly produce a new work that "sounded like" Shakespeare's works, with similar vocabulary, wording, punctuation, etc.? What if we chose words at random, instead of individual letters? Suppose that rather than each word having an equal probability of being chosen, we weighted the probability based on how often that word appeared in Shakespeare's works?

					Picking random words would likely produce gibberish, but let's look at chains of two words in a row. For example, perhaps Shakespeare uses the word "to" occurs 10 times total, and 7 of those occurrences are followed by "be", 1 time by "go", and 2 times by "eat". We can use those ratios when choosing the next word. If the last word we chose is "to", randomly choose "be" next 7/10 of the time, "go" 1/10 of the time, and "eat" 2/10. We never choose any other word to follow "to". We call a chain of two words like this, such as "to be", a 2-gram.

Go, get you have seen, and now he makes as itself? (2-gram)

					A sentence of 2-grams isn't great, but look at chains of 3 words (3-grams). If we chose the words "to be", what word should follow? If we had a collection of all sequences of 3 words-in-a-row with probabilities, we could make a weighted random choice. If Shakespeare uses "to be" 22 times and follows them with "or" 5 times, "in" 3 times, "with" 10 times, and "alone" 4 times, we could use these weights to randomly choose the next word. So now the algorithm would pick the third word based on the first two, and the fourth based on the (second+third), and so on.

One woe doth tread upon another's heel, so fast they follow. (3-gram)

					You can generalize the idea from 2-grams to N-grams for any integer N. If you make a collection of all groups of N-1 words along with their possible following words, you can use this to select an Nth word given the preceding N-1 words. The higher N level you use, the more similar the new random text will be to the original data source. Here is a random sentence generated from 5-grams of Hamlet, which is starting to sound a lot like the original:

					I cannot live to hear the news from England, But I do prophesy th'election lights on Fortinbras. (5-gram)

					Each particular piece of text randomly generated in this way is also called a Markov chain. Markov chains are very useful in computer science and elsewhere, such as artificial intelligence, machine learning, economics, and statistics.

Here are a few more example runs:

									Writter Run #1

									Writter Run #2

									Writter Run #3

									Writter Run #4

									Writter Run #5

Step 1: Building Map of N-Grams

					In this program, you will read the input file one word at a time and build a particular compound collection, a map from prefixes to suffixes. If you are building 3-grams, that is, N-grams for N=3, then your code should examine sequences of 2 words and look at what third word follows those two. For later lookup, your map should be built so that it connects a collection of N-1 words with another collection of all possible suffixes; that is, all possible N'th words that follow the previous N-1 words in the original text. For example if you are computing N-grams for N=3 and the pair of words "to be" is followed by "or" twice and "just" once, your collection should map the key {to, be} to the value {or, just, or}. The following figure illustrates the map you should build from the file:

					When reading the input file, the idea is to keep a window of N-1 words at all times, and as you read each word from the file, discard the first word from your window and append the new word. The following figure shows the file being read and the map being built over time as each of the first few words is read to make 3-grams:

							File Location

							Data

						 to be | or not to be just ...

map    = {}
window = {to, be}

						to  be or |  not to be just ...

map    = { {to, be} : {or} }
window = {be, or}

						to be or not | to be just ...

map    = { {to, be} : {or},
           {be, or} : {not} }
window = {or, not}

						to be or  not to | be just ...

map    = { {to, be} : {or},
           {be, or} : {not},
           {or, not} : {to} }
window = {not, to}

						to be or not  to be | just ...

map    = { {to, be} : {or},
           {be, or} : {not},
           {or, not} : {to},
           {not, to} : {be} }
window = {to, be}

						to be or not to  be just | ...

map    = { {to, be} : {or, just},
           {be, or} : {not},
           {or, not} : {to},
           {not, to} : {be} }
window = {be, just}

to be or not to be just

be who you want to be

or not okay you want okay|

map    = { {to, be} : {or, just, or},
           {be, or} : {not, not},
           {or, not} : {to, okay},
           {not, to} : {be},
           {be, just} : {be},
           {just, be} : {who},
           {be, who} : {you},
           {who, you} : {want},
           {you, want} : {to, okay},
           {want, to} : {be},
           {not, okay} : {you},
           {okay, you} : {want},
           {want, okay} : {to},
           {okay, to} : {be} }

					Note that the order matters: For example, the prefix {you, are} is different from the prefix {are, you}. Note that the same word can occur multiple times as a suffix, such as "or" occurring twice after the prefix {to, be}.

					Also notice that the map wraps around. For example, if you are computing 3-grams like the above example, perform 2 more iterations to connect the last 2 prefixes in the end of the file to the first 2 words at the start of the file. In our example above, this leads to {want, okay} connecting to "to" and {okay, to} connecting to "be". If we were doing 5-grams, we would perform 4 more iterations and connect the last 4 prefixes to the first 4 words in the file, and so on. This turns out to be very useful to help your algorithm later on in the program.

					You should not change case or strip punctuation of words as you read them. The casing and punctuation turns out to help the sentences start and end in a more authentic way. Just store the words in the map as you read them.

Step 2: Generating Random Text

					To generate random text from your map of N-grams, first choose a random starting point for the document. To do this, pick a randomly chosen key from your map. Each key is a collection of N-1 words. Those N-1 words will form the start of your random text. This collection of N-1 words will be your sliding "window" as you create your text.

					For all subsequent words, use your map to look up all possible next words that can follow the current N-1 words, and randomly choose one with appropriate weighted probability. If you have built your map the way we described, as a map from {prefix} → {suffixes}, this simply amounts to choosing one of the possible suffix words at random. Once you have chose your random suffix word, slide your current "window" of N-1 words by discarding the first word in the window and appending the new suffix.

					Since your random text likely won't happen to start and end at the beginning/end of a sentence, just prefix and suffix your random text with "..." to indicate this. Here is another partial log of execution:

Input file? tiny.txt
Value of N? 3
# of random words to generate (0 to quit)? 16
... who you want okay to be who you want to be or not to be or ...

					Your code should check for several kinds of user input errors, and not assume that the user will type valid input. Specifically, re-prompt the user if they type the name of a file that does not exist. Also re-prompt the user if they type a value for N that not an integer, or is an integer less than 2 (a 2-gram has prefixes of length 1; but a 1-gram is essentially just choosing random words from the file and is uninteresting for our purposes). When prompting the user for the number of words to randomly generate, re-prompt them if the number of random words to generate is not at least N. You may assume that the value the user types for N is not greater than the number of words found in the file. See the logs of execution on the course web site for examples of proper program output for various cases.

Creative Aspect myinput.txt

					Along with your program, submit a file myinput.txt that contains a text file that can be used as input for Part B. This can be anything you want, as long as it is non-empty and is something you gathered yourself (not just a copy of an existing input file). This is meant to be just-for-fun; for example, if you like a particular band, you could paste several of their songs into a text file, which leads to funny new songs when you run your N-grams program on this data. Or gather the text of a book you really like, or poems, or anything you want. This is worth a small part of your grade on the assignment.

Development Strategy and Hints

					This program can be tricky if you don't develop and debug it step-by-step. Don't try to write everything all at once. Make sure to test each part of the algorithm before you move on.

Unlike in the previous assignment, here we are interested in each word. If you want to read a file one word at a time, an effective way to do so is using the input >> variable; syntax rather than getLine, etc.

Think about exactly what types of collections to use for each part. Are duplicates allowed? Does order matter? Do you need random access? Where will you add/remove elements? Etc. Note that some parts of each program require you to make compound collections, that is, a collection of collections.

Test each function with a very small input first. For example, use input file tiny.txt with a small number of words because you can print your entire map and examine its contents.

Recall that you can print the contents of any collection to cout and examine its contents for debugging.

Remember that when you assign one collection to another using the = operator, it makes a full copy of the
 entire contents of the collection. This could be useful if you want to copy a collection.

To choose a random prefix from a map, consider using the map's keys member function, which returns a Vector containing all of the keys in the map. For randomness in general, include "random.h" and call the global function randomInteger(min, max).

You can loop over the elements of a vector or set using a for-each loop. A for-each also works on a map, iterating over the keys in the map. You can look up each associated value based on the key in the loop.

Don't forget to test your input on unusual inputs, like large and small values of N, large /small # of words to generate, large and small input files, and so on. It's hard to verify random input, but you can look in smallish input files to verify that a given word really does follow a given prefix from your map.

					Possible Extra Features:

Thats all! You are done. Consider adding extra features.

				<button id="extensionButton" type="button" class="btn btn-primary btn-lg" onclick='$("#extension").show();$("#extensionButton").hide();'>Show Extensions</button>

					Though your solution to this assignment must match all of the specifications mentioned previously, it is allowed and encouraged for you to add extra features to your program if you'd like to go beyond the basic assignment. Here are some example ideas for extra features that you could add to your program.

Allow word ladders between words of different length: The typical solution forbids word ladders between words that are not the same length. But as an extra feature, you could make it so that it is considered legal to add or remove a single letter from your string at each hop along the way. This would make it possible to, for example, generate a word ladder from "car" to "cheat": car, cat, chat, cheat.

Allow word ladder end-points to be outside the dictionary: Generally we want our word ladders to consist of words that are valid English words found in the dictionary. But it can be fun to allow only the start and end words to be non-dictionary words. For example, "Marty" is not an English word, but if you did this extra feature, you could produce a word ladder from "Marty" to "curls" as: marty, party, parts, carts, cards, curds, curls.

Make the N-grams be complete sentences: The typical version of the assignment indicates that you should start and end your input with "..." since it will likely not begin with the start of a sentence nor end with the end of a sentence from the original input. As an extra feature, make it so that when you are creating your map of N-1 word prefixes, you also keep track of which prefixes are the start of a sentence (prefixes whose first word begins with an uppercase letter) and which words are the end of a sentence (words that end with a period, question mark, or exclamation mark). Use this extra data to begin your randomly generated text with a random sentence starter, rather than any random prefix. And instead of generating exactly the number of words requested by the user, keep going until you reach the end of a sentence. That is, if the user requests 100 words, after generating those 100 words, if you aren't at the end of a sentence, keep going until you end it.

Other: If you have your own creative idea for an extra feature, ask your SL and / or the instructor about it. If the idea is big enough, consider also submitting it as a contest entry.

Indicating that you have done extra features:

					 If you complete any extra features, then in the comment heading on the top of your program, please list all extra features that you worked on and where in the code they can be found (what functions, lines, etc. so that the grader can look at their code easily).

Submitting a program with extra features:

Since we use automated testing for part of our grading process, it is important that you submit a program that conforms to the preceding spec, even if you want to do extra features. If your feature(s) cause your program to change the output that it produces in such a way that it no longer matches the expected sample output test cases provided, you should submit two versions of your program file: a first one named life.cpp without any extra features added (or with all necessary features disabled or commented out), and a second one named life-extra.cpp with the extra features enabled. Please distinguish them in by explaining which is which in the comment header. Our turnin system saves every submission you make, so if you make multiple submissions we will be able to view all of them; your previously submitted files will not be lost or overwritten.

		%include templates/parts/footer.html


text:
function getMentions (candidate, callback) {
  return $.getJSON(candidate + '.json', callback);
}

function renderMentions (mentions, candidate) {
  var content = mentions.map(function (mention) {
    return $('<li>', { text: mention.tweet, 'class': colors[candidate] });
  });
  $('#mentions').append(content);
}

$.when(getMentions ('yu'), getMentions ('ya'))
 .done(function (data1, data2) {
   var c1 = data1[0], c2 = data2[0];
   if (c1.length > c2.length) {
     c1.length = c2.length - 1;
   }

   renderMentions(c1, 'yu');
   renderMentions(c2, 'ya');
 })
 .fail(function () {
   console.log('Та-дааам! Хулиганы захватили урны и власть!')
 })


text:
<?php

require_once '../dja/dja.php';

define('DJA_TESTS_DIR', dirname(__FILE__));

// Add current directory to apps, so that tests can find `templates` and `templatetags`.
Dja::setSetting('INSTALLED_APPS', array(DJA_TESTS_DIR));
Dja::setSetting('TEMPLATE_DIRS', array(DJA_TESTS_DIR, 'templates'));


text:
rd /s /q sim
del program*.hex


text:
@class NSString;

@interface IDEInspectorKeyPath : NSObject <NSCopying>
{
    NSString *_observationKeyPath;
    NSString *_applicationKeyPath;
}

+ (id)keyPathWithApplicationKeyPath:(id)arg1;
@property(readonly) NSString *applicationKeyPath; // @synthesize applicationKeyPath=_applicationKeyPath;
@property(readonly) NSString *observationKeyPath; // @synthesize observationKeyPath=_observationKeyPath;
- (void).cxx_destruct;
- (id)description;
- (id)copyWithZone:(struct _NSZone *)arg1;
- (id)initWithApplicationKeyPath:(id)arg1;

@end


text:
checkbox基本使用

已选checkbox

                        <input type="checkbox" class="u-checkbox-input" checked>
                        Checkbox

未选checkbox

                        <input type="checkbox" class="u-checkbox-input">
                        Checkbox

不可用未选checkbox

                        <input type="checkbox" class="u-checkbox-input" disabled>
                        Checkbox

不可用已选checkbox

                        <input type="checkbox" class="u-checkbox-input" disabled checked>
                        Checkbox

不同色彩的checkbox

                        <input type="checkbox" class="u-checkbox-input" checked>
                        green

                        <input type="checkbox" class="u-checkbox-input" checked>
                        blue

                        <input type="checkbox" class="u-checkbox-input" checked>
                        yellow

                        <input type="checkbox" class="u-checkbox-input" checked>
                        red

                        <input type="checkbox" class="u-checkbox-input" checked>
                        grey

图片checkbox

                        <input type="checkbox" class="u-checkbox-input" checked>

                        <input type="checkbox" class="u-checkbox-input">

个性checkbox

                        <input type="checkbox" class="u-checkbox-input" checked>
                        30天免息


text:
package peregin.gpv.gui.gauge

import com.google.common.cache.{CacheBuilder, CacheLoader, LoadingCache}
import peregin.gpv.util.ImageConverter

import java.awt._
import java.awt.image.BufferedImage
import java.util.concurrent.TimeUnit

object ImageCache {

  case class CacheKey(imagePath: String, w: Int, h: Int, gray: Int)

  val cache: LoadingCache[CacheKey, BufferedImage] = CacheBuilder
    .newBuilder()
    .maximumSize(1000)
    .expireAfterWrite(1, TimeUnit.DAYS)
    .build(new CacheLoader[CacheKey, BufferedImage] {
      override def load(key: CacheKey): BufferedImage = {
        val svgImage = ImageConverter.loadSvg(key.imagePath, key.w, key.h)
        ImageConverter.fillColor(svgImage, key.gray, key.gray, key.gray)
      }
    })

  def svgImage(imagePath: String, w: Int, h: Int, gray: Int): BufferedImage = {
    val key = CacheKey(imagePath, w, h, gray)
    cache.get(key)
  }
}

trait SvgGauge extends GaugePainter {

  def imagePath: String

  def valueText: String

  def unitText: String

  override def paint(g: Graphics2D, w: Int, h: Int) = {
    super.paint(g, w, h)

    val box = math.min(w, h)
    val cy = h / 2
    val d = box / 5
    val r = d / 4

    // draw heart icon
    g.setColor(Color.white)
    val px = 10
    val py = (h - 10) / 2

    val sx = w / 4
    val sy = h / 4

    val whiteImage = ImageCache.svgImage(imagePath, sx, sy, 255)
    g.drawImage(whiteImage, px, py, null)

    // fill the heart based on the current value
    val pointerHeight = (input.current - input.boundary.min) * sy / input.boundary.diff
    g.clipRect(px, py + sy - pointerHeight.toInt, sx, pointerHeight.toInt)

    val grayImage = ImageCache.svgImage(imagePath, sx, sy, 150)
    g.drawImage(grayImage, px, py, null)
    // revert clip
    g.setClip(null)

    // draw current value
    g.setFont(gaugeFont.deriveFont(Font.BOLD, (box / 4).toFloat))
    val tb = g.getFontMetrics.getStringBounds(valueText, g)
    textWidthShadow(g, valueText, px + (w - tb.getWidth) / 2, (h + tb.getHeight) / 2)
    // draw unit
    g.setFont(gaugeFont.deriveFont(Font.BOLD, (box / 12).toFloat))
    val utb = g.getFontMetrics.getStringBounds(unitText, g)
    textWidthShadow(g, unitText, px + (w - utb.getWidth) / 2, cy + utb.getHeight * 2.2)
  }

}


text:
package main

import (
	"flag"
	"net/http"
	"os"

	"github.com/kyokomi/slackbot"
	"github.com/kyokomi/slackbot/plugins/echo"
)

func main() {
	var token string
	flag.StringVar(&token, "token", os.Getenv("SLACK_BOT_TOKEN"), "SlackのBotToken")
	flag.Parse()

	bot, err := slackbot.NewBotContext(token)
	if err != nil {
		panic(err)
	}
	bot.AddPlugin("echo", echo.NewPlugin())

	bot.WebSocketRTM()

	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("OK"))
	})
	http.ListenAndServe(":8000", nil)
}


text:
class AddIndexToConditionalIdOnElements < ActiveRecord::Migration

	# def self.up
	# end

	# def self.down
	# end

  def self.up
    add_index Qe::Element.table_name, :conditional_id
    add_index Qe::Element.table_name, :question_grid_id
  end

  def self.down
    remove_index Qe::Element.table_name, :question_grid_id
    remove_index Qe::Element.table_name, :conditional_id
  end
end


text:
SELECT *
FROM users
WHERE github_profile = ?


text:
"""Support for IKEA Tradfri lights."""
from __future__ import annotations

from collections.abc import Callable
from typing import Any, cast

from pytradfri.command import Command

from homeassistant.components.light import (
    ATTR_BRIGHTNESS,
    ATTR_COLOR_TEMP,
    ATTR_HS_COLOR,
    ATTR_TRANSITION,
    SUPPORT_BRIGHTNESS,
    SUPPORT_COLOR,
    SUPPORT_COLOR_TEMP,
    LightEntity,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
import homeassistant.util.color as color_util

from .base_class import TradfriBaseClass, TradfriBaseDevice
from .const import (
    ATTR_DIMMER,
    ATTR_HUE,
    ATTR_SAT,
    ATTR_TRANSITION_TIME,
    CONF_GATEWAY_ID,
    CONF_IMPORT_GROUPS,
    DEVICES,
    DOMAIN,
    GROUPS,
    KEY_API,
    SUPPORTED_GROUP_FEATURES,
    SUPPORTED_LIGHT_FEATURES,
)

async def async_setup_entry(
    hass: HomeAssistant,
    config_entry: ConfigEntry,
    async_add_entities: AddEntitiesCallback,
) -> None:
    """Load Tradfri lights based on a config entry."""
    gateway_id = config_entry.data[CONF_GATEWAY_ID]
    tradfri_data = hass.data[DOMAIN][config_entry.entry_id]
    api = tradfri_data[KEY_API]
    devices = tradfri_data[DEVICES]

    lights = [dev for dev in devices if dev.has_light_control]
    if lights:
        async_add_entities(TradfriLight(light, api, gateway_id) for light in lights)

    if config_entry.data[CONF_IMPORT_GROUPS] and (groups := tradfri_data[GROUPS]):
        async_add_entities(TradfriGroup(group, api, gateway_id) for group in groups)

class TradfriGroup(TradfriBaseClass, LightEntity):
    """The platform class for light groups required by hass."""

    _attr_supported_features = SUPPORTED_GROUP_FEATURES

    def __init__(
        self,
        device: Command,
        api: Callable[[Command | list[Command]], Any],
        gateway_id: str,
    ) -> None:
        """Initialize a Group."""
        super().__init__(device, api, gateway_id)

        self._attr_unique_id = f"group-{gateway_id}-{device.id}"
        self._attr_should_poll = True
        self._refresh(device)

    async def async_update(self) -> None:
        """Fetch new state data for the group.

        This method is required for groups to update properly.
        """
        await self._api(self._device.update())

    @property
    def is_on(self) -> bool:
        """Return true if group lights are on."""
        return cast(bool, self._device.state)

    @property
    def brightness(self) -> int | None:
        """Return the brightness of the group lights."""
        return cast(int, self._device.dimmer)

    async def async_turn_off(self, **kwargs: Any) -> None:
        """Instruct the group lights to turn off."""
        await self._api(self._device.set_state(0))

    async def async_turn_on(self, **kwargs: Any) -> None:
        """Instruct the group lights to turn on, or dim."""
        keys = {}
        if ATTR_TRANSITION in kwargs:
            keys["transition_time"] = int(kwargs[ATTR_TRANSITION]) * 10

        if ATTR_BRIGHTNESS in kwargs:
            if kwargs[ATTR_BRIGHTNESS] == 255:
                kwargs[ATTR_BRIGHTNESS] = 254

            await self._api(self._device.set_dimmer(kwargs[ATTR_BRIGHTNESS], **keys))
        else:
            await self._api(self._device.set_state(1))

class TradfriLight(TradfriBaseDevice, LightEntity):
    """The platform class required by Home Assistant."""

    def __init__(
        self,
        device: Command,
        api: Callable[[Command | list[Command]], Any],
        gateway_id: str,
    ) -> None:
        """Initialize a Light."""
        super().__init__(device, api, gateway_id)
        self._attr_unique_id = f"light-{gateway_id}-{device.id}"
        self._hs_color = None

        # Calculate supported features
        _features = SUPPORTED_LIGHT_FEATURES
        if device.light_control.can_set_dimmer:
            _features |= SUPPORT_BRIGHTNESS
        if device.light_control.can_set_color:
            _features |= SUPPORT_COLOR | SUPPORT_COLOR_TEMP
        if device.light_control.can_set_temp:
            _features |= SUPPORT_COLOR_TEMP
        self._attr_supported_features = _features

        self._refresh(device)
        if self._device_control:
            self._attr_min_mireds = self._device_control.min_mireds
            self._attr_max_mireds = self._device_control.max_mireds

    @property
    def is_on(self) -> bool:
        """Return true if light is on."""
        if not self._device_data:
            return False
        return cast(bool, self._device_data.state)

    @property
    def brightness(self) -> int | None:
        """Return the brightness of the light."""
        if not self._device_data:
            return None
        return cast(int, self._device_data.dimmer)

    @property
    def color_temp(self) -> int | None:
        """Return the color temp value in mireds."""
        if not self._device_data:
            return None
        return cast(int, self._device_data.color_temp)

    @property
    def hs_color(self) -> tuple[float, float] | None:
        """HS color of the light."""
        if not self._device_control or not self._device_data:
            return None
        if self._device_control.can_set_color:
            hsbxy = self._device_data.hsb_xy_color
            hue = hsbxy[0] / (self._device_control.max_hue / 360)
            sat = hsbxy[1] / (self._device_control.max_saturation / 100)
            if hue is not None and sat is not None:
                return hue, sat
        return None

    async def async_turn_off(self, **kwargs: Any) -> None:
        """Instruct the light to turn off."""
        # This allows transitioning to off, but resets the brightness
        # to 1 for the next set_state(True) command
        if not self._device_control:
            return
        transition_time = None
        if ATTR_TRANSITION in kwargs:
            transition_time = int(kwargs[ATTR_TRANSITION]) * 10

            dimmer_data = {ATTR_DIMMER: 0, ATTR_TRANSITION_TIME: transition_time}
            await self._api(self._device_control.set_dimmer(**dimmer_data))
        else:
            await self._api(self._device_control.set_state(False))

    async def async_turn_on(self, **kwargs: Any) -> None:
        """Instruct the light to turn on."""
        if not self._device_control:
            return
        transition_time = None
        if ATTR_TRANSITION in kwargs:
            transition_time = int(kwargs[ATTR_TRANSITION]) * 10

        dimmer_command = None
        if ATTR_BRIGHTNESS in kwargs:
            brightness = kwargs[ATTR_BRIGHTNESS]
            brightness = min(brightness, 254)
            dimmer_data = {
                ATTR_DIMMER: brightness,
                ATTR_TRANSITION_TIME: transition_time,
            }
            dimmer_command = self._device_control.set_dimmer(**dimmer_data)
            transition_time = None
        else:
            dimmer_command = self._device_control.set_state(True)

        color_command = None
        if ATTR_HS_COLOR in kwargs and self._device_control.can_set_color:
            hue = int(kwargs[ATTR_HS_COLOR][0] * (self._device_control.max_hue / 360))
            sat = int(
                kwargs[ATTR_HS_COLOR][1] * (self._device_control.max_saturation / 100)
            )
            color_data = {
                ATTR_HUE: hue,
                ATTR_SAT: sat,
                ATTR_TRANSITION_TIME: transition_time,
            }
            color_command = self._device_control.set_hsb(**color_data)
            transition_time = None

        temp_command = None
        if ATTR_COLOR_TEMP in kwargs and (
            self._device_control.can_set_temp or self._device_control.can_set_color
        ):
            temp = kwargs[ATTR_COLOR_TEMP]
            # White Spectrum bulb
            if self._device_control.can_set_temp:
                if temp > self.max_mireds:
                    temp = self.max_mireds
                elif temp < self.min_mireds:
                    temp = self.min_mireds
                temp_data = {
                    ATTR_COLOR_TEMP: temp,
                    ATTR_TRANSITION_TIME: transition_time,
                }
                temp_command = self._device_control.set_color_temp(**temp_data)
                transition_time = None
            # Color bulb (CWS)
            # color_temp needs to be set with hue/saturation
            elif self._device_control.can_set_color:
                temp_k = color_util.color_temperature_mired_to_kelvin(temp)
                hs_color = color_util.color_temperature_to_hs(temp_k)
                hue = int(hs_color[0] * (self._device_control.max_hue / 360))
                sat = int(hs_color[1] * (self._device_control.max_saturation / 100))
                color_data = {
                    ATTR_HUE: hue,
                    ATTR_SAT: sat,
                    ATTR_TRANSITION_TIME: transition_time,
                }
                color_command = self._device_control.set_hsb(**color_data)
                transition_time = None

        # HSB can always be set, but color temp + brightness is bulb dependent
        if (command := dimmer_command) is not None:
            command += color_command
        else:
            command = color_command

        if self._device_control.can_combine_commands:
            await self._api(command + temp_command)
        else:
            if temp_command is not None:
                await self._api(temp_command)
            if command is not None:
                await self._api(command)

    def _refresh(self, device: Command) -> None:
        """Refresh the light data."""
        super()._refresh(device)

        # Caching of LightControl and light object
        self._device_control = device.light_control
        self._device_data = device.light_control.lights[0]


text:
set -e

usage() {
    echo "Usage: $0 [debug|stripped]"
    exit 1
}

check_args() {
    if [ $# -lt 1 ]; then
        usage
    fi

    type=$1

    if [ "$type" != "debug" ] && [ "$type" != "stripped" ]; then
        usage
    fi
}

main() {
    check_args $*
    if [ -z "${ENVOY_TAG}" ]; then
        ENVOY_TAG="latest"
    fi

    if [ "${type}" == "debug" ]; then
        ENVOY_IMAGE=lyft/envoy-alpine-debug:${ENVOY_TAG}
    else
        ENVOY_IMAGE=lyft/envoy-alpine:${ENVOY_TAG}
    fi
    TEST_CONTAINER=alpine_envoy_test_ct

    # Spin up a test container for the smoke test.
    set +e
    docker rm -fv ${TEST_CONTAINER}
    set -e
    docker run -d --name ${TEST_CONTAINER} ${ENVOY_IMAGE} /usr/local/bin/envoy -c /usr/local/conf/envoy/google_com_proxy.json
    output=`docker exec alpine_envoy_test_ct ps aux | grep google_com_proxy`
    if [ -z "$output" ]; then
	    echo "Failed to detect envoy binary to be running!"
	    exit 1
    fi
    echo "Successfully started envoy in container ${TEST_CONTAINER}"
    #TODO - add more tests, like a health check.
}

main $*


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.ServiceModel;
using System.ServiceModel.Channels;

namespace WcfService.TestResources
{
    internal class HttpsDigestResource : HttpsResource
    {
        protected override string Address { get { return "https-digest"; } }

        protected override Binding GetBinding()
        {
            var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport);
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Digest;
            return binding;
        }
    }
}