text:
<file_sep><?php

namespace App\Price;

use App\Movie;

class NewReleasePrice extends Price
{
    /**
     * 新作の料金コードを返す
     *
     * @return int
     */
    public function getPriceCode()
    {
        return Movie::NEW_RELEASE;
    }

    /**
     * @param $dayRented
     * @return float|int
     */
    public function getCharge($dayRented)
    {
        return $dayRented * 3;
    }

    /**
     * @param $dayRented
     * @return int
     */
    public function getFrequentRentalPoint($dayRented)
    {
        return ($dayRented > 1) ? 2 : 1;
    }
}
<file_sep><?php

namespace Tests\Price;

use App\Movie;
use App\Price\NewReleasePrice;
use PHPUnit_Framework_TestCase;

class NewReleaseTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var NewReleasePrice
     */
    protected $newReleasePrice;

    protected function setUp()
    {
        $this->newReleasePrice = new NewReleasePrice;
    }

    /**
     * @test
     *
     */
    public function testGetPriceCode()
    {
        $this->assertSame(Movie::NEW_RELEASE, $this->newReleasePrice->getPriceCode());
    }

    /**
     * @test
     *
     */
    public function testGetCharge()
    {
        $dayRented = 3;
        $expected = $dayRented * 3;
        $this->assertSame($expected, $this->newReleasePrice->getCharge($dayRented));
    }

    /**
     * @test
     *
     */
    public function testGetFrequentRentalPoint()
    {
        // レンタル泊数が１日以下の場合
        $dayRented = 1;
        $expectedWithin1days = 1;
        $this->assertSame($expectedWithin1days, $this->newReleasePrice->getFrequentRentalPoint($dayRented));

        // レンタル泊数が２日以上の場合
        $dayRented = 2;
        $expectedOver2days = 2;
        $this->assertSame($expectedOver2days, $this->newReleasePrice->getFrequentRentalPoint($dayRented));
    }
}
<file_sep><?php

namespace Tests;

use App\Customer;
use App\Movie;
use App\Price\NewReleasePrice;
use App\Price\RegularPrice;
use App\Rental;
use PHPUnit_Framework_TestCase;

class CustomerTest extends PHPUnit_Framework_TestCase
{
    /**
     * @test
     *
     */
    public function testGetTotalCharge()
    {
        $customer_taro = new Customer('テスト太郎');

        $movie1 = new Movie('一般向け映画1', Movie::REGULAR);
        $movie2 = new Movie('一般向け映画2', Movie::REGULAR);
        $rental1 = new Rental($movie1, 7);
        $rental2 = new Rental($movie2, 7);

        $customer_taro->addRental($rental1);
        $customer_taro->addRental($rental2);

        $regularPrice = new RegularPrice();
        $expected = $regularPrice->getCharge(7) * 2;

        $this->assertEquals($expected, $customer_taro->getTotalCharge());
    }

    /**
     * @test
     *
     */
    public function testGetTotalFrequentRentalPoint()
    {
        // 新作映画を借りた場合
        $customer_hanako = new Customer('テスト花子');

        $newReleaseMovie1 = new Movie('新作映画1', Movie::NEW_RELEASE);
        $newReleaseMovie2 = new Movie('新作映画2', Movie::NEW_RELEASE);
        $rental1 = new Rental($newReleaseMovie1, 7);
        $rental2 = new Rental($newReleaseMovie2, 7);

        $customer_hanako->addRental($rental1);
        $customer_hanako->addRental($rental2);

        $newReleasePrice = new NewReleasePrice();
        $expected_newRelease = $newReleasePrice->getFrequentRentalPoint(7) * 2;

        $this->assertSame($expected_newRelease, $customer_hanako->getTotalFrequentRentalPoint());

        // 新作以外を借りた場合は、１本につき１ポイント
        $customer_ziro = new Customer('次郎');

        $regularMovie = new Movie('一般向け映画', Movie::REGULAR);
        $childMovie = new Movie('子供向け映画', Movie::CHILD);
        $rental3 = new Rental($regularMovie, 7);
        $rental4 = new Rental($childMovie, 7);

        $customer_ziro->addRental($rental3);
        $customer_ziro->addRental($rental4);

        $expected_expectNewRelease = 2;

        $this->assertSame($expected_expectNewRelease, $customer_ziro->getTotalFrequentRentalPoint());
    }

    /**
     * @test
     *
     */
    public function testStatement()
    {
        $customer_saburo = new Customer('三郎');

        $newReleaseMovie1 = new Movie('新作映画1', Movie::NEW_RELEASE);
        $newReleaseMovie2 = new Movie('新作映画2', Movie::NEW_RELEASE);
        $rental1 = new Rental($newReleaseMovie1, 7);
        $rental2 = new Rental($newReleaseMovie2, 7);

        $customer_saburo->addRental($rental1);
        $customer_saburo->addRental($rental2);

        // 新作映画の料金は、レンタル泊数の３倍　新作映画のFrequentRentalPointは１作につき２ポイント
        $expected = 'Rental Point for 三郎' . "\n" . "\t" . '新作映画1' . "\t" . 21 . "\n" . "\t" . '新作映画2' . "\t" . 21 . "\n"
            . 'Amount owed is ' . 42 . "\n" . 'You earned ' . 4 . ' frequent renter points' . "\n";

        $this->assertEquals($expected, $customer_saburo->statement());
    }
}<file_sep><?php

namespace App\Price;

use App\Movie;

class ChildrenPrice extends Price
{
    /**
     * 子供向けビデオの料金コードを返す
     *
     * @return int
     */
    public function getPriceCode()
    {
        return Movie::CHILD;
    }

    public function getCharge($dayRented)
    {
        $result = 1.5;
        if ($dayRented > 3) {
            $result += ($dayRented - 3) * 1.5;
        }
        return $result;
    }
}<file_sep><?php

namespace App\Price;

use App\Movie;

class RegularPrice extends Price
{
    /**
     * 一般向けの料金コードを返す
     *
     * @return int
     */
    public function getPriceCode()
    {
       return Movie::REGULAR;
    }

    /**
     * @param $dayRented
     * @return float|int|mixed
     */
    public function getCharge($dayRented)
    {
        $result = 2;

        if ($dayRented > 2) {
            $result += ($dayRented - 2) * 1.5;
        }

        return $result;
    }
}<file_sep><?php
require 'vendor/autoload.php';

use App\Customer;
use App\Movie;
use App\Rental;

$movie = new Movie('シンドラーのリスト',0);
$rental = new Rental($movie,7);
$customer = new Customer('スティーヴン・スピルバーグ');
$customer->addRental($rental);

echo $customer->statement();<file_sep><?php

namespace App;

use App\Price\ChildrenPrice;
use App\Price\NewReleasePrice;
use App\Price\Price;
use App\Price\RegularPrice;

class Movie
{
    /** 一般向け
     *
     * @var int
     */
    const REGULAR = 0;

    /** 新着ビデオ
     *
     * @var int
     */
    const NEW_RELEASE = 1;

    /** 子供向け
     *
     * @var int
     */
    const CHILD = 2;

    /** @var string */
    private $title;

    /**
     * @var Price
     */
    private $price;

    public function __construct($title, $priceCode)
    {
        $this->title = $title;
        $this->setPriceCode($priceCode);
    }

    /**
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * @param string $title
     */
    public function setTitle($title)
    {
        $this->title = $title;
    }

    /**
     * @return int
     */
    public function getPriceCode()
    {
        return $this->price->getPriceCode();
    }

    /**
     * 料金コードをセット
     *
     * @param $arg
     */
    public function setPriceCode($arg)
    {
        switch ($arg) {
            case Movie::REGULAR:
                $this->price = new RegularPrice();
                break;
            case Movie::NEW_RELEASE:
                $this->price = new NewReleasePrice();
                break;
            case Movie::CHILD:
                $this->price = new ChildrenPrice();
                break;
            default:
                throw new \InvalidArgumentException('不正な料金コード');
        }
    }

    /**
     * ビデオのカテゴリとレンタル泊数に応じてポイントを返す
     *
     * @param $dayRented
     * @return float|int
     */
    public function getCharge($dayRented)
    {
       return $this->price->getCharge($dayRented);
    }

    /**
     * 新作を２日以上借りた場合は、ボーナスポイント
     *
     * @param $dayRented
     * @return int
     */
    public function getFrequentRentalPoint($dayRented)
    {
        return $this->price->getFrequentRentalPoint($dayRented);
    }
}<file_sep><?php

namespace Tests;

use App\Movie;
use PHPUnit_Framework_TestCase;

class MovieTest extends PHPUnit_Framework_TestCase
{
    /** @var Movie 一般向け映画 */
    private $regularMovie;

    /** @var Movie 新作映画 */
    private $newReleaseMovie;

    /** @var Movie 子供向け映画 */
    private $childMovie;

    protected function setUp()
    {
        $this->regularMovie = new Movie('一般向け映画', Movie::REGULAR);
        $this->newReleaseMovie = new Movie('新作映画', Movie::NEW_RELEASE);
        $this->childMovie = new Movie('子供向け映画', Movie::CHILD);
    }

    /**
     *　@test
     */
    public function testPriceCode()
    {
        $this->assertEquals(Movie::REGULAR, $this->regularMovie->getPriceCode());
        $this->assertEquals(Movie::NEW_RELEASE, $this->newReleaseMovie->getPriceCode());
        $this->assertEquals(Movie::CHILD, $this->childMovie->getPriceCode());
    }
}
<file_sep><?php

namespace Tests\Price;

use App\Movie;
use App\Price\ChildrenPrice;
use PHPUnit_Framework_TestCase;

class ChildrenPriceTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var ChildrenPrice
     */
    protected $childrenPrice;

    protected function setUp()
    {
        $this->childrenPrice = new ChildrenPrice;
    }

    /**
     * @test
     *
     */
    public function testGetPriceCode()
    {
        $this->assertSame(Movie::CHILD, $this->childrenPrice->getPriceCode());
    }

    /**
     * @test
     *
     */
    public function testGetCharge()
    {
        // レンタル泊数が３日以下の場合
        $dayRented = 3;
        $expectedWithin3days = 1.5;
        $this->assertEquals($expectedWithin3days, $this->childrenPrice->getCharge($dayRented));

        // レンタル泊数が４日以上の場合
        $dayRented = 4;
        $within3daysCharge = 1.5;
        $expectedOver4days = ($dayRented - 3) * 1.5 + $within3daysCharge;
        $this->assertEquals($expectedOver4days, $this->childrenPrice->getCharge($dayRented));
    }
}
<file_sep><?php

namespace App\Price;

abstract class Price
{
    /**
     * @return mixed
     */
    abstract public function getPriceCode();

    /**
     * @param $dayRented
     * @return mixed
     */
    abstract public function getCharge($dayRented);

    /**
     * @param $dayRented
     * @return int
     */
    public function getFrequentRentalPoint($dayRented){
        return 1;
    }
}<file_sep><?php

namespace App;

use App\Movie;

class Rental
{
    /**
     * @var Movie
     */
    private $movie;

    /** @var int */
    private $dayRented;

    /**
     * Rental constructor.
     *
     * @param Movie $movie
     * @param       $dayRented
     */
    public function __construct(Movie $movie, $dayRented)
    {
        $this->movie = $movie;
        $this->dayRented = $dayRented;
    }

    /**
     * レンタルしたビデオの名前を返す
     *
     * @return Movie
     */
    public function getMovie()
    {
        return $this->movie;
    }

    /**
     * レンタル泊数を返す
     *
     * @return int
     */
    public function getDaysRented()
    {
        return $this->dayRented;
    }

    /**
     * ビデオのカテゴリとレンタル泊数に応じてポイントを返す
     *
     * @return float|int
     */
    public function getCharge()
    {
        return $this->movie->getCharge($this->dayRented);
    }

    /**
     * 新作を２日以上借りた場合は、ボーナスポイント
     *
     * @return int
     */
    public function getFrequentRentalPoint()
    {
        return $this->movie->getFrequentRentalPoint($this->dayRented);
    }
}<file_sep><?php

namespace Tests\Price;

use App\Movie;
use App\Price\RegularPrice;
use PHPUnit_Framework_TestCase;

class RegularTest extends PHPUnit_Framework_TestCase
{
    /**
     * @var RegularPrice
     */
    protected $regularPrice;

    protected function setUp()
    {
        $this->regularPrice = new RegularPrice;
    }

    /**
     * @test
     *
     */
    public function testGetPriceCode()
    {
        $this->assertSame(Movie::REGULAR, $this->regularPrice->getPriceCode());
    }

    /**
     * @test
     *
     */
    public function testGetCharge()
    {
        // レンタル泊数が２日以下の場合
        $dayRented = 2;
        $expectedWithin2days = 2;
        $this->assertEquals($expectedWithin2days, $this->regularPrice->getCharge($dayRented));

        // レンタル泊数が３日以上の場合
        $dayRented = 3;
        $within2daysCharge = 2;
        $expectedOver2days = ($dayRented - 2) * 1.5 + $within2daysCharge;
        $this->assertEquals($expectedOver2days, $this->regularPrice->getCharge($dayRented));
    }
}
<file_sep><?php

namespace App;

class Customer
{
    /** @var string */
    private $name;

    /** @var array */
    private $rentals = [];

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

    /**
     * @param Rental $rental
     */
    public function addRental(Rental $rental)
    {
        $this->rentals[] = $rental;
    }

    /**
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return string
     */
    public function statement()
    {
        $result = 'Rental Point for ' . $this->getName() . "\n";

        foreach ($this->rentals as $rental) {
            $result .= "\t" . $rental->getMovie()->getTitle() . "\t" . $rental->getCharge(). "\n";
        }
        $result .= 'Amount owed is ' . $this->getTotalCharge() . "\n";
        $result .= 'You earned ' . $this->getTotalFrequentRentalPoint() . ' frequent renter points' . "\n";

        return $result;
    }

    /**
     * @return int
     */
    public function getTotalCharge()
    {
        $result = 0;
        foreach ($this->rentals as $rental) {
            $result += $rental->getCharge();
        }
        return $result;
    }

    /**
     * @return int
     */
    public function getTotalFrequentRentalPoint()
    {
        $result = 0;
        foreach ($this->rentals as $rental) {
            $result += $rental->getFrequentRentalPoint();
        }
        return $result;
    }
}

repo_language: PHP


text:
<repo_name>gongzuoqu/golang<file_sep>/src/cryptocurrency/bitcoin/keys/keys.go
package keys

import (
	"math/big"
	"io"
	"fmt"
	"os"
	"hash"
	"bytes"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/md5"
	"crypto/sha256"
	"golang.org/x/crypto/ripemd160"
	"strings"
)

type PrivateKey struct {
	ecdsa.PrivateKey
}

type PublicKey struct {
	ecdsa.PublicKey
	btckey string
}

func (pubkey *PublicKey) generateBitcoinAddress() (address string) {

	x := pubkey.PublicKey.X.Bytes()
	y := pubkey.PublicKey.Y.Bytes()

	/* Pad X and Y coordinate bytes to 32-bytes */
	padded_x := append(bytes.Repeat([]byte{0x00}, 32-len(x)), x...)
	padded_y := append(bytes.Repeat([]byte{0x00}, 32-len(y)), y...)

	/* Add prefix 0x04 for uncompressed coordinates */
	var clear_key = append([]byte{0x04}, append(padded_x, padded_y...)...)

	/* SHA256 Hash */
	sha256_h := sha256.New()
	sha256_h.Reset()
	sha256_h.Write(clear_key)
	pub_hash_1 := sha256_h.Sum(nil)

	/* RIPEMD-160 Hash */
	ripemd160_h := ripemd160.New()
	ripemd160_h.Reset()
	ripemd160_h.Write(pub_hash_1)
	pub_hash_2 := ripemd160_h.Sum(nil)

	/* Convert hash bytes to base58 check encoded sequence */
	address = b58checkencode(0x00, pub_hash_2)

	return address
}

func (pubkey *PublicKey) processHash() ([]byte) {

	/* Convert the public key to bytes */
	pub_bytes := pubkey.ToBytesUncompressed()

	/* SHA256 Hash */
	sha256_h := sha256.New()
	sha256_h.Reset()
	sha256_h.Write(pub_bytes)
	pub_hash_1 := sha256_h.Sum(nil)

	/* RIPEMD-160 Hash */
	ripemd160_h := ripemd160.New()
	ripemd160_h.Reset()
	ripemd160_h.Write(pub_hash_1)
	pub_hash_2 := ripemd160_h.Sum(nil)

	return pub_hash_2
}

// ToBytesUncompressed converts a Bitcoin public key to a 65-byte byte slice without point compression.
func (pubkey *PublicKey) ToBytesUncompressed() (b []byte) {
	/* See Certicom SEC1 2.3.3, pg. 10 */

	x := pubkey.PublicKey.X.Bytes()
	y := pubkey.PublicKey.Y.Bytes()

	/* Pad X and Y coordinate bytes to 32-bytes */
	padded_x := append(bytes.Repeat([]byte{0x00}, 32-len(x)), x...)
	padded_y := append(bytes.Repeat([]byte{0x00}, 32-len(y)), y...)

	/* Add prefix 0x04 for uncompressed coordinates */
	return append([]byte{0x04}, append(padded_x, padded_y...)...)
}

// ToAddressUncompressed converts a Bitcoin public key to an uncompressed Bitcoin address string.
func (pubkey *PublicKey) ToAddressUncompressed() (address string) {
	/* See https://en.bitcoin.it/wiki/Technical_background_of_Bitcoin_addresses */

	/* Convert the public key to bytes */
	pub_bytes := pubkey.ToBytesUncompressed()

	/* SHA256 Hash */
	sha256_h := sha256.New()
	sha256_h.Reset()
	sha256_h.Write(pub_bytes)
	pub_hash_1 := sha256_h.Sum(nil)

	/* RIPEMD-160 Hash */
	ripemd160_h := ripemd160.New()
	ripemd160_h.Reset()
	ripemd160_h.Write(pub_hash_1)
	pub_hash_2 := ripemd160_h.Sum(nil)

	/* Convert hash bytes to base58 check encoded sequence */
	address = b58checkencode(0x00, pub_hash_2)

	return address
}

// b58checkencode encodes version ver and byte slice b into a base-58 check encoded string.
func b58checkencode(ver uint8, b []byte) (s string) {
	/* Prepend version */
	bcpy := append([]byte{ver}, b...)

	/* Create a new SHA256 context */
	sha256_h := sha256.New()

	/* SHA256 Hash #1 */
	sha256_h.Reset()
	sha256_h.Write(bcpy)
	hash1 := sha256_h.Sum(nil)

	/* SHA256 Hash #2 */
	sha256_h.Reset()
	sha256_h.Write(hash1)
	hash2 := sha256_h.Sum(nil)

	/* Append first four bytes of hash */
	bcpy = append(bcpy, hash2[0:4]...)

	/* Encode base58 string */
	s = b58encode(bcpy)

	/* For number of leading 0's in bytes, prepend 1 */
	for _, v := range bcpy {
		if v != 0 {
			break
		}
		s = "1" + s
	}

	return s
}

// b58checkdecode decodes base-58 check encoded string s into a version ver and byte slice b.
func b58checkdecode(s string) (ver uint8, b []byte, err error) {
	/* Decode base58 string */
	b, err = b58decode(s)
	if err != nil {
		return 0, nil, err
	}

	/* Add leading zero bytes */
	for i := 0; i < len(s); i++ {
		if s[i] != '1' {
			break
		}
		b = append([]byte{0x00}, b...)
	}

	/* Verify checksum */
	if len(b) < 5 {
		return 0, nil, fmt.Errorf("Invalid base-58 check string: missing checksum.")
	}

	/* Create a new SHA256 context */
	sha256_h := sha256.New()

	/* SHA256 Hash #1 */
	sha256_h.Reset()
	sha256_h.Write(b[:len(b)-4])
	hash1 := sha256_h.Sum(nil)

	/* SHA256 Hash #2 */
	sha256_h.Reset()
	sha256_h.Write(hash1)
	hash2 := sha256_h.Sum(nil)

	/* Compare checksum */
	if bytes.Compare(hash2[0:4], b[len(b)-4:]) != 0 {
		return 0, nil, fmt.Errorf("Invalid base-58 check string: invalid checksum.")
	}

	/* Strip checksum bytes */
	b = b[:len(b)-4]

	/* Extract and strip version */
	ver = b[0]
	b = b[1:]

	return ver, b, nil
}

// b58encode encodes a byte slice b into a base-58 encoded string.
func b58encode(b []byte) (s string) {
	/* See https://en.bitcoin.it/wiki/Base58Check_encoding */

	const BITCOIN_BASE58_TABLE = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

	/* Convert big endian bytes to big int */
	x := new(big.Int).SetBytes(b)

	/* Initialize */
	r := new(big.Int)
	m := big.NewInt(58)
	zero := big.NewInt(0)
	s = ""

	/* Convert big int to string */
	for x.Cmp(zero) > 0 {
		/* x, r = (x / 58, x % 58) */
		x.QuoRem(x, m, r)
		/* Prepend ASCII character */
		s = string(BITCOIN_BASE58_TABLE[r.Int64()]) + s
	}

	return s
}

// b58decode decodes a base-58 encoded string into a byte slice b.
func b58decode(s string) (b []byte, err error) {
	/* See https://en.bitcoin.it/wiki/Base58Check_encoding */

	const BITCOIN_BASE58_TABLE = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"

	/* Initialize */
	x := big.NewInt(0)
	m := big.NewInt(58)

	/* Convert string to big int */
	for i := 0; i < len(s); i++ {
		b58index := strings.IndexByte(BITCOIN_BASE58_TABLE, s[i])
		if b58index == -1 {
			return nil, fmt.Errorf("Invalid base-58 character encountered: '%c', index %d.", s[i], i)
		}
		b58value := big.NewInt(int64(b58index))
		x.Mul(x, m)
		x.Add(x, b58value)
	}

	/* Convert big int to big endian bytes */
	b = x.Bytes()

	return b, nil
}

func generateKeyPair() (privatekey *ecdsa.PrivateKey)  {

	pubkeyCurve := elliptic.P256() //see http://golang.org/pkg/crypto/elliptic/#P256
	privatekey, err := ecdsa.GenerateKey(pubkeyCurve, rand.Reader) // this generates a public & private key pair

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	return privatekey
}

func testkey() {

	pubkeyCurve := elliptic.P256() //see http://golang.org/pkg/crypto/elliptic/#P256

	privatekey := new(ecdsa.PrivateKey)
	privatekey, err := ecdsa.GenerateKey(pubkeyCurve, rand.Reader) // this generates a public & private key pair

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	var pubkey ecdsa.PublicKey
	pubkey = privatekey.PublicKey

	fmt.Println("Private Key :")
	fmt.Printf("%x \n", privatekey)

	fmt.Println("Public Key :")
	fmt.Printf("%x \n", pubkey)

	// Sign ecdsa style

	var h hash.Hash
	h = md5.New()
	r := big.NewInt(0)
	s := big.NewInt(0)

	io.WriteString(h, "This is a message to be signed and verified by ECDSA!")
	signhash := h.Sum(nil)

	r, s, serr := ecdsa.Sign(rand.Reader, privatekey, signhash)
	if serr != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	signature := r.Bytes()
	signature = append(signature, s.Bytes()...)

	fmt.Printf("Signature : %x\n", signature)

	// Verify
	verifystatus := ecdsa.Verify(&pubkey, signhash, r, s)
	fmt.Println(verifystatus) // should be true
}

func main() {
	fmt.Println("Hello World from keys")
}<file_sep>/src/cryptocurrency/bitcoin/keys/keys_test.go
package keys

import (
	"testing"
	"crypto/ecdsa"
	"fmt"
)

func TestKeyGeneration(t *testing.T) {

	privateKey := generateKeyPair()

	var publicKey ecdsa.PublicKey
	publicKey = privateKey.PublicKey

	fmt.Println("Private Key :")
	fmt.Printf("%x \n", privateKey)

	fmt.Println("Public Key :")
	fmt.Printf("%x \n", publicKey)

	t.Log("FIN\n")
}

branch_name: refs/heads/master

repo_language: Go

repo_name: gongzuoqu/golang


text:
<repo_name>minprogramador/getProxy<file_sep>/get_rede.php
<?php

require('Curl.php');

$keyapi  = '<KEY>';
$url_api = "http://falcon.proxyrotator.com:51337/?apiKey={$keyapi}&country=br&port=3128";

if(count($argv) > 1) {
	foreach($argv as $arv){
		if(stristr($arv, 'u=')){
			$url = str_replace('u=', '', $arv);
		}
		if(stristr($arv, 's=')){
			$strurl = str_replace('s=', '', $arv);
		}
		if(stristr($arv, 't=')){
			$timeoutproxy = str_replace('t=', '', $arv);
		}
	}
}else{
	die('--> exemplo de uso:'.PHP_EOL.PHP_EOL.'php get_rede.php u="https://google.." s="google" t=3'.PHP_EOL.PHP_EOL);
}

if(!$url) {
	die('insira uma url valida! ex: php get_rede.php u="https://google.." s="google" t=3' . PHP_EOL);
}

if(!$strurl) {
	die('insira a string da url! ex: php get_rede.php u="https://google.." s="google" t=3' . PHP_EOL);
}

if(!$timeoutproxy) {
	$timeoutproxy = 5;
}

$max_get      = 5;
$count_get    = 0;
$total_stress = 10;
$max_chance   = 10;
$max_chancei  = 0;
$resultado    = [];
$resultok     = [];

while(true) {

	if($max_chancei >= $max_chance) {
		if(isset($infosokk)){
			$infosokk['url'] = $url;
			$infosokk['strurl'] = $strurl;
			print_r($infosokk);
		}else{
			echo 'nada encontrado, tente denovo';
		}
		break;
	}

	if($count_get >= 5) {
		echo "tentou pegar proxy 5x, e nao conseguiu, stop.";
		break;
	}

	$Curl = new Curl();
	$Curl->setTimeout(5);
	$Curl->add($url_api);
	$respr = $Curl->run();
	$respr = $respr['body'][0];
	$respr = json_decode($respr);

	if($respr->proxy and stristr($respr->proxy, ':')){
		$count_get    = 0;
		$proxy        = $respr->proxy;
		$pr_count_cod = 0;
		$pr_count_on  = 0;
		$pr_list_time = [];
		$pr_media = 0;

		$Curlin = new Curl();
		$useragent = $respr->randomUserAgent;
		$Curlin->setTimeout($timeoutproxy);

		for ($i = 1; $i <= $total_stress; $i++) {
			$Curlin->add($url, null, null, $proxy);
		}
		$respr = $Curlin->run();

		foreach($respr['body'] as $key => $value) {
			$inf       = $respr['info'][$key];
			$timeinf   = $inf['total_time'];
			$pr_media  = $pr_media + $timeinf;
			$pr_list_time[] = $timeinf;
			$statusinf = $inf['http_code'];
			$res       = $value;

			if($statusinf == '200'){
				$pr_count_cod++;
			}

			if(strlen($res) > 10)
			{
				if (stripos($res,$strurl) !== false) {
					$resultado[] = [
						'proxy'    => $proxy,
						'timeout'  => $timeinf,
						'httpcode' => $statusinf,
						'status'   => 'on'
					];
					$pr_count_on++;
				}
			}
			else
			{
				$resultado[] = [
					'proxy'    => $proxy,
					'timeout'  => $timeinf,
					'httpcode' => $statusinf,
					'status'   => 'off'
				];
			}
		}

		$pr_media_ok = array_sum($pr_list_time)/count($pr_list_time);
		$pr_media_ok = round($pr_media_ok, 2);
		$pr_media_ok = round($pr_media_ok);

		if($pr_media_ok < 5) {

			if($pr_count_on === $total_stress) {
				$infosokk = [
					'count_test' => $pr_count_on,
					'total_test' => $total_stress,
					'timeout' => $pr_media_ok,
					'proxy'   => $proxy
				];
				$max_chancei = $max_chance+10;
			}

		}else{
			echo "\n--> proxy: $proxy - timeout media: $pr_media_ok  - count_test: $pr_count_on de $total_stress ~ passando para o proximo...\n";
		}
	} else {
		$count_get++;
		continue;
	}

	$max_chancei++;
}
<file_sep>/README.md
# getProxy

exemplo de uso.

```
php get_rede.php u="https://google.." s="google" t=3
```

languages: Markdown PHP

repo_language: Markdown

repo_name: minprogramador/getProxy


text:
<repo_name>Nirmaljeet/starting_with_bash<file_sep>/bash.sh
#!/bin/bash
read number1
echo " enter the value of $number1 "
read number2
echo " enter the value of $number2 "
if [ $number1 -eq $number2 ]; then
echo "$number1 is equal to $number2"
else
echo "$number1 is not equl to $number2"
fi
<file_sep>/bash8.sh
arr = (10 8 20 100 12)
echo "array in original order is"
echo ${arr[*]}
for ((i = 0; i < 5; i++))
do
for((j = 1; j < 5-i-1; j++))
do
if((${arr[j]} > ${arr[$((j+1))]}))
then
temp = ${arr[$j]}
arr[$j] = ${arr[$((j+1))]}
arr[$((j+1))] = $temp
fi
done
done
echo "array in sorted order is "
echo ${arr[*]}
<file_sep>/bash6.sh
#!/bin/bash
count ="9"
while [ $count -gt 0 ]; do
echo "$count"
count=$[$count-1]
done
<file_sep>/bash3.sh
#!/bin/bash
read name1
echo "please enter $name1"
read name2
echo "please enter $name2"
read name3
echo "please enter $name3"
for name in $names; do
echo "hello $name"
done
for number in 'seq 1 10 ' ; do
echo " i am $number"
done
<file_sep>/command.sh
#!/bin/bash
mkdir nirmal
cd nirmal
nano nirmaljeet
pwd
cd ..
ls
mkdir abcd
cd abcd
pwd
cd ..
cd ~
mkdir 12345
cd 12345
nano abcde
ls

<file_sep>/bash1.sh
#!/bin/bash
number1=6; number2=5
if [ $number1 -ne $number2 ]; then
if [ $number1 -gt $number2 ]; then
echo "$number1 is greater than $number2"
else
echo "$number1 is lesser than $number2"
fi
else
echo "$number1 is equal to $number2"
fi

<file_sep>/bash4.sh
#!/bin/bash
function greet {
echo "hello !"
}
greet "world"
greet "user"
<file_sep>/bash5.sh
#!/bin/bash
number1=5; number2=5
if [ $number1 -gt $number2 ]; then
echo "$number1 is lesser than $number2"
elif [ $number1 -lt $number2 ]; then
echo "$number1 is lesser than the $number2"
else
echo "$number1 is equal to $number2"
fi
<file_sep>/server.sh
echo " enter the pattern you want to search"
read ch
grep -c $ch access.log
grep -n $ch access.log
<file_sep>/cal1.sh.save
#!/bin/bash
echo "Enter two numbers"
read a
read b
echo "enter choice"
echo "1.addition"
echo "2.subtraction"
echo "3.multiplication"
echo "4.division"
echo "the answer of addition is"
case $ch
<file_sep>/bash7.sh
declare -a nirmaljeet
echo "how many groups you want to enter"
read group_count
echo "enter $group_count groups :"
for(( c = 0 ; c <= $group_count ; c++))
do
read abc_elements
while read abc_elements
do
nirmaljeet[$c]="$abc_elements"
done
done
echo -e "${nirmaljeet[@]}"
<file_sep>/bash2.sh
#!/bin/bash
name="john"
case "$name" in
john) echo "Welcome admin" ;&
alexa) echo "welcome user" ;&
*) echo "access denied" ;&
esac
<file_sep>/script.sh
#!/bin/bash
echo enter the number you want to find the factorial
read var
./a.out $var
read $var

repo_language: Shell


text:
<repo_name>reritom/ShiftRe<file_sep>/README.md
# ShiftRe
Code for interfacing and configuring any number of daisy-chained 74HC595 shift registers so they can be effectively used as additional ports for microcontrollers.

The 595 is a serial-in parallel-out shift register, more information can be found here https://www.arduino.cc/en/Tutorial/ShiftOut

Multiple 595s can be chained together, and by shifting out the bits and keeping track of the states of each bit, these 595s can be used as additional output ports which can be set to HIGH or LOW. For better use as an output, each of the output bits will be the base for a transistor with more useable collector current. The current from the shift registers are quite low, but enough to be used as the base current.

This code uses bitwise operators to keep track of which outputs are HIGH and LOW for an indefinite number of daisy-chained shift registers.

As it is written to run on an Arduino, there are the compulsory loop and setup functions. Loop runs the main program, setup is used to set the latch, data and clock pins. The ShiftOut function is taken from the link above, and the TurnPort function is the one used to turn outputs on and off and keep track of the changes.

For example, three daisy-chained 595s would have N=3 and 24 additional ports. To turn on port 1, use TurnPort(1), and to turn it back off, use TurnPort(-1). The ports are indexed from 1 instead of zero so that the sign can be used to indicate the action.
<file_sep>/ShiftRe.c
#define R 5    //The number of shift registers

int dataPin = 11;
int latchPin = 10;
int clockPin = 12;
int t = 100;

int bitArray[8] = { 1, 2, 4, 8, 16, 32, 64, 128 }; //for comparing

void setup ()
{
pinMode(dataPin, OUTPUT);
pinMode(latchPin, OUTPUT);
pinMode(clockPin, OUTPUT); //Set the arduino ports as outputs
}

void loop ()
{
//The main programme using the shift register function is here.
}

void turn_on(int n, int dataArray[R])
{
int i;

if ( n > 0)   //for given number is positive, to turn on
    {
    if ((n <= (R*8)) && (n > 0))
    {
     for (i = 0; i < R; ++i)
          {
           if ((n > (8*i)) && (n<= (8*(i+1))))
                {
                int bit = n - 8*i -1;
                dataArray[i] = dataArray[i] | bitArray[bit];
                }
          }
     }
       digitalWrite(latchPin, 0);
          for (i=R; i>0; --i)
       {
           int s = i - 1;

               shiftOut(dataPin, clockPin, dataArray[s]);

            delay(t);
       }
              digitalWrite(latchPin, 1);
    }

if (n < 0) //for if the  given number is negative, to turn off
    {
    n = -n;
    if ((n <= (R*8)) || (n > 0))
    {
     for (i = 0; i < R; ++i)
          {
           if ((n > (8*i)) && (n<= (8*(i+1))))
                {
                int bit = n - 8*i -1;
                dataArray[i] = (dataArray[i] & (~(dataArray[i] & bitArray[bit])));
                }
          }
     }
              digitalWrite(latchPin, 0);
          for (i=R; i>0; --i)
       {
int s = i - 1;
               shiftOut(dataPin, clockPin, dataArray[s]);

            delay(t);
       }
              digitalWrite(latchPin, 1);
    }
return;
}

void shiftOut(int myDataPin, int myClockPin, byte myDataOut) {

 int i=0;
 int pinState;

 digitalWrite(myDataPin, 0);
 digitalWrite(myClockPin, 0);

 for (i=7; i>=0; i--)  {
    digitalWrite(myClockPin, 0);

    if ( myDataOut & (1<<i) ) {
     pinState= 1;
    }
    else {
     pinState= 0;
    }
    digitalWrite(myDataPin, pinState);
    digitalWrite(myClockPin, 1);
    digitalWrite(myDataPin, 0);
 }
 digitalWrite(myClockPin, 0);
}

languages: Markdown C

repo_name: reritom/ShiftRe


text:
<file_sep># -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html

import scrapy

# 关于每一个问题的信息
class QuesInfoItem(scrapy.Item):
	created_time = scrapy.Field() #活动类型
	action_text = scrapy.Field() #活动类型
	content = scrapy.Field() #内容
	question = scrapy.Field() #问题

class CommentInfoItem(scrapy.Item):
	name = scrapy.Field() #评论者姓名
	bio = scrapy.Field() #评论者简介
	url = scrapy.Field() #评论者主页url
	content = scrapy.Field() #评论内容
<file_sep># -*- coding: utf-8 -*-
import scrapy
#import requests
from scrapy import Request
from scrapy.spiders import CrawlSpider
import time
import datetime
import re
import json
from ZhihuSpider.items import QuesInfoItem

class ZhSpider(CrawlSpider):
    name = 'ZhSpider'
    allowed_domains = ['zhihu.com']
    # start_urls是Spider在启动时进行爬取的入口URL列表。第一个被获取到的页面的URL将是其中一个，
    # 后续的URL从初始的URL的响应中获取
    #start_urls = ['https://www.zhihu.com/r/search?q=%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0',
    #'https://www.zhihu.com/r/search?q=%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0&correction=1&type=content&offset=30',
    #]
    #base_url = 'https://www.zhihu.com/people/excited-vczh/activities'
    base_url = 'https://www.zhihu.com/people/yanghui-92'
    #start_urls = ['https://www.zhihu.com/people/excited-vczh/activities']
    #start_urls = ['https://www.zhihu.com/api/v4/members/excited-vczh/activities?limit=7&session_id=1183758912434778112&after_id=1575445096&desktop=True']
    start_urls = ['https://www.zhihu.com/api/v3/moments/yanghui-92/activities?limit=7&session_id=1358733206741721089&after_id=1638511426&desktop=true']
    #start_urls = ['https://www.zhihu.com/api/v4/members/yanghui-92/activities?limit=7&session_id=1183758912434778112&after_id=1575445096&desktop=True']
    # parse是Spider的一个方法。被调用时，每个初始的URL响应后返回的response对象，将会作为唯一的参数返回给该方法
    # 该方法负责解析返回的数据（respose data）、提取数据（item）以及生成需要进一步处理的URL的Response对象

    #数字（1970年开始的秒数）转换为日期格式
    def timeStamp(timeNum):
        timeStamp = float(timeNum)
        timeArray = time.localtime(timeStamp)
        otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
        print (otherStyleTime)

    def parse(self, response):

        # print('***********************\n',response.body,'***********************\n\n')
        print('*************开始下载json文件:*********************')
        # 1、实现网页的解析，生成item
        # 首先打开js路径，获取'htmls'KEY下面的内容，是一个整体的str文件，没有标KEY，所以用re去解析它
        try:
            # print(type(response.body))
            # print(type(response.text))
            jsDict = json.loads(response.body)
            # print(type(jsDict))
            print('*************开始解析页面*********************')
            activities = jsDict['data']
            print(activities)
            # 抽取所有的问题和对应的follwer_num, answer_num和answer_abstract
            for q in activities:
                item = QuesInfoItem()
                # 删去源代码中关键词“机器学习”的标签
                #q = q.replace('','').replace('','')
                # 问题信息在标签 class=\"js-title-link\">和当中
                #question = re.findall('class=\"js-title-link\">(.*?)',q)[0]
                #print(q)
                #当日日期转换为1970秒数
                timeDateStr=str(datetime.date.today())
                time1=datetime.datetime.strptime(timeDateStr,"%Y-%m-%d")
                todaysecondsFrom1970=int(time.mktime(time1.timetuple()))
                print(todaysecondsFrom1970)
                print(q['created_time'])
                #只爬取当天的
                '''
                if q['created_time'] < todaysecondsFrom1970:
                    print("非当日活动，爬虫结束！")
                    break
                '''

                #把1970秒数转换为日期字符串
                item['created_time'] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(float(q['created_time'])))
                item['action_text'] = q['action_text']
                if item['action_text'] == '赞同了回答':
                    item['content'] = q['target']['content']
                    item['question'] = q['target']['question']['title']
                elif item['action_text'] == '发布了想法':
                    item['content'] = q['target']['content']
                elif item['action_text'] == '回答了问题':
                    item['content'] = q['target']['content']
                    item['question'] = q['target']['question']['title']
                elif item['action_text'] == '关注了问题':
                    item['question'] = q['target']['title']
                elif item['action_text'] == '赞同了文章':
                    item['content'] = q['target']['content']
                    item['question'] = q['target']['title']
                yield item
                time.sleep(1)

            # 2、构造下一页的链接并回调给parse方法
            #first_url = 'https://www.zhihu.com/r/search?q=%E6%9C%BA%E5%99%A8%E5%AD%A6%E4%B9%A0'
            # 下一页链接信息在js文件的['paging']标签下的['next']KEY中
            if q['created_time'] > todaysecondsFrom1970:
                print("当日活动，继续爬取下一页！")
                nexturl = jsDict['paging']['next']
                print("next url is---")
                print(nexturl)
                yield Request(nexturl, callback=self.parse)

        except json.decoder.JSONDecodeError as e: #这个报错开始是因为找错了url一直报错加的，现在应该没关系可以去掉了
            print('JSONDecodeError')

<file_sep># -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
import csv
import os,sys
import sqlite3
from ZhihuSpider.items import QuesInfoItem

class ZhihuSpiderWriteToCSVPipeline(object):

    def open_spider(self, spider):
        # print("abs path is %s" %(os.path.abspath(sys.argv[0])))

        self.csvFile = open(os.path.abspath('C:/Users/yangh/Desktop/test.csv'), "w+",newline='')
        try:
            self.write = csv.writer(self.csvFile)
            self.write.writerow('action_text')
            self.write.writerow('question')
            self.write.writerow('content')
        except Exception as e:
            pass

    def close_spider(self, spider):
        self.csvFile.close()

    def process_item(self, item, spider):
        try:
            self.write.writerow((item["action_text"]))
            self.write.writerow((item["question"]))
            self.write.writerow((item["content"]))
        except BaseException as e:
            pass

        return item

class ZhihuSpiderWriteToDBPipeline(object):

    def open_spider(self, spider):
        try:
            self.conn = sqlite3.connect(os.path.abspath('C:/Users/yangh/Desktop/test.db'))
            self.cursor = self.conn.cursor()
        except BaseException as e:
            pass

    def close_spider(self, spider):
        try:
            self.cursor.close()
            self.conn.commit()
            self.conn.close()
        except BaseException as e:
            pass

    def process_item(self, item, spider):
        try:
            if isinstance(item, QuesInfoItem):
                self.cursor.execute('insert into question (question, author_name, author_bio, answer_content) values (?, ?, ?, ?)', (item["question"], item["author_name"], item["author_bio"], item["answer_content"]))
        except BaseException as e:
            print(e)
            pass

        return item

repo_language: Python

repo_name: yanghuibuaa/GetStock


text:
<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Timeline;
using UnityEngine.Playables;
using System.Collections.Generic;

public class SectionCinematic : MonoBehaviour
{
    public PlayableDirector introduction;

    public void PlayIntroduction()
    {
        introduction.Play();
    }
}<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Timeline;
using UnityEngine.Playables;
using System.Collections.Generic;

public enum FlowState
{
    Cinematic = 0,
    Situation = 1,
    WordSelection = 2,
    Speech = 3,
    OpponentSpeech = 4
};

public class OrchestratorFlow : MonoBehaviour
{
    [Header("Header")]
    public bool debug = true;

    [Header("States")]
    public FlowState defaultState;
    private FlowState currentState;

    public SectionCinematic cinematic;
    public SectionSituation situation;
    public SectionWordSelection wordSelection;
    public SectionSpeech speech;
    public SectionSpeech opponentSpeech;

    protected void Start()
    {
        currentState = defaultState;

        // Start intro cinematic
        if (!debug)
        {
            cinematic.PlayIntroduction();
        }
        else
        {
            SetCurrentStateToWordSelection();
        }

        // On word selection ending, make it so that we switch to switch
        situation.OnSituationEnded += SetCurrentStateToWordSelection;
        wordSelection.OnWordSelectionEnded += SetCurrentStateToSpeech;
        speech.OnSpeechEnded += SetCurrentStateToOpponentSpeech;
        opponentSpeech.OnSpeechEnded += SetCurrentStateToCinematic;
    }

    protected void Update()
    {
        switch (currentState)
        {
            case FlowState.Situation:
                situation.CustomUpdate();
                break;

            case FlowState.WordSelection:
                wordSelection.CustomUpdate();
                break;

            case FlowState.Speech:
                speech.CustomUpdate();
                break;

            case FlowState.OpponentSpeech:
                opponentSpeech.CustomUpdate();
                break;

            default:
                break;
        }
    }

    public void SetCurrentStateToCinematic()
    {
        currentState = FlowState.Cinematic;
    }

    public void SetCurrentStateToSituation()
    {
        currentState = FlowState.Situation;

        situation.gameObject.SetActive(true);
        situation.Initialise();
    }

    public void SetCurrentStateToWordSelection()
    {
        currentState = FlowState.WordSelection;

        wordSelection.gameObject.SetActive(true);
    }

    public void SetCurrentStateToSpeech()
    {
        currentState = FlowState.Speech;
    }

    public void SetCurrentStateToOpponentSpeech()
    {
        currentState = FlowState.OpponentSpeech;
    }

    private void OnDestroy()
    {
        situation.OnSituationEnded -= SetCurrentStateToWordSelection;
        wordSelection.OnWordSelectionEnded -= SetCurrentStateToSpeech;
        speech.OnSpeechEnded -= SetCurrentStateToOpponentSpeech;
        opponentSpeech.OnSpeechEnded -= SetCurrentStateToCinematic;
    }
}<file_sep>using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System.Collections;
using UnityEngine.Playables;
using System.Collections.Generic;

public class SectionSpeech : CustomUpdateUser
{
    [Header("Opponent")]
    public bool isOpponentSpeech;
    public SectionSpeech opponentSpeech;
    [Range(1f, 5f)]
    public float slideDuration = 2f;
    private bool opponentCoroutine;

    [Header("Cinematic")]
    public PlayableDirector cinematic;

    [Header("Speeches Game Objects")]
    public Canvas[] speechesCanvas;
    public string[] allSpeeches;

    [Header("Possibles Speeches")]
    public Text[] speechesText;

    [Header("Score Related")]
    public PopularityScore popularityScore;
    public int[] speechesIndexes;
    public int[] validSpeeches;
    public int[] wrongSpeeches;

    private int currentSlideIndex;

    public UnityAction OnSpeechEnded;

    public void OnSpeechSectionStarting(int[] indexes)
    {
        speechesIndexes = indexes;

        speechesText[0].text = allSpeeches[indexes[0]];

        speechesText[1].text = allSpeeches[indexes[1]];
        speechesCanvas[1].gameObject.SetActive(false);

        speechesText[2].text = allSpeeches[indexes[2]];
        speechesCanvas[2].gameObject.SetActive(false);

        gameObject.SetActive(true);
    }

    public override void CustomUpdate()
    {
        if (isOpponentSpeech && !opponentCoroutine)
        {
            StartCoroutine(PlayOpponentSpeech());
        }
        else
        {
            if (Input.GetKeyDown(KeyCode.Space) && !isOpponentSpeech)
            {
                SwitchToNextSpeechSlide();
            }
        }
    }

    private IEnumerator PlayOpponentSpeech()
    {
        opponentCoroutine = true;

        while (currentSlideIndex < speechesText.Length)
        {
            yield return new WaitForSeconds(slideDuration);
            SwitchToNextSpeechSlide();
        }

        opponentCoroutine = false;

        yield return null;
    }

    private void SwitchToNextSpeechSlide()
    {
        int previousIndex = currentSlideIndex;
        currentSlideIndex = Mathf.Clamp(currentSlideIndex + 1, 0, speechesText.Length);

        CalculateScore();

        if (currentSlideIndex >= speechesText.Length)
        {
            EndSpeech();
            return;
        }

        speechesCanvas[previousIndex].gameObject.SetActive(false);
        speechesCanvas[currentSlideIndex].gameObject.SetActive(true);
    }

    public void CalculateScore()
    {
        // Loop through all good/wrong speeches
        for (int i = 0; i < speechesIndexes.Length; i++)
        {
            for (int j = 0; j < validSpeeches.Length; j++)
            {
                // In case valid
                if (speechesIndexes[i] == validSpeeches[j])
                {
                    popularityScore.HighPopularityIncrement();
                    return;
                }

                // In case INvalid
                if (speechesIndexes[i] == wrongSpeeches[j])
                {
                    popularityScore.HighPopularityDecrement();
                    return;
                }
            }
        }

        // Else random choice because no time ; not by design.
        float mediumOrLow = Random.Range(0f, 1f);
        float moreOrLess = Random.Range(0f, 1f);
        if (mediumOrLow > 0.5f)
        {
            if (moreOrLess > 0.5f)
            {
                popularityScore.MediumPopularityIncrement();
            }
            else
            {
                popularityScore.MediumPopularityDecrement();
            }
        }
        else
        {
            if (moreOrLess > 0.5f)
            {
                popularityScore.LowPopularityIncrement();
            }
            else
            {
                popularityScore.LowPopularityDecrement();
            }
        }
    }

    public void ToggleSectionSpeechTo(bool value)
    {
        gameObject.SetActive(value);
    }

    private void EndSpeech()
    {
        if (OnSpeechEnded != null)
        {
            OnSpeechEnded.Invoke();
        }

        if (!isOpponentSpeech)
        {
            opponentSpeech.ToggleSectionSpeechTo(true);
        }
        else
        {
            cinematic.Play();
        }

        ToggleSectionSpeechTo(false);
    }
}<file_sep>using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.SceneManagement;

public class Debugger : MonoBehaviour
{
    [Header("Time Management")]

    [Range(0f, 1f)]
    public float slowSpeed = 0.5f;
    [Range(1f, 10f)]
    public float fastSpeed = 2f;

    private void Update()
    {
        // SCENE MANAGEMENT
        // RELOAD
        if (Input.GetKeyDown(KeyCode.Keypad0))
        {
            SceneManager.LoadScene(0);
        }

        // TIME MANAGEMENT
        // FAST
        if (Input.GetKeyDown(KeyCode.KeypadPlus))
        {
            Time.timeScale = fastSpeed;
        }
        // SLOW
        if (Input.GetKeyDown(KeyCode.KeypadMinus))
        {
            Time.timeScale = slowSpeed;
        }
        // BACK TO NORMAL
        if (Input.GetKeyDown(KeyCode.KeypadMultiply))
        {
            Time.timeScale = 1f;
        }
    }
}<file_sep>using System;
using UnityEngine;
using System.Collections;
using UnityEngine.Timeline;
using UnityEngine.Playables;
using System.Collections.Generic;

[Serializable]
public class PlayableAssetSetCurrentGameStateTo : PlayableAsset, ITimelineClipAsset
{
    [SerializeField]
    private BehaviourSetCurrentGameStateTo template = new BehaviourSetCurrentGameStateTo();

    public ClipCaps clipCaps { get { return ClipCaps.None; } }

    public override Playable CreatePlayable(PlayableGraph graph, GameObject owner)
    {
        return ScriptPlayable<BehaviourSetCurrentGameStateTo>.Create(graph, template);
    }
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine.Events;
using System;
using UnityEngine;
using UnityEngine.UI;

public class SectionWordSelection : CustomUpdateUser
{
    public Transform root;

    [Range(1, 4)]
    public int amountOfWordsToPick = 3;
    private int currentAmountOfWordsPicked;

    public CanvasGroup wordSelectionUI;

    [Header("Validate Button")]
    public GameObject validateButton;
    public SectionSpeech speech;

    [Header("Words")]
    public string[] allWords;

    [Header("Colors")]
    public Color selectedColor;
    public Color unselectedColor;

    private Text[] allTexts;
    private Button[] allButtons;

    private List<int> selectedWordsIndexes = new List<int>();

    public UnityAction OnWordSelectionEnded;

    private void Start()
    {
        InitialiseVariables();
    }

    private void InitialiseVariables()
    {
        int childrenCount = root.childCount;

        allButtons = new Button[childrenCount];
        allTexts = new Text[childrenCount];

        for (int i = 0; i < childrenCount; i++)
        {
            allButtons[i] = root.GetChild(i).GetComponent<Button>();

            allTexts[i] = root.GetChild(i).GetComponentInChildren<Text>();
            allTexts[i].text = allWords[i];
        }
    }

    private void ActivateSpeech()
    {

    }

    public void OnWordSelectionStarting()
    {

    }

    public void OnWordSelectionEnding()
    {
        // Activate Speech
        speech.OnSpeechSectionStarting(selectedWordsIndexes.ToArray());
        speech.ToggleSectionSpeechTo(true);

        // Deactivate Word Selection
        gameObject.SetActive(false);
    }

    public void UpdateWordList(int index)
    {
        // Add / remove a word
        if (selectedWordsIndexes.Contains(index))
        {
            RemoveWord(index);
        }
        else
        {
            AddWord(index);
        }

        // Update UI
        validateButton.gameObject.SetActive(selectedWordsIndexes.Count >= amountOfWordsToPick);
    }

    private void AddWord(int index)
    {
        if (selectedWordsIndexes.Count >= amountOfWordsToPick)
        {
            return;
        }

        selectedWordsIndexes.Add(index);
        allButtons[index].image.color = selectedColor;
    }

    private void RemoveWord(int index)
    {
        allButtons[index].image.color = unselectedColor;
        selectedWordsIndexes.Remove(index);
    }

    public override void CustomUpdate()
    {

    }

    public void OnDestroy()
    {
        OnWordSelectionEnded -= ActivateSpeech;
    }
}<file_sep>using System;
using UnityEngine;
using System.Collections;
using UnityEngine.Timeline;
using UnityEngine.Playables;
using System.Collections.Generic;

[Serializable]
public class BehaviourSetCurrentGameStateTo : PlayableBehaviour
{
    [SerializeField]
    private FlowState newFlowState;

    public override void ProcessFrame(Playable playable, FrameData info, object playerData)
    {
        base.ProcessFrame(playable, info, playerData);

        var orchestrator = playerData as OrchestratorFlow;
        if (orchestrator == null)
            return;

        switch (newFlowState)
        {
            case FlowState.Cinematic:
                orchestrator.SetCurrentStateToCinematic();
                break;

            case FlowState.Situation:
                orchestrator.SetCurrentStateToSituation();
                break;

            case FlowState.WordSelection:
                orchestrator.SetCurrentStateToWordSelection();
                break;

            case FlowState.Speech:
                orchestrator.SetCurrentStateToSpeech();
                break;

            case FlowState.OpponentSpeech:
                orchestrator.SetCurrentStateToOpponentSpeech();
                break;
        }
    }
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(SetChildrenInCircle))]
public class SteleInstantiationEditor : Editor
{
    public override void OnInspectorGUI()
    {
        base.OnInspectorGUI();

        SetChildrenInCircle steleInstantiation = (SetChildrenInCircle) target;

        if (GUILayout.Button("Set Steles"))
        {
            steleInstantiation.SetStelesAroundAutel();
        }
    }
}<file_sep>using UnityEngine;
using UnityEngine.Events;
using System.Collections;
using System.Collections.Generic;

public class SectionSituation : CustomUpdateUser
{
    public GameObject situationUI;

    float timeElapsed;
    float duration = 2f;

    public UnityAction OnSituationEnded;

    public void Initialise()
    {
        gameObject.SetActive(true);
        situationUI.SetActive(true);
        OnSituationEnded += End;
    }

    public void End()
    {
        situationUI.SetActive(false);
    }

    public override void CustomUpdate()
    {
        timeElapsed += Time.deltaTime;
        if (timeElapsed >= duration)
        {
            OnSituationEnded();
        }
    }
}<file_sep>using UnityEngine;
using System.Collections;
using UnityEngine.Timeline;
using UnityEngine.Playables;
using System.Collections.Generic;

[TrackBindingType(typeof(OrchestratorFlow))]
[TrackClipType(typeof(PlayableAssetSetCurrentGameStateTo))]
public class TrackSetCurrentGameStateTo : TrackAsset
{

}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SetChildrenInCircle : MonoBehaviour
{
    public bool forceLookAt;

    [Range(0f, 360f)]
    public float angleAmplitude = 360f;
    [Range(5f, 1000f)]
    public float amplitude;
    [Range(0f, 5f)]
    public float yOffset;
    private Transform[] children;

    [ExecuteInEditMode]
    public void SetStelesAroundAutel()
    {
        children = new Transform[transform.childCount];

        float x, z;
        Vector3 stelePosition = Vector3.zero;
        float incr = (angleAmplitude / children.Length) * Mathf.Deg2Rad;
        float theta = 0f;

        for (int i = 0; i < children.Length; i++)
        {
            x = (amplitude * Mathf.Sin(theta));
            z = (amplitude * Mathf.Cos(theta));

            stelePosition.x = x;
            stelePosition.y = yOffset;
            stelePosition.z = z;

            theta += incr;

            children[i] = transform.GetChild(i);
            children[i].transform.position = stelePosition;

            if (forceLookAt)
            {
                children[i].LookAt(transform.position);
            }
        }
    }
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class PopularityScore : MonoBehaviour
{
    [Header("Score")]
    public Text tScore;
    public float avatarPopularityTarget;
    private float avatarPopularity;

    public float opponentPopularityTarget;
    private float opponentPopularity;

    [Header("Score Update")]
    public float lowIncrement;
    public float mediumIncrement;
    public float highIncrement;

    public float scoreUpdateSpeed;

    protected void Start()
    {
        avatarPopularity = avatarPopularityTarget;
        opponentPopularity = opponentPopularityTarget;
    }

    protected void Update()
    {
        avatarPopularity = Mathf.MoveTowards(avatarPopularity, avatarPopularityTarget, scoreUpdateSpeed * Time.deltaTime);
        opponentPopularity = Mathf.MoveTowards(opponentPopularity, opponentPopularityTarget, scoreUpdateSpeed * Time.deltaTime);

        int avatarPop = (int)avatarPopularity;
        int opponentPop = (int)opponentPopularity;

        tScore.text = avatarPop.ToString() + " - " + opponentPop.ToString();
    }

    public void LowPopularityDecrement()
    {
        UpdatePopularity(-lowIncrement);
    }

    public void MediumPopularityDecrement()
    {
        UpdatePopularity(-mediumIncrement);
    }

    public void HighPopularityDecrement()
    {
        UpdatePopularity(-highIncrement);
    }

    public void LowPopularityIncrement()
    {
        UpdatePopularity(lowIncrement);
    }

    public void MediumPopularityIncrement()
    {
        UpdatePopularity(mediumIncrement);
    }

    public void HighPopularityIncrement()
    {
        UpdatePopularity(highIncrement);
    }

    private void UpdatePopularity(float inc)
    {
        avatarPopularityTarget = Mathf.Clamp(avatarPopularityTarget + inc, 0f, 100f);
        opponentPopularityTarget = Mathf.Clamp(opponentPopularityTarget - inc, 0f, 100f);
    }
}

repo_language: C#


text:
<file_sep>from lettuce import *

from lettuce_webdriver.util import AssertContextManager
import lettuce_webdriver.webdriver
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

@before.all
def setup_browser():
	world.browser = webdriver.Chrome()

@step('I go to "(.*?)"')
def i_go_to_url(step, url):
	world.response = world.browser.get(url)

def find_field_by_class(browser, attribute):
    xpath = "//input[@class='%s']" % attribute
    elems = browser.find_elements_by_xpath(xpath)
    return elems[0] if elems else False

@step('I fill in field with class "(.*?)" with "(.*?)"')
def fill_in_textfield_by_class(step, field_name, value):
    with AssertContextManager(step):
        text_field = find_field_by_class(world.browser, field_name)
        text_field.clear()
        text_field.send_keys(value, Keys.ENTER)


text:
<file_sep>"""
Topic modelling with Pyspark and spark. The dataset is Amazon musical instruments reviews on Kaggle.
"""

import sparknlp

spark = sparknlp.start()

# We need to select the relevant columns from the dataset, we can use Pyspark for this.

from pyspark.sql import function as F

path = './dataset/musical_instruments_reviews.csv'
data = spark.read.csv(path, header=None)

text_col = 'reviewText'
review_text = data.select(text_col).filter(F.col(text_col).isNotNull())

# transform our data to annotations format so sparknlp can understand

from sparknlp.base import DocumentAssembler

document_assembler = DocumentAssembler().setInputCol(text_col).setOutputCol('Document')

# tokenize data

from sparknlp.annotators import Tokenizer

tokenizer = Tokenizer().setInputCols(['Document']).setOutputCol('tokenized')

# normalize data

from sparknlp.annotators import Normalizer

normalizer = Normalizer().setInputCols(['tokenized']).setOutputCol('normalized').setLowercase(True)

# lemmatization

from sparknlp.annotators import LemmatizerModel

lemmatizer = LemmatizerModel.pretrained().setInputCols(['normalizer']).setOutputCol('lemmatized')

# remove stop-words

from nltk.corpus import stopwords

stopwords = stopwords.words('english')

from sparknl.annotators import StopWordsCleaner

stopwords_cleaner = StopWordsCleaner().setInputCols(['lemmatized']).setOutputCol('no_stop_lemmatized').setStopWords('stopwords')

# using pos_tagger

from sparknlp.annotators import PerceptronModel

pos_tagger = PerceptronModel.pretrained('pos-anc').setInputCols(['document','lemmatized']).setOutputCol('pos')

# filtering out non meaningful n-grams using Chunker

from sparknlp.annotators import Chunker

allowed_tags = ['<JJ>+<JN>', '<NN>+<NN>']

chunker = Chunker().setInputCols(['docoment','pos']).setOutputCol('ngrams').setRegexParsers(allowed_tags)

# transform from annotation format to human readable

from sparknlp.base import Finisher

finisher = Finisher().setInputCols(['unigrams', 'ngrams'])

# create pipeline

frim pyspark.ml import Pipeline

pipeline = Pipeline().setStages([document_assembler,
    tokenizer,
    normalizer,
    lemmatizer,
    stopwords_cleaner,
    pos_tagger,
    chunker,
    finisher])

# fitting the data

processed_review = pipeline.fit(review_text).transform(review_text)

# combine unigrams and ngrams

from pyspark.sql.functions import concat

processed_review = processed_review.withColumn('final', concat(F.col('finished_unigrams'), F.col('finished_unigrams')))

# vectorizer: convert textual data into numeric one

from pyspark.ml.feature import CountVectorizer

count_vect = CountVectorizer(inputCol='finished_no_stop_lemmatized', outputCol='tf_features')

tf_model = count_vect.fit(processed_review)
tf_result = tf_model.transform(processed_review)

# inverse frequency of documents

from pyspark.ml.feature import IDF

idf = IDF(inputCol='tf_features', outputCol='tf_idf_features')

tfidf_model = idf.fit(tf_result)
tfidf_result = tfidf_model.transform(tf_result)

# topic modelling with Pyspark using LDA algorithm

from pyspark.ml.clustering import LDA

num_topics = 6
max_iter = 10

lda = LDA(k=num_topics,
          maxIter=max_iter,
          featuresCol='tfidf_features')

lda_model = lda.fit(tfidf_result)

# convert word ids into words

vocab = tf_model.vocabulary

def get_words(token_list):
    return [vocab[token_id] for token_id in token_list]

udf_to_words =  F.udf(get_words, T.ArrayType(T.StringType()))

# show 7 most relevant words to a topic

num_words = 7

topics = lda_model.describeTopics(num_words).withColumn('topicWords',udf_to_words=(F.col('termIndices')))

topics.select('topic', 'topicwords').show(truncate=100)

branch_name: refs/heads/main


text:
<repo_name>e-arslan/WeeklyNewRPackage<file_sep>/README.md
disk.frame
-----------
* What does this package do?

	* disk.frame performs a similar role to distributed systems such as Apache Spark, Python’s Dask, and Julia’s JuliaDB.jl for medium data which are datasets that are too large for RAM but not quite large enough to qualify as big data.

* You should use this package, if
	* You are dealing with medium size data(100s of gigabyte) ![Examples](images/data_sizes.png)
	* would like to leverage from ssd level performance & paralelization to fasten your data analysis

* Any avaialble tutorial?
	* [if you don't have time (\~20 mins)](https://diskframe.com/articles/intro-disk-frame.html)
	* [if you have time (> 1 hour)](https://www.youtube.com/watch?v=kjPjXs0mkwE)

* Main functions
	*
	*

Dependencies to Other Packages:
Usability:
Reaching to Large Audiance:
Maintanance:

Overall Score: Silver

![Silver](images/silver.png)

Basic example to run
``` r
```

repo_name: e-arslan/WeeklyNewRPackage


text: <file_sep># tf2-question-and-answer


text:
<file_sep># MINIE-BOOK
GitHub Pages

repo_name: doceszeroacucar/MINIE-BOOK


text:
<file_sep>#todo {
    display: flex;
    align-items: center;
    padding: 10px;
}

#add-tasks {
    display: inline-block;
    padding-left: 50px;
}
#tasks {
    width: 400px;
}

.remaining {
    height: 30px;
    width: 300px;
    line-height: 30px;
    border: solid black;
    background: lightgray;
    display: inline-block;
}

.completed {
    background: green;
    text-decoration: line-through;
}<file_sep>console.log('working');

// add a cool background picture
document.body.style.backgroundImage = "url('pics/space-background.jpg')";

// function getSpacePeople() {
//     console.log('...getting space people...');

//     // get the data
//     fetch('https://api.open-notify.org/astros.json')
//     .then((response) => {
//         return response.json();
//     })
//     .then((data) => {
//         console.log(data);
//         //displayNumAstros(data);
//         createAstros(data);
//     });
// }

var people = '{ "astros" : [' +
'{ "name":"<NAME>"},' +
'{ "name":"<NAME>"},' +
'{ "name":"<NAME>"} ]}';

let spacePeople = JSON.parse(people);
console.log(spacePeople);
console.log(spacePeople.astros[0].name);
displayNumAstros();
createAstros();

function displayNumAstros() {
    // use the api to get the number of the astros in space
    // removed because of https issues
    // const numAstros = `<h2>There are ${data.number} people in space right now!</h2>`;

    const numAstros = `<h2>There are ${spacePeople.astros.length} people in space right now!</h2>`;

    document.body.innerHTML += numAstros;
}

function createAstros() {
    // log the api data
    //console.log(data);

    let astroNames = [];
    let astros = [];

    // add the astros in the api to an array for easy access
    for(let i = 0; i < spacePeople.astros.length; i++) {
        console.log(i);
        // astros += `
        //

        //
${data.people[i].name}

        //
${data.people[i].name}

        //
${data.people[i].name}

        //
`;

        astros += `

${spacePeople.astros[i].name}

${spacePeople.astros[i].name}

${spacePeople.astros[i].name}

        `

        astroNames[i] = spacePeople.astros[i].name;
    }
    // now time to add the astros to the screen with their information
    addAstros(astros, astroNames);
}

function addAstros(astros, astroNames) {
    // make sure that we got the data that we need
    console.log(astroNames);

    // add the information to the body
    document.body.innerHTML += `<div id="astro-info"></div`
    for(let i = 0; i < astroNames.length; i++) {
        if(astroNames[i] == '<NAME>') {
            document.getElementById('astro-info').innerHTML +=`<div id='andrew-morgan'><img src='pics/andrew-morgan.jpg'></img></div>`;
            let andrewInfo = document.createElement('h2');
            andrewInfo.innerHTML = "<NAME>";
            document.getElementById('andrew-morgan').appendChild(andrewInfo);

        } else if(astroNames[i] == '<NAME>') {
            document.getElementById('astro-info').innerHTML +=`<div id="oleg-skripochka"><img src='pics/oleg-skripochka.jpg'></img></div>`;
            let olegInfo = document.createElement('h2');
            olegInfo.innerHTML = "<NAME>";
            document.getElementById('oleg-skripochka').appendChild(olegInfo);

        } else if(astroNames[i] == '<NAME>') {
            document.getElementById('astro-info').innerHTML +=`<div id="jessica-meir"   ><img src='pics/jessica-meir.jpg'></img></div>`;
            let jessicaInfo = document.createElement('h2');
            jessicaInfo.innerHTML = "<NAME>";
            document.getElementById('jessica-meir').appendChild(jessicaInfo);
        }
        else {
            document.body.innerHTML +=`<p>img not found</p>`;
        }
    }
}<file_sep>const hikeList = [
    {
      name: "<NAME>",
      imgSrc: "big-tree.jpg",
      imgAlt: "Image of Bechler Falls",
      distance: "3 miles",
      difficulty: "Easy",
      description:
        "Beautiful short hike along the Bechler river to Bechler Falls",
      directions:
        "Take Highway 20 north to Ashton. Turn right into the town and continue through. Follow that road for a few miles then turn left again onto the Cave Falls road.Drive to the end of the Cave Falls road. There is a parking area at the trailhead."
    },
    {
      name: "<NAME>",
      imgSrc: "big-tree.jpg",
      imgAlt: "Image of Bechler Falls",
      distance: "3 miles",
      difficulty: "Easy",
      description: "Beautiful short (or long) hike through Teton Canyon.",
      directions:
        "Take Highway 33 East to Driggs. Turn left onto Teton Canyon Road. Follow that road for a few miles then turn right onto Staline Raod for a short distance, then left onto Alta Road. Veer right after Alta back onto Teton Canyon Road. There is a parking area at the trailhead."
    },
    {
      name: "<NAME>",
      imgSrc: "big-tree.jpg",
      imgAlt: "Image of Bechler Falls",
      distance: "7 miles",
      difficulty: "Moderate",
      description:
        "Beautiful hike through Bechler meadows river to Denanda Falls",
      directions:
        "Take Highway 20 north to Ashton. Turn right into the town and continue through. Follow that road for a few miles then turn left again onto the Cave Falls road. Drive to until you see the sign for Bechler Meadows on the left. Turn there. There is a parking area at the trailhead."
    }
  ];

  let hikesDiv = document.getElementById('hikes2');
  hikesDiv.innerHTML = '';
  for(let i = 0; i < hikeList.length; i++) {
      hikesDiv.innerHTML += `

${hikeList[i].name}

Distance

${hikeList[i].distance}

Difficulty

${hikeList[i].difficulty}

Description

${hikeList[i].description}

Directions

${hikeList[i].directions}

`;
  }<file_sep># cit261
Course code and notes for cit261 course at byui

languages: Markdown JavaScript CSS


text:
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ShweStock
{
    public partial class ucUserMgrSetup : UserControl
    {
        public ucUserMgrSetup()
        {
            InitializeComponent();
            bindUserRoles();
            bindDataGridView();
            txtUserName.Focus();
        }

        public void bindUserRoles()
        {
            UserMgrBLL obj_UserMgrBLL = new UserMgrBLL();
            DataTable dtUserRoles = obj_UserMgrBLL.getAllUserRoles();
            cbbUserRole.Items.Clear();
            cbbUserRole.LoadingType = MTGCComboBox.CaricamentoCombo.DataTable;
            cbbUserRole.SourceDataString = new string[] { "UserRoleName", "UserRoleId" };
            cbbUserRole.ColumnNum = 2;
            cbbUserRole.ColumnWidth = "150;0";
            cbbUserRole.SourceDataTable = dtUserRoles;
            cbbUserRole.Text = string.Empty;
        }

        private Boolean ValidateUserInput()
        {
            bool bool_Test = true;

            if (txtUserName.Text.Trim().Length == 0)
            {
                bool_Test = false;
                errorProvider1.SetError(txtUserName, "Plase Enter UserName");
                string str_error = errorProvider1.GetError(txtUserName);
                MessageBox.Show(str_error, "Save Fail");
            }
            else if (txtPassword.Text.Trim().Length == 0)
            {
                bool_Test = false;
                errorProvider1.SetError(txtPassword, "Plase Enter Password!");
                string str_error = errorProvider1.GetError(txtPassword);
                MessageBox.Show(str_error, "Save Fail");
            }

            else if (txtPassword.Text.Trim().Length < 4)
            {
                bool_Test = false;
                errorProvider1.SetError(txtPassword, "Your Password must have 4 characters at least!");
                string str_error = errorProvider1.GetError(txtPassword);
                MessageBox.Show(str_error, "Save Fail");
            }

            else if (cbbUserRole.Text.Trim().Length == 0 || cbbUserRole.SelectedValue == null)
            {
                bool_Test = false;
                errorProvider1.SetError(cbbUserRole, "Plase Select User Role");
                string str_error = errorProvider1.GetError(cbbUserRole);
                MessageBox.Show(str_error, "Save Fail");
            }

            errorProvider1.Clear();
            return bool_Test;
        }

        private void AssignData(DEUserMgr u)
        {
            u.UserId = Convert.ToInt32(txtUserName.Tag);
            u.UserName = txtUserName.Text.Trim();
            u.Password = <PASSWORD>(txtPassword.Text.Trim());
            u.UserRoleId = Convert.ToInt32(cbbUserRole.SelectedItem.Col2);
            u.UpdatedBy = DEGlobal.int32_UserID;
            if (u.UserId == 0)
                u.Action = 1;
            else
                u.Action = 2;
        }

        public string Encrypt(string plainText)
        {
            try
            {
                byte[] encData_byte = new byte[plainText.Length];
                encData_byte = System.Text.Encoding.UTF8.GetBytes(plainText);
                string encodedData = Convert.ToBase64String(encData_byte);
                return encodedData;
            }
            catch (Exception e)
            {
                throw new Exception("Error in base64Encode" + e.Message);
            }
        }

        public string Decrypt(string sData)
        {
            System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding();
            System.Text.Decoder utf8Decode = encoder.GetDecoder();
            byte[] todecode_byte = Convert.FromBase64String(sData);
            int charCount = utf8Decode.GetCharCount(todecode_byte, 0, todecode_byte.Length);
            char[] decoded_char = new char[charCount];
            utf8Decode.GetChars(todecode_byte, 0, todecode_byte.Length, decoded_char, 0);
            string result = new String(decoded_char);
            return result;
        }

        private void save()
        {
            DEUserMgr u = new DEUserMgr();
            AssignData(u);

            UserMgrBLL obj_UserMgrBLL = new UserMgrBLL();

            try
            {
                int int_Result = obj_UserMgrBLL.CUUsers(u);
                MessageBox.Show(UIConstantMessage.Const_strSaveSuccessfully);
                bindDataGridView();
                ClearData();

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                u = null;
                obj_UserMgrBLL = null;
            }

        }

        private void ClearData()
        {
            txtUserName.Text = String.Empty;
            txtPassword.Text = String.Empty;
            txtUserName.Tag = 0;
            cbbUserRole.SelectedIndex = -1;

        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            if (ValidateUserInput())
            {
                this.save();
            }
        }

        private void btn_Rest_Click(object sender, EventArgs e)
        {
            ClearData();
        }

        private void bindDataGridView()
        {
            UserMgrBLL obj_UserMgrBLL = new UserMgrBLL();
            DEUserMgr u = new DEUserMgr();
            DataTable dt_Users = obj_UserMgrBLL.getAllUsers(u);

            dgvUser.DataSource = dt_Users;
            dgvUser.Columns[1].Visible = false;
            dgvUser.Columns[2].Width = 200;
            dgvUser.Columns[3].Width = 300;
            dgvUser.Columns[4].Visible = false;
            dgvUser.Columns[5].Visible = false;

            ClearData();

        }

        private void dgvUser_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            DEUserMgr u = new DEUserMgr();

            try
            {

                u.UserId = Convert.ToInt32(dgvUser.CurrentRow.Cells["UserId"].Value);
                u.UserName = Convert.ToString(dgvUser.CurrentRow.Cells["UserName"].Value);
                u.Password = Convert.ToString(dgvUser.CurrentRow.Cells["Password"].Value);
                u.UserRoleId = Convert.ToInt32(dgvUser.CurrentRow.Cells["UserRoleId"].Value);

                displayData(u);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            u = null;
        }

        private void displayData(DEUserMgr u)
        {
            txtUserName.Tag = u.UserId;
            txtUserName.Text = u.UserName;
            txtPassword.Text = Decrypt(u.Password);
            cbbUserRole.SelectedValue = u.UserRoleId.ToString();

        }

    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ShweStock
{
    public partial class ucSetup : UserControl
    {
        public ucSetup()
        {
            InitializeComponent();
        }

        private void btnUserMgr_Click(object sender, EventArgs e)
        {
            pnlMain.Controls.Clear();

            ucUserMgrSetup control = new ucUserMgrSetup();
            control.Dock = DockStyle.Fill;

            pnlMain.Controls.Add(control);
        }

    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShweStock
{
    class UserMgrBLL
    {
        public DataTable getAllUserRoles()
        {
            UserMgrDAL obj_UserMgrDAL = new UserMgrDAL();
            DataTable dtUserRoles = obj_UserMgrDAL.getAllUserRoles();
            obj_UserMgrDAL = null;
            return dtUserRoles;

        }

        public int CUUsers(DEUserMgr u)
        {
            UserMgrDAL obj_UserMgrDAL = new UserMgrDAL();

            int int_Result = obj_UserMgrDAL.CUUsers(u);

            obj_UserMgrDAL = null;

            return int_Result;
        }

        public DataTable getAllUsers(DEUserMgr u)
        {
            UserMgrDAL obj_UserMgrDAL = new UserMgrDAL();

            DataTable dt_Users = obj_UserMgrDAL.getAllUsers(u);

            obj_UserMgrDAL = null;

            return dt_Users;
        }

        public DataTable getUserByNameAndPassword(DEUserMgr u)
        {
            UserMgrDAL obj_UserMgrDAL = new UserMgrDAL();
            DataTable dt_User = obj_UserMgrDAL.getUserByNameAndPassword(u);
            obj_UserMgrDAL = null;
            return dt_User;

        }
    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace ShweStock
{
    public static class GenericDataAccess
    {
        static GenericDataAccess()
        {

        }
        public static string DataConn = Properties.Settings.Default.Setting;

        // executes a command and returns the results as a DataTable object
        public static DataTable ExecuteSelectCommand(SqlCommand command)
        {
            // The DataTable to be returned
            DataTable table;
            try
            {
                command.Connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                table = new DataTable();
                table.Load(reader);

                reader.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                // Close the connection
                command.Connection.Close();
            }
            return table;
        }

        // executes a command and returns the results as a DataTable object
        public static DataSet ExecuteSelectDataSetCommand(SqlCommand command)
        {
            // The DataSet to be returned
            DataSet dataSet = new DataSet();

            try
            {
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                adapter.Fill(dataSet);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                // Close the connection
                command.Connection.Close();
            }
            return dataSet;
        }

        // creates and prepares a new DbCommand object on a new connection
        public static SqlCommand CreateCommand()
        {
            string connectionString = Properties.Settings.Default.Setting;
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = connectionString;
            SqlCommand comm = conn.CreateCommand();
            comm.CommandType = CommandType.StoredProcedure;
            return comm;
        }

        // execute an update, delete, or insert command
        // and return the number of affected rows
        public static int ExecuteNonQuery(SqlCommand command)
        {
            // The number of affected rows
            int affectedRows = 0;

            try
            {
                command.Connection.Open();
                affectedRows = command.ExecuteNonQuery();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                command.Connection.Close();
            }

            return affectedRows;
        }

        // execute a select command and return a single result as a string
        public static string ExecuteScalar(SqlCommand command)
        {
            string value = "";

            try
            {
                command.Connection.Open();

                value = command.ExecuteScalar().ToString();
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                command.Connection.Close();
            }

            return value;
        }

        public static Boolean GetScalar(SqlCommand command)
        {
            //string value = "";

            try
            {
                command.Connection.Open();

                command.ExecuteScalar();
                return Convert.ToBoolean(command.ExecuteScalar());

            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                command.Connection.Close();
            }

        }
        public static int GetSQLTransVoid(SqlCommand sqlCmd)
        {
            int int_Result = 0;
            try
            {
                int_Result = sqlCmd.ExecuteNonQuery();
            }
            catch (SqlException sqx)
            {
                throw sqx;
                //DevExpress.XtraEditors.XtraMessageBox.Show(sqx.Message + sqx.Source);
            }
            finally
            {
                // sqlCon.Close();
            }

            return int_Result;
        }
    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ShweStock
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }

        private void btnUser_Click(object sender, EventArgs e)
        {
            pnlMain.Controls.Clear();

            ucUserMgrSetup control = new ucUserMgrSetup();
            control.Dock = DockStyle.Fill;

            pnlMain.Controls.Add(control);
        }
    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShweStock
{
    class DEUserMgr
    {
        #region +++ public access method (Constructor) +++

        public DEUserMgr()
        {
            this.UserId = 0;
            this.UserRoleId = 0;
            this.UserName = string.Empty;
            this.Password = string.Empty;
            this.CreatedDate = DEGlobal.dateTime_ToDayDate;
            this.CreatedBy = DEGlobal.int32_UserID;
            this.UpdatedDate = DEGlobal.dateTime_ToDayDate;
            this.UpdatedBy = DEGlobal.int32_UserID;
            this.IsActive = true;
            this.Action = 0;
        }

        #endregion

        #region +++ properties declaration +++
        public int UserId { get; set; }
        public int UserRoleId { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }
        public DateTime CreatedDate { get; set; }
        public int CreatedBy { get; set; }
        public DateTime UpdatedDate { get; set; }
        public int UpdatedBy { get; set; }
        public bool IsActive { get; set; }
        public int Action { get; set; }

        #endregion
    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShweStock
{
    class UserMgrDAL
    {
        #region +++  Codes of private access methods  +++

        private SqlCommand DeclareSqlCmdParameter(SqlCommand SqlCmd, DEUserMgr u)
        {
            SqlCmd.Parameters.AddWithValue("@UserId", u.UserId);
            SqlCmd.Parameters.AddWithValue("@UserName", u.UserName);
            SqlCmd.Parameters.AddWithValue("@Password", <PASSWORD>);
            SqlCmd.Parameters.AddWithValue("@UserRoleId", u.UserRoleId);
            SqlCmd.Parameters.AddWithValue("@CreatedDate", u.CreatedDate);
            SqlCmd.Parameters.AddWithValue("@CreatedBy", u.CreatedBy);
            SqlCmd.Parameters.AddWithValue("@UpdatedDate", u.UpdatedDate);
            SqlCmd.Parameters.AddWithValue("@UpdatedBy", u.UpdatedBy);
            SqlCmd.Parameters.AddWithValue("@IsActive", u.IsActive);
            SqlCmd.Parameters.AddWithValue("@Action", u.Action);

            return SqlCmd;
        }

        #endregion

        public DataTable getAllUserRoles()
        {
            SqlCommand cmd = GenericDataAccess.CreateCommand();
            cmd.CommandText = "sp_getAllUserRoles";
            cmd.CommandType = CommandType.StoredProcedure;
            return GenericDataAccess.ExecuteSelectCommand(cmd);
        }

        public int CUUsers(DEUserMgr u)
        {
            SqlCommand cmd = GenericDataAccess.CreateCommand();
            DeclareSqlCmdParameter(cmd, u);
            cmd.CommandText = "sp_CUUsers";
            cmd.CommandType = CommandType.StoredProcedure;
            return GenericDataAccess.ExecuteNonQuery(cmd);

        }

        public DataTable getAllUsers(DEUserMgr u)
        {
            SqlCommand cmd = GenericDataAccess.CreateCommand();
            //DeclareSqlCmdParameter(cmd, u);
            cmd.CommandText = "sp_getAllUsers";
            cmd.CommandType = CommandType.StoredProcedure;
            return GenericDataAccess.ExecuteSelectCommand(cmd);
        }

        public DataTable getUserByNameAndPassword(DEUserMgr u)
        {
            SqlCommand cmd = GenericDataAccess.CreateCommand();
            DeclareSqlCmdParameter(cmd, u);
            cmd.CommandText = "sp_getUserAndPassword";
            cmd.CommandType = CommandType.StoredProcedure;
            return GenericDataAccess.ExecuteSelectCommand(cmd);
        }

    }
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ShweStock
{
    public partial class frmLogin : Form
    {
        DataTable dt_User { get; set; }
        int i = 1;
        public frmLogin()
        {
            InitializeComponent();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            login();
        }

        private void login()
        {
            string userName = txtUserName.Text;
            string password = Encrypt(txtPassword.Text);
            DEUserMgr u = new DEUserMgr();
            u.UserName = userName;
            u.Password = <PASSWORD>;
            UserMgrBLL obj_UserMgrBLL = new UserMgrBLL();
            dt_User = obj_UserMgrBLL.getUserByNameAndPassword(u);
            if (dt_User.Rows.Count == 0)
            {
                if (i != 3)
                {
                    MessageBox.Show("Invalid UserName or Password!", "Unauthorized Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    txtPassword.Focus();
                    i++;
                }
                else
                {

                    MessageBox.Show("You have already tried 3 times. Your password may have been changed. Please contact your system administrator.", "Unauthorized Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Application.Exit();
                }
            }
            else
            {
                DEGlobal.int32_UserID = Convert.ToInt32(dt_User.Rows[0]["UserId"].ToString());
                DEGlobal.int32_UserRoleID = Convert.ToInt32(dt_User.Rows[0]["UserRoleId"].ToString());
                this.Hide();
                frmMain main = new frmMain();
                main.Show();

            }
        }
        //private string Encrypt(string clearText)
        //{
        //    string EncryptionKey = "<KEY>";
        //    byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        //    using (Aes encryptor = Aes.Create())
        //    {
        //        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
        //        encryptor.Key = pdb.GetBytes(32);
        //        encryptor.IV = pdb.GetBytes(16);
        //        using (MemoryStream ms = new MemoryStream())
        //        {
        //            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
        //            {
        //                cs.Write(clearBytes, 0, clearBytes.Length);
        //                cs.Close();
        //            }
        //            clearText = Convert.ToBase64String(ms.ToArray());
        //        }
        //    }
        //    return clearText;
        //}

        public string Encrypt(string plainText)
        {
            try
            {
                byte[] encData_byte = new byte[plainText.Length];
                encData_byte = System.Text.Encoding.UTF8.GetBytes(plainText);
                string encodedData = Convert.ToBase64String(encData_byte);
                return encodedData;
            }
            catch (Exception e)
            {
                throw new Exception("Error in base64Encode" + e.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void frmLogin_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                login();
            }
        }

        private void txtPassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                login();
            }
        }

    }
}


text:
<repo_name>AndnixSH/Npp-Logcat-Highlighter<file_sep>/README.md
# Npp-Logcat-Highlighter

repo_name: AndnixSH/Npp-Logcat-Highlighter